xref: /linux/kernel/time/tick-sched.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
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 		/*
289 		 * In case the current tick fired too early past its expected
290 		 * expiration, make sure we don't bypass the next clock reprogramming
291 		 * to the same deadline.
292 		 */
293 		ts->next_tick = 0;
294 	}
295 
296 	update_process_times(user_mode(regs));
297 	profile_tick(CPU_PROFILING);
298 }
299 
300 /*
301  * We rearm the timer until we get disabled by the idle code.
302  * Called with interrupts disabled.
303  */
304 static enum hrtimer_restart tick_nohz_handler(struct hrtimer *timer)
305 {
306 	struct tick_sched *ts =	container_of(timer, struct tick_sched, sched_timer);
307 	struct pt_regs *regs = get_irq_regs();
308 	ktime_t now = ktime_get();
309 
310 	tick_sched_do_timer(ts, now);
311 
312 	/*
313 	 * Do not call when we are not in IRQ context and have
314 	 * no valid 'regs' pointer
315 	 */
316 	if (regs)
317 		tick_sched_handle(ts, regs);
318 	else
319 		ts->next_tick = 0;
320 
321 	/*
322 	 * In dynticks mode, tick reprogram is deferred:
323 	 * - to the idle task if in dynticks-idle
324 	 * - to IRQ exit if in full-dynticks.
325 	 */
326 	if (unlikely(tick_sched_flag_test(ts, TS_FLAG_STOPPED)))
327 		return HRTIMER_NORESTART;
328 
329 	hrtimer_forward(timer, now, TICK_NSEC);
330 
331 	return HRTIMER_RESTART;
332 }
333 
334 #ifdef CONFIG_NO_HZ_FULL
335 cpumask_var_t tick_nohz_full_mask;
336 EXPORT_SYMBOL_GPL(tick_nohz_full_mask);
337 bool tick_nohz_full_running;
338 EXPORT_SYMBOL_GPL(tick_nohz_full_running);
339 static atomic_t tick_dep_mask;
340 
341 static bool check_tick_dependency(atomic_t *dep)
342 {
343 	int val = atomic_read(dep);
344 
345 	if (likely(!tracepoint_enabled(tick_stop)))
346 		return !!val;
347 
348 	if (val & TICK_DEP_MASK_POSIX_TIMER) {
349 		trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
350 		return true;
351 	}
352 
353 	if (val & TICK_DEP_MASK_PERF_EVENTS) {
354 		trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
355 		return true;
356 	}
357 
358 	if (val & TICK_DEP_MASK_SCHED) {
359 		trace_tick_stop(0, TICK_DEP_MASK_SCHED);
360 		return true;
361 	}
362 
363 	if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
364 		trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
365 		return true;
366 	}
367 
368 	if (val & TICK_DEP_MASK_RCU) {
369 		trace_tick_stop(0, TICK_DEP_MASK_RCU);
370 		return true;
371 	}
372 
373 	if (val & TICK_DEP_MASK_RCU_EXP) {
374 		trace_tick_stop(0, TICK_DEP_MASK_RCU_EXP);
375 		return true;
376 	}
377 
378 	return false;
379 }
380 
381 static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
382 {
383 	lockdep_assert_irqs_disabled();
384 
385 	if (unlikely(!cpu_online(cpu)))
386 		return false;
387 
388 	if (check_tick_dependency(&tick_dep_mask))
389 		return false;
390 
391 	if (check_tick_dependency(&ts->tick_dep_mask))
392 		return false;
393 
394 	if (check_tick_dependency(&current->tick_dep_mask))
395 		return false;
396 
397 	if (check_tick_dependency(&current->signal->tick_dep_mask))
398 		return false;
399 
400 	return true;
401 }
402 
403 static void nohz_full_kick_func(struct irq_work *work)
404 {
405 	/* Empty, the tick restart happens on tick_nohz_irq_exit() */
406 }
407 
408 static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) =
409 	IRQ_WORK_INIT_HARD(nohz_full_kick_func);
410 
411 /*
412  * Kick this CPU if it's full dynticks in order to force it to
413  * re-evaluate its dependency on the tick and restart it if necessary.
414  * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
415  * is NMI safe.
416  */
417 static void tick_nohz_full_kick(void)
418 {
419 	if (!tick_nohz_full_cpu(smp_processor_id()))
420 		return;
421 
422 	irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
423 }
424 
425 /*
426  * Kick the CPU if it's full dynticks in order to force it to
427  * re-evaluate its dependency on the tick and restart it if necessary.
428  */
429 void tick_nohz_full_kick_cpu(int cpu)
430 {
431 	if (!tick_nohz_full_cpu(cpu))
432 		return;
433 
434 	irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
435 }
436 
437 static void tick_nohz_kick_task(struct task_struct *tsk)
438 {
439 	int cpu;
440 
441 	/*
442 	 * If the task is not running, run_posix_cpu_timers()
443 	 * has nothing to elapse, and an IPI can then be optimized out.
444 	 *
445 	 * activate_task()                      STORE p->tick_dep_mask
446 	 *   STORE p->on_rq
447 	 * __schedule() (switch to task 'p')    smp_mb() (atomic_fetch_or())
448 	 *   LOCK rq->lock                      LOAD p->on_rq
449 	 *   smp_mb__after_spin_lock()
450 	 *   tick_nohz_task_switch()
451 	 *     LOAD p->tick_dep_mask
452 	 *
453 	 * XXX given a task picks up the dependency on schedule(), should we
454 	 * only care about tasks that are currently on the CPU instead of all
455 	 * that are on the runqueue?
456 	 *
457 	 * That is, does this want to be: task_on_cpu() / task_curr()?
458 	 */
459 	if (!sched_task_on_rq(tsk))
460 		return;
461 
462 	/*
463 	 * If the task concurrently migrates to another CPU,
464 	 * we guarantee it sees the new tick dependency upon
465 	 * schedule.
466 	 *
467 	 * set_task_cpu(p, cpu);
468 	 *   STORE p->cpu = @cpu
469 	 * __schedule() (switch to task 'p')
470 	 *   LOCK rq->lock
471 	 *   smp_mb__after_spin_lock()          STORE p->tick_dep_mask
472 	 *   tick_nohz_task_switch()            smp_mb() (atomic_fetch_or())
473 	 *      LOAD p->tick_dep_mask           LOAD p->cpu
474 	 */
475 	cpu = task_cpu(tsk);
476 
477 	preempt_disable();
478 	if (cpu_online(cpu))
479 		tick_nohz_full_kick_cpu(cpu);
480 	preempt_enable();
481 }
482 
483 /*
484  * Kick all full dynticks CPUs in order to force these to re-evaluate
485  * their dependency on the tick and restart it if necessary.
486  */
487 static void tick_nohz_full_kick_all(void)
488 {
489 	int cpu;
490 
491 	if (!tick_nohz_full_running)
492 		return;
493 
494 	preempt_disable();
495 	for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
496 		tick_nohz_full_kick_cpu(cpu);
497 	preempt_enable();
498 }
499 
500 static void tick_nohz_dep_set_all(atomic_t *dep,
501 				  enum tick_dep_bits bit)
502 {
503 	int prev;
504 
505 	prev = atomic_fetch_or(BIT(bit), dep);
506 	if (!prev)
507 		tick_nohz_full_kick_all();
508 }
509 
510 /*
511  * Set a global tick dependency. Used by perf events that rely on freq and
512  * unstable clocks.
513  */
514 void tick_nohz_dep_set(enum tick_dep_bits bit)
515 {
516 	tick_nohz_dep_set_all(&tick_dep_mask, bit);
517 }
518 
519 void tick_nohz_dep_clear(enum tick_dep_bits bit)
520 {
521 	atomic_andnot(BIT(bit), &tick_dep_mask);
522 }
523 
524 /*
525  * Set per-CPU tick dependency. Used by scheduler and perf events in order to
526  * manage event-throttling.
527  */
528 void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
529 {
530 	int prev;
531 	struct tick_sched *ts;
532 
533 	ts = per_cpu_ptr(&tick_cpu_sched, cpu);
534 
535 	prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
536 	if (!prev) {
537 		preempt_disable();
538 		/* Perf needs local kick that is NMI safe */
539 		if (cpu == smp_processor_id()) {
540 			tick_nohz_full_kick();
541 		} else {
542 			/* Remote IRQ work not NMI-safe */
543 			if (!WARN_ON_ONCE(in_nmi()))
544 				tick_nohz_full_kick_cpu(cpu);
545 		}
546 		preempt_enable();
547 	}
548 }
549 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
550 
551 void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
552 {
553 	struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
554 
555 	atomic_andnot(BIT(bit), &ts->tick_dep_mask);
556 }
557 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
558 
559 /*
560  * Set a per-task tick dependency. RCU needs this. Also posix CPU timers
561  * in order to elapse per task timers.
562  */
563 void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
564 {
565 	if (!atomic_fetch_or(BIT(bit), &tsk->tick_dep_mask))
566 		tick_nohz_kick_task(tsk);
567 }
568 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_task);
569 
570 void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
571 {
572 	atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
573 }
574 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_task);
575 
576 /*
577  * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
578  * per process timers.
579  */
580 void tick_nohz_dep_set_signal(struct task_struct *tsk,
581 			      enum tick_dep_bits bit)
582 {
583 	int prev;
584 	struct signal_struct *sig = tsk->signal;
585 
586 	prev = atomic_fetch_or(BIT(bit), &sig->tick_dep_mask);
587 	if (!prev) {
588 		struct task_struct *t;
589 
590 		lockdep_assert_held(&tsk->sighand->siglock);
591 		__for_each_thread(sig, t)
592 			tick_nohz_kick_task(t);
593 	}
594 }
595 
596 void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
597 {
598 	atomic_andnot(BIT(bit), &sig->tick_dep_mask);
599 }
600 
601 /*
602  * Re-evaluate the need for the tick as we switch the current task.
603  * It might need the tick due to per task/process properties:
604  * perf events, posix CPU timers, ...
605  */
606 void __tick_nohz_task_switch(void)
607 {
608 	struct tick_sched *ts;
609 
610 	if (!tick_nohz_full_cpu(smp_processor_id()))
611 		return;
612 
613 	ts = this_cpu_ptr(&tick_cpu_sched);
614 
615 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
616 		if (atomic_read(&current->tick_dep_mask) ||
617 		    atomic_read(&current->signal->tick_dep_mask))
618 			tick_nohz_full_kick();
619 	}
620 }
621 
622 /* Get the boot-time nohz CPU list from the kernel parameters. */
623 void __init tick_nohz_full_setup(cpumask_var_t cpumask)
624 {
625 	alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
626 	cpumask_copy(tick_nohz_full_mask, cpumask);
627 	tick_nohz_full_running = true;
628 }
629 
630 bool tick_nohz_cpu_hotpluggable(unsigned int cpu)
631 {
632 	/*
633 	 * The 'tick_do_timer_cpu' CPU handles housekeeping duty (unbound
634 	 * timers, workqueues, timekeeping, ...) on behalf of full dynticks
635 	 * CPUs. It must remain online when nohz full is enabled.
636 	 */
637 	if (tick_nohz_full_running && READ_ONCE(tick_do_timer_cpu) == cpu)
638 		return false;
639 	return true;
640 }
641 
642 static int tick_nohz_cpu_down(unsigned int cpu)
643 {
644 	return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
645 }
646 
647 void __init tick_nohz_init(void)
648 {
649 	int cpu, ret;
650 
651 	if (!tick_nohz_full_running)
652 		return;
653 
654 	/*
655 	 * Full dynticks uses IRQ work to drive the tick rescheduling on safe
656 	 * locking contexts. But then we need IRQ work to raise its own
657 	 * interrupts to avoid circular dependency on the tick.
658 	 */
659 	if (!arch_irq_work_has_interrupt()) {
660 		pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support IRQ work self-IPIs\n");
661 		cpumask_clear(tick_nohz_full_mask);
662 		tick_nohz_full_running = false;
663 		return;
664 	}
665 
666 	if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
667 			!IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
668 		cpu = smp_processor_id();
669 
670 		if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
671 			pr_warn("NO_HZ: Clearing %d from nohz_full range "
672 				"for timekeeping\n", cpu);
673 			cpumask_clear_cpu(cpu, tick_nohz_full_mask);
674 		}
675 	}
676 
677 	for_each_cpu(cpu, tick_nohz_full_mask)
678 		ct_cpu_track_user(cpu);
679 
680 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
681 					"kernel/nohz:predown", NULL,
682 					tick_nohz_cpu_down);
683 	WARN_ON(ret < 0);
684 	pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
685 		cpumask_pr_args(tick_nohz_full_mask));
686 }
687 #endif /* #ifdef CONFIG_NO_HZ_FULL */
688 
689 /*
690  * NOHZ - aka dynamic tick functionality
691  */
692 #ifdef CONFIG_NO_HZ_COMMON
693 /*
694  * NO HZ enabled ?
695  */
696 bool tick_nohz_enabled __read_mostly  = true;
697 static unsigned long tick_nohz_active  __read_mostly;
698 /*
699  * Enable / Disable tickless mode
700  */
701 static int __init setup_tick_nohz(char *str)
702 {
703 	return (kstrtobool(str, &tick_nohz_enabled) == 0);
704 }
705 
706 __setup("nohz=", setup_tick_nohz);
707 
708 bool tick_nohz_is_active(void)
709 {
710 	return tick_nohz_active;
711 }
712 EXPORT_SYMBOL_GPL(tick_nohz_is_active);
713 
714 bool tick_nohz_tick_stopped(void)
715 {
716 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
717 
718 	return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
719 }
720 
721 bool tick_nohz_tick_stopped_cpu(int cpu)
722 {
723 	struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
724 
725 	return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
726 }
727 
728 /**
729  * tick_nohz_update_jiffies - update jiffies when idle was interrupted
730  * @now: current ktime_t
731  *
732  * Called from interrupt entry when the CPU was idle
733  *
734  * In case the sched_tick was stopped on this CPU, we have to check if jiffies
735  * must be updated. Otherwise an interrupt handler could use a stale jiffy
736  * value. We do this unconditionally on any CPU, as we don't know whether the
737  * CPU, which has the update task assigned, is in a long sleep.
738  */
739 static void tick_nohz_update_jiffies(ktime_t now)
740 {
741 	unsigned long flags;
742 
743 	__this_cpu_write(tick_cpu_sched.idle_waketime, now);
744 
745 	local_irq_save(flags);
746 	tick_do_update_jiffies64(now);
747 	local_irq_restore(flags);
748 
749 	touch_softlockup_watchdog_sched();
750 }
751 
752 /* Simplified variant of hrtimer_forward_now() */
753 static ktime_t tick_forward_now(ktime_t expires, ktime_t now)
754 {
755 	ktime_t delta = now - expires;
756 
757 	if (likely(delta < TICK_NSEC))
758 		return expires + TICK_NSEC;
759 
760 	expires += TICK_NSEC * ktime_divns(delta, TICK_NSEC);
761 	if (expires > now)
762 		return expires;
763 	return expires + TICK_NSEC;
764 }
765 
766 static void tick_nohz_forward_last_tick(struct tick_sched *ts, ktime_t now)
767 {
768 	if (now >= ts->last_tick)
769 		ts->last_tick = tick_forward_now(ts->last_tick, now);
770 }
771 
772 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
773 {
774 	ktime_t expires;
775 
776 	tick_nohz_forward_last_tick(ts, now);
777 	expires = ts->last_tick;
778 
779 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
780 		hrtimer_start(&ts->sched_timer,	expires, HRTIMER_MODE_ABS_PINNED_HARD);
781 	} else {
782 		hrtimer_set_expires(&ts->sched_timer, expires);
783 		tick_program_event(expires, 1);
784 	}
785 
786 	/*
787 	 * Reset to make sure the next tick stop doesn't get fooled by past
788 	 * cached clock deadline.
789 	 */
790 	ts->next_tick = 0;
791 }
792 
793 static inline bool local_timer_softirq_pending(void)
794 {
795 	return local_timers_pending() & BIT(TIMER_SOFTIRQ);
796 }
797 
798 /*
799  * Read jiffies and the time when jiffies were updated last
800  */
801 u64 get_jiffies_update(unsigned long *basej)
802 {
803 	unsigned long basejiff;
804 	unsigned int seq;
805 	u64 basemono;
806 
807 	do {
808 		seq = read_seqcount_begin(&jiffies_seq);
809 		basemono = last_jiffies_update;
810 		basejiff = jiffies;
811 	} while (read_seqcount_retry(&jiffies_seq, seq));
812 	*basej = basejiff;
813 	return basemono;
814 }
815 
816 /**
817  * tick_nohz_next_event() - return the clock monotonic based next event
818  * @ts:		pointer to tick_sched struct
819  * @cpu:	CPU number
820  *
821  * Return:
822  * *%0		- When the next event is a maximum of TICK_NSEC in the future
823  *		  and the tick is not stopped yet
824  * *%next_event	- Next event based on clock monotonic
825  */
826 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
827 {
828 	u64 basemono, next_tick, delta, expires;
829 	unsigned long basejiff;
830 	int tick_cpu;
831 
832 	basemono = get_jiffies_update(&basejiff);
833 	ts->last_jiffies = basejiff;
834 	ts->timer_expires_base = basemono;
835 
836 	/*
837 	 * Keep the periodic tick, when RCU or irq_work requests it.
838 	 * Aside of that, check whether the local timer softirq is
839 	 * pending. If so, its a bad idea to call get_next_timer_interrupt(),
840 	 * because there is an already expired timer, so it will request
841 	 * immediate expiry, which rearms the hardware timer with a
842 	 * minimal delta, which brings us back to this place
843 	 * immediately. Lather, rinse and repeat...
844 	 */
845 	if (rcu_needs_cpu() || irq_work_needs_cpu() ||
846 	    local_timer_softirq_pending()) {
847 		next_tick = basemono + TICK_NSEC;
848 	} else {
849 		/*
850 		 * Get the next pending timer. If high resolution
851 		 * timers are enabled this only takes the timer wheel
852 		 * timers into account. If high resolution timers are
853 		 * disabled this also looks at the next expiring
854 		 * hrtimer.
855 		 */
856 		next_tick = get_next_timer_interrupt(basejiff, basemono);
857 		ts->next_timer = next_tick;
858 	}
859 
860 	/* Make sure next_tick is never before basemono! */
861 	if (WARN_ON_ONCE(basemono > next_tick))
862 		next_tick = basemono;
863 
864 	/*
865 	 * If the tick is due in the next period, keep it ticking or
866 	 * force prod the timer.
867 	 */
868 	delta = next_tick - basemono;
869 	if (delta <= (u64)TICK_NSEC) {
870 		/*
871 		 * We've not stopped the tick yet, and there's a timer in the
872 		 * next period, so no point in stopping it either, bail.
873 		 */
874 		if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
875 			ts->timer_expires = 0;
876 			goto out;
877 		}
878 	}
879 
880 	/*
881 	 * If this CPU is the one which had the do_timer() duty last, we limit
882 	 * the sleep time to the timekeeping 'max_deferment' value.
883 	 * Otherwise we can sleep as long as we want.
884 	 */
885 	delta = timekeeping_max_deferment();
886 	tick_cpu = READ_ONCE(tick_do_timer_cpu);
887 	if (tick_cpu != cpu &&
888 	    (tick_cpu != TICK_DO_TIMER_NONE || !tick_sched_flag_test(ts, TS_FLAG_DO_TIMER_LAST)))
889 		delta = KTIME_MAX;
890 
891 	/* Calculate the next expiry time */
892 	if (delta < (KTIME_MAX - basemono))
893 		expires = basemono + delta;
894 	else
895 		expires = KTIME_MAX;
896 
897 	ts->timer_expires = min_t(u64, expires, next_tick);
898 
899 out:
900 	return ts->timer_expires;
901 }
902 
903 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
904 {
905 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
906 	unsigned long basejiff = ts->last_jiffies;
907 	u64 basemono = ts->timer_expires_base;
908 	bool timer_idle = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
909 	int tick_cpu;
910 	u64 expires;
911 
912 	/* Make sure we won't be trying to stop it twice in a row. */
913 	ts->timer_expires_base = 0;
914 
915 	/*
916 	 * Now the tick should be stopped definitely - so the timer base needs
917 	 * to be marked idle as well to not miss a newly queued timer.
918 	 */
919 	expires = timer_base_try_to_set_idle(basejiff, basemono, &timer_idle);
920 	if (expires > ts->timer_expires) {
921 		/*
922 		 * This path could only happen when the first timer was removed
923 		 * between calculating the possible sleep length and now (when
924 		 * high resolution mode is not active, timer could also be a
925 		 * hrtimer).
926 		 *
927 		 * We have to stick to the original calculated expiry value to
928 		 * not stop the tick for too long with a shallow C-state (which
929 		 * was programmed by cpuidle because of an early next expiration
930 		 * value).
931 		 */
932 		expires = ts->timer_expires;
933 	}
934 
935 	/* If the timer base is not idle, retain the not yet stopped tick. */
936 	if (!timer_idle)
937 		return;
938 
939 	/*
940 	 * If this CPU is the one which updates jiffies, then give up
941 	 * the assignment and let it be taken by the CPU which runs
942 	 * the tick timer next, which might be this CPU as well. If we
943 	 * don't drop this here, the jiffies might be stale and
944 	 * do_timer() never gets invoked. Keep track of the fact that it
945 	 * was the one which had the do_timer() duty last.
946 	 */
947 	tick_cpu = READ_ONCE(tick_do_timer_cpu);
948 	if (tick_cpu == cpu) {
949 		WRITE_ONCE(tick_do_timer_cpu, TICK_DO_TIMER_NONE);
950 		tick_sched_flag_set(ts, TS_FLAG_DO_TIMER_LAST);
951 	} else if (tick_cpu != TICK_DO_TIMER_NONE) {
952 		tick_sched_flag_clear(ts, TS_FLAG_DO_TIMER_LAST);
953 	}
954 
955 	/* Skip reprogram of event if it's not changed */
956 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED) && (expires == ts->next_tick)) {
957 		/* Sanity check: make sure clockevent is actually programmed */
958 		if (expires == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
959 			return;
960 
961 		WARN_ONCE(1, "basemono: %llu ts->next_tick: %llu dev->next_event: %llu "
962 			  "timer->active: %d timer->expires: %llu\n", basemono, ts->next_tick,
963 			  dev->next_event, hrtimer_active(&ts->sched_timer),
964 			  hrtimer_get_expires(&ts->sched_timer));
965 	}
966 
967 	/*
968 	 * tick_nohz_stop_tick() can be called several times before
969 	 * tick_nohz_restart_sched_tick() is called. This happens when
970 	 * interrupts arrive which do not cause a reschedule. In the first
971 	 * call we save the current tick time, so we can restart the
972 	 * scheduler tick in tick_nohz_restart_sched_tick().
973 	 */
974 	if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
975 		calc_load_nohz_start();
976 		quiet_vmstat();
977 
978 		ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
979 		tick_sched_flag_set(ts, TS_FLAG_STOPPED);
980 		trace_tick_stop(1, TICK_DEP_MASK_NONE);
981 	}
982 
983 	ts->next_tick = expires;
984 
985 	/*
986 	 * If the expiration time == KTIME_MAX, then we simply stop
987 	 * the tick timer.
988 	 */
989 	if (unlikely(expires == KTIME_MAX)) {
990 		if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
991 			hrtimer_cancel(&ts->sched_timer);
992 		else
993 			tick_program_event(KTIME_MAX, 1);
994 		return;
995 	}
996 
997 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
998 		hrtimer_start(&ts->sched_timer, expires,
999 			      HRTIMER_MODE_ABS_PINNED_HARD);
1000 	} else {
1001 		hrtimer_set_expires(&ts->sched_timer, expires);
1002 		tick_program_event(expires, 1);
1003 	}
1004 }
1005 
1006 static void tick_nohz_retain_tick(struct tick_sched *ts)
1007 {
1008 	ts->timer_expires_base = 0;
1009 }
1010 
1011 #ifdef CONFIG_NO_HZ_FULL
1012 static void tick_nohz_full_stop_tick(struct tick_sched *ts, int cpu)
1013 {
1014 	if (tick_nohz_next_event(ts, cpu))
1015 		tick_nohz_stop_tick(ts, cpu);
1016 	else
1017 		tick_nohz_retain_tick(ts);
1018 }
1019 #endif /* CONFIG_NO_HZ_FULL */
1020 
1021 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
1022 {
1023 	/* Update jiffies first */
1024 	tick_do_update_jiffies64(now);
1025 
1026 	/*
1027 	 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
1028 	 * the clock forward checks in the enqueue path:
1029 	 */
1030 	timer_clear_idle();
1031 
1032 	calc_load_nohz_stop();
1033 	touch_softlockup_watchdog_sched();
1034 
1035 	/* Cancel the scheduled timer and restore the tick: */
1036 	tick_sched_flag_clear(ts, TS_FLAG_STOPPED);
1037 	tick_nohz_restart(ts, now);
1038 }
1039 
1040 static void __tick_nohz_full_update_tick(struct tick_sched *ts,
1041 					 ktime_t now)
1042 {
1043 #ifdef CONFIG_NO_HZ_FULL
1044 	int cpu = smp_processor_id();
1045 
1046 	if (can_stop_full_tick(cpu, ts))
1047 		tick_nohz_full_stop_tick(ts, cpu);
1048 	else if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1049 		tick_nohz_restart_sched_tick(ts, now);
1050 #endif
1051 }
1052 
1053 static void tick_nohz_full_update_tick(struct tick_sched *ts)
1054 {
1055 	if (!tick_nohz_full_cpu(smp_processor_id()))
1056 		return;
1057 
1058 	if (!tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1059 		return;
1060 
1061 	__tick_nohz_full_update_tick(ts, ktime_get());
1062 }
1063 
1064 /*
1065  * A pending softirq outside an IRQ (or softirq disabled section) context
1066  * should be waiting for ksoftirqd to handle it. Therefore we shouldn't
1067  * reach this code due to the need_resched() early check in can_stop_idle_tick().
1068  *
1069  * However if we are between CPUHP_AP_SMPBOOT_THREADS and CPU_TEARDOWN_CPU on the
1070  * cpu_down() process, softirqs can still be raised while ksoftirqd is parked,
1071  * triggering the code below, since wakep_softirqd() is ignored.
1072  *
1073  */
1074 static bool report_idle_softirq(void)
1075 {
1076 	static int ratelimit;
1077 	unsigned int pending = local_softirq_pending();
1078 
1079 	if (likely(!pending))
1080 		return false;
1081 
1082 	/* Some softirqs claim to be safe against hotplug and ksoftirqd parking */
1083 	if (!cpu_active(smp_processor_id())) {
1084 		pending &= ~SOFTIRQ_HOTPLUG_SAFE_MASK;
1085 		if (!pending)
1086 			return false;
1087 	}
1088 
1089 	/* On RT, softirq handling may be waiting on some lock */
1090 	if (local_bh_blocked())
1091 		return false;
1092 
1093 	if (ratelimit < 10) {
1094 		pr_warn("NOHZ tick-stop error: local softirq work is pending, handler #%02x!!!\n",
1095 			pending);
1096 		ratelimit++;
1097 	}
1098 
1099 	return true;
1100 }
1101 
1102 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
1103 {
1104 	WARN_ON_ONCE(cpu_is_offline(cpu));
1105 
1106 	if (unlikely(!tick_sched_flag_test(ts, TS_FLAG_NOHZ)))
1107 		return false;
1108 
1109 	if (need_resched())
1110 		return false;
1111 
1112 	if (unlikely(report_idle_softirq()))
1113 		return false;
1114 
1115 	if (tick_nohz_full_enabled()) {
1116 		int tick_cpu = READ_ONCE(tick_do_timer_cpu);
1117 
1118 		/*
1119 		 * Keep the tick alive to guarantee timekeeping progression
1120 		 * if there are full dynticks CPUs around
1121 		 */
1122 		if (tick_cpu == cpu)
1123 			return false;
1124 
1125 		/* Should not happen for nohz-full */
1126 		if (WARN_ON_ONCE(tick_cpu == TICK_DO_TIMER_NONE))
1127 			return false;
1128 	}
1129 
1130 	return true;
1131 }
1132 
1133 /**
1134  * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1135  *
1136  * When the next event is more than a tick into the future, stop the idle tick
1137  */
1138 void tick_nohz_idle_stop_tick(void)
1139 {
1140 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1141 	int cpu = smp_processor_id();
1142 	ktime_t expires;
1143 
1144 	/*
1145 	 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
1146 	 * tick timer expiration time is known already.
1147 	 */
1148 	if (ts->timer_expires_base)
1149 		expires = ts->timer_expires;
1150 	else if (can_stop_idle_tick(cpu, ts))
1151 		expires = tick_nohz_next_event(ts, cpu);
1152 	else
1153 		return;
1154 
1155 	ts->idle_calls++;
1156 
1157 	if (expires > 0LL) {
1158 		int was_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1159 
1160 		tick_nohz_stop_tick(ts, cpu);
1161 
1162 		ts->idle_sleeps++;
1163 		ts->idle_expires = expires;
1164 
1165 		if (!was_stopped && tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1166 			kcpustat_dyntick_start(ts->idle_entrytime);
1167 			nohz_balance_enter_idle(cpu);
1168 		}
1169 	} else {
1170 		tick_nohz_retain_tick(ts);
1171 	}
1172 }
1173 
1174 void tick_nohz_idle_retain_tick(void)
1175 {
1176 	tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1177 }
1178 
1179 static void tick_nohz_clock_sleep(struct tick_sched *ts)
1180 {
1181 	tick_sched_flag_set(ts, TS_FLAG_IDLE_ACTIVE);
1182 	sched_clock_idle_sleep_event();
1183 }
1184 
1185 static void tick_nohz_clock_wakeup(struct tick_sched *ts)
1186 {
1187 	if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE)) {
1188 		tick_sched_flag_clear(ts, TS_FLAG_IDLE_ACTIVE);
1189 		sched_clock_idle_wakeup_event();
1190 	}
1191 }
1192 
1193 /**
1194  * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1195  *
1196  * Called when we start the idle loop.
1197  */
1198 void tick_nohz_idle_enter(void)
1199 {
1200 	struct tick_sched *ts;
1201 
1202 	lockdep_assert_irqs_enabled();
1203 
1204 	local_irq_disable();
1205 
1206 	ts = this_cpu_ptr(&tick_cpu_sched);
1207 	WARN_ON_ONCE(ts->timer_expires_base);
1208 	tick_sched_flag_set(ts, TS_FLAG_INIDLE);
1209 	ts->idle_entrytime = ktime_get();
1210 	tick_nohz_clock_sleep(ts);
1211 
1212 	local_irq_enable();
1213 }
1214 
1215 /**
1216  * tick_nohz_irq_exit - Notify the tick about IRQ exit
1217  *
1218  * A timer may have been added/modified/deleted either by the current IRQ,
1219  * or by another place using this IRQ as a notification. This IRQ may have
1220  * also updated the RCU callback list. These events may require a
1221  * re-evaluation of the next tick. Depending on the context:
1222  *
1223  * 1) If the CPU is idle and no resched is pending, just proceed with idle
1224  *    time accounting. The next tick will be re-evaluated on the next idle
1225  *    loop iteration.
1226  *
1227  * 2) If the CPU is nohz_full:
1228  *
1229  *    2.1) If there is any tick dependency, restart the tick if stopped.
1230  *
1231  *    2.2) If there is no tick dependency, (re-)evaluate the next tick and
1232  *         stop/update it accordingly.
1233  */
1234 void tick_nohz_irq_exit(void)
1235 {
1236 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1237 
1238 	if (tick_sched_flag_test(ts, TS_FLAG_INIDLE)) {
1239 		tick_nohz_clock_sleep(ts);
1240 		ts->idle_entrytime = ktime_get();
1241 		if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1242 			kcpustat_irq_exit(ts->idle_entrytime);
1243 	} else {
1244 		tick_nohz_full_update_tick(ts);
1245 	}
1246 }
1247 
1248 /**
1249  * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1250  *
1251  * Return: %true if the tick handler has run, otherwise %false
1252  */
1253 bool tick_nohz_idle_got_tick(void)
1254 {
1255 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1256 
1257 	if (ts->got_idle_tick) {
1258 		ts->got_idle_tick = 0;
1259 		return true;
1260 	}
1261 	return false;
1262 }
1263 
1264 /**
1265  * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1266  * or the tick, whichever expires first. Note that, if the tick has been
1267  * stopped, it returns the next hrtimer.
1268  *
1269  * Called from power state control code with interrupts disabled
1270  *
1271  * Return: the next expiration time
1272  */
1273 ktime_t tick_nohz_get_next_hrtimer(void)
1274 {
1275 	return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1276 }
1277 
1278 /**
1279  * tick_nohz_get_sleep_length - return the expected length of the current sleep
1280  * @delta_next: duration until the next event if the tick cannot be stopped
1281  *
1282  * Called from power state control code with interrupts disabled.
1283  *
1284  * The return value of this function and/or the value returned by it through the
1285  * @delta_next pointer can be negative which must be taken into account by its
1286  * callers.
1287  *
1288  * Return: the expected length of the current sleep
1289  */
1290 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1291 {
1292 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1293 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1294 	int cpu = smp_processor_id();
1295 	/*
1296 	 * The idle entry time is expected to be a sufficient approximation of
1297 	 * the current time at this point.
1298 	 */
1299 	ktime_t now = ts->idle_entrytime;
1300 	ktime_t next_event;
1301 
1302 	WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1303 
1304 	*delta_next = ktime_sub(dev->next_event, now);
1305 
1306 	if (!can_stop_idle_tick(cpu, ts))
1307 		return *delta_next;
1308 
1309 	next_event = tick_nohz_next_event(ts, cpu);
1310 	if (!next_event)
1311 		return *delta_next;
1312 
1313 	/*
1314 	 * If the next highres timer to expire is earlier than 'next_event', the
1315 	 * idle governor needs to know that.
1316 	 */
1317 	next_event = min(next_event, hrtimer_next_event_without(&ts->sched_timer));
1318 
1319 	return ktime_sub(next_event, now);
1320 }
1321 
1322 /**
1323  * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1324  * for a particular CPU.
1325  * @cpu: target CPU number
1326  *
1327  * Called from the schedutil frequency scaling governor in scheduler context.
1328  *
1329  * Return: the current idle calls counter value for @cpu
1330  */
1331 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1332 {
1333 	struct tick_sched *ts = tick_get_tick_sched(cpu);
1334 
1335 	return ts->idle_calls;
1336 }
1337 
1338 static void tick_nohz_dyntick_stop(struct tick_sched *ts, ktime_t now)
1339 {
1340 	tick_nohz_forward_last_tick(ts, now);
1341 	kcpustat_dyntick_stop(now, ts->last_tick - TICK_NSEC);
1342 }
1343 
1344 void tick_nohz_idle_restart_tick(void)
1345 {
1346 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1347 
1348 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1349 		/*
1350 		 * Update entrytime here in case the tick restart is due to temporary
1351 		 * polling on forced broadcast. The tick may be stopped again later within
1352 		 * the same idle trip. The idle_entrytime was updated recently but make sure
1353 		 * no tiny amount of idle time is accounted twice.
1354 		 */
1355 		ts->idle_entrytime = ktime_get();
1356 		tick_nohz_dyntick_stop(ts, ts->idle_entrytime);
1357 		tick_nohz_restart_sched_tick(ts, ts->idle_entrytime);
1358 	}
1359 }
1360 
1361 static void tick_nohz_idle_update_tick(struct tick_sched *ts, ktime_t now)
1362 {
1363 	if (tick_nohz_full_cpu(smp_processor_id()))
1364 		__tick_nohz_full_update_tick(ts, now);
1365 	else
1366 		tick_nohz_restart_sched_tick(ts, now);
1367 }
1368 
1369 /**
1370  * tick_nohz_idle_exit - Update the tick upon idle task exit
1371  *
1372  * When the idle task exits, update the tick depending on the
1373  * following situations:
1374  *
1375  * 1) If the CPU is not in nohz_full mode (most cases), then
1376  *    restart the tick.
1377  *
1378  * 2) If the CPU is in nohz_full mode (corner case):
1379  *   2.1) If the tick can be kept stopped (no tick dependencies)
1380  *        then re-evaluate the next tick and try to keep it stopped
1381  *        as long as possible.
1382  *   2.2) If the tick has dependencies, restart the tick.
1383  *
1384  */
1385 void tick_nohz_idle_exit(void)
1386 {
1387 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1388 	ktime_t now;
1389 
1390 	local_irq_disable();
1391 
1392 	WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1393 	WARN_ON_ONCE(ts->timer_expires_base);
1394 
1395 	tick_sched_flag_clear(ts, TS_FLAG_INIDLE);
1396 	tick_nohz_clock_wakeup(ts);
1397 
1398 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1399 		now = ktime_get();
1400 		tick_nohz_dyntick_stop(ts, now);
1401 		tick_nohz_idle_update_tick(ts, now);
1402 	}
1403 
1404 	local_irq_enable();
1405 }
1406 
1407 /*
1408  * In low-resolution mode, the tick handler must be implemented directly
1409  * at the clockevent level. hrtimer can't be used instead, because its
1410  * infrastructure actually relies on the tick itself as a backend in
1411  * low-resolution mode (see hrtimer_run_queues()).
1412  */
1413 static void tick_nohz_lowres_handler(struct clock_event_device *dev)
1414 {
1415 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1416 
1417 	dev->next_event = KTIME_MAX;
1418 	dev->next_event_forced = 0;
1419 
1420 	if (likely(tick_nohz_handler(&ts->sched_timer) == HRTIMER_RESTART))
1421 		tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1422 }
1423 
1424 static inline void tick_nohz_activate(struct tick_sched *ts)
1425 {
1426 	if (!tick_nohz_enabled)
1427 		return;
1428 	tick_sched_flag_set(ts, TS_FLAG_NOHZ);
1429 	/* One update is enough */
1430 	if (!test_and_set_bit(0, &tick_nohz_active))
1431 		timers_update_nohz();
1432 }
1433 
1434 /**
1435  * tick_nohz_switch_to_nohz - switch to NOHZ mode
1436  */
1437 static void tick_nohz_switch_to_nohz(void)
1438 {
1439 	if (!tick_nohz_enabled)
1440 		return;
1441 
1442 	if (tick_switch_to_oneshot(tick_nohz_lowres_handler))
1443 		return;
1444 
1445 	/*
1446 	 * Recycle the hrtimer in 'ts', so we can share the
1447 	 * highres code.
1448 	 */
1449 	tick_setup_sched_timer(false);
1450 }
1451 
1452 static inline void tick_nohz_irq_enter(void)
1453 {
1454 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1455 	ktime_t now;
1456 
1457 	tick_nohz_clock_wakeup(ts);
1458 
1459 	if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1460 		return;
1461 
1462 	now = ktime_get();
1463 	kcpustat_irq_enter(now);
1464 
1465 	/*
1466 	 * If all CPUs are idle we may need to update a stale jiffies value.
1467 	 * Note nohz_full is a special case: a timekeeper is guaranteed to stay
1468 	 * alive but it might be busy looping with interrupts disabled in some
1469 	 * rare case (typically stop machine). So we must make sure we have a
1470 	 * last resort.
1471 	 */
1472 	tick_nohz_update_jiffies(now);
1473 }
1474 
1475 #else
1476 
1477 static inline void tick_nohz_switch_to_nohz(void) { }
1478 static inline void tick_nohz_irq_enter(void) { }
1479 static inline void tick_nohz_activate(struct tick_sched *ts) { }
1480 
1481 #endif /* CONFIG_NO_HZ_COMMON */
1482 
1483 /*
1484  * Called from irq_enter() to notify about the possible interruption of idle()
1485  */
1486 void tick_irq_enter(void)
1487 {
1488 	tick_check_oneshot_broadcast_this_cpu();
1489 	tick_nohz_irq_enter();
1490 }
1491 
1492 static int sched_skew_tick;
1493 
1494 static int __init skew_tick(char *str)
1495 {
1496 	get_option(&str, &sched_skew_tick);
1497 
1498 	return 0;
1499 }
1500 early_param("skew_tick", skew_tick);
1501 
1502 /**
1503  * tick_setup_sched_timer - setup the tick emulation timer
1504  * @hrtimer: whether to use the hrtimer or not
1505  */
1506 void tick_setup_sched_timer(bool hrtimer)
1507 {
1508 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1509 
1510 	/* Emulate tick processing via per-CPU hrtimers: */
1511 	hrtimer_setup(&ts->sched_timer, tick_nohz_handler, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1512 
1513 	if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
1514 		tick_sched_flag_set(ts, TS_FLAG_HIGHRES);
1515 
1516 	/* Get the next period (per-CPU) */
1517 	hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1518 
1519 	/* Offset the tick to avert 'jiffies_lock' contention. */
1520 	if (sched_skew_tick) {
1521 		u64 offset = TICK_NSEC >> 1;
1522 		do_div(offset, num_possible_cpus());
1523 		offset *= smp_processor_id();
1524 		hrtimer_add_expires_ns(&ts->sched_timer, offset);
1525 	}
1526 
1527 	hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1528 	if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
1529 		hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1530 	else
1531 		tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1532 	tick_nohz_activate(ts);
1533 }
1534 
1535 /*
1536  * Shut down the tick and make sure the CPU won't try to retake the timekeeping
1537  * duty before disabling IRQs in idle for the last time.
1538  */
1539 void tick_sched_timer_dying(int cpu)
1540 {
1541 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1542 	unsigned long idle_calls, idle_sleeps;
1543 
1544 	/* This must happen before hrtimers are migrated! */
1545 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
1546 		hrtimer_cancel(&ts->sched_timer);
1547 
1548 	idle_calls = ts->idle_calls;
1549 	idle_sleeps = ts->idle_sleeps;
1550 	memset(ts, 0, sizeof(*ts));
1551 	ts->idle_calls = idle_calls;
1552 	ts->idle_sleeps = idle_sleeps;
1553 }
1554 
1555 /*
1556  * Async notification about clocksource changes
1557  */
1558 void tick_clock_notify(void)
1559 {
1560 	int cpu;
1561 
1562 	for_each_possible_cpu(cpu)
1563 		set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1564 }
1565 
1566 /*
1567  * Async notification about clock event changes
1568  */
1569 void tick_oneshot_notify(void)
1570 {
1571 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1572 
1573 	set_bit(0, &ts->check_clocks);
1574 }
1575 
1576 /*
1577  * Check if a change happened, which makes oneshot possible.
1578  *
1579  * Called cyclically from the hrtimer softirq (driven by the timer
1580  * softirq). 'allow_nohz' signals that we can switch into low-res NOHZ
1581  * mode, because high resolution timers are disabled (either compile
1582  * or runtime). Called with interrupts disabled.
1583  */
1584 int tick_check_oneshot_change(int allow_nohz)
1585 {
1586 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1587 
1588 	if (!test_and_clear_bit(0, &ts->check_clocks))
1589 		return 0;
1590 
1591 	if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1592 		return 0;
1593 
1594 	if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1595 		return 0;
1596 
1597 	if (!allow_nohz)
1598 		return 1;
1599 
1600 	tick_nohz_switch_to_nohz();
1601 	return 0;
1602 }
1603