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