• 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 		context_tracking_cpu_set(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, next_tmr, next_rcu, 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(basemono, &next_rcu) || 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_tmr = get_next_timer_interrupt(basejiff, basemono);
846 		ts->next_timer = next_tmr;
847 		/* Take the next rcu event into account */
848 		next_tick = next_rcu < next_tmr ? next_rcu : next_tmr;
849 	}
850 
851 	/*
852 	 * If the tick is due in the next period, keep it ticking or
853 	 * force prod the timer.
854 	 */
855 	delta = next_tick - basemono;
856 	if (delta <= (u64)TICK_NSEC) {
857 		/*
858 		 * Tell the timer code that the base is not idle, i.e. undo
859 		 * the effect of get_next_timer_interrupt():
860 		 */
861 		timer_clear_idle();
862 		/*
863 		 * We've not stopped the tick yet, and there's a timer in the
864 		 * next period, so no point in stopping it either, bail.
865 		 */
866 		if (!ts->tick_stopped) {
867 			ts->timer_expires = 0;
868 			goto out;
869 		}
870 	}
871 
872 	/*
873 	 * If this CPU is the one which had the do_timer() duty last, we limit
874 	 * the sleep time to the timekeeping max_deferment value.
875 	 * Otherwise we can sleep as long as we want.
876 	 */
877 	delta = timekeeping_max_deferment();
878 	if (cpu != tick_do_timer_cpu &&
879 	    (tick_do_timer_cpu != TICK_DO_TIMER_NONE || !ts->do_timer_last))
880 		delta = KTIME_MAX;
881 
882 	/* Calculate the next expiry time */
883 	if (delta < (KTIME_MAX - basemono))
884 		expires = basemono + delta;
885 	else
886 		expires = KTIME_MAX;
887 
888 	ts->timer_expires = min_t(u64, expires, next_tick);
889 
890 out:
891 	return ts->timer_expires;
892 }
893 
tick_nohz_stop_tick(struct tick_sched * ts,int cpu)894 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
895 {
896 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
897 	u64 basemono = ts->timer_expires_base;
898 	u64 expires = ts->timer_expires;
899 	ktime_t tick = expires;
900 
901 	/* Make sure we won't be trying to stop it twice in a row. */
902 	ts->timer_expires_base = 0;
903 
904 	/*
905 	 * If this CPU is the one which updates jiffies, then give up
906 	 * the assignment and let it be taken by the CPU which runs
907 	 * the tick timer next, which might be this CPU as well. If we
908 	 * don't drop this here the jiffies might be stale and
909 	 * do_timer() never invoked. Keep track of the fact that it
910 	 * was the one which had the do_timer() duty last.
911 	 */
912 	if (cpu == tick_do_timer_cpu) {
913 		tick_do_timer_cpu = TICK_DO_TIMER_NONE;
914 		ts->do_timer_last = 1;
915 	} else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
916 		ts->do_timer_last = 0;
917 	}
918 
919 	/* Skip reprogram of event if its not changed */
920 	if (ts->tick_stopped && (expires == ts->next_tick)) {
921 		/* Sanity check: make sure clockevent is actually programmed */
922 		if (tick == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
923 			return;
924 
925 		WARN_ON_ONCE(1);
926 		printk_once("basemono: %llu ts->next_tick: %llu dev->next_event: %llu timer->active: %d timer->expires: %llu\n",
927 			    basemono, ts->next_tick, dev->next_event,
928 			    hrtimer_active(&ts->sched_timer), hrtimer_get_expires(&ts->sched_timer));
929 	}
930 
931 	/*
932 	 * nohz_stop_sched_tick can be called several times before
933 	 * the nohz_restart_sched_tick is called. This happens when
934 	 * interrupts arrive which do not cause a reschedule. In the
935 	 * first call we save the current tick time, so we can restart
936 	 * the scheduler tick in nohz_restart_sched_tick.
937 	 */
938 	if (!ts->tick_stopped) {
939 		calc_load_nohz_start();
940 		quiet_vmstat();
941 
942 		ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
943 		ts->tick_stopped = 1;
944 		trace_tick_stop(1, TICK_DEP_MASK_NONE);
945 	}
946 
947 	ts->next_tick = tick;
948 
949 	/*
950 	 * If the expiration time == KTIME_MAX, then we simply stop
951 	 * the tick timer.
952 	 */
953 	if (unlikely(expires == KTIME_MAX)) {
954 		if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
955 			hrtimer_cancel(&ts->sched_timer);
956 		else
957 			tick_program_event(KTIME_MAX, 1);
958 		return;
959 	}
960 
961 	if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
962 		hrtimer_start(&ts->sched_timer, tick,
963 			      HRTIMER_MODE_ABS_PINNED_HARD);
964 	} else {
965 		hrtimer_set_expires(&ts->sched_timer, tick);
966 		tick_program_event(tick, 1);
967 	}
968 }
969 
tick_nohz_retain_tick(struct tick_sched * ts)970 static void tick_nohz_retain_tick(struct tick_sched *ts)
971 {
972 	ts->timer_expires_base = 0;
973 }
974 
975 #ifdef CONFIG_NO_HZ_FULL
tick_nohz_stop_sched_tick(struct tick_sched * ts,int cpu)976 static void tick_nohz_stop_sched_tick(struct tick_sched *ts, int cpu)
977 {
978 	if (tick_nohz_next_event(ts, cpu))
979 		tick_nohz_stop_tick(ts, cpu);
980 	else
981 		tick_nohz_retain_tick(ts);
982 }
983 #endif /* CONFIG_NO_HZ_FULL */
984 
tick_nohz_restart_sched_tick(struct tick_sched * ts,ktime_t now)985 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
986 {
987 	/* Update jiffies first */
988 	tick_do_update_jiffies64(now);
989 
990 	/*
991 	 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
992 	 * the clock forward checks in the enqueue path:
993 	 */
994 	timer_clear_idle();
995 
996 	calc_load_nohz_stop();
997 	touch_softlockup_watchdog_sched();
998 	/*
999 	 * Cancel the scheduled timer and restore the tick
1000 	 */
1001 	ts->tick_stopped  = 0;
1002 	tick_nohz_restart(ts, now);
1003 }
1004 
__tick_nohz_full_update_tick(struct tick_sched * ts,ktime_t now)1005 static void __tick_nohz_full_update_tick(struct tick_sched *ts,
1006 					 ktime_t now)
1007 {
1008 #ifdef CONFIG_NO_HZ_FULL
1009 	int cpu = smp_processor_id();
1010 
1011 	if (can_stop_full_tick(cpu, ts))
1012 		tick_nohz_stop_sched_tick(ts, cpu);
1013 	else if (ts->tick_stopped)
1014 		tick_nohz_restart_sched_tick(ts, now);
1015 #endif
1016 }
1017 
tick_nohz_full_update_tick(struct tick_sched * ts)1018 static void tick_nohz_full_update_tick(struct tick_sched *ts)
1019 {
1020 	if (!tick_nohz_full_cpu(smp_processor_id()))
1021 		return;
1022 
1023 	if (!ts->tick_stopped && ts->nohz_mode == NOHZ_MODE_INACTIVE)
1024 		return;
1025 
1026 	__tick_nohz_full_update_tick(ts, ktime_get());
1027 }
1028 
can_stop_idle_tick(int cpu,struct tick_sched * ts)1029 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
1030 {
1031 	/*
1032 	 * If this CPU is offline and it is the one which updates
1033 	 * jiffies, then give up the assignment and let it be taken by
1034 	 * the CPU which runs the tick timer next. If we don't drop
1035 	 * this here the jiffies might be stale and do_timer() never
1036 	 * invoked.
1037 	 */
1038 	if (unlikely(!cpu_online(cpu))) {
1039 		if (cpu == tick_do_timer_cpu)
1040 			tick_do_timer_cpu = TICK_DO_TIMER_NONE;
1041 		/*
1042 		 * Make sure the CPU doesn't get fooled by obsolete tick
1043 		 * deadline if it comes back online later.
1044 		 */
1045 		ts->next_tick = 0;
1046 		return false;
1047 	}
1048 
1049 	if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
1050 		return false;
1051 
1052 	if (need_resched())
1053 		return false;
1054 
1055 	if (unlikely(local_softirq_pending())) {
1056 		static int ratelimit;
1057 
1058 		if (ratelimit < 10 && !local_bh_blocked() &&
1059 		    (local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
1060 			pr_warn("NOHZ tick-stop error: Non-RCU local softirq work is pending, handler #%02x!!!\n",
1061 				(unsigned int) local_softirq_pending());
1062 			ratelimit++;
1063 		}
1064 		return false;
1065 	}
1066 
1067 	if (tick_nohz_full_enabled()) {
1068 		/*
1069 		 * Keep the tick alive to guarantee timekeeping progression
1070 		 * if there are full dynticks CPUs around
1071 		 */
1072 		if (tick_do_timer_cpu == cpu)
1073 			return false;
1074 
1075 		/* Should not happen for nohz-full */
1076 		if (WARN_ON_ONCE(tick_do_timer_cpu == TICK_DO_TIMER_NONE))
1077 			return false;
1078 	}
1079 
1080 	return true;
1081 }
1082 
__tick_nohz_idle_stop_tick(struct tick_sched * ts)1083 static void __tick_nohz_idle_stop_tick(struct tick_sched *ts)
1084 {
1085 	ktime_t expires;
1086 	int cpu = smp_processor_id();
1087 
1088 	/*
1089 	 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
1090 	 * tick timer expiration time is known already.
1091 	 */
1092 	if (ts->timer_expires_base)
1093 		expires = ts->timer_expires;
1094 	else if (can_stop_idle_tick(cpu, ts))
1095 		expires = tick_nohz_next_event(ts, cpu);
1096 	else
1097 		return;
1098 
1099 	ts->idle_calls++;
1100 
1101 	if (expires > 0LL) {
1102 		int was_stopped = ts->tick_stopped;
1103 
1104 		tick_nohz_stop_tick(ts, cpu);
1105 
1106 		ts->idle_sleeps++;
1107 		ts->idle_expires = expires;
1108 
1109 		if (!was_stopped && ts->tick_stopped) {
1110 			ts->idle_jiffies = ts->last_jiffies;
1111 			nohz_balance_enter_idle(cpu);
1112 		}
1113 	} else {
1114 		tick_nohz_retain_tick(ts);
1115 	}
1116 }
1117 
1118 /**
1119  * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1120  *
1121  * When the next event is more than a tick into the future, stop the idle tick
1122  */
tick_nohz_idle_stop_tick(void)1123 void tick_nohz_idle_stop_tick(void)
1124 {
1125 	__tick_nohz_idle_stop_tick(this_cpu_ptr(&tick_cpu_sched));
1126 }
1127 
tick_nohz_idle_retain_tick(void)1128 void tick_nohz_idle_retain_tick(void)
1129 {
1130 	tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1131 	/*
1132 	 * Undo the effect of get_next_timer_interrupt() called from
1133 	 * tick_nohz_next_event().
1134 	 */
1135 	timer_clear_idle();
1136 }
1137 
1138 /**
1139  * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1140  *
1141  * Called when we start the idle loop.
1142  */
tick_nohz_idle_enter(void)1143 void tick_nohz_idle_enter(void)
1144 {
1145 	struct tick_sched *ts;
1146 
1147 	lockdep_assert_irqs_enabled();
1148 
1149 	local_irq_disable();
1150 
1151 	ts = this_cpu_ptr(&tick_cpu_sched);
1152 
1153 	WARN_ON_ONCE(ts->timer_expires_base);
1154 
1155 	ts->inidle = 1;
1156 	tick_nohz_start_idle(ts);
1157 
1158 	local_irq_enable();
1159 }
1160 
1161 /**
1162  * tick_nohz_irq_exit - update next tick event from interrupt exit
1163  *
1164  * When an interrupt fires while we are idle and it doesn't cause
1165  * a reschedule, it may still add, modify or delete a timer, enqueue
1166  * an RCU callback, etc...
1167  * So we need to re-calculate and reprogram the next tick event.
1168  */
tick_nohz_irq_exit(void)1169 void tick_nohz_irq_exit(void)
1170 {
1171 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1172 
1173 	if (ts->inidle)
1174 		tick_nohz_start_idle(ts);
1175 	else
1176 		tick_nohz_full_update_tick(ts);
1177 }
1178 
1179 /**
1180  * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1181  */
tick_nohz_idle_got_tick(void)1182 bool tick_nohz_idle_got_tick(void)
1183 {
1184 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1185 
1186 	if (ts->got_idle_tick) {
1187 		ts->got_idle_tick = 0;
1188 		return true;
1189 	}
1190 	return false;
1191 }
1192 
1193 /**
1194  * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1195  * or the tick, whatever that expires first. Note that, if the tick has been
1196  * stopped, it returns the next hrtimer.
1197  *
1198  * Called from power state control code with interrupts disabled
1199  */
tick_nohz_get_next_hrtimer(void)1200 ktime_t tick_nohz_get_next_hrtimer(void)
1201 {
1202 	return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1203 }
1204 
1205 /**
1206  * tick_nohz_get_sleep_length - return the expected length of the current sleep
1207  * @delta_next: duration until the next event if the tick cannot be stopped
1208  *
1209  * Called from power state control code with interrupts disabled.
1210  *
1211  * The return value of this function and/or the value returned by it through the
1212  * @delta_next pointer can be negative which must be taken into account by its
1213  * callers.
1214  */
tick_nohz_get_sleep_length(ktime_t * delta_next)1215 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1216 {
1217 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1218 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1219 	int cpu = smp_processor_id();
1220 	/*
1221 	 * The idle entry time is expected to be a sufficient approximation of
1222 	 * the current time at this point.
1223 	 */
1224 	ktime_t now = ts->idle_entrytime;
1225 	ktime_t next_event;
1226 
1227 	WARN_ON_ONCE(!ts->inidle);
1228 
1229 	*delta_next = ktime_sub(dev->next_event, now);
1230 
1231 	if (!can_stop_idle_tick(cpu, ts))
1232 		return *delta_next;
1233 
1234 	next_event = tick_nohz_next_event(ts, cpu);
1235 	if (!next_event)
1236 		return *delta_next;
1237 
1238 	/*
1239 	 * If the next highres timer to expire is earlier than next_event, the
1240 	 * idle governor needs to know that.
1241 	 */
1242 	next_event = min_t(u64, next_event,
1243 			   hrtimer_next_event_without(&ts->sched_timer));
1244 
1245 	return ktime_sub(next_event, now);
1246 }
1247 EXPORT_SYMBOL_GPL(tick_nohz_get_sleep_length);
1248 
1249 /**
1250  * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1251  * for a particular CPU.
1252  *
1253  * Called from the schedutil frequency scaling governor in scheduler context.
1254  */
tick_nohz_get_idle_calls_cpu(int cpu)1255 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1256 {
1257 	struct tick_sched *ts = tick_get_tick_sched(cpu);
1258 
1259 	return ts->idle_calls;
1260 }
1261 EXPORT_SYMBOL_GPL(tick_nohz_get_idle_calls_cpu);
1262 
1263 /**
1264  * tick_nohz_get_idle_calls - return the current idle calls counter value
1265  *
1266  * Called from the schedutil frequency scaling governor in scheduler context.
1267  */
tick_nohz_get_idle_calls(void)1268 unsigned long tick_nohz_get_idle_calls(void)
1269 {
1270 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1271 
1272 	return ts->idle_calls;
1273 }
1274 
tick_nohz_account_idle_time(struct tick_sched * ts,ktime_t now)1275 static void tick_nohz_account_idle_time(struct tick_sched *ts,
1276 					ktime_t now)
1277 {
1278 	unsigned long ticks;
1279 
1280 	ts->idle_exittime = now;
1281 
1282 	if (vtime_accounting_enabled_this_cpu())
1283 		return;
1284 	/*
1285 	 * We stopped the tick in idle. Update process times would miss the
1286 	 * time we slept as update_process_times does only a 1 tick
1287 	 * accounting. Enforce that this is accounted to idle !
1288 	 */
1289 	ticks = jiffies - ts->idle_jiffies;
1290 	/*
1291 	 * We might be one off. Do not randomly account a huge number of ticks!
1292 	 */
1293 	if (ticks && ticks < LONG_MAX)
1294 		account_idle_ticks(ticks);
1295 }
1296 
tick_nohz_idle_restart_tick(void)1297 void tick_nohz_idle_restart_tick(void)
1298 {
1299 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1300 
1301 	if (ts->tick_stopped) {
1302 		ktime_t now = ktime_get();
1303 		tick_nohz_restart_sched_tick(ts, now);
1304 		tick_nohz_account_idle_time(ts, now);
1305 	}
1306 }
1307 
tick_nohz_idle_update_tick(struct tick_sched * ts,ktime_t now)1308 static void tick_nohz_idle_update_tick(struct tick_sched *ts, ktime_t now)
1309 {
1310 	if (tick_nohz_full_cpu(smp_processor_id()))
1311 		__tick_nohz_full_update_tick(ts, now);
1312 	else
1313 		tick_nohz_restart_sched_tick(ts, now);
1314 
1315 	tick_nohz_account_idle_time(ts, now);
1316 }
1317 
1318 /**
1319  * tick_nohz_idle_exit - restart the idle tick from the idle task
1320  *
1321  * Restart the idle tick when the CPU is woken up from idle
1322  * This also exit the RCU extended quiescent state. The CPU
1323  * can use RCU again after this function is called.
1324  */
tick_nohz_idle_exit(void)1325 void tick_nohz_idle_exit(void)
1326 {
1327 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1328 	bool idle_active, tick_stopped;
1329 	ktime_t now;
1330 
1331 	local_irq_disable();
1332 
1333 	WARN_ON_ONCE(!ts->inidle);
1334 	WARN_ON_ONCE(ts->timer_expires_base);
1335 
1336 	ts->inidle = 0;
1337 	idle_active = ts->idle_active;
1338 	tick_stopped = ts->tick_stopped;
1339 
1340 	if (idle_active || tick_stopped)
1341 		now = ktime_get();
1342 
1343 	if (idle_active)
1344 		tick_nohz_stop_idle(ts, now);
1345 
1346 	if (tick_stopped)
1347 		tick_nohz_idle_update_tick(ts, now);
1348 
1349 	local_irq_enable();
1350 }
1351 
1352 /*
1353  * The nohz low res interrupt handler
1354  */
tick_nohz_handler(struct clock_event_device * dev)1355 static void tick_nohz_handler(struct clock_event_device *dev)
1356 {
1357 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1358 	struct pt_regs *regs = get_irq_regs();
1359 	ktime_t now = ktime_get();
1360 
1361 	dev->next_event = KTIME_MAX;
1362 
1363 	tick_sched_do_timer(ts, now);
1364 	tick_sched_handle(ts, regs);
1365 
1366 	if (unlikely(ts->tick_stopped)) {
1367 		/*
1368 		 * The clockevent device is not reprogrammed, so change the
1369 		 * clock event device to ONESHOT_STOPPED to avoid spurious
1370 		 * interrupts on devices which might not be truly one shot.
1371 		 */
1372 		tick_program_event(KTIME_MAX, 1);
1373 		return;
1374 	}
1375 
1376 	hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1377 	tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1378 }
1379 
tick_nohz_activate(struct tick_sched * ts,int mode)1380 static inline void tick_nohz_activate(struct tick_sched *ts, int mode)
1381 {
1382 	if (!tick_nohz_enabled)
1383 		return;
1384 	ts->nohz_mode = mode;
1385 	/* One update is enough */
1386 	if (!test_and_set_bit(0, &tick_nohz_active))
1387 		timers_update_nohz();
1388 }
1389 
1390 /**
1391  * tick_nohz_switch_to_nohz - switch to nohz mode
1392  */
tick_nohz_switch_to_nohz(void)1393 static void tick_nohz_switch_to_nohz(void)
1394 {
1395 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1396 	ktime_t next;
1397 
1398 	if (!tick_nohz_enabled)
1399 		return;
1400 
1401 	if (tick_switch_to_oneshot(tick_nohz_handler))
1402 		return;
1403 
1404 	/*
1405 	 * Recycle the hrtimer in ts, so we can share the
1406 	 * hrtimer_forward with the highres code.
1407 	 */
1408 	hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1409 	/* Get the next period */
1410 	next = tick_init_jiffy_update();
1411 
1412 	hrtimer_set_expires(&ts->sched_timer, next);
1413 	hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1414 	tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1415 	tick_nohz_activate(ts, NOHZ_MODE_LOWRES);
1416 }
1417 
tick_nohz_irq_enter(void)1418 static inline void tick_nohz_irq_enter(void)
1419 {
1420 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1421 	ktime_t now;
1422 
1423 	if (!ts->idle_active && !ts->tick_stopped)
1424 		return;
1425 	now = ktime_get();
1426 	if (ts->idle_active)
1427 		tick_nohz_stop_idle(ts, now);
1428 	/*
1429 	 * If all CPUs are idle. We may need to update a stale jiffies value.
1430 	 * Note nohz_full is a special case: a timekeeper is guaranteed to stay
1431 	 * alive but it might be busy looping with interrupts disabled in some
1432 	 * rare case (typically stop machine). So we must make sure we have a
1433 	 * last resort.
1434 	 */
1435 	if (ts->tick_stopped)
1436 		tick_nohz_update_jiffies(now);
1437 }
1438 
1439 #else
1440 
tick_nohz_switch_to_nohz(void)1441 static inline void tick_nohz_switch_to_nohz(void) { }
tick_nohz_irq_enter(void)1442 static inline void tick_nohz_irq_enter(void) { }
tick_nohz_activate(struct tick_sched * ts,int mode)1443 static inline void tick_nohz_activate(struct tick_sched *ts, int mode) { }
1444 
1445 #endif /* CONFIG_NO_HZ_COMMON */
1446 
1447 /*
1448  * Called from irq_enter to notify about the possible interruption of idle()
1449  */
tick_irq_enter(void)1450 void tick_irq_enter(void)
1451 {
1452 	tick_check_oneshot_broadcast_this_cpu();
1453 	tick_nohz_irq_enter();
1454 }
1455 
1456 /*
1457  * High resolution timer specific code
1458  */
1459 #ifdef CONFIG_HIGH_RES_TIMERS
1460 /*
1461  * We rearm the timer until we get disabled by the idle code.
1462  * Called with interrupts disabled.
1463  */
tick_sched_timer(struct hrtimer * timer)1464 static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
1465 {
1466 	struct tick_sched *ts =
1467 		container_of(timer, struct tick_sched, sched_timer);
1468 	struct pt_regs *regs = get_irq_regs();
1469 	ktime_t now = ktime_get();
1470 
1471 	tick_sched_do_timer(ts, now);
1472 
1473 	/*
1474 	 * Do not call, when we are not in irq context and have
1475 	 * no valid regs pointer
1476 	 */
1477 	if (regs)
1478 		tick_sched_handle(ts, regs);
1479 	else
1480 		ts->next_tick = 0;
1481 
1482 	/* No need to reprogram if we are in idle or full dynticks mode */
1483 	if (unlikely(ts->tick_stopped))
1484 		return HRTIMER_NORESTART;
1485 
1486 	hrtimer_forward(timer, now, TICK_NSEC);
1487 
1488 	return HRTIMER_RESTART;
1489 }
1490 
1491 static int sched_skew_tick;
1492 
skew_tick(char * str)1493 static int __init skew_tick(char *str)
1494 {
1495 	get_option(&str, &sched_skew_tick);
1496 
1497 	return 0;
1498 }
1499 early_param("skew_tick", skew_tick);
1500 
1501 /**
1502  * tick_setup_sched_timer - setup the tick emulation timer
1503  */
tick_setup_sched_timer(void)1504 void tick_setup_sched_timer(void)
1505 {
1506 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1507 	ktime_t now = ktime_get();
1508 
1509 	/*
1510 	 * Emulate tick processing via per-CPU hrtimers:
1511 	 */
1512 	hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1513 	ts->sched_timer.function = tick_sched_timer;
1514 
1515 	/* Get the next period (per-CPU) */
1516 	hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1517 
1518 	/* Offset the tick to avert jiffies_lock contention. */
1519 	if (sched_skew_tick) {
1520 		u64 offset = TICK_NSEC >> 1;
1521 		do_div(offset, num_possible_cpus());
1522 		offset *= smp_processor_id();
1523 		hrtimer_add_expires_ns(&ts->sched_timer, offset);
1524 	}
1525 
1526 	hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1527 	hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1528 	tick_nohz_activate(ts, NOHZ_MODE_HIGHRES);
1529 }
1530 #endif /* HIGH_RES_TIMERS */
1531 
1532 #if defined CONFIG_NO_HZ_COMMON || defined CONFIG_HIGH_RES_TIMERS
tick_cancel_sched_timer(int cpu)1533 void tick_cancel_sched_timer(int cpu)
1534 {
1535 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1536 	ktime_t idle_sleeptime, iowait_sleeptime;
1537 	unsigned long idle_calls, idle_sleeps;
1538 
1539 # ifdef CONFIG_HIGH_RES_TIMERS
1540 	if (ts->sched_timer.base)
1541 		hrtimer_cancel(&ts->sched_timer);
1542 # endif
1543 
1544 	idle_sleeptime = ts->idle_sleeptime;
1545 	iowait_sleeptime = ts->iowait_sleeptime;
1546 	idle_calls = ts->idle_calls;
1547 	idle_sleeps = ts->idle_sleeps;
1548 	memset(ts, 0, sizeof(*ts));
1549 	ts->idle_sleeptime = idle_sleeptime;
1550 	ts->iowait_sleeptime = iowait_sleeptime;
1551 	ts->idle_calls = idle_calls;
1552 	ts->idle_sleeps = idle_sleeps;
1553 }
1554 #endif
1555 
1556 /**
1557  * Async notification about clocksource changes
1558  */
tick_clock_notify(void)1559 void tick_clock_notify(void)
1560 {
1561 	int cpu;
1562 
1563 	for_each_possible_cpu(cpu)
1564 		set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1565 }
1566 
1567 /*
1568  * Async notification about clock event changes
1569  */
tick_oneshot_notify(void)1570 void tick_oneshot_notify(void)
1571 {
1572 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1573 
1574 	set_bit(0, &ts->check_clocks);
1575 }
1576 
1577 /**
1578  * Check, if a change happened, which makes oneshot possible.
1579  *
1580  * Called cyclic from the hrtimer softirq (driven by the timer
1581  * softirq) allow_nohz signals, that we can switch into low-res nohz
1582  * mode, because high resolution timers are disabled (either compile
1583  * or runtime). Called with interrupts disabled.
1584  */
tick_check_oneshot_change(int allow_nohz)1585 int tick_check_oneshot_change(int allow_nohz)
1586 {
1587 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1588 
1589 	if (!test_and_clear_bit(0, &ts->check_clocks))
1590 		return 0;
1591 
1592 	if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
1593 		return 0;
1594 
1595 	if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1596 		return 0;
1597 
1598 	if (!allow_nohz)
1599 		return 1;
1600 
1601 	tick_nohz_switch_to_nohz();
1602 	return 0;
1603 }
1604