1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
4 * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
5 * Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
7 * No idle tick implementation for low and high resolution timers
9 * Started by: Thomas Gleixner and Ingo Molnar
11 #include <linux/cpu.h>
12 #include <linux/err.h>
13 #include <linux/hrtimer.h>
14 #include <linux/interrupt.h>
15 #include <linux/kernel_stat.h>
16 #include <linux/percpu.h>
17 #include <linux/nmi.h>
18 #include <linux/profile.h>
19 #include <linux/sched/signal.h>
20 #include <linux/sched/clock.h>
21 #include <linux/sched/stat.h>
22 #include <linux/sched/nohz.h>
23 #include <linux/module.h>
24 #include <linux/irq_work.h>
25 #include <linux/posix-timers.h>
26 #include <linux/context_tracking.h>
29 #include <asm/irq_regs.h>
31 #include "tick-internal.h"
33 #include <trace/events/timer.h>
36 * Per-CPU nohz control structure
38 static DEFINE_PER_CPU(struct tick_sched, tick_cpu_sched);
40 struct tick_sched *tick_get_tick_sched(int cpu)
42 return &per_cpu(tick_cpu_sched, cpu);
45 #if defined(CONFIG_NO_HZ_COMMON) || defined(CONFIG_HIGH_RES_TIMERS)
47 * The time, when the last jiffy update happened. Protected by jiffies_lock.
49 static ktime_t last_jiffies_update;
52 * Must be called with interrupts disabled !
54 static void tick_do_update_jiffies64(ktime_t now)
56 unsigned long ticks = 1;
60 * Do a quick check without holding jiffies_lock. The READ_ONCE()
61 * pairs with the update done later in this function.
63 * This is also an intentional data race which is even safe on
64 * 32bit in theory. If there is a concurrent update then the check
65 * might give a random answer. It does not matter because if it
66 * returns then the concurrent update is already taking care, if it
67 * falls through then it will pointlessly contend on jiffies_lock.
69 * Though there is one nasty case on 32bit due to store tearing of
70 * the 64bit value. If the first 32bit store makes the quick check
71 * return on all other CPUs and the writing CPU context gets
72 * delayed to complete the second store (scheduled out on virt)
73 * then jiffies can become stale for up to ~2^32 nanoseconds
74 * without noticing. After that point all CPUs will wait for
77 * OTOH, this is not any different than the situation with NOHZ=off
78 * where one CPU is responsible for updating jiffies and
79 * timekeeping. If that CPU goes out for lunch then all other CPUs
80 * will operate on stale jiffies until it decides to come back.
82 if (ktime_before(now, READ_ONCE(tick_next_period)))
85 /* Reevaluate with jiffies_lock held */
86 raw_spin_lock(&jiffies_lock);
87 if (ktime_before(now, tick_next_period)) {
88 raw_spin_unlock(&jiffies_lock);
92 write_seqcount_begin(&jiffies_seq);
94 delta = ktime_sub(now, tick_next_period);
95 if (unlikely(delta >= TICK_NSEC)) {
96 /* Slow path for long idle sleep times */
99 ticks += ktime_divns(delta, incr);
101 last_jiffies_update = ktime_add_ns(last_jiffies_update,
104 last_jiffies_update = ktime_add_ns(last_jiffies_update,
111 * Keep the tick_next_period variable up to date. WRITE_ONCE()
112 * pairs with the READ_ONCE() in the lockless quick check above.
114 WRITE_ONCE(tick_next_period,
115 ktime_add_ns(last_jiffies_update, TICK_NSEC));
117 write_seqcount_end(&jiffies_seq);
118 raw_spin_unlock(&jiffies_lock);
123 * Initialize and return retrieve the jiffies update.
125 static ktime_t tick_init_jiffy_update(void)
129 raw_spin_lock(&jiffies_lock);
130 write_seqcount_begin(&jiffies_seq);
131 /* Did we start the jiffies update yet ? */
132 if (last_jiffies_update == 0) {
136 * Ensure that the tick is aligned to a multiple of
139 div_u64_rem(tick_next_period, TICK_NSEC, &rem);
141 tick_next_period += TICK_NSEC - rem;
143 last_jiffies_update = tick_next_period;
145 period = last_jiffies_update;
146 write_seqcount_end(&jiffies_seq);
147 raw_spin_unlock(&jiffies_lock);
151 static void tick_sched_do_timer(struct tick_sched *ts, ktime_t now)
153 int cpu = smp_processor_id();
155 #ifdef CONFIG_NO_HZ_COMMON
157 * Check if the do_timer duty was dropped. We don't care about
158 * concurrency: This happens only when the CPU in charge went
159 * into a long sleep. If two CPUs happen to assign themselves to
160 * this duty, then the jiffies update is still serialized by
163 * If nohz_full is enabled, this should not happen because the
164 * tick_do_timer_cpu never relinquishes.
166 if (unlikely(tick_do_timer_cpu == TICK_DO_TIMER_NONE)) {
167 #ifdef CONFIG_NO_HZ_FULL
168 WARN_ON_ONCE(tick_nohz_full_running);
170 tick_do_timer_cpu = cpu;
174 /* Check, if the jiffies need an update */
175 if (tick_do_timer_cpu == cpu)
176 tick_do_update_jiffies64(now);
179 ts->got_idle_tick = 1;
182 static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
184 #ifdef CONFIG_NO_HZ_COMMON
186 * When we are idle and the tick is stopped, we have to touch
187 * the watchdog as we might not schedule for a really long
188 * time. This happens on complete idle SMP systems while
189 * waiting on the login prompt. We also increment the "start of
190 * idle" jiffy stamp so the idle accounting adjustment we do
191 * when we go busy again does not account too much ticks.
193 if (ts->tick_stopped) {
194 touch_softlockup_watchdog_sched();
195 if (is_idle_task(current))
198 * In case the current tick fired too early past its expected
199 * expiration, make sure we don't bypass the next clock reprogramming
200 * to the same deadline.
205 update_process_times(user_mode(regs));
206 profile_tick(CPU_PROFILING);
210 #ifdef CONFIG_NO_HZ_FULL
211 cpumask_var_t tick_nohz_full_mask;
212 bool tick_nohz_full_running;
213 static atomic_t tick_dep_mask;
215 static bool check_tick_dependency(atomic_t *dep)
217 int val = atomic_read(dep);
219 if (val & TICK_DEP_MASK_POSIX_TIMER) {
220 trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
224 if (val & TICK_DEP_MASK_PERF_EVENTS) {
225 trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
229 if (val & TICK_DEP_MASK_SCHED) {
230 trace_tick_stop(0, TICK_DEP_MASK_SCHED);
234 if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
235 trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
239 if (val & TICK_DEP_MASK_RCU) {
240 trace_tick_stop(0, TICK_DEP_MASK_RCU);
247 static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
249 lockdep_assert_irqs_disabled();
251 if (unlikely(!cpu_online(cpu)))
254 if (check_tick_dependency(&tick_dep_mask))
257 if (check_tick_dependency(&ts->tick_dep_mask))
260 if (check_tick_dependency(¤t->tick_dep_mask))
263 if (check_tick_dependency(¤t->signal->tick_dep_mask))
269 static void nohz_full_kick_func(struct irq_work *work)
271 /* Empty, the tick restart happens on tick_nohz_irq_exit() */
274 static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) = {
275 .func = nohz_full_kick_func,
279 * Kick this CPU if it's full dynticks in order to force it to
280 * re-evaluate its dependency on the tick and restart it if necessary.
281 * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
284 static void tick_nohz_full_kick(void)
286 if (!tick_nohz_full_cpu(smp_processor_id()))
289 irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
293 * Kick the CPU if it's full dynticks in order to force it to
294 * re-evaluate its dependency on the tick and restart it if necessary.
296 void tick_nohz_full_kick_cpu(int cpu)
298 if (!tick_nohz_full_cpu(cpu))
301 irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
305 * Kick all full dynticks CPUs in order to force these to re-evaluate
306 * their dependency on the tick and restart it if necessary.
308 static void tick_nohz_full_kick_all(void)
312 if (!tick_nohz_full_running)
316 for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
317 tick_nohz_full_kick_cpu(cpu);
321 static void tick_nohz_dep_set_all(atomic_t *dep,
322 enum tick_dep_bits bit)
326 prev = atomic_fetch_or(BIT(bit), dep);
328 tick_nohz_full_kick_all();
332 * Set a global tick dependency. Used by perf events that rely on freq and
335 void tick_nohz_dep_set(enum tick_dep_bits bit)
337 tick_nohz_dep_set_all(&tick_dep_mask, bit);
340 void tick_nohz_dep_clear(enum tick_dep_bits bit)
342 atomic_andnot(BIT(bit), &tick_dep_mask);
346 * Set per-CPU tick dependency. Used by scheduler and perf events in order to
347 * manage events throttling.
349 void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
352 struct tick_sched *ts;
354 ts = per_cpu_ptr(&tick_cpu_sched, cpu);
356 prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
359 /* Perf needs local kick that is NMI safe */
360 if (cpu == smp_processor_id()) {
361 tick_nohz_full_kick();
363 /* Remote irq work not NMI-safe */
364 if (!WARN_ON_ONCE(in_nmi()))
365 tick_nohz_full_kick_cpu(cpu);
370 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
372 void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
374 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
376 atomic_andnot(BIT(bit), &ts->tick_dep_mask);
378 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
381 * Set a per-task tick dependency. Posix CPU timers need this in order to elapse
384 void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
387 * We could optimize this with just kicking the target running the task
388 * if that noise matters for nohz full users.
390 tick_nohz_dep_set_all(&tsk->tick_dep_mask, bit);
393 void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
395 atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
399 * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
400 * per process timers.
402 void tick_nohz_dep_set_signal(struct signal_struct *sig, enum tick_dep_bits bit)
404 tick_nohz_dep_set_all(&sig->tick_dep_mask, bit);
407 void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
409 atomic_andnot(BIT(bit), &sig->tick_dep_mask);
413 * Re-evaluate the need for the tick as we switch the current task.
414 * It might need the tick due to per task/process properties:
415 * perf events, posix CPU timers, ...
417 void __tick_nohz_task_switch(void)
420 struct tick_sched *ts;
422 local_irq_save(flags);
424 if (!tick_nohz_full_cpu(smp_processor_id()))
427 ts = this_cpu_ptr(&tick_cpu_sched);
429 if (ts->tick_stopped) {
430 if (atomic_read(¤t->tick_dep_mask) ||
431 atomic_read(¤t->signal->tick_dep_mask))
432 tick_nohz_full_kick();
435 local_irq_restore(flags);
438 /* Get the boot-time nohz CPU list from the kernel parameters. */
439 void __init tick_nohz_full_setup(cpumask_var_t cpumask)
441 alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
442 cpumask_copy(tick_nohz_full_mask, cpumask);
443 tick_nohz_full_running = true;
446 bool tick_nohz_cpu_hotpluggable(unsigned int cpu)
449 * The tick_do_timer_cpu CPU handles housekeeping duty (unbound
450 * timers, workqueues, timekeeping, ...) on behalf of full dynticks
451 * CPUs. It must remain online when nohz full is enabled.
453 if (tick_nohz_full_running && tick_do_timer_cpu == cpu)
458 static int tick_nohz_cpu_down(unsigned int cpu)
460 return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
463 void __init tick_nohz_init(void)
467 if (!tick_nohz_full_running)
471 * Full dynticks uses irq work to drive the tick rescheduling on safe
472 * locking contexts. But then we need irq work to raise its own
473 * interrupts to avoid circular dependency on the tick
475 if (!arch_irq_work_has_interrupt()) {
476 pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support irq work self-IPIs\n");
477 cpumask_clear(tick_nohz_full_mask);
478 tick_nohz_full_running = false;
482 if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
483 !IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
484 cpu = smp_processor_id();
486 if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
487 pr_warn("NO_HZ: Clearing %d from nohz_full range "
488 "for timekeeping\n", cpu);
489 cpumask_clear_cpu(cpu, tick_nohz_full_mask);
493 for_each_cpu(cpu, tick_nohz_full_mask)
494 context_tracking_cpu_set(cpu);
496 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
497 "kernel/nohz:predown", NULL,
500 pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
501 cpumask_pr_args(tick_nohz_full_mask));
506 * NOHZ - aka dynamic tick functionality
508 #ifdef CONFIG_NO_HZ_COMMON
512 bool tick_nohz_enabled __read_mostly = true;
513 unsigned long tick_nohz_active __read_mostly;
515 * Enable / Disable tickless mode
517 static int __init setup_tick_nohz(char *str)
519 return (kstrtobool(str, &tick_nohz_enabled) == 0);
522 __setup("nohz=", setup_tick_nohz);
524 bool tick_nohz_tick_stopped(void)
526 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
528 return ts->tick_stopped;
531 bool tick_nohz_tick_stopped_cpu(int cpu)
533 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
535 return ts->tick_stopped;
539 * tick_nohz_update_jiffies - update jiffies when idle was interrupted
541 * Called from interrupt entry when the CPU was idle
543 * In case the sched_tick was stopped on this CPU, we have to check if jiffies
544 * must be updated. Otherwise an interrupt handler could use a stale jiffy
545 * value. We do this unconditionally on any CPU, as we don't know whether the
546 * CPU, which has the update task assigned is in a long sleep.
548 static void tick_nohz_update_jiffies(ktime_t now)
552 __this_cpu_write(tick_cpu_sched.idle_waketime, now);
554 local_irq_save(flags);
555 tick_do_update_jiffies64(now);
556 local_irq_restore(flags);
558 touch_softlockup_watchdog_sched();
562 * Updates the per-CPU time idle statistics counters
565 update_ts_time_stats(int cpu, struct tick_sched *ts, ktime_t now, u64 *last_update_time)
569 if (ts->idle_active) {
570 delta = ktime_sub(now, ts->idle_entrytime);
571 if (nr_iowait_cpu(cpu) > 0)
572 ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
574 ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
575 ts->idle_entrytime = now;
578 if (last_update_time)
579 *last_update_time = ktime_to_us(now);
583 static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
585 update_ts_time_stats(smp_processor_id(), ts, now, NULL);
588 sched_clock_idle_wakeup_event();
591 static void tick_nohz_start_idle(struct tick_sched *ts)
593 ts->idle_entrytime = ktime_get();
595 sched_clock_idle_sleep_event();
599 * get_cpu_idle_time_us - get the total idle time of a CPU
600 * @cpu: CPU number to query
601 * @last_update_time: variable to store update time in. Do not update
604 * Return the cumulative idle time (since boot) for a given
605 * CPU, in microseconds.
607 * This time is measured via accounting rather than sampling,
608 * and is as accurate as ktime_get() is.
610 * This function returns -1 if NOHZ is not enabled.
612 u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
614 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
617 if (!tick_nohz_active)
621 if (last_update_time) {
622 update_ts_time_stats(cpu, ts, now, last_update_time);
623 idle = ts->idle_sleeptime;
625 if (ts->idle_active && !nr_iowait_cpu(cpu)) {
626 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
628 idle = ktime_add(ts->idle_sleeptime, delta);
630 idle = ts->idle_sleeptime;
634 return ktime_to_us(idle);
637 EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
640 * get_cpu_iowait_time_us - get the total iowait time of a CPU
641 * @cpu: CPU number to query
642 * @last_update_time: variable to store update time in. Do not update
645 * Return the cumulative iowait time (since boot) for a given
646 * CPU, in microseconds.
648 * This time is measured via accounting rather than sampling,
649 * and is as accurate as ktime_get() is.
651 * This function returns -1 if NOHZ is not enabled.
653 u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
655 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
658 if (!tick_nohz_active)
662 if (last_update_time) {
663 update_ts_time_stats(cpu, ts, now, last_update_time);
664 iowait = ts->iowait_sleeptime;
666 if (ts->idle_active && nr_iowait_cpu(cpu) > 0) {
667 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
669 iowait = ktime_add(ts->iowait_sleeptime, delta);
671 iowait = ts->iowait_sleeptime;
675 return ktime_to_us(iowait);
677 EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
679 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
681 hrtimer_cancel(&ts->sched_timer);
682 hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
684 /* Forward the time to expire in the future */
685 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
687 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
688 hrtimer_start_expires(&ts->sched_timer,
689 HRTIMER_MODE_ABS_PINNED_HARD);
691 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
695 * Reset to make sure next tick stop doesn't get fooled by past
696 * cached clock deadline.
701 static inline bool local_timer_softirq_pending(void)
703 return local_softirq_pending() & BIT(TIMER_SOFTIRQ);
706 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
708 u64 basemono, next_tick, next_tmr, next_rcu, delta, expires;
709 unsigned long basejiff;
712 /* Read jiffies and the time when jiffies were updated last */
714 seq = read_seqcount_begin(&jiffies_seq);
715 basemono = last_jiffies_update;
717 } while (read_seqcount_retry(&jiffies_seq, seq));
718 ts->last_jiffies = basejiff;
719 ts->timer_expires_base = basemono;
722 * Keep the periodic tick, when RCU, architecture or irq_work
724 * Aside of that check whether the local timer softirq is
725 * pending. If so its a bad idea to call get_next_timer_interrupt()
726 * because there is an already expired timer, so it will request
727 * immeditate expiry, which rearms the hardware timer with a
728 * minimal delta which brings us back to this place
729 * immediately. Lather, rinse and repeat...
731 if (rcu_needs_cpu(basemono, &next_rcu) || arch_needs_cpu() ||
732 irq_work_needs_cpu() || local_timer_softirq_pending()) {
733 next_tick = basemono + TICK_NSEC;
736 * Get the next pending timer. If high resolution
737 * timers are enabled this only takes the timer wheel
738 * timers into account. If high resolution timers are
739 * disabled this also looks at the next expiring
742 next_tmr = get_next_timer_interrupt(basejiff, basemono);
743 ts->next_timer = next_tmr;
744 /* Take the next rcu event into account */
745 next_tick = next_rcu < next_tmr ? next_rcu : next_tmr;
749 * If the tick is due in the next period, keep it ticking or
750 * force prod the timer.
752 delta = next_tick - basemono;
753 if (delta <= (u64)TICK_NSEC) {
755 * Tell the timer code that the base is not idle, i.e. undo
756 * the effect of get_next_timer_interrupt():
760 * We've not stopped the tick yet, and there's a timer in the
761 * next period, so no point in stopping it either, bail.
763 if (!ts->tick_stopped) {
764 ts->timer_expires = 0;
770 * If this CPU is the one which had the do_timer() duty last, we limit
771 * the sleep time to the timekeeping max_deferment value.
772 * Otherwise we can sleep as long as we want.
774 delta = timekeeping_max_deferment();
775 if (cpu != tick_do_timer_cpu &&
776 (tick_do_timer_cpu != TICK_DO_TIMER_NONE || !ts->do_timer_last))
779 /* Calculate the next expiry time */
780 if (delta < (KTIME_MAX - basemono))
781 expires = basemono + delta;
785 ts->timer_expires = min_t(u64, expires, next_tick);
788 return ts->timer_expires;
791 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
793 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
794 u64 basemono = ts->timer_expires_base;
795 u64 expires = ts->timer_expires;
796 ktime_t tick = expires;
798 /* Make sure we won't be trying to stop it twice in a row. */
799 ts->timer_expires_base = 0;
802 * If this CPU is the one which updates jiffies, then give up
803 * the assignment and let it be taken by the CPU which runs
804 * the tick timer next, which might be this CPU as well. If we
805 * don't drop this here the jiffies might be stale and
806 * do_timer() never invoked. Keep track of the fact that it
807 * was the one which had the do_timer() duty last.
809 if (cpu == tick_do_timer_cpu) {
810 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
811 ts->do_timer_last = 1;
812 } else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
813 ts->do_timer_last = 0;
816 /* Skip reprogram of event if its not changed */
817 if (ts->tick_stopped && (expires == ts->next_tick)) {
818 /* Sanity check: make sure clockevent is actually programmed */
819 if (tick == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
823 printk_once("basemono: %llu ts->next_tick: %llu dev->next_event: %llu timer->active: %d timer->expires: %llu\n",
824 basemono, ts->next_tick, dev->next_event,
825 hrtimer_active(&ts->sched_timer), hrtimer_get_expires(&ts->sched_timer));
829 * nohz_stop_sched_tick can be called several times before
830 * the nohz_restart_sched_tick is called. This happens when
831 * interrupts arrive which do not cause a reschedule. In the
832 * first call we save the current tick time, so we can restart
833 * the scheduler tick in nohz_restart_sched_tick.
835 if (!ts->tick_stopped) {
836 calc_load_nohz_start();
839 ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
840 ts->tick_stopped = 1;
841 trace_tick_stop(1, TICK_DEP_MASK_NONE);
844 ts->next_tick = tick;
847 * If the expiration time == KTIME_MAX, then we simply stop
850 if (unlikely(expires == KTIME_MAX)) {
851 if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
852 hrtimer_cancel(&ts->sched_timer);
856 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
857 hrtimer_start(&ts->sched_timer, tick,
858 HRTIMER_MODE_ABS_PINNED_HARD);
860 hrtimer_set_expires(&ts->sched_timer, tick);
861 tick_program_event(tick, 1);
865 static void tick_nohz_retain_tick(struct tick_sched *ts)
867 ts->timer_expires_base = 0;
870 #ifdef CONFIG_NO_HZ_FULL
871 static void tick_nohz_stop_sched_tick(struct tick_sched *ts, int cpu)
873 if (tick_nohz_next_event(ts, cpu))
874 tick_nohz_stop_tick(ts, cpu);
876 tick_nohz_retain_tick(ts);
878 #endif /* CONFIG_NO_HZ_FULL */
880 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
882 /* Update jiffies first */
883 tick_do_update_jiffies64(now);
886 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
887 * the clock forward checks in the enqueue path:
891 calc_load_nohz_stop();
892 touch_softlockup_watchdog_sched();
894 * Cancel the scheduled timer and restore the tick
896 ts->tick_stopped = 0;
897 ts->idle_exittime = now;
899 tick_nohz_restart(ts, now);
902 static void tick_nohz_full_update_tick(struct tick_sched *ts)
904 #ifdef CONFIG_NO_HZ_FULL
905 int cpu = smp_processor_id();
907 if (!tick_nohz_full_cpu(cpu))
910 if (!ts->tick_stopped && ts->nohz_mode == NOHZ_MODE_INACTIVE)
913 if (can_stop_full_tick(cpu, ts))
914 tick_nohz_stop_sched_tick(ts, cpu);
915 else if (ts->tick_stopped)
916 tick_nohz_restart_sched_tick(ts, ktime_get());
920 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
923 * If this CPU is offline and it is the one which updates
924 * jiffies, then give up the assignment and let it be taken by
925 * the CPU which runs the tick timer next. If we don't drop
926 * this here the jiffies might be stale and do_timer() never
929 if (unlikely(!cpu_online(cpu))) {
930 if (cpu == tick_do_timer_cpu)
931 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
933 * Make sure the CPU doesn't get fooled by obsolete tick
934 * deadline if it comes back online later.
940 if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
946 if (unlikely(local_softirq_pending())) {
947 static int ratelimit;
949 if (ratelimit < 10 &&
950 (local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
951 pr_warn("NOHZ: local_softirq_pending %02x\n",
952 (unsigned int) local_softirq_pending());
958 if (tick_nohz_full_enabled()) {
960 * Keep the tick alive to guarantee timekeeping progression
961 * if there are full dynticks CPUs around
963 if (tick_do_timer_cpu == cpu)
966 /* Should not happen for nohz-full */
967 if (WARN_ON_ONCE(tick_do_timer_cpu == TICK_DO_TIMER_NONE))
974 static void __tick_nohz_idle_stop_tick(struct tick_sched *ts)
977 int cpu = smp_processor_id();
980 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
981 * tick timer expiration time is known already.
983 if (ts->timer_expires_base)
984 expires = ts->timer_expires;
985 else if (can_stop_idle_tick(cpu, ts))
986 expires = tick_nohz_next_event(ts, cpu);
993 int was_stopped = ts->tick_stopped;
995 tick_nohz_stop_tick(ts, cpu);
998 ts->idle_expires = expires;
1000 if (!was_stopped && ts->tick_stopped) {
1001 ts->idle_jiffies = ts->last_jiffies;
1002 nohz_balance_enter_idle(cpu);
1005 tick_nohz_retain_tick(ts);
1010 * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1012 * When the next event is more than a tick into the future, stop the idle tick
1014 void tick_nohz_idle_stop_tick(void)
1016 __tick_nohz_idle_stop_tick(this_cpu_ptr(&tick_cpu_sched));
1019 void tick_nohz_idle_retain_tick(void)
1021 tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1023 * Undo the effect of get_next_timer_interrupt() called from
1024 * tick_nohz_next_event().
1030 * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1032 * Called when we start the idle loop.
1034 void tick_nohz_idle_enter(void)
1036 struct tick_sched *ts;
1038 lockdep_assert_irqs_enabled();
1040 local_irq_disable();
1042 ts = this_cpu_ptr(&tick_cpu_sched);
1044 WARN_ON_ONCE(ts->timer_expires_base);
1047 tick_nohz_start_idle(ts);
1053 * tick_nohz_irq_exit - update next tick event from interrupt exit
1055 * When an interrupt fires while we are idle and it doesn't cause
1056 * a reschedule, it may still add, modify or delete a timer, enqueue
1057 * an RCU callback, etc...
1058 * So we need to re-calculate and reprogram the next tick event.
1060 void tick_nohz_irq_exit(void)
1062 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1065 tick_nohz_start_idle(ts);
1067 tick_nohz_full_update_tick(ts);
1071 * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1073 bool tick_nohz_idle_got_tick(void)
1075 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1077 if (ts->got_idle_tick) {
1078 ts->got_idle_tick = 0;
1085 * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1086 * or the tick, whatever that expires first. Note that, if the tick has been
1087 * stopped, it returns the next hrtimer.
1089 * Called from power state control code with interrupts disabled
1091 ktime_t tick_nohz_get_next_hrtimer(void)
1093 return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1097 * tick_nohz_get_sleep_length - return the expected length of the current sleep
1098 * @delta_next: duration until the next event if the tick cannot be stopped
1100 * Called from power state control code with interrupts disabled
1102 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1104 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1105 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1106 int cpu = smp_processor_id();
1108 * The idle entry time is expected to be a sufficient approximation of
1109 * the current time at this point.
1111 ktime_t now = ts->idle_entrytime;
1114 WARN_ON_ONCE(!ts->inidle);
1116 *delta_next = ktime_sub(dev->next_event, now);
1118 if (!can_stop_idle_tick(cpu, ts))
1121 next_event = tick_nohz_next_event(ts, cpu);
1126 * If the next highres timer to expire is earlier than next_event, the
1127 * idle governor needs to know that.
1129 next_event = min_t(u64, next_event,
1130 hrtimer_next_event_without(&ts->sched_timer));
1132 return ktime_sub(next_event, now);
1136 * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1137 * for a particular CPU.
1139 * Called from the schedutil frequency scaling governor in scheduler context.
1141 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1143 struct tick_sched *ts = tick_get_tick_sched(cpu);
1145 return ts->idle_calls;
1149 * tick_nohz_get_idle_calls - return the current idle calls counter value
1151 * Called from the schedutil frequency scaling governor in scheduler context.
1153 unsigned long tick_nohz_get_idle_calls(void)
1155 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1157 return ts->idle_calls;
1160 static void tick_nohz_account_idle_ticks(struct tick_sched *ts)
1162 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
1163 unsigned long ticks;
1165 if (vtime_accounting_cpu_enabled())
1168 * We stopped the tick in idle. Update process times would miss the
1169 * time we slept as update_process_times does only a 1 tick
1170 * accounting. Enforce that this is accounted to idle !
1172 ticks = jiffies - ts->idle_jiffies;
1174 * We might be one off. Do not randomly account a huge number of ticks!
1176 if (ticks && ticks < LONG_MAX)
1177 account_idle_ticks(ticks);
1181 static void __tick_nohz_idle_restart_tick(struct tick_sched *ts, ktime_t now)
1183 tick_nohz_restart_sched_tick(ts, now);
1184 tick_nohz_account_idle_ticks(ts);
1187 void tick_nohz_idle_restart_tick(void)
1189 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1191 if (ts->tick_stopped)
1192 __tick_nohz_idle_restart_tick(ts, ktime_get());
1196 * tick_nohz_idle_exit - restart the idle tick from the idle task
1198 * Restart the idle tick when the CPU is woken up from idle
1199 * This also exit the RCU extended quiescent state. The CPU
1200 * can use RCU again after this function is called.
1202 void tick_nohz_idle_exit(void)
1204 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1205 bool idle_active, tick_stopped;
1208 local_irq_disable();
1210 WARN_ON_ONCE(!ts->inidle);
1211 WARN_ON_ONCE(ts->timer_expires_base);
1214 idle_active = ts->idle_active;
1215 tick_stopped = ts->tick_stopped;
1217 if (idle_active || tick_stopped)
1221 tick_nohz_stop_idle(ts, now);
1224 __tick_nohz_idle_restart_tick(ts, now);
1230 * The nohz low res interrupt handler
1232 static void tick_nohz_handler(struct clock_event_device *dev)
1234 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1235 struct pt_regs *regs = get_irq_regs();
1236 ktime_t now = ktime_get();
1238 dev->next_event = KTIME_MAX;
1240 tick_sched_do_timer(ts, now);
1241 tick_sched_handle(ts, regs);
1243 /* No need to reprogram if we are running tickless */
1244 if (unlikely(ts->tick_stopped))
1247 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1248 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1251 static inline void tick_nohz_activate(struct tick_sched *ts, int mode)
1253 if (!tick_nohz_enabled)
1255 ts->nohz_mode = mode;
1256 /* One update is enough */
1257 if (!test_and_set_bit(0, &tick_nohz_active))
1258 timers_update_nohz();
1262 * tick_nohz_switch_to_nohz - switch to nohz mode
1264 static void tick_nohz_switch_to_nohz(void)
1266 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1269 if (!tick_nohz_enabled)
1272 if (tick_switch_to_oneshot(tick_nohz_handler))
1276 * Recycle the hrtimer in ts, so we can share the
1277 * hrtimer_forward with the highres code.
1279 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1280 /* Get the next period */
1281 next = tick_init_jiffy_update();
1283 hrtimer_set_expires(&ts->sched_timer, next);
1284 hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1285 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1286 tick_nohz_activate(ts, NOHZ_MODE_LOWRES);
1289 static inline void tick_nohz_irq_enter(void)
1291 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1294 if (!ts->idle_active && !ts->tick_stopped)
1297 if (ts->idle_active)
1298 tick_nohz_stop_idle(ts, now);
1299 if (ts->tick_stopped)
1300 tick_nohz_update_jiffies(now);
1305 static inline void tick_nohz_switch_to_nohz(void) { }
1306 static inline void tick_nohz_irq_enter(void) { }
1307 static inline void tick_nohz_activate(struct tick_sched *ts, int mode) { }
1309 #endif /* CONFIG_NO_HZ_COMMON */
1312 * Called from irq_enter to notify about the possible interruption of idle()
1314 void tick_irq_enter(void)
1316 tick_check_oneshot_broadcast_this_cpu();
1317 tick_nohz_irq_enter();
1321 * High resolution timer specific code
1323 #ifdef CONFIG_HIGH_RES_TIMERS
1325 * We rearm the timer until we get disabled by the idle code.
1326 * Called with interrupts disabled.
1328 static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
1330 struct tick_sched *ts =
1331 container_of(timer, struct tick_sched, sched_timer);
1332 struct pt_regs *regs = get_irq_regs();
1333 ktime_t now = ktime_get();
1335 tick_sched_do_timer(ts, now);
1338 * Do not call, when we are not in irq context and have
1339 * no valid regs pointer
1342 tick_sched_handle(ts, regs);
1346 /* No need to reprogram if we are in idle or full dynticks mode */
1347 if (unlikely(ts->tick_stopped))
1348 return HRTIMER_NORESTART;
1350 hrtimer_forward(timer, now, TICK_NSEC);
1352 return HRTIMER_RESTART;
1355 static int sched_skew_tick;
1357 static int __init skew_tick(char *str)
1359 get_option(&str, &sched_skew_tick);
1363 early_param("skew_tick", skew_tick);
1366 * tick_setup_sched_timer - setup the tick emulation timer
1368 void tick_setup_sched_timer(void)
1370 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1371 ktime_t now = ktime_get();
1374 * Emulate tick processing via per-CPU hrtimers:
1376 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1377 ts->sched_timer.function = tick_sched_timer;
1379 /* Get the next period (per-CPU) */
1380 hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1382 /* Offset the tick to avert jiffies_lock contention. */
1383 if (sched_skew_tick) {
1384 u64 offset = TICK_NSEC >> 1;
1385 do_div(offset, num_possible_cpus());
1386 offset *= smp_processor_id();
1387 hrtimer_add_expires_ns(&ts->sched_timer, offset);
1390 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1391 hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1392 tick_nohz_activate(ts, NOHZ_MODE_HIGHRES);
1394 #endif /* HIGH_RES_TIMERS */
1396 #if defined CONFIG_NO_HZ_COMMON || defined CONFIG_HIGH_RES_TIMERS
1397 void tick_cancel_sched_timer(int cpu)
1399 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1400 ktime_t idle_sleeptime, iowait_sleeptime;
1401 unsigned long idle_calls, idle_sleeps;
1403 # ifdef CONFIG_HIGH_RES_TIMERS
1404 if (ts->sched_timer.base)
1405 hrtimer_cancel(&ts->sched_timer);
1408 idle_sleeptime = ts->idle_sleeptime;
1409 iowait_sleeptime = ts->iowait_sleeptime;
1410 idle_calls = ts->idle_calls;
1411 idle_sleeps = ts->idle_sleeps;
1412 memset(ts, 0, sizeof(*ts));
1413 ts->idle_sleeptime = idle_sleeptime;
1414 ts->iowait_sleeptime = iowait_sleeptime;
1415 ts->idle_calls = idle_calls;
1416 ts->idle_sleeps = idle_sleeps;
1421 * Async notification about clocksource changes
1423 void tick_clock_notify(void)
1427 for_each_possible_cpu(cpu)
1428 set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1432 * Async notification about clock event changes
1434 void tick_oneshot_notify(void)
1436 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1438 set_bit(0, &ts->check_clocks);
1442 * Check, if a change happened, which makes oneshot possible.
1444 * Called cyclic from the hrtimer softirq (driven by the timer
1445 * softirq) allow_nohz signals, that we can switch into low-res nohz
1446 * mode, because high resolution timers are disabled (either compile
1447 * or runtime). Called with interrupts disabled.
1449 int tick_check_oneshot_change(int allow_nohz)
1451 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1453 if (!test_and_clear_bit(0, &ts->check_clocks))
1456 if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
1459 if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1465 tick_nohz_switch_to_nohz();