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