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