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