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. Write access must hold
48 * jiffies_lock and jiffies_seq. tick_nohz_next_event() needs to get a
49 * consistent view of jiffies and last_jiffies_update.
51 static ktime_t last_jiffies_update;
54 * Must be called with interrupts disabled !
56 static void tick_do_update_jiffies64(ktime_t now)
58 unsigned long ticks = 1;
62 * Do a quick check without holding jiffies_lock. The READ_ONCE()
63 * pairs with the update done later in this function.
65 * This is also an intentional data race which is even safe on
66 * 32bit in theory. If there is a concurrent update then the check
67 * might give a random answer. It does not matter because if it
68 * returns then the concurrent update is already taking care, if it
69 * falls through then it will pointlessly contend on jiffies_lock.
71 * Though there is one nasty case on 32bit due to store tearing of
72 * the 64bit value. If the first 32bit store makes the quick check
73 * return on all other CPUs and the writing CPU context gets
74 * delayed to complete the second store (scheduled out on virt)
75 * then jiffies can become stale for up to ~2^32 nanoseconds
76 * without noticing. After that point all CPUs will wait for
79 * OTOH, this is not any different than the situation with NOHZ=off
80 * where one CPU is responsible for updating jiffies and
81 * timekeeping. If that CPU goes out for lunch then all other CPUs
82 * will operate on stale jiffies until it decides to come back.
84 if (ktime_before(now, READ_ONCE(tick_next_period)))
87 /* Reevaluate with jiffies_lock held */
88 raw_spin_lock(&jiffies_lock);
89 if (ktime_before(now, tick_next_period)) {
90 raw_spin_unlock(&jiffies_lock);
94 write_seqcount_begin(&jiffies_seq);
96 delta = ktime_sub(now, tick_next_period);
97 if (unlikely(delta >= tick_period)) {
98 /* Slow path for long idle sleep times */
99 s64 incr = ktime_to_ns(tick_period);
101 ticks += ktime_divns(delta, incr);
103 last_jiffies_update = ktime_add_ns(last_jiffies_update,
106 last_jiffies_update = ktime_add(last_jiffies_update,
113 * Keep the tick_next_period variable up to date. WRITE_ONCE()
114 * pairs with the READ_ONCE() in the lockless quick check above.
116 WRITE_ONCE(tick_next_period,
117 ktime_add(last_jiffies_update, tick_period));
119 write_seqcount_end(&jiffies_seq);
120 raw_spin_unlock(&jiffies_lock);
125 * Initialize and return retrieve the jiffies update.
127 static ktime_t tick_init_jiffy_update(void)
131 raw_spin_lock(&jiffies_lock);
132 write_seqcount_begin(&jiffies_seq);
133 /* Did we start the jiffies update yet ? */
134 if (last_jiffies_update == 0)
135 last_jiffies_update = tick_next_period;
136 period = last_jiffies_update;
137 write_seqcount_end(&jiffies_seq);
138 raw_spin_unlock(&jiffies_lock);
142 static void tick_sched_do_timer(struct tick_sched *ts, ktime_t now)
144 int cpu = smp_processor_id();
146 #ifdef CONFIG_NO_HZ_COMMON
148 * Check if the do_timer duty was dropped. We don't care about
149 * concurrency: This happens only when the CPU in charge went
150 * into a long sleep. If two CPUs happen to assign themselves to
151 * this duty, then the jiffies update is still serialized by
154 * If nohz_full is enabled, this should not happen because the
155 * tick_do_timer_cpu never relinquishes.
157 if (unlikely(tick_do_timer_cpu == TICK_DO_TIMER_NONE)) {
158 #ifdef CONFIG_NO_HZ_FULL
159 WARN_ON(tick_nohz_full_running);
161 tick_do_timer_cpu = cpu;
165 /* Check, if the jiffies need an update */
166 if (tick_do_timer_cpu == cpu)
167 tick_do_update_jiffies64(now);
170 ts->got_idle_tick = 1;
173 static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
175 #ifdef CONFIG_NO_HZ_COMMON
177 * When we are idle and the tick is stopped, we have to touch
178 * the watchdog as we might not schedule for a really long
179 * time. This happens on complete idle SMP systems while
180 * waiting on the login prompt. We also increment the "start of
181 * idle" jiffy stamp so the idle accounting adjustment we do
182 * when we go busy again does not account too much ticks.
184 if (ts->tick_stopped) {
185 touch_softlockup_watchdog_sched();
186 if (is_idle_task(current))
189 * In case the current tick fired too early past its expected
190 * expiration, make sure we don't bypass the next clock reprogramming
191 * to the same deadline.
196 update_process_times(user_mode(regs));
197 profile_tick(CPU_PROFILING);
201 #ifdef CONFIG_NO_HZ_FULL
202 cpumask_var_t tick_nohz_full_mask;
203 bool tick_nohz_full_running;
204 EXPORT_SYMBOL_GPL(tick_nohz_full_running);
205 static atomic_t tick_dep_mask;
207 static bool check_tick_dependency(atomic_t *dep)
209 int val = atomic_read(dep);
211 if (val & TICK_DEP_MASK_POSIX_TIMER) {
212 trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
216 if (val & TICK_DEP_MASK_PERF_EVENTS) {
217 trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
221 if (val & TICK_DEP_MASK_SCHED) {
222 trace_tick_stop(0, TICK_DEP_MASK_SCHED);
226 if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
227 trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
231 if (val & TICK_DEP_MASK_RCU) {
232 trace_tick_stop(0, TICK_DEP_MASK_RCU);
239 static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
241 lockdep_assert_irqs_disabled();
243 if (unlikely(!cpu_online(cpu)))
246 if (check_tick_dependency(&tick_dep_mask))
249 if (check_tick_dependency(&ts->tick_dep_mask))
252 if (check_tick_dependency(¤t->tick_dep_mask))
255 if (check_tick_dependency(¤t->signal->tick_dep_mask))
261 static void nohz_full_kick_func(struct irq_work *work)
263 /* Empty, the tick restart happens on tick_nohz_irq_exit() */
266 static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) = {
267 .func = nohz_full_kick_func,
268 .flags = ATOMIC_INIT(IRQ_WORK_HARD_IRQ),
272 * Kick this CPU if it's full dynticks in order to force it to
273 * re-evaluate its dependency on the tick and restart it if necessary.
274 * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
277 static void tick_nohz_full_kick(void)
279 if (!tick_nohz_full_cpu(smp_processor_id()))
282 irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
286 * Kick the CPU if it's full dynticks in order to force it to
287 * re-evaluate its dependency on the tick and restart it if necessary.
289 void tick_nohz_full_kick_cpu(int cpu)
291 if (!tick_nohz_full_cpu(cpu))
294 irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
298 * Kick all full dynticks CPUs in order to force these to re-evaluate
299 * their dependency on the tick and restart it if necessary.
301 static void tick_nohz_full_kick_all(void)
305 if (!tick_nohz_full_running)
309 for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
310 tick_nohz_full_kick_cpu(cpu);
314 static void tick_nohz_dep_set_all(atomic_t *dep,
315 enum tick_dep_bits bit)
319 prev = atomic_fetch_or(BIT(bit), dep);
321 tick_nohz_full_kick_all();
325 * Set a global tick dependency. Used by perf events that rely on freq and
328 void tick_nohz_dep_set(enum tick_dep_bits bit)
330 tick_nohz_dep_set_all(&tick_dep_mask, bit);
333 void tick_nohz_dep_clear(enum tick_dep_bits bit)
335 atomic_andnot(BIT(bit), &tick_dep_mask);
339 * Set per-CPU tick dependency. Used by scheduler and perf events in order to
340 * manage events throttling.
342 void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
345 struct tick_sched *ts;
347 ts = per_cpu_ptr(&tick_cpu_sched, cpu);
349 prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
352 /* Perf needs local kick that is NMI safe */
353 if (cpu == smp_processor_id()) {
354 tick_nohz_full_kick();
356 /* Remote irq work not NMI-safe */
357 if (!WARN_ON_ONCE(in_nmi()))
358 tick_nohz_full_kick_cpu(cpu);
363 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
365 void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
367 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
369 atomic_andnot(BIT(bit), &ts->tick_dep_mask);
371 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
374 * Set a per-task tick dependency. RCU need this. Also posix CPU timers
375 * in order to elapse per task timers.
377 void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
379 if (!atomic_fetch_or(BIT(bit), &tsk->tick_dep_mask)) {
380 if (tsk == current) {
382 tick_nohz_full_kick();
386 * Some future tick_nohz_full_kick_task()
387 * should optimize this.
389 tick_nohz_full_kick_all();
393 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_task);
395 void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
397 atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
399 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_task);
402 * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
403 * per process timers.
405 void tick_nohz_dep_set_signal(struct signal_struct *sig, enum tick_dep_bits bit)
407 tick_nohz_dep_set_all(&sig->tick_dep_mask, bit);
410 void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
412 atomic_andnot(BIT(bit), &sig->tick_dep_mask);
416 * Re-evaluate the need for the tick as we switch the current task.
417 * It might need the tick due to per task/process properties:
418 * perf events, posix CPU timers, ...
420 void __tick_nohz_task_switch(void)
423 struct tick_sched *ts;
425 local_irq_save(flags);
427 if (!tick_nohz_full_cpu(smp_processor_id()))
430 ts = this_cpu_ptr(&tick_cpu_sched);
432 if (ts->tick_stopped) {
433 if (atomic_read(¤t->tick_dep_mask) ||
434 atomic_read(¤t->signal->tick_dep_mask))
435 tick_nohz_full_kick();
438 local_irq_restore(flags);
441 /* Get the boot-time nohz CPU list from the kernel parameters. */
442 void __init tick_nohz_full_setup(cpumask_var_t cpumask)
444 alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
445 cpumask_copy(tick_nohz_full_mask, cpumask);
446 tick_nohz_full_running = true;
448 EXPORT_SYMBOL_GPL(tick_nohz_full_setup);
450 static int tick_nohz_cpu_down(unsigned int cpu)
453 * The tick_do_timer_cpu CPU handles housekeeping duty (unbound
454 * timers, workqueues, timekeeping, ...) on behalf of full dynticks
455 * CPUs. It must remain online when nohz full is enabled.
457 if (tick_nohz_full_running && tick_do_timer_cpu == cpu)
462 void __init tick_nohz_init(void)
466 if (!tick_nohz_full_running)
470 * Full dynticks uses irq work to drive the tick rescheduling on safe
471 * locking contexts. But then we need irq work to raise its own
472 * interrupts to avoid circular dependency on the tick
474 if (!arch_irq_work_has_interrupt()) {
475 pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support irq work self-IPIs\n");
476 cpumask_clear(tick_nohz_full_mask);
477 tick_nohz_full_running = false;
481 if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
482 !IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
483 cpu = smp_processor_id();
485 if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
486 pr_warn("NO_HZ: Clearing %d from nohz_full range "
487 "for timekeeping\n", cpu);
488 cpumask_clear_cpu(cpu, tick_nohz_full_mask);
492 for_each_cpu(cpu, tick_nohz_full_mask)
493 context_tracking_cpu_set(cpu);
495 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
496 "kernel/nohz:predown", NULL,
499 pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
500 cpumask_pr_args(tick_nohz_full_mask));
505 * NOHZ - aka dynamic tick functionality
507 #ifdef CONFIG_NO_HZ_COMMON
511 bool tick_nohz_enabled __read_mostly = true;
512 unsigned long tick_nohz_active __read_mostly;
514 * Enable / Disable tickless mode
516 static int __init setup_tick_nohz(char *str)
518 return (kstrtobool(str, &tick_nohz_enabled) == 0);
521 __setup("nohz=", setup_tick_nohz);
523 bool tick_nohz_tick_stopped(void)
525 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
527 return ts->tick_stopped;
530 bool tick_nohz_tick_stopped_cpu(int cpu)
532 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
534 return ts->tick_stopped;
538 * tick_nohz_update_jiffies - update jiffies when idle was interrupted
540 * Called from interrupt entry when the CPU was idle
542 * In case the sched_tick was stopped on this CPU, we have to check if jiffies
543 * must be updated. Otherwise an interrupt handler could use a stale jiffy
544 * value. We do this unconditionally on any CPU, as we don't know whether the
545 * CPU, which has the update task assigned is in a long sleep.
547 static void tick_nohz_update_jiffies(ktime_t now)
551 __this_cpu_write(tick_cpu_sched.idle_waketime, now);
553 local_irq_save(flags);
554 tick_do_update_jiffies64(now);
555 local_irq_restore(flags);
557 touch_softlockup_watchdog_sched();
561 * Updates the per-CPU time idle statistics counters
564 update_ts_time_stats(int cpu, struct tick_sched *ts, ktime_t now, u64 *last_update_time)
568 if (ts->idle_active) {
569 delta = ktime_sub(now, ts->idle_entrytime);
570 if (nr_iowait_cpu(cpu) > 0)
571 ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
573 ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
574 ts->idle_entrytime = now;
577 if (last_update_time)
578 *last_update_time = ktime_to_us(now);
582 static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
584 update_ts_time_stats(smp_processor_id(), ts, now, NULL);
587 sched_clock_idle_wakeup_event();
590 static void tick_nohz_start_idle(struct tick_sched *ts)
592 ts->idle_entrytime = ktime_get();
594 sched_clock_idle_sleep_event();
598 * get_cpu_idle_time_us - get the total idle time of a CPU
599 * @cpu: CPU number to query
600 * @last_update_time: variable to store update time in. Do not update
603 * Return the cumulative idle time (since boot) for a given
604 * CPU, in microseconds.
606 * This time is measured via accounting rather than sampling,
607 * and is as accurate as ktime_get() is.
609 * This function returns -1 if NOHZ is not enabled.
611 u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
613 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
616 if (!tick_nohz_active)
620 if (last_update_time) {
621 update_ts_time_stats(cpu, ts, now, last_update_time);
622 idle = ts->idle_sleeptime;
624 if (ts->idle_active && !nr_iowait_cpu(cpu)) {
625 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
627 idle = ktime_add(ts->idle_sleeptime, delta);
629 idle = ts->idle_sleeptime;
633 return ktime_to_us(idle);
636 EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
639 * get_cpu_iowait_time_us - get the total iowait time of a CPU
640 * @cpu: CPU number to query
641 * @last_update_time: variable to store update time in. Do not update
644 * Return the cumulative iowait time (since boot) for a given
645 * CPU, in microseconds.
647 * This time is measured via accounting rather than sampling,
648 * and is as accurate as ktime_get() is.
650 * This function returns -1 if NOHZ is not enabled.
652 u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
654 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
657 if (!tick_nohz_active)
661 if (last_update_time) {
662 update_ts_time_stats(cpu, ts, now, last_update_time);
663 iowait = ts->iowait_sleeptime;
665 if (ts->idle_active && nr_iowait_cpu(cpu) > 0) {
666 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
668 iowait = ktime_add(ts->iowait_sleeptime, delta);
670 iowait = ts->iowait_sleeptime;
674 return ktime_to_us(iowait);
676 EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
678 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
680 hrtimer_cancel(&ts->sched_timer);
681 hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
683 /* Forward the time to expire in the future */
684 hrtimer_forward(&ts->sched_timer, now, tick_period);
686 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
687 hrtimer_start_expires(&ts->sched_timer,
688 HRTIMER_MODE_ABS_PINNED_HARD);
690 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
694 * Reset to make sure next tick stop doesn't get fooled by past
695 * cached clock deadline.
700 static inline bool local_timer_softirq_pending(void)
702 return local_softirq_pending() & BIT(TIMER_SOFTIRQ);
705 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
707 u64 basemono, next_tick, next_tmr, next_rcu, delta, expires;
708 unsigned long basejiff;
711 /* Read jiffies and the time when jiffies were updated last */
713 seq = read_seqcount_begin(&jiffies_seq);
714 basemono = last_jiffies_update;
716 } while (read_seqcount_retry(&jiffies_seq, seq));
717 ts->last_jiffies = basejiff;
718 ts->timer_expires_base = basemono;
721 * Keep the periodic tick, when RCU, architecture or irq_work
723 * Aside of that check whether the local timer softirq is
724 * pending. If so its a bad idea to call get_next_timer_interrupt()
725 * because there is an already expired timer, so it will request
726 * immeditate expiry, which rearms the hardware timer with a
727 * minimal delta which brings us back to this place
728 * immediately. Lather, rinse and repeat...
730 if (rcu_needs_cpu(basemono, &next_rcu) || arch_needs_cpu() ||
731 irq_work_needs_cpu() || local_timer_softirq_pending()) {
732 next_tick = basemono + TICK_NSEC;
735 * Get the next pending timer. If high resolution
736 * timers are enabled this only takes the timer wheel
737 * timers into account. If high resolution timers are
738 * disabled this also looks at the next expiring
741 next_tmr = get_next_timer_interrupt(basejiff, basemono);
742 ts->next_timer = next_tmr;
743 /* Take the next rcu event into account */
744 next_tick = next_rcu < next_tmr ? next_rcu : next_tmr;
748 * If the tick is due in the next period, keep it ticking or
749 * force prod the timer.
751 delta = next_tick - basemono;
752 if (delta <= (u64)TICK_NSEC) {
754 * Tell the timer code that the base is not idle, i.e. undo
755 * the effect of get_next_timer_interrupt():
759 * We've not stopped the tick yet, and there's a timer in the
760 * next period, so no point in stopping it either, bail.
762 if (!ts->tick_stopped) {
763 ts->timer_expires = 0;
769 * If this CPU is the one which had the do_timer() duty last, we limit
770 * the sleep time to the timekeeping max_deferment value.
771 * Otherwise we can sleep as long as we want.
773 delta = timekeeping_max_deferment();
774 if (cpu != tick_do_timer_cpu &&
775 (tick_do_timer_cpu != TICK_DO_TIMER_NONE || !ts->do_timer_last))
778 /* Calculate the next expiry time */
779 if (delta < (KTIME_MAX - basemono))
780 expires = basemono + delta;
784 ts->timer_expires = min_t(u64, expires, next_tick);
787 return ts->timer_expires;
790 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
792 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
793 u64 basemono = ts->timer_expires_base;
794 u64 expires = ts->timer_expires;
795 ktime_t tick = expires;
797 /* Make sure we won't be trying to stop it twice in a row. */
798 ts->timer_expires_base = 0;
801 * If this CPU is the one which updates jiffies, then give up
802 * the assignment and let it be taken by the CPU which runs
803 * the tick timer next, which might be this CPU as well. If we
804 * don't drop this here the jiffies might be stale and
805 * do_timer() never invoked. Keep track of the fact that it
806 * was the one which had the do_timer() duty last.
808 if (cpu == tick_do_timer_cpu) {
809 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
810 ts->do_timer_last = 1;
811 } else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
812 ts->do_timer_last = 0;
815 /* Skip reprogram of event if its not changed */
816 if (ts->tick_stopped && (expires == ts->next_tick)) {
817 /* Sanity check: make sure clockevent is actually programmed */
818 if (tick == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
822 printk_once("basemono: %llu ts->next_tick: %llu dev->next_event: %llu timer->active: %d timer->expires: %llu\n",
823 basemono, ts->next_tick, dev->next_event,
824 hrtimer_active(&ts->sched_timer), hrtimer_get_expires(&ts->sched_timer));
828 * nohz_stop_sched_tick can be called several times before
829 * the nohz_restart_sched_tick is called. This happens when
830 * interrupts arrive which do not cause a reschedule. In the
831 * first call we save the current tick time, so we can restart
832 * the scheduler tick in nohz_restart_sched_tick.
834 if (!ts->tick_stopped) {
835 calc_load_nohz_start();
838 ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
839 ts->tick_stopped = 1;
840 trace_tick_stop(1, TICK_DEP_MASK_NONE);
843 ts->next_tick = tick;
846 * If the expiration time == KTIME_MAX, then we simply stop
849 if (unlikely(expires == KTIME_MAX)) {
850 if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
851 hrtimer_cancel(&ts->sched_timer);
855 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
856 hrtimer_start(&ts->sched_timer, tick,
857 HRTIMER_MODE_ABS_PINNED_HARD);
859 hrtimer_set_expires(&ts->sched_timer, tick);
860 tick_program_event(tick, 1);
864 static void tick_nohz_retain_tick(struct tick_sched *ts)
866 ts->timer_expires_base = 0;
869 #ifdef CONFIG_NO_HZ_FULL
870 static void tick_nohz_stop_sched_tick(struct tick_sched *ts, int cpu)
872 if (tick_nohz_next_event(ts, cpu))
873 tick_nohz_stop_tick(ts, cpu);
875 tick_nohz_retain_tick(ts);
877 #endif /* CONFIG_NO_HZ_FULL */
879 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
881 /* Update jiffies first */
882 tick_do_update_jiffies64(now);
885 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
886 * the clock forward checks in the enqueue path:
890 calc_load_nohz_stop();
891 touch_softlockup_watchdog_sched();
893 * Cancel the scheduled timer and restore the tick
895 ts->tick_stopped = 0;
896 ts->idle_exittime = now;
898 tick_nohz_restart(ts, now);
901 static void tick_nohz_full_update_tick(struct tick_sched *ts)
903 #ifdef CONFIG_NO_HZ_FULL
904 int cpu = smp_processor_id();
906 if (!tick_nohz_full_cpu(cpu))
909 if (!ts->tick_stopped && ts->nohz_mode == NOHZ_MODE_INACTIVE)
912 if (can_stop_full_tick(cpu, ts))
913 tick_nohz_stop_sched_tick(ts, cpu);
914 else if (ts->tick_stopped)
915 tick_nohz_restart_sched_tick(ts, ktime_get());
919 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
922 * If this CPU is offline and it is the one which updates
923 * jiffies, then give up the assignment and let it be taken by
924 * the CPU which runs the tick timer next. If we don't drop
925 * this here the jiffies might be stale and do_timer() never
928 if (unlikely(!cpu_online(cpu))) {
929 if (cpu == tick_do_timer_cpu)
930 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
932 * Make sure the CPU doesn't get fooled by obsolete tick
933 * deadline if it comes back online later.
939 if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
945 if (unlikely(local_softirq_pending())) {
946 static int ratelimit;
948 if (ratelimit < 10 &&
949 (local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
950 pr_warn("NOHZ tick-stop error: Non-RCU local softirq work is pending, handler #%02x!!!\n",
951 (unsigned int) local_softirq_pending());
957 if (tick_nohz_full_enabled()) {
959 * Keep the tick alive to guarantee timekeeping progression
960 * if there are full dynticks CPUs around
962 if (tick_do_timer_cpu == cpu)
965 * Boot safety: make sure the timekeeping duty has been
966 * assigned before entering dyntick-idle mode,
967 * tick_do_timer_cpu is TICK_DO_TIMER_BOOT
969 if (unlikely(tick_do_timer_cpu == TICK_DO_TIMER_BOOT))
972 /* Should not happen for nohz-full */
973 if (WARN_ON_ONCE(tick_do_timer_cpu == TICK_DO_TIMER_NONE))
980 static void __tick_nohz_idle_stop_tick(struct tick_sched *ts)
983 int cpu = smp_processor_id();
986 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
987 * tick timer expiration time is known already.
989 if (ts->timer_expires_base)
990 expires = ts->timer_expires;
991 else if (can_stop_idle_tick(cpu, ts))
992 expires = tick_nohz_next_event(ts, cpu);
999 int was_stopped = ts->tick_stopped;
1001 tick_nohz_stop_tick(ts, cpu);
1004 ts->idle_expires = expires;
1006 if (!was_stopped && ts->tick_stopped) {
1007 ts->idle_jiffies = ts->last_jiffies;
1008 nohz_balance_enter_idle(cpu);
1011 tick_nohz_retain_tick(ts);
1016 * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1018 * When the next event is more than a tick into the future, stop the idle tick
1020 void tick_nohz_idle_stop_tick(void)
1022 __tick_nohz_idle_stop_tick(this_cpu_ptr(&tick_cpu_sched));
1025 void tick_nohz_idle_retain_tick(void)
1027 tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1029 * Undo the effect of get_next_timer_interrupt() called from
1030 * tick_nohz_next_event().
1036 * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1038 * Called when we start the idle loop.
1040 void tick_nohz_idle_enter(void)
1042 struct tick_sched *ts;
1044 lockdep_assert_irqs_enabled();
1046 local_irq_disable();
1048 ts = this_cpu_ptr(&tick_cpu_sched);
1050 WARN_ON_ONCE(ts->timer_expires_base);
1053 tick_nohz_start_idle(ts);
1059 * tick_nohz_irq_exit - update next tick event from interrupt exit
1061 * When an interrupt fires while we are idle and it doesn't cause
1062 * a reschedule, it may still add, modify or delete a timer, enqueue
1063 * an RCU callback, etc...
1064 * So we need to re-calculate and reprogram the next tick event.
1066 void tick_nohz_irq_exit(void)
1068 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1071 tick_nohz_start_idle(ts);
1073 tick_nohz_full_update_tick(ts);
1077 * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1079 bool tick_nohz_idle_got_tick(void)
1081 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1083 if (ts->got_idle_tick) {
1084 ts->got_idle_tick = 0;
1091 * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1092 * or the tick, whatever that expires first. Note that, if the tick has been
1093 * stopped, it returns the next hrtimer.
1095 * Called from power state control code with interrupts disabled
1097 ktime_t tick_nohz_get_next_hrtimer(void)
1099 return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1103 * tick_nohz_get_sleep_length - return the expected length of the current sleep
1104 * @delta_next: duration until the next event if the tick cannot be stopped
1106 * Called from power state control code with interrupts disabled
1108 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1110 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1111 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1112 int cpu = smp_processor_id();
1114 * The idle entry time is expected to be a sufficient approximation of
1115 * the current time at this point.
1117 ktime_t now = ts->idle_entrytime;
1120 WARN_ON_ONCE(!ts->inidle);
1122 *delta_next = ktime_sub(dev->next_event, now);
1124 if (!can_stop_idle_tick(cpu, ts))
1127 next_event = tick_nohz_next_event(ts, cpu);
1132 * If the next highres timer to expire is earlier than next_event, the
1133 * idle governor needs to know that.
1135 next_event = min_t(u64, next_event,
1136 hrtimer_next_event_without(&ts->sched_timer));
1138 return ktime_sub(next_event, now);
1142 * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1143 * for a particular CPU.
1145 * Called from the schedutil frequency scaling governor in scheduler context.
1147 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1149 struct tick_sched *ts = tick_get_tick_sched(cpu);
1151 return ts->idle_calls;
1155 * tick_nohz_get_idle_calls - return the current idle calls counter value
1157 * Called from the schedutil frequency scaling governor in scheduler context.
1159 unsigned long tick_nohz_get_idle_calls(void)
1161 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1163 return ts->idle_calls;
1166 static void tick_nohz_account_idle_ticks(struct tick_sched *ts)
1168 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
1169 unsigned long ticks;
1171 if (vtime_accounting_enabled_this_cpu())
1174 * We stopped the tick in idle. Update process times would miss the
1175 * time we slept as update_process_times does only a 1 tick
1176 * accounting. Enforce that this is accounted to idle !
1178 ticks = jiffies - ts->idle_jiffies;
1180 * We might be one off. Do not randomly account a huge number of ticks!
1182 if (ticks && ticks < LONG_MAX)
1183 account_idle_ticks(ticks);
1187 static void __tick_nohz_idle_restart_tick(struct tick_sched *ts, ktime_t now)
1189 tick_nohz_restart_sched_tick(ts, now);
1190 tick_nohz_account_idle_ticks(ts);
1193 void tick_nohz_idle_restart_tick(void)
1195 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1197 if (ts->tick_stopped)
1198 __tick_nohz_idle_restart_tick(ts, ktime_get());
1202 * tick_nohz_idle_exit - restart the idle tick from the idle task
1204 * Restart the idle tick when the CPU is woken up from idle
1205 * This also exit the RCU extended quiescent state. The CPU
1206 * can use RCU again after this function is called.
1208 void tick_nohz_idle_exit(void)
1210 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1211 bool idle_active, tick_stopped;
1214 local_irq_disable();
1216 WARN_ON_ONCE(!ts->inidle);
1217 WARN_ON_ONCE(ts->timer_expires_base);
1220 idle_active = ts->idle_active;
1221 tick_stopped = ts->tick_stopped;
1223 if (idle_active || tick_stopped)
1227 tick_nohz_stop_idle(ts, now);
1230 __tick_nohz_idle_restart_tick(ts, now);
1236 * The nohz low res interrupt handler
1238 static void tick_nohz_handler(struct clock_event_device *dev)
1240 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1241 struct pt_regs *regs = get_irq_regs();
1242 ktime_t now = ktime_get();
1244 dev->next_event = KTIME_MAX;
1246 tick_sched_do_timer(ts, now);
1247 tick_sched_handle(ts, regs);
1249 /* No need to reprogram if we are running tickless */
1250 if (unlikely(ts->tick_stopped))
1253 hrtimer_forward(&ts->sched_timer, now, tick_period);
1254 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1257 static inline void tick_nohz_activate(struct tick_sched *ts, int mode)
1259 if (!tick_nohz_enabled)
1261 ts->nohz_mode = mode;
1262 /* One update is enough */
1263 if (!test_and_set_bit(0, &tick_nohz_active))
1264 timers_update_nohz();
1268 * tick_nohz_switch_to_nohz - switch to nohz mode
1270 static void tick_nohz_switch_to_nohz(void)
1272 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1275 if (!tick_nohz_enabled)
1278 if (tick_switch_to_oneshot(tick_nohz_handler))
1282 * Recycle the hrtimer in ts, so we can share the
1283 * hrtimer_forward with the highres code.
1285 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1286 /* Get the next period */
1287 next = tick_init_jiffy_update();
1289 hrtimer_set_expires(&ts->sched_timer, next);
1290 hrtimer_forward_now(&ts->sched_timer, tick_period);
1291 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1292 tick_nohz_activate(ts, NOHZ_MODE_LOWRES);
1295 static inline void tick_nohz_irq_enter(void)
1297 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1300 if (!ts->idle_active && !ts->tick_stopped)
1303 if (ts->idle_active)
1304 tick_nohz_stop_idle(ts, now);
1305 if (ts->tick_stopped)
1306 tick_nohz_update_jiffies(now);
1311 static inline void tick_nohz_switch_to_nohz(void) { }
1312 static inline void tick_nohz_irq_enter(void) { }
1313 static inline void tick_nohz_activate(struct tick_sched *ts, int mode) { }
1315 #endif /* CONFIG_NO_HZ_COMMON */
1318 * Called from irq_enter to notify about the possible interruption of idle()
1320 void tick_irq_enter(void)
1322 tick_check_oneshot_broadcast_this_cpu();
1323 tick_nohz_irq_enter();
1327 * High resolution timer specific code
1329 #ifdef CONFIG_HIGH_RES_TIMERS
1331 * We rearm the timer until we get disabled by the idle code.
1332 * Called with interrupts disabled.
1334 static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
1336 struct tick_sched *ts =
1337 container_of(timer, struct tick_sched, sched_timer);
1338 struct pt_regs *regs = get_irq_regs();
1339 ktime_t now = ktime_get();
1341 tick_sched_do_timer(ts, now);
1344 * Do not call, when we are not in irq context and have
1345 * no valid regs pointer
1348 tick_sched_handle(ts, regs);
1352 /* No need to reprogram if we are in idle or full dynticks mode */
1353 if (unlikely(ts->tick_stopped))
1354 return HRTIMER_NORESTART;
1356 hrtimer_forward(timer, now, tick_period);
1358 return HRTIMER_RESTART;
1361 static int sched_skew_tick;
1363 static int __init skew_tick(char *str)
1365 get_option(&str, &sched_skew_tick);
1369 early_param("skew_tick", skew_tick);
1372 * tick_setup_sched_timer - setup the tick emulation timer
1374 void tick_setup_sched_timer(void)
1376 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1377 ktime_t now = ktime_get();
1380 * Emulate tick processing via per-CPU hrtimers:
1382 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1383 ts->sched_timer.function = tick_sched_timer;
1385 /* Get the next period (per-CPU) */
1386 hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1388 /* Offset the tick to avert jiffies_lock contention. */
1389 if (sched_skew_tick) {
1390 u64 offset = ktime_to_ns(tick_period) >> 1;
1391 do_div(offset, num_possible_cpus());
1392 offset *= smp_processor_id();
1393 hrtimer_add_expires_ns(&ts->sched_timer, offset);
1396 hrtimer_forward(&ts->sched_timer, now, tick_period);
1397 hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1398 tick_nohz_activate(ts, NOHZ_MODE_HIGHRES);
1400 #endif /* HIGH_RES_TIMERS */
1402 #if defined CONFIG_NO_HZ_COMMON || defined CONFIG_HIGH_RES_TIMERS
1403 void tick_cancel_sched_timer(int cpu)
1405 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1407 # ifdef CONFIG_HIGH_RES_TIMERS
1408 if (ts->sched_timer.base)
1409 hrtimer_cancel(&ts->sched_timer);
1412 memset(ts, 0, sizeof(*ts));
1417 * Async notification about clocksource changes
1419 void tick_clock_notify(void)
1423 for_each_possible_cpu(cpu)
1424 set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1428 * Async notification about clock event changes
1430 void tick_oneshot_notify(void)
1432 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1434 set_bit(0, &ts->check_clocks);
1438 * Check, if a change happened, which makes oneshot possible.
1440 * Called cyclic from the hrtimer softirq (driven by the timer
1441 * softirq) allow_nohz signals, that we can switch into low-res nohz
1442 * mode, because high resolution timers are disabled (either compile
1443 * or runtime). Called with interrupts disabled.
1445 int tick_check_oneshot_change(int allow_nohz)
1447 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1449 if (!test_and_clear_bit(0, &ts->check_clocks))
1452 if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
1455 if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1461 tick_nohz_switch_to_nohz();