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