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