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