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