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 #define MAX_STALLED_JIFFIES 5
153 static void tick_sched_do_timer(struct tick_sched *ts, ktime_t now)
155 int cpu = smp_processor_id();
157 #ifdef CONFIG_NO_HZ_COMMON
159 * Check if the do_timer duty was dropped. We don't care about
160 * concurrency: This happens only when the CPU in charge went
161 * into a long sleep. If two CPUs happen to assign themselves to
162 * this duty, then the jiffies update is still serialized by
165 * If nohz_full is enabled, this should not happen because the
166 * tick_do_timer_cpu never relinquishes.
168 if (unlikely(tick_do_timer_cpu == TICK_DO_TIMER_NONE)) {
169 #ifdef CONFIG_NO_HZ_FULL
170 WARN_ON_ONCE(tick_nohz_full_running);
172 tick_do_timer_cpu = cpu;
176 /* Check, if the jiffies need an update */
177 if (tick_do_timer_cpu == cpu)
178 tick_do_update_jiffies64(now);
181 * If jiffies update stalled for too long (timekeeper in stop_machine()
182 * or VMEXIT'ed for several msecs), force an update.
184 if (ts->last_tick_jiffies != jiffies) {
185 ts->stalled_jiffies = 0;
186 ts->last_tick_jiffies = READ_ONCE(jiffies);
188 if (++ts->stalled_jiffies == MAX_STALLED_JIFFIES) {
189 tick_do_update_jiffies64(now);
190 ts->stalled_jiffies = 0;
191 ts->last_tick_jiffies = READ_ONCE(jiffies);
196 ts->got_idle_tick = 1;
199 static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
201 #ifdef CONFIG_NO_HZ_COMMON
203 * When we are idle and the tick is stopped, we have to touch
204 * the watchdog as we might not schedule for a really long
205 * time. This happens on complete idle SMP systems while
206 * waiting on the login prompt. We also increment the "start of
207 * idle" jiffy stamp so the idle accounting adjustment we do
208 * when we go busy again does not account too much ticks.
210 if (ts->tick_stopped) {
211 touch_softlockup_watchdog_sched();
212 if (is_idle_task(current))
215 * In case the current tick fired too early past its expected
216 * expiration, make sure we don't bypass the next clock reprogramming
217 * to the same deadline.
222 update_process_times(user_mode(regs));
223 profile_tick(CPU_PROFILING);
227 #ifdef CONFIG_NO_HZ_FULL
228 cpumask_var_t tick_nohz_full_mask;
229 bool tick_nohz_full_running;
230 EXPORT_SYMBOL_GPL(tick_nohz_full_running);
231 static atomic_t tick_dep_mask;
233 static bool check_tick_dependency(atomic_t *dep)
235 int val = atomic_read(dep);
237 if (val & TICK_DEP_MASK_POSIX_TIMER) {
238 trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
242 if (val & TICK_DEP_MASK_PERF_EVENTS) {
243 trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
247 if (val & TICK_DEP_MASK_SCHED) {
248 trace_tick_stop(0, TICK_DEP_MASK_SCHED);
252 if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
253 trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
257 if (val & TICK_DEP_MASK_RCU) {
258 trace_tick_stop(0, TICK_DEP_MASK_RCU);
262 if (val & TICK_DEP_MASK_RCU_EXP) {
263 trace_tick_stop(0, TICK_DEP_MASK_RCU_EXP);
270 static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
272 lockdep_assert_irqs_disabled();
274 if (unlikely(!cpu_online(cpu)))
277 if (check_tick_dependency(&tick_dep_mask))
280 if (check_tick_dependency(&ts->tick_dep_mask))
283 if (check_tick_dependency(¤t->tick_dep_mask))
286 if (check_tick_dependency(¤t->signal->tick_dep_mask))
292 static void nohz_full_kick_func(struct irq_work *work)
294 /* Empty, the tick restart happens on tick_nohz_irq_exit() */
297 static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) = {
298 .func = nohz_full_kick_func,
299 .flags = ATOMIC_INIT(IRQ_WORK_HARD_IRQ),
303 * Kick this CPU if it's full dynticks in order to force it to
304 * re-evaluate its dependency on the tick and restart it if necessary.
305 * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
308 static void tick_nohz_full_kick(void)
310 if (!tick_nohz_full_cpu(smp_processor_id()))
313 irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
317 * Kick the CPU if it's full dynticks in order to force it to
318 * re-evaluate its dependency on the tick and restart it if necessary.
320 void tick_nohz_full_kick_cpu(int cpu)
322 if (!tick_nohz_full_cpu(cpu))
325 irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
329 * Kick all full dynticks CPUs in order to force these to re-evaluate
330 * their dependency on the tick and restart it if necessary.
332 static void tick_nohz_full_kick_all(void)
336 if (!tick_nohz_full_running)
340 for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
341 tick_nohz_full_kick_cpu(cpu);
345 static void tick_nohz_dep_set_all(atomic_t *dep,
346 enum tick_dep_bits bit)
350 prev = atomic_fetch_or(BIT(bit), dep);
352 tick_nohz_full_kick_all();
356 * Set a global tick dependency. Used by perf events that rely on freq and
359 void tick_nohz_dep_set(enum tick_dep_bits bit)
361 tick_nohz_dep_set_all(&tick_dep_mask, bit);
364 void tick_nohz_dep_clear(enum tick_dep_bits bit)
366 atomic_andnot(BIT(bit), &tick_dep_mask);
370 * Set per-CPU tick dependency. Used by scheduler and perf events in order to
371 * manage events throttling.
373 void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
376 struct tick_sched *ts;
378 ts = per_cpu_ptr(&tick_cpu_sched, cpu);
380 prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
383 /* Perf needs local kick that is NMI safe */
384 if (cpu == smp_processor_id()) {
385 tick_nohz_full_kick();
387 /* Remote irq work not NMI-safe */
388 if (!WARN_ON_ONCE(in_nmi()))
389 tick_nohz_full_kick_cpu(cpu);
394 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
396 void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
398 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
400 atomic_andnot(BIT(bit), &ts->tick_dep_mask);
402 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
405 * Set a per-task tick dependency. RCU need this. Also posix CPU timers
406 * in order to elapse per task timers.
408 void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
410 if (!atomic_fetch_or(BIT(bit), &tsk->tick_dep_mask)) {
411 if (tsk == current) {
413 tick_nohz_full_kick();
417 * Some future tick_nohz_full_kick_task()
418 * should optimize this.
420 tick_nohz_full_kick_all();
424 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_task);
426 void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
428 atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
430 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_task);
433 * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
434 * per process timers.
436 void tick_nohz_dep_set_signal(struct signal_struct *sig, enum tick_dep_bits bit)
438 tick_nohz_dep_set_all(&sig->tick_dep_mask, bit);
441 void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
443 atomic_andnot(BIT(bit), &sig->tick_dep_mask);
447 * Re-evaluate the need for the tick as we switch the current task.
448 * It might need the tick due to per task/process properties:
449 * perf events, posix CPU timers, ...
451 void __tick_nohz_task_switch(void)
454 struct tick_sched *ts;
456 local_irq_save(flags);
458 if (!tick_nohz_full_cpu(smp_processor_id()))
461 ts = this_cpu_ptr(&tick_cpu_sched);
463 if (ts->tick_stopped) {
464 if (atomic_read(¤t->tick_dep_mask) ||
465 atomic_read(¤t->signal->tick_dep_mask))
466 tick_nohz_full_kick();
469 local_irq_restore(flags);
472 /* Get the boot-time nohz CPU list from the kernel parameters. */
473 void __init tick_nohz_full_setup(cpumask_var_t cpumask)
475 alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
476 cpumask_copy(tick_nohz_full_mask, cpumask);
477 tick_nohz_full_running = true;
480 bool tick_nohz_cpu_hotpluggable(unsigned int cpu)
483 * The tick_do_timer_cpu CPU handles housekeeping duty (unbound
484 * timers, workqueues, timekeeping, ...) on behalf of full dynticks
485 * CPUs. It must remain online when nohz full is enabled.
487 if (tick_nohz_full_running && tick_do_timer_cpu == cpu)
492 static int tick_nohz_cpu_down(unsigned int cpu)
494 return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
497 void __init tick_nohz_init(void)
501 if (!tick_nohz_full_running)
505 * Full dynticks uses irq work to drive the tick rescheduling on safe
506 * locking contexts. But then we need irq work to raise its own
507 * interrupts to avoid circular dependency on the tick
509 if (!arch_irq_work_has_interrupt()) {
510 pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support irq work self-IPIs\n");
511 cpumask_clear(tick_nohz_full_mask);
512 tick_nohz_full_running = false;
516 if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
517 !IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
518 cpu = smp_processor_id();
520 if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
521 pr_warn("NO_HZ: Clearing %d from nohz_full range "
522 "for timekeeping\n", cpu);
523 cpumask_clear_cpu(cpu, tick_nohz_full_mask);
527 for_each_cpu(cpu, tick_nohz_full_mask)
528 context_tracking_cpu_set(cpu);
530 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
531 "kernel/nohz:predown", NULL,
534 pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
535 cpumask_pr_args(tick_nohz_full_mask));
540 * NOHZ - aka dynamic tick functionality
542 #ifdef CONFIG_NO_HZ_COMMON
546 bool tick_nohz_enabled __read_mostly = true;
547 unsigned long tick_nohz_active __read_mostly;
549 * Enable / Disable tickless mode
551 static int __init setup_tick_nohz(char *str)
553 return (kstrtobool(str, &tick_nohz_enabled) == 0);
556 __setup("nohz=", setup_tick_nohz);
558 bool tick_nohz_tick_stopped(void)
560 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
562 return ts->tick_stopped;
565 bool tick_nohz_tick_stopped_cpu(int cpu)
567 struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
569 return ts->tick_stopped;
573 * tick_nohz_update_jiffies - update jiffies when idle was interrupted
575 * Called from interrupt entry when the CPU was idle
577 * In case the sched_tick was stopped on this CPU, we have to check if jiffies
578 * must be updated. Otherwise an interrupt handler could use a stale jiffy
579 * value. We do this unconditionally on any CPU, as we don't know whether the
580 * CPU, which has the update task assigned is in a long sleep.
582 static void tick_nohz_update_jiffies(ktime_t now)
586 __this_cpu_write(tick_cpu_sched.idle_waketime, now);
588 local_irq_save(flags);
589 tick_do_update_jiffies64(now);
590 local_irq_restore(flags);
592 touch_softlockup_watchdog_sched();
596 * Updates the per-CPU time idle statistics counters
599 update_ts_time_stats(int cpu, struct tick_sched *ts, ktime_t now, u64 *last_update_time)
603 if (ts->idle_active) {
604 delta = ktime_sub(now, ts->idle_entrytime);
605 if (nr_iowait_cpu(cpu) > 0)
606 ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
608 ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
609 ts->idle_entrytime = now;
612 if (last_update_time)
613 *last_update_time = ktime_to_us(now);
617 static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
619 update_ts_time_stats(smp_processor_id(), ts, now, NULL);
622 sched_clock_idle_wakeup_event();
625 static void tick_nohz_start_idle(struct tick_sched *ts)
627 ts->idle_entrytime = ktime_get();
629 sched_clock_idle_sleep_event();
633 * get_cpu_idle_time_us - get the total idle time of a CPU
634 * @cpu: CPU number to query
635 * @last_update_time: variable to store update time in. Do not update
638 * Return the cumulative idle time (since boot) for a given
639 * CPU, in microseconds.
641 * This time is measured via accounting rather than sampling,
642 * and is as accurate as ktime_get() is.
644 * This function returns -1 if NOHZ is not enabled.
646 u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
648 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
651 if (!tick_nohz_active)
655 if (last_update_time) {
656 update_ts_time_stats(cpu, ts, now, last_update_time);
657 idle = ts->idle_sleeptime;
659 if (ts->idle_active && !nr_iowait_cpu(cpu)) {
660 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
662 idle = ktime_add(ts->idle_sleeptime, delta);
664 idle = ts->idle_sleeptime;
668 return ktime_to_us(idle);
671 EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
674 * get_cpu_iowait_time_us - get the total iowait time of a CPU
675 * @cpu: CPU number to query
676 * @last_update_time: variable to store update time in. Do not update
679 * Return the cumulative iowait time (since boot) for a given
680 * CPU, in microseconds.
682 * This time is measured via accounting rather than sampling,
683 * and is as accurate as ktime_get() is.
685 * This function returns -1 if NOHZ is not enabled.
687 u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
689 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
692 if (!tick_nohz_active)
696 if (last_update_time) {
697 update_ts_time_stats(cpu, ts, now, last_update_time);
698 iowait = ts->iowait_sleeptime;
700 if (ts->idle_active && nr_iowait_cpu(cpu) > 0) {
701 ktime_t delta = ktime_sub(now, ts->idle_entrytime);
703 iowait = ktime_add(ts->iowait_sleeptime, delta);
705 iowait = ts->iowait_sleeptime;
709 return ktime_to_us(iowait);
711 EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
713 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
715 hrtimer_cancel(&ts->sched_timer);
716 hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
718 /* Forward the time to expire in the future */
719 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
721 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
722 hrtimer_start_expires(&ts->sched_timer,
723 HRTIMER_MODE_ABS_PINNED_HARD);
725 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
729 * Reset to make sure next tick stop doesn't get fooled by past
730 * cached clock deadline.
735 static inline bool local_timer_softirq_pending(void)
737 return local_softirq_pending() & BIT(TIMER_SOFTIRQ);
740 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
742 u64 basemono, next_tick, next_tmr, next_rcu, delta, expires;
743 unsigned long basejiff;
746 /* Read jiffies and the time when jiffies were updated last */
748 seq = read_seqcount_begin(&jiffies_seq);
749 basemono = last_jiffies_update;
751 } while (read_seqcount_retry(&jiffies_seq, seq));
752 ts->last_jiffies = basejiff;
753 ts->timer_expires_base = basemono;
756 * Keep the periodic tick, when RCU, architecture or irq_work
758 * Aside of that check whether the local timer softirq is
759 * pending. If so its a bad idea to call get_next_timer_interrupt()
760 * because there is an already expired timer, so it will request
761 * immeditate expiry, which rearms the hardware timer with a
762 * minimal delta which brings us back to this place
763 * immediately. Lather, rinse and repeat...
765 if (rcu_needs_cpu(basemono, &next_rcu) || arch_needs_cpu() ||
766 irq_work_needs_cpu() || local_timer_softirq_pending()) {
767 next_tick = basemono + TICK_NSEC;
770 * Get the next pending timer. If high resolution
771 * timers are enabled this only takes the timer wheel
772 * timers into account. If high resolution timers are
773 * disabled this also looks at the next expiring
776 next_tmr = get_next_timer_interrupt(basejiff, basemono);
777 ts->next_timer = next_tmr;
778 /* Take the next rcu event into account */
779 next_tick = next_rcu < next_tmr ? next_rcu : next_tmr;
783 * If the tick is due in the next period, keep it ticking or
784 * force prod the timer.
786 delta = next_tick - basemono;
787 if (delta <= (u64)TICK_NSEC) {
789 * Tell the timer code that the base is not idle, i.e. undo
790 * the effect of get_next_timer_interrupt():
794 * We've not stopped the tick yet, and there's a timer in the
795 * next period, so no point in stopping it either, bail.
797 if (!ts->tick_stopped) {
798 ts->timer_expires = 0;
804 * If this CPU is the one which had the do_timer() duty last, we limit
805 * the sleep time to the timekeeping max_deferment value.
806 * Otherwise we can sleep as long as we want.
808 delta = timekeeping_max_deferment();
809 if (cpu != tick_do_timer_cpu &&
810 (tick_do_timer_cpu != TICK_DO_TIMER_NONE || !ts->do_timer_last))
813 /* Calculate the next expiry time */
814 if (delta < (KTIME_MAX - basemono))
815 expires = basemono + delta;
819 ts->timer_expires = min_t(u64, expires, next_tick);
822 return ts->timer_expires;
825 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
827 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
828 u64 basemono = ts->timer_expires_base;
829 u64 expires = ts->timer_expires;
830 ktime_t tick = expires;
832 /* Make sure we won't be trying to stop it twice in a row. */
833 ts->timer_expires_base = 0;
836 * If this CPU is the one which updates jiffies, then give up
837 * the assignment and let it be taken by the CPU which runs
838 * the tick timer next, which might be this CPU as well. If we
839 * don't drop this here the jiffies might be stale and
840 * do_timer() never invoked. Keep track of the fact that it
841 * was the one which had the do_timer() duty last.
843 if (cpu == tick_do_timer_cpu) {
844 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
845 ts->do_timer_last = 1;
846 } else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
847 ts->do_timer_last = 0;
850 /* Skip reprogram of event if its not changed */
851 if (ts->tick_stopped && (expires == ts->next_tick)) {
852 /* Sanity check: make sure clockevent is actually programmed */
853 if (tick == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
857 printk_once("basemono: %llu ts->next_tick: %llu dev->next_event: %llu timer->active: %d timer->expires: %llu\n",
858 basemono, ts->next_tick, dev->next_event,
859 hrtimer_active(&ts->sched_timer), hrtimer_get_expires(&ts->sched_timer));
863 * nohz_stop_sched_tick can be called several times before
864 * the nohz_restart_sched_tick is called. This happens when
865 * interrupts arrive which do not cause a reschedule. In the
866 * first call we save the current tick time, so we can restart
867 * the scheduler tick in nohz_restart_sched_tick.
869 if (!ts->tick_stopped) {
870 calc_load_nohz_start();
873 ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
874 ts->tick_stopped = 1;
875 trace_tick_stop(1, TICK_DEP_MASK_NONE);
878 ts->next_tick = tick;
881 * If the expiration time == KTIME_MAX, then we simply stop
884 if (unlikely(expires == KTIME_MAX)) {
885 if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
886 hrtimer_cancel(&ts->sched_timer);
888 tick_program_event(KTIME_MAX, 1);
892 if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
893 hrtimer_start(&ts->sched_timer, tick,
894 HRTIMER_MODE_ABS_PINNED_HARD);
896 hrtimer_set_expires(&ts->sched_timer, tick);
897 tick_program_event(tick, 1);
901 static void tick_nohz_retain_tick(struct tick_sched *ts)
903 ts->timer_expires_base = 0;
906 #ifdef CONFIG_NO_HZ_FULL
907 static void tick_nohz_stop_sched_tick(struct tick_sched *ts, int cpu)
909 if (tick_nohz_next_event(ts, cpu))
910 tick_nohz_stop_tick(ts, cpu);
912 tick_nohz_retain_tick(ts);
914 #endif /* CONFIG_NO_HZ_FULL */
916 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
918 /* Update jiffies first */
919 tick_do_update_jiffies64(now);
922 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
923 * the clock forward checks in the enqueue path:
927 calc_load_nohz_stop();
928 touch_softlockup_watchdog_sched();
930 * Cancel the scheduled timer and restore the tick
932 ts->tick_stopped = 0;
933 ts->idle_exittime = now;
935 tick_nohz_restart(ts, now);
938 static void tick_nohz_full_update_tick(struct tick_sched *ts)
940 #ifdef CONFIG_NO_HZ_FULL
941 int cpu = smp_processor_id();
943 if (!tick_nohz_full_cpu(cpu))
946 if (!ts->tick_stopped && ts->nohz_mode == NOHZ_MODE_INACTIVE)
949 if (can_stop_full_tick(cpu, ts))
950 tick_nohz_stop_sched_tick(ts, cpu);
951 else if (ts->tick_stopped)
952 tick_nohz_restart_sched_tick(ts, ktime_get());
956 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
959 * If this CPU is offline and it is the one which updates
960 * jiffies, then give up the assignment and let it be taken by
961 * the CPU which runs the tick timer next. If we don't drop
962 * this here the jiffies might be stale and do_timer() never
965 if (unlikely(!cpu_online(cpu))) {
966 if (cpu == tick_do_timer_cpu)
967 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
969 * Make sure the CPU doesn't get fooled by obsolete tick
970 * deadline if it comes back online later.
976 if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
982 if (unlikely(local_softirq_pending())) {
983 static int ratelimit;
985 if (ratelimit < 10 &&
986 (local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
987 pr_warn("NOHZ tick-stop error: Non-RCU local softirq work is pending, handler #%02x!!!\n",
988 (unsigned int) local_softirq_pending());
994 if (tick_nohz_full_enabled()) {
996 * Keep the tick alive to guarantee timekeeping progression
997 * if there are full dynticks CPUs around
999 if (tick_do_timer_cpu == cpu)
1002 /* Should not happen for nohz-full */
1003 if (WARN_ON_ONCE(tick_do_timer_cpu == TICK_DO_TIMER_NONE))
1010 static void __tick_nohz_idle_stop_tick(struct tick_sched *ts)
1013 int cpu = smp_processor_id();
1016 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
1017 * tick timer expiration time is known already.
1019 if (ts->timer_expires_base)
1020 expires = ts->timer_expires;
1021 else if (can_stop_idle_tick(cpu, ts))
1022 expires = tick_nohz_next_event(ts, cpu);
1028 if (expires > 0LL) {
1029 int was_stopped = ts->tick_stopped;
1031 tick_nohz_stop_tick(ts, cpu);
1034 ts->idle_expires = expires;
1036 if (!was_stopped && ts->tick_stopped) {
1037 ts->idle_jiffies = ts->last_jiffies;
1038 nohz_balance_enter_idle(cpu);
1041 tick_nohz_retain_tick(ts);
1046 * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1048 * When the next event is more than a tick into the future, stop the idle tick
1050 void tick_nohz_idle_stop_tick(void)
1052 __tick_nohz_idle_stop_tick(this_cpu_ptr(&tick_cpu_sched));
1055 void tick_nohz_idle_retain_tick(void)
1057 tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1059 * Undo the effect of get_next_timer_interrupt() called from
1060 * tick_nohz_next_event().
1066 * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1068 * Called when we start the idle loop.
1070 void tick_nohz_idle_enter(void)
1072 struct tick_sched *ts;
1074 lockdep_assert_irqs_enabled();
1076 local_irq_disable();
1078 ts = this_cpu_ptr(&tick_cpu_sched);
1080 WARN_ON_ONCE(ts->timer_expires_base);
1083 tick_nohz_start_idle(ts);
1089 * tick_nohz_irq_exit - update next tick event from interrupt exit
1091 * When an interrupt fires while we are idle and it doesn't cause
1092 * a reschedule, it may still add, modify or delete a timer, enqueue
1093 * an RCU callback, etc...
1094 * So we need to re-calculate and reprogram the next tick event.
1096 void tick_nohz_irq_exit(void)
1098 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1101 tick_nohz_start_idle(ts);
1103 tick_nohz_full_update_tick(ts);
1107 * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1109 bool tick_nohz_idle_got_tick(void)
1111 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1113 if (ts->got_idle_tick) {
1114 ts->got_idle_tick = 0;
1121 * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1122 * or the tick, whatever that expires first. Note that, if the tick has been
1123 * stopped, it returns the next hrtimer.
1125 * Called from power state control code with interrupts disabled
1127 ktime_t tick_nohz_get_next_hrtimer(void)
1129 return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1133 * tick_nohz_get_sleep_length - return the expected length of the current sleep
1134 * @delta_next: duration until the next event if the tick cannot be stopped
1136 * Called from power state control code with interrupts disabled
1138 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1140 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1141 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1142 int cpu = smp_processor_id();
1144 * The idle entry time is expected to be a sufficient approximation of
1145 * the current time at this point.
1147 ktime_t now = ts->idle_entrytime;
1150 WARN_ON_ONCE(!ts->inidle);
1152 *delta_next = ktime_sub(dev->next_event, now);
1154 if (!can_stop_idle_tick(cpu, ts))
1157 next_event = tick_nohz_next_event(ts, cpu);
1162 * If the next highres timer to expire is earlier than next_event, the
1163 * idle governor needs to know that.
1165 next_event = min_t(u64, next_event,
1166 hrtimer_next_event_without(&ts->sched_timer));
1168 return ktime_sub(next_event, now);
1172 * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1173 * for a particular CPU.
1175 * Called from the schedutil frequency scaling governor in scheduler context.
1177 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1179 struct tick_sched *ts = tick_get_tick_sched(cpu);
1181 return ts->idle_calls;
1185 * tick_nohz_get_idle_calls - return the current idle calls counter value
1187 * Called from the schedutil frequency scaling governor in scheduler context.
1189 unsigned long tick_nohz_get_idle_calls(void)
1191 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1193 return ts->idle_calls;
1196 static void tick_nohz_account_idle_ticks(struct tick_sched *ts)
1198 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
1199 unsigned long ticks;
1201 if (vtime_accounting_enabled_this_cpu())
1204 * We stopped the tick in idle. Update process times would miss the
1205 * time we slept as update_process_times does only a 1 tick
1206 * accounting. Enforce that this is accounted to idle !
1208 ticks = jiffies - ts->idle_jiffies;
1210 * We might be one off. Do not randomly account a huge number of ticks!
1212 if (ticks && ticks < LONG_MAX)
1213 account_idle_ticks(ticks);
1217 static void __tick_nohz_idle_restart_tick(struct tick_sched *ts, ktime_t now)
1219 tick_nohz_restart_sched_tick(ts, now);
1220 tick_nohz_account_idle_ticks(ts);
1223 void tick_nohz_idle_restart_tick(void)
1225 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1227 if (ts->tick_stopped)
1228 __tick_nohz_idle_restart_tick(ts, ktime_get());
1232 * tick_nohz_idle_exit - restart the idle tick from the idle task
1234 * Restart the idle tick when the CPU is woken up from idle
1235 * This also exit the RCU extended quiescent state. The CPU
1236 * can use RCU again after this function is called.
1238 void tick_nohz_idle_exit(void)
1240 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1241 bool idle_active, tick_stopped;
1244 local_irq_disable();
1246 WARN_ON_ONCE(!ts->inidle);
1247 WARN_ON_ONCE(ts->timer_expires_base);
1250 idle_active = ts->idle_active;
1251 tick_stopped = ts->tick_stopped;
1253 if (idle_active || tick_stopped)
1257 tick_nohz_stop_idle(ts, now);
1260 __tick_nohz_idle_restart_tick(ts, now);
1266 * The nohz low res interrupt handler
1268 static void tick_nohz_handler(struct clock_event_device *dev)
1270 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1271 struct pt_regs *regs = get_irq_regs();
1272 ktime_t now = ktime_get();
1274 dev->next_event = KTIME_MAX;
1276 tick_sched_do_timer(ts, now);
1277 tick_sched_handle(ts, regs);
1279 if (unlikely(ts->tick_stopped)) {
1281 * The clockevent device is not reprogrammed, so change the
1282 * clock event device to ONESHOT_STOPPED to avoid spurious
1283 * interrupts on devices which might not be truly one shot.
1285 tick_program_event(KTIME_MAX, 1);
1289 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1290 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1293 static inline void tick_nohz_activate(struct tick_sched *ts, int mode)
1295 if (!tick_nohz_enabled)
1297 ts->nohz_mode = mode;
1298 /* One update is enough */
1299 if (!test_and_set_bit(0, &tick_nohz_active))
1300 timers_update_nohz();
1304 * tick_nohz_switch_to_nohz - switch to nohz mode
1306 static void tick_nohz_switch_to_nohz(void)
1308 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1311 if (!tick_nohz_enabled)
1314 if (tick_switch_to_oneshot(tick_nohz_handler))
1318 * Recycle the hrtimer in ts, so we can share the
1319 * hrtimer_forward with the highres code.
1321 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1322 /* Get the next period */
1323 next = tick_init_jiffy_update();
1325 hrtimer_set_expires(&ts->sched_timer, next);
1326 hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1327 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1328 tick_nohz_activate(ts, NOHZ_MODE_LOWRES);
1331 static inline void tick_nohz_irq_enter(void)
1333 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1336 if (!ts->idle_active && !ts->tick_stopped)
1339 if (ts->idle_active)
1340 tick_nohz_stop_idle(ts, now);
1341 if (ts->tick_stopped)
1342 tick_nohz_update_jiffies(now);
1347 static inline void tick_nohz_switch_to_nohz(void) { }
1348 static inline void tick_nohz_irq_enter(void) { }
1349 static inline void tick_nohz_activate(struct tick_sched *ts, int mode) { }
1351 #endif /* CONFIG_NO_HZ_COMMON */
1354 * Called from irq_enter to notify about the possible interruption of idle()
1356 void tick_irq_enter(void)
1358 tick_check_oneshot_broadcast_this_cpu();
1359 tick_nohz_irq_enter();
1363 * High resolution timer specific code
1365 #ifdef CONFIG_HIGH_RES_TIMERS
1367 * We rearm the timer until we get disabled by the idle code.
1368 * Called with interrupts disabled.
1370 static enum hrtimer_restart tick_sched_timer(struct hrtimer *timer)
1372 struct tick_sched *ts =
1373 container_of(timer, struct tick_sched, sched_timer);
1374 struct pt_regs *regs = get_irq_regs();
1375 ktime_t now = ktime_get();
1377 tick_sched_do_timer(ts, now);
1380 * Do not call, when we are not in irq context and have
1381 * no valid regs pointer
1384 tick_sched_handle(ts, regs);
1388 /* No need to reprogram if we are in idle or full dynticks mode */
1389 if (unlikely(ts->tick_stopped))
1390 return HRTIMER_NORESTART;
1392 hrtimer_forward(timer, now, TICK_NSEC);
1394 return HRTIMER_RESTART;
1397 static int sched_skew_tick;
1399 static int __init skew_tick(char *str)
1401 get_option(&str, &sched_skew_tick);
1405 early_param("skew_tick", skew_tick);
1408 * tick_setup_sched_timer - setup the tick emulation timer
1410 void tick_setup_sched_timer(void)
1412 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1413 ktime_t now = ktime_get();
1416 * Emulate tick processing via per-CPU hrtimers:
1418 hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1419 ts->sched_timer.function = tick_sched_timer;
1421 /* Get the next period (per-CPU) */
1422 hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1424 /* Offset the tick to avert jiffies_lock contention. */
1425 if (sched_skew_tick) {
1426 u64 offset = TICK_NSEC >> 1;
1427 do_div(offset, num_possible_cpus());
1428 offset *= smp_processor_id();
1429 hrtimer_add_expires_ns(&ts->sched_timer, offset);
1432 hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
1433 hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1434 tick_nohz_activate(ts, NOHZ_MODE_HIGHRES);
1436 #endif /* HIGH_RES_TIMERS */
1438 #if defined CONFIG_NO_HZ_COMMON || defined CONFIG_HIGH_RES_TIMERS
1439 void tick_cancel_sched_timer(int cpu)
1441 struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1442 ktime_t idle_sleeptime, iowait_sleeptime;
1443 unsigned long idle_calls, idle_sleeps;
1445 # ifdef CONFIG_HIGH_RES_TIMERS
1446 if (ts->sched_timer.base)
1447 hrtimer_cancel(&ts->sched_timer);
1450 idle_sleeptime = ts->idle_sleeptime;
1451 iowait_sleeptime = ts->iowait_sleeptime;
1452 idle_calls = ts->idle_calls;
1453 idle_sleeps = ts->idle_sleeps;
1454 memset(ts, 0, sizeof(*ts));
1455 ts->idle_sleeptime = idle_sleeptime;
1456 ts->iowait_sleeptime = iowait_sleeptime;
1457 ts->idle_calls = idle_calls;
1458 ts->idle_sleeps = idle_sleeps;
1463 * Async notification about clocksource changes
1465 void tick_clock_notify(void)
1469 for_each_possible_cpu(cpu)
1470 set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1474 * Async notification about clock event changes
1476 void tick_oneshot_notify(void)
1478 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1480 set_bit(0, &ts->check_clocks);
1484 * Check, if a change happened, which makes oneshot possible.
1486 * Called cyclic from the hrtimer softirq (driven by the timer
1487 * softirq) allow_nohz signals, that we can switch into low-res nohz
1488 * mode, because high resolution timers are disabled (either compile
1489 * or runtime). Called with interrupts disabled.
1491 int tick_check_oneshot_change(int allow_nohz)
1493 struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1495 if (!test_and_clear_bit(0, &ts->check_clocks))
1498 if (ts->nohz_mode != NOHZ_MODE_INACTIVE)
1501 if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1507 tick_nohz_switch_to_nohz();