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