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