xref: /linux/kernel/time/tick-sched.c (revision 40efcb05f213180b7cc8fd8d963377305f236c28)
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  *  For licencing details see kernel-base/COPYING
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/tick.h>
23 
24 #include <asm/irq_regs.h>
25 
26 #include "tick-internal.h"
27 
28 /*
29  * Per cpu nohz control structure
30  */
31 static DEFINE_PER_CPU(struct tick_sched, tick_cpu_sched);
32 
33 /*
34  * The time, when the last jiffy update happened. Protected by xtime_lock.
35  */
36 static ktime_t last_jiffies_update;
37 
38 struct tick_sched *tick_get_tick_sched(int cpu)
39 {
40 	return &per_cpu(tick_cpu_sched, cpu);
41 }
42 
43 /*
44  * Must be called with interrupts disabled !
45  */
46 static void tick_do_update_jiffies64(ktime_t now)
47 {
48 	unsigned long ticks = 0;
49 	ktime_t delta;
50 
51 	/* Reevalute with xtime_lock held */
52 	write_seqlock(&xtime_lock);
53 
54 	delta = ktime_sub(now, last_jiffies_update);
55 	if (delta.tv64 >= tick_period.tv64) {
56 
57 		delta = ktime_sub(delta, tick_period);
58 		last_jiffies_update = ktime_add(last_jiffies_update,
59 						tick_period);
60 
61 		/* Slow path for long timeouts */
62 		if (unlikely(delta.tv64 >= tick_period.tv64)) {
63 			s64 incr = ktime_to_ns(tick_period);
64 
65 			ticks = ktime_divns(delta, incr);
66 
67 			last_jiffies_update = ktime_add_ns(last_jiffies_update,
68 							   incr * ticks);
69 		}
70 		do_timer(++ticks);
71 	}
72 	write_sequnlock(&xtime_lock);
73 }
74 
75 /*
76  * Initialize and return retrieve the jiffies update.
77  */
78 static ktime_t tick_init_jiffy_update(void)
79 {
80 	ktime_t period;
81 
82 	write_seqlock(&xtime_lock);
83 	/* Did we start the jiffies update yet ? */
84 	if (last_jiffies_update.tv64 == 0)
85 		last_jiffies_update = tick_next_period;
86 	period = last_jiffies_update;
87 	write_sequnlock(&xtime_lock);
88 	return period;
89 }
90 
91 /*
92  * NOHZ - aka dynamic tick functionality
93  */
94 #ifdef CONFIG_NO_HZ
95 /*
96  * NO HZ enabled ?
97  */
98 static int tick_nohz_enabled __read_mostly  = 1;
99 
100 /*
101  * Enable / Disable tickless mode
102  */
103 static int __init setup_tick_nohz(char *str)
104 {
105 	if (!strcmp(str, "off"))
106 		tick_nohz_enabled = 0;
107 	else if (!strcmp(str, "on"))
108 		tick_nohz_enabled = 1;
109 	else
110 		return 0;
111 	return 1;
112 }
113 
114 __setup("nohz=", setup_tick_nohz);
115 
116 /**
117  * tick_nohz_update_jiffies - update jiffies when idle was interrupted
118  *
119  * Called from interrupt entry when the CPU was idle
120  *
121  * In case the sched_tick was stopped on this CPU, we have to check if jiffies
122  * must be updated. Otherwise an interrupt handler could use a stale jiffy
123  * value. We do this unconditionally on any cpu, as we don't know whether the
124  * cpu, which has the update task assigned is in a long sleep.
125  */
126 void tick_nohz_update_jiffies(void)
127 {
128 	int cpu = smp_processor_id();
129 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
130 	unsigned long flags;
131 	ktime_t now;
132 
133 	if (!ts->tick_stopped)
134 		return;
135 
136 	touch_softlockup_watchdog();
137 
138 	cpu_clear(cpu, nohz_cpu_mask);
139 	now = ktime_get();
140 
141 	local_irq_save(flags);
142 	tick_do_update_jiffies64(now);
143 	local_irq_restore(flags);
144 }
145 
146 /**
147  * tick_nohz_stop_sched_tick - stop the idle tick from the idle task
148  *
149  * When the next event is more than a tick into the future, stop the idle tick
150  * Called either from the idle loop or from irq_exit() when an idle period was
151  * just interrupted by an interrupt which did not cause a reschedule.
152  */
153 void tick_nohz_stop_sched_tick(void)
154 {
155 	unsigned long seq, last_jiffies, next_jiffies, delta_jiffies, flags;
156 	struct tick_sched *ts;
157 	ktime_t last_update, expires, now, delta;
158 	struct clock_event_device *dev = __get_cpu_var(tick_cpu_device).evtdev;
159 	int cpu;
160 
161 	local_irq_save(flags);
162 
163 	cpu = smp_processor_id();
164 	ts = &per_cpu(tick_cpu_sched, cpu);
165 
166 	/*
167 	 * If this cpu is offline and it is the one which updates
168 	 * jiffies, then give up the assignment and let it be taken by
169 	 * the cpu which runs the tick timer next. If we don't drop
170 	 * this here the jiffies might be stale and do_timer() never
171 	 * invoked.
172 	 */
173 	if (unlikely(!cpu_online(cpu))) {
174 		if (cpu == tick_do_timer_cpu)
175 			tick_do_timer_cpu = -1;
176 	}
177 
178 	if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
179 		goto end;
180 
181 	if (need_resched())
182 		goto end;
183 
184 	cpu = smp_processor_id();
185 	if (unlikely(local_softirq_pending())) {
186 		static int ratelimit;
187 
188 		if (ratelimit < 10) {
189 			printk(KERN_ERR "NOHZ: local_softirq_pending %02x\n",
190 			       local_softirq_pending());
191 			ratelimit++;
192 		}
193 	}
194 
195 	now = ktime_get();
196 	/*
197 	 * When called from irq_exit we need to account the idle sleep time
198 	 * correctly.
199 	 */
200 	if (ts->tick_stopped) {
201 		delta = ktime_sub(now, ts->idle_entrytime);
202 		ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
203 	}
204 
205 	ts->idle_entrytime = now;
206 	ts->idle_calls++;
207 
208 	/* Read jiffies and the time when jiffies were updated last */
209 	do {
210 		seq = read_seqbegin(&xtime_lock);
211 		last_update = last_jiffies_update;
212 		last_jiffies = jiffies;
213 	} while (read_seqretry(&xtime_lock, seq));
214 
215 	/* Get the next timer wheel timer */
216 	next_jiffies = get_next_timer_interrupt(last_jiffies);
217 	delta_jiffies = next_jiffies - last_jiffies;
218 
219 	if (rcu_needs_cpu(cpu))
220 		delta_jiffies = 1;
221 	/*
222 	 * Do not stop the tick, if we are only one off
223 	 * or if the cpu is required for rcu
224 	 */
225 	if (!ts->tick_stopped && delta_jiffies == 1)
226 		goto out;
227 
228 	/* Schedule the tick, if we are at least one jiffie off */
229 	if ((long)delta_jiffies >= 1) {
230 
231 		if (delta_jiffies > 1)
232 			cpu_set(cpu, nohz_cpu_mask);
233 		/*
234 		 * nohz_stop_sched_tick can be called several times before
235 		 * the nohz_restart_sched_tick is called. This happens when
236 		 * interrupts arrive which do not cause a reschedule. In the
237 		 * first call we save the current tick time, so we can restart
238 		 * the scheduler tick in nohz_restart_sched_tick.
239 		 */
240 		if (!ts->tick_stopped) {
241 			if (select_nohz_load_balancer(1)) {
242 				/*
243 				 * sched tick not stopped!
244 				 */
245 				cpu_clear(cpu, nohz_cpu_mask);
246 				goto out;
247 			}
248 
249 			ts->idle_tick = ts->sched_timer.expires;
250 			ts->tick_stopped = 1;
251 			ts->idle_jiffies = last_jiffies;
252 		}
253 
254 		/*
255 		 * If this cpu is the one which updates jiffies, then
256 		 * give up the assignment and let it be taken by the
257 		 * cpu which runs the tick timer next, which might be
258 		 * this cpu as well. If we don't drop this here the
259 		 * jiffies might be stale and do_timer() never
260 		 * invoked.
261 		 */
262 		if (cpu == tick_do_timer_cpu)
263 			tick_do_timer_cpu = -1;
264 
265 		ts->idle_sleeps++;
266 
267 		/*
268 		 * delta_jiffies >= NEXT_TIMER_MAX_DELTA signals that
269 		 * there is no timer pending or at least extremly far
270 		 * into the future (12 days for HZ=1000). In this case
271 		 * we simply stop the tick timer:
272 		 */
273 		if (unlikely(delta_jiffies >= NEXT_TIMER_MAX_DELTA)) {
274 			ts->idle_expires.tv64 = KTIME_MAX;
275 			if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
276 				hrtimer_cancel(&ts->sched_timer);
277 			goto out;
278 		}
279 
280 		/*
281 		 * calculate the expiry time for the next timer wheel
282 		 * timer
283 		 */
284 		expires = ktime_add_ns(last_update, tick_period.tv64 *
285 				       delta_jiffies);
286 		ts->idle_expires = expires;
287 
288 		if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
289 			hrtimer_start(&ts->sched_timer, expires,
290 				      HRTIMER_MODE_ABS);
291 			/* Check, if the timer was already in the past */
292 			if (hrtimer_active(&ts->sched_timer))
293 				goto out;
294 		} else if(!tick_program_event(expires, 0))
295 				goto out;
296 		/*
297 		 * We are past the event already. So we crossed a
298 		 * jiffie boundary. Update jiffies and raise the
299 		 * softirq.
300 		 */
301 		tick_do_update_jiffies64(ktime_get());
302 		cpu_clear(cpu, nohz_cpu_mask);
303 	}
304 	raise_softirq_irqoff(TIMER_SOFTIRQ);
305 out:
306 	ts->next_jiffies = next_jiffies;
307 	ts->last_jiffies = last_jiffies;
308 	ts->sleep_length = ktime_sub(dev->next_event, now);
309 end:
310 	local_irq_restore(flags);
311 }
312 
313 /**
314  * tick_nohz_get_sleep_length - return the length of the current sleep
315  *
316  * Called from power state control code with interrupts disabled
317  */
318 ktime_t tick_nohz_get_sleep_length(void)
319 {
320 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
321 
322 	return ts->sleep_length;
323 }
324 
325 /**
326  * tick_nohz_restart_sched_tick - restart the idle tick from the idle task
327  *
328  * Restart the idle tick when the CPU is woken up from idle
329  */
330 void tick_nohz_restart_sched_tick(void)
331 {
332 	int cpu = smp_processor_id();
333 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
334 	unsigned long ticks;
335 	ktime_t now, delta;
336 
337 	if (!ts->tick_stopped)
338 		return;
339 
340 	/* Update jiffies first */
341 	now = ktime_get();
342 
343 	local_irq_disable();
344 	select_nohz_load_balancer(0);
345 	tick_do_update_jiffies64(now);
346 	cpu_clear(cpu, nohz_cpu_mask);
347 
348 	/* Account the idle time */
349 	delta = ktime_sub(now, ts->idle_entrytime);
350 	ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
351 
352 	/*
353 	 * We stopped the tick in idle. Update process times would miss the
354 	 * time we slept as update_process_times does only a 1 tick
355 	 * accounting. Enforce that this is accounted to idle !
356 	 */
357 	ticks = jiffies - ts->idle_jiffies;
358 	/*
359 	 * We might be one off. Do not randomly account a huge number of ticks!
360 	 */
361 	if (ticks && ticks < LONG_MAX) {
362 		add_preempt_count(HARDIRQ_OFFSET);
363 		account_system_time(current, HARDIRQ_OFFSET,
364 				    jiffies_to_cputime(ticks));
365 		sub_preempt_count(HARDIRQ_OFFSET);
366 	}
367 
368 	/*
369 	 * Cancel the scheduled timer and restore the tick
370 	 */
371 	ts->tick_stopped  = 0;
372 	hrtimer_cancel(&ts->sched_timer);
373 	ts->sched_timer.expires = ts->idle_tick;
374 
375 	while (1) {
376 		/* Forward the time to expire in the future */
377 		hrtimer_forward(&ts->sched_timer, now, tick_period);
378 
379 		if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
380 			hrtimer_start(&ts->sched_timer,
381 				      ts->sched_timer.expires,
382 				      HRTIMER_MODE_ABS);
383 			/* Check, if the timer was already in the past */
384 			if (hrtimer_active(&ts->sched_timer))
385 				break;
386 		} else {
387 			if (!tick_program_event(ts->sched_timer.expires, 0))
388 				break;
389 		}
390 		/* Update jiffies and reread time */
391 		tick_do_update_jiffies64(now);
392 		now = ktime_get();
393 	}
394 	local_irq_enable();
395 }
396 
397 static int tick_nohz_reprogram(struct tick_sched *ts, ktime_t now)
398 {
399 	hrtimer_forward(&ts->sched_timer, now, tick_period);
400 	return tick_program_event(ts->sched_timer.expires, 0);
401 }
402 
403 /*
404  * The nohz low res interrupt handler
405  */
406 static void tick_nohz_handler(struct clock_event_device *dev)
407 {
408 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
409 	struct pt_regs *regs = get_irq_regs();
410 	int cpu = smp_processor_id();
411 	ktime_t now = ktime_get();
412 
413 	dev->next_event.tv64 = KTIME_MAX;
414 
415 	/*
416 	 * Check if the do_timer duty was dropped. We don't care about
417 	 * concurrency: This happens only when the cpu in charge went
418 	 * into a long sleep. If two cpus happen to assign themself to
419 	 * this duty, then the jiffies update is still serialized by
420 	 * xtime_lock.
421 	 */
422 	if (unlikely(tick_do_timer_cpu == -1))
423 		tick_do_timer_cpu = cpu;
424 
425 	/* Check, if the jiffies need an update */
426 	if (tick_do_timer_cpu == cpu)
427 		tick_do_update_jiffies64(now);
428 
429 	/*
430 	 * When we are idle and the tick is stopped, we have to touch
431 	 * the watchdog as we might not schedule for a really long
432 	 * time. This happens on complete idle SMP systems while
433 	 * waiting on the login prompt. We also increment the "start
434 	 * of idle" jiffy stamp so the idle accounting adjustment we
435 	 * do when we go busy again does not account too much ticks.
436 	 */
437 	if (ts->tick_stopped) {
438 		touch_softlockup_watchdog();
439 		ts->idle_jiffies++;
440 	}
441 
442 	update_process_times(user_mode(regs));
443 	profile_tick(CPU_PROFILING);
444 
445 	/* Do not restart, when we are in the idle loop */
446 	if (ts->tick_stopped)
447 		return;
448 
449 	while (tick_nohz_reprogram(ts, now)) {
450 		now = ktime_get();
451 		tick_do_update_jiffies64(now);
452 	}
453 }
454 
455 /**
456  * tick_nohz_switch_to_nohz - switch to nohz mode
457  */
458 static void tick_nohz_switch_to_nohz(void)
459 {
460 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
461 	ktime_t next;
462 
463 	if (!tick_nohz_enabled)
464 		return;
465 
466 	local_irq_disable();
467 	if (tick_switch_to_oneshot(tick_nohz_handler)) {
468 		local_irq_enable();
469 		return;
470 	}
471 
472 	ts->nohz_mode = NOHZ_MODE_LOWRES;
473 
474 	/*
475 	 * Recycle the hrtimer in ts, so we can share the
476 	 * hrtimer_forward with the highres code.
477 	 */
478 	hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
479 	/* Get the next period */
480 	next = tick_init_jiffy_update();
481 
482 	for (;;) {
483 		ts->sched_timer.expires = next;
484 		if (!tick_program_event(next, 0))
485 			break;
486 		next = ktime_add(next, tick_period);
487 	}
488 	local_irq_enable();
489 
490 	printk(KERN_INFO "Switched to NOHz mode on CPU #%d\n",
491 	       smp_processor_id());
492 }
493 
494 #else
495 
496 static inline void tick_nohz_switch_to_nohz(void) { }
497 
498 #endif /* NO_HZ */
499 
500 /*
501  * High resolution timer specific code
502  */
503 #ifdef CONFIG_HIGH_RES_TIMERS
504 /*
505  * We rearm the timer until we get disabled by the idle code
506  * Called with interrupts disabled and timer->base->cpu_base->lock held.
507  */
508 static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
509 {
510 	struct tick_sched *ts =
511 		container_of(timer, struct tick_sched, sched_timer);
512 	struct hrtimer_cpu_base *base = timer->base->cpu_base;
513 	struct pt_regs *regs = get_irq_regs();
514 	ktime_t now = ktime_get();
515 	int cpu = smp_processor_id();
516 
517 #ifdef CONFIG_NO_HZ
518 	/*
519 	 * Check if the do_timer duty was dropped. We don't care about
520 	 * concurrency: This happens only when the cpu in charge went
521 	 * into a long sleep. If two cpus happen to assign themself to
522 	 * this duty, then the jiffies update is still serialized by
523 	 * xtime_lock.
524 	 */
525 	if (unlikely(tick_do_timer_cpu == -1))
526 		tick_do_timer_cpu = cpu;
527 #endif
528 
529 	/* Check, if the jiffies need an update */
530 	if (tick_do_timer_cpu == cpu)
531 		tick_do_update_jiffies64(now);
532 
533 	/*
534 	 * Do not call, when we are not in irq context and have
535 	 * no valid regs pointer
536 	 */
537 	if (regs) {
538 		/*
539 		 * When we are idle and the tick is stopped, we have to touch
540 		 * the watchdog as we might not schedule for a really long
541 		 * time. This happens on complete idle SMP systems while
542 		 * waiting on the login prompt. We also increment the "start of
543 		 * idle" jiffy stamp so the idle accounting adjustment we do
544 		 * when we go busy again does not account too much ticks.
545 		 */
546 		if (ts->tick_stopped) {
547 			touch_softlockup_watchdog();
548 			ts->idle_jiffies++;
549 		}
550 		/*
551 		 * update_process_times() might take tasklist_lock, hence
552 		 * drop the base lock. sched-tick hrtimers are per-CPU and
553 		 * never accessible by userspace APIs, so this is safe to do.
554 		 */
555 		spin_unlock(&base->lock);
556 		update_process_times(user_mode(regs));
557 		profile_tick(CPU_PROFILING);
558 		spin_lock(&base->lock);
559 	}
560 
561 	/* Do not restart, when we are in the idle loop */
562 	if (ts->tick_stopped)
563 		return HRTIMER_NORESTART;
564 
565 	hrtimer_forward(timer, now, tick_period);
566 
567 	return HRTIMER_RESTART;
568 }
569 
570 /**
571  * tick_setup_sched_timer - setup the tick emulation timer
572  */
573 void tick_setup_sched_timer(void)
574 {
575 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
576 	ktime_t now = ktime_get();
577 	u64 offset;
578 
579 	/*
580 	 * Emulate tick processing via per-CPU hrtimers:
581 	 */
582 	hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
583 	ts->sched_timer.function = tick_sched_timer;
584 	ts->sched_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
585 
586 	/* Get the next period (per cpu) */
587 	ts->sched_timer.expires = tick_init_jiffy_update();
588 	offset = ktime_to_ns(tick_period) >> 1;
589 	do_div(offset, num_possible_cpus());
590 	offset *= smp_processor_id();
591 	ts->sched_timer.expires = ktime_add_ns(ts->sched_timer.expires, offset);
592 
593 	for (;;) {
594 		hrtimer_forward(&ts->sched_timer, now, tick_period);
595 		hrtimer_start(&ts->sched_timer, ts->sched_timer.expires,
596 			      HRTIMER_MODE_ABS);
597 		/* Check, if the timer was already in the past */
598 		if (hrtimer_active(&ts->sched_timer))
599 			break;
600 		now = ktime_get();
601 	}
602 
603 #ifdef CONFIG_NO_HZ
604 	if (tick_nohz_enabled)
605 		ts->nohz_mode = NOHZ_MODE_HIGHRES;
606 #endif
607 }
608 
609 void tick_cancel_sched_timer(int cpu)
610 {
611 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
612 
613 	if (ts->sched_timer.base)
614 		hrtimer_cancel(&ts->sched_timer);
615 	ts->tick_stopped = 0;
616 	ts->nohz_mode = NOHZ_MODE_INACTIVE;
617 }
618 #endif /* HIGH_RES_TIMERS */
619 
620 /**
621  * Async notification about clocksource changes
622  */
623 void tick_clock_notify(void)
624 {
625 	int cpu;
626 
627 	for_each_possible_cpu(cpu)
628 		set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
629 }
630 
631 /*
632  * Async notification about clock event changes
633  */
634 void tick_oneshot_notify(void)
635 {
636 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
637 
638 	set_bit(0, &ts->check_clocks);
639 }
640 
641 /**
642  * Check, if a change happened, which makes oneshot possible.
643  *
644  * Called cyclic from the hrtimer softirq (driven by the timer
645  * softirq) allow_nohz signals, that we can switch into low-res nohz
646  * mode, because high resolution timers are disabled (either compile
647  * or runtime).
648  */
649 int tick_check_oneshot_change(int allow_nohz)
650 {
651 	struct tick_sched *ts = &__get_cpu_var(tick_cpu_sched);
652 
653 	if (!test_and_clear_bit(0, &ts->check_clocks))
654 		return 0;
655 
656 	if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
657 		return 0;
658 
659 	if (!timekeeping_is_continuous() || !tick_is_oneshot_available())
660 		return 0;
661 
662 	if (!allow_nohz)
663 		return 1;
664 
665 	tick_nohz_switch_to_nohz();
666 	return 0;
667 }
668