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