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