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