636c4b9cac38037a08407f7bf96faac2427825af
[cascardo/linux.git] / kernel / sched / core.c
1 /*
2  *  kernel/sched/core.c
3  *
4  *  Kernel scheduler and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  *
8  *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
9  *              make semaphores SMP safe
10  *  1998-11-19  Implemented schedule_timeout() and related stuff
11  *              by Andrea Arcangeli
12  *  2002-01-04  New ultra-scalable O(1) scheduler by Ingo Molnar:
13  *              hybrid priority-list and round-robin design with
14  *              an array-switch method of distributing timeslices
15  *              and per-CPU runqueues.  Cleanups and useful suggestions
16  *              by Davide Libenzi, preemptible kernel bits by Robert Love.
17  *  2003-09-03  Interactivity tuning by Con Kolivas.
18  *  2004-04-02  Scheduler domains code by Nick Piggin
19  *  2007-04-15  Work begun on replacing all interactivity tuning with a
20  *              fair scheduling design by Con Kolivas.
21  *  2007-05-05  Load balancing (smp-nice) and other improvements
22  *              by Peter Williams
23  *  2007-05-06  Interactivity improvements to CFS by Mike Galbraith
24  *  2007-07-01  Group scheduling enhancements by Srivatsa Vaddagiri
25  *  2007-11-29  RT balancing improvements by Steven Rostedt, Gregory Haskins,
26  *              Thomas Gleixner, Mike Kravetz
27  */
28
29 #include <linux/kasan.h>
30 #include <linux/mm.h>
31 #include <linux/module.h>
32 #include <linux/nmi.h>
33 #include <linux/init.h>
34 #include <linux/uaccess.h>
35 #include <linux/highmem.h>
36 #include <linux/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/ctype.h>
71 #include <linux/ftrace.h>
72 #include <linux/slab.h>
73 #include <linux/init_task.h>
74 #include <linux/context_tracking.h>
75 #include <linux/compiler.h>
76 #include <linux/frame.h>
77
78 #include <asm/switch_to.h>
79 #include <asm/tlb.h>
80 #include <asm/irq_regs.h>
81 #include <asm/mutex.h>
82 #ifdef CONFIG_PARAVIRT
83 #include <asm/paravirt.h>
84 #endif
85
86 #include "sched.h"
87 #include "../workqueue_internal.h"
88 #include "../smpboot.h"
89
90 #define CREATE_TRACE_POINTS
91 #include <trace/events/sched.h>
92
93 DEFINE_MUTEX(sched_domains_mutex);
94 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
95
96 static void update_rq_clock_task(struct rq *rq, s64 delta);
97
98 void update_rq_clock(struct rq *rq)
99 {
100         s64 delta;
101
102         lockdep_assert_held(&rq->lock);
103
104         if (rq->clock_skip_update & RQCF_ACT_SKIP)
105                 return;
106
107         delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
108         if (delta < 0)
109                 return;
110         rq->clock += delta;
111         update_rq_clock_task(rq, delta);
112 }
113
114 /*
115  * Debugging: various feature bits
116  */
117
118 #define SCHED_FEAT(name, enabled)       \
119         (1UL << __SCHED_FEAT_##name) * enabled |
120
121 const_debug unsigned int sysctl_sched_features =
122 #include "features.h"
123         0;
124
125 #undef SCHED_FEAT
126
127 /*
128  * Number of tasks to iterate in a single balance run.
129  * Limited because this is done with IRQs disabled.
130  */
131 const_debug unsigned int sysctl_sched_nr_migrate = 32;
132
133 /*
134  * period over which we average the RT time consumption, measured
135  * in ms.
136  *
137  * default: 1s
138  */
139 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
140
141 /*
142  * period over which we measure -rt task cpu usage in us.
143  * default: 1s
144  */
145 unsigned int sysctl_sched_rt_period = 1000000;
146
147 __read_mostly int scheduler_running;
148
149 /*
150  * part of the period that we allow rt tasks to run in us.
151  * default: 0.95s
152  */
153 int sysctl_sched_rt_runtime = 950000;
154
155 /* cpus with isolated domains */
156 cpumask_var_t cpu_isolated_map;
157
158 /*
159  * this_rq_lock - lock this runqueue and disable interrupts.
160  */
161 static struct rq *this_rq_lock(void)
162         __acquires(rq->lock)
163 {
164         struct rq *rq;
165
166         local_irq_disable();
167         rq = this_rq();
168         raw_spin_lock(&rq->lock);
169
170         return rq;
171 }
172
173 /*
174  * __task_rq_lock - lock the rq @p resides on.
175  */
176 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
177         __acquires(rq->lock)
178 {
179         struct rq *rq;
180
181         lockdep_assert_held(&p->pi_lock);
182
183         for (;;) {
184                 rq = task_rq(p);
185                 raw_spin_lock(&rq->lock);
186                 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
187                         rf->cookie = lockdep_pin_lock(&rq->lock);
188                         return rq;
189                 }
190                 raw_spin_unlock(&rq->lock);
191
192                 while (unlikely(task_on_rq_migrating(p)))
193                         cpu_relax();
194         }
195 }
196
197 /*
198  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
199  */
200 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
201         __acquires(p->pi_lock)
202         __acquires(rq->lock)
203 {
204         struct rq *rq;
205
206         for (;;) {
207                 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
208                 rq = task_rq(p);
209                 raw_spin_lock(&rq->lock);
210                 /*
211                  *      move_queued_task()              task_rq_lock()
212                  *
213                  *      ACQUIRE (rq->lock)
214                  *      [S] ->on_rq = MIGRATING         [L] rq = task_rq()
215                  *      WMB (__set_task_cpu())          ACQUIRE (rq->lock);
216                  *      [S] ->cpu = new_cpu             [L] task_rq()
217                  *                                      [L] ->on_rq
218                  *      RELEASE (rq->lock)
219                  *
220                  * If we observe the old cpu in task_rq_lock, the acquire of
221                  * the old rq->lock will fully serialize against the stores.
222                  *
223                  * If we observe the new cpu in task_rq_lock, the acquire will
224                  * pair with the WMB to ensure we must then also see migrating.
225                  */
226                 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
227                         rf->cookie = lockdep_pin_lock(&rq->lock);
228                         return rq;
229                 }
230                 raw_spin_unlock(&rq->lock);
231                 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
232
233                 while (unlikely(task_on_rq_migrating(p)))
234                         cpu_relax();
235         }
236 }
237
238 #ifdef CONFIG_SCHED_HRTICK
239 /*
240  * Use HR-timers to deliver accurate preemption points.
241  */
242
243 static void hrtick_clear(struct rq *rq)
244 {
245         if (hrtimer_active(&rq->hrtick_timer))
246                 hrtimer_cancel(&rq->hrtick_timer);
247 }
248
249 /*
250  * High-resolution timer tick.
251  * Runs from hardirq context with interrupts disabled.
252  */
253 static enum hrtimer_restart hrtick(struct hrtimer *timer)
254 {
255         struct rq *rq = container_of(timer, struct rq, hrtick_timer);
256
257         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
258
259         raw_spin_lock(&rq->lock);
260         update_rq_clock(rq);
261         rq->curr->sched_class->task_tick(rq, rq->curr, 1);
262         raw_spin_unlock(&rq->lock);
263
264         return HRTIMER_NORESTART;
265 }
266
267 #ifdef CONFIG_SMP
268
269 static void __hrtick_restart(struct rq *rq)
270 {
271         struct hrtimer *timer = &rq->hrtick_timer;
272
273         hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
274 }
275
276 /*
277  * called from hardirq (IPI) context
278  */
279 static void __hrtick_start(void *arg)
280 {
281         struct rq *rq = arg;
282
283         raw_spin_lock(&rq->lock);
284         __hrtick_restart(rq);
285         rq->hrtick_csd_pending = 0;
286         raw_spin_unlock(&rq->lock);
287 }
288
289 /*
290  * Called to set the hrtick timer state.
291  *
292  * called with rq->lock held and irqs disabled
293  */
294 void hrtick_start(struct rq *rq, u64 delay)
295 {
296         struct hrtimer *timer = &rq->hrtick_timer;
297         ktime_t time;
298         s64 delta;
299
300         /*
301          * Don't schedule slices shorter than 10000ns, that just
302          * doesn't make sense and can cause timer DoS.
303          */
304         delta = max_t(s64, delay, 10000LL);
305         time = ktime_add_ns(timer->base->get_time(), delta);
306
307         hrtimer_set_expires(timer, time);
308
309         if (rq == this_rq()) {
310                 __hrtick_restart(rq);
311         } else if (!rq->hrtick_csd_pending) {
312                 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
313                 rq->hrtick_csd_pending = 1;
314         }
315 }
316
317 #else
318 /*
319  * Called to set the hrtick timer state.
320  *
321  * called with rq->lock held and irqs disabled
322  */
323 void hrtick_start(struct rq *rq, u64 delay)
324 {
325         /*
326          * Don't schedule slices shorter than 10000ns, that just
327          * doesn't make sense. Rely on vruntime for fairness.
328          */
329         delay = max_t(u64, delay, 10000LL);
330         hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
331                       HRTIMER_MODE_REL_PINNED);
332 }
333 #endif /* CONFIG_SMP */
334
335 static void init_rq_hrtick(struct rq *rq)
336 {
337 #ifdef CONFIG_SMP
338         rq->hrtick_csd_pending = 0;
339
340         rq->hrtick_csd.flags = 0;
341         rq->hrtick_csd.func = __hrtick_start;
342         rq->hrtick_csd.info = rq;
343 #endif
344
345         hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
346         rq->hrtick_timer.function = hrtick;
347 }
348 #else   /* CONFIG_SCHED_HRTICK */
349 static inline void hrtick_clear(struct rq *rq)
350 {
351 }
352
353 static inline void init_rq_hrtick(struct rq *rq)
354 {
355 }
356 #endif  /* CONFIG_SCHED_HRTICK */
357
358 /*
359  * cmpxchg based fetch_or, macro so it works for different integer types
360  */
361 #define fetch_or(ptr, mask)                                             \
362         ({                                                              \
363                 typeof(ptr) _ptr = (ptr);                               \
364                 typeof(mask) _mask = (mask);                            \
365                 typeof(*_ptr) _old, _val = *_ptr;                       \
366                                                                         \
367                 for (;;) {                                              \
368                         _old = cmpxchg(_ptr, _val, _val | _mask);       \
369                         if (_old == _val)                               \
370                                 break;                                  \
371                         _val = _old;                                    \
372                 }                                                       \
373         _old;                                                           \
374 })
375
376 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
377 /*
378  * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
379  * this avoids any races wrt polling state changes and thereby avoids
380  * spurious IPIs.
381  */
382 static bool set_nr_and_not_polling(struct task_struct *p)
383 {
384         struct thread_info *ti = task_thread_info(p);
385         return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
386 }
387
388 /*
389  * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
390  *
391  * If this returns true, then the idle task promises to call
392  * sched_ttwu_pending() and reschedule soon.
393  */
394 static bool set_nr_if_polling(struct task_struct *p)
395 {
396         struct thread_info *ti = task_thread_info(p);
397         typeof(ti->flags) old, val = READ_ONCE(ti->flags);
398
399         for (;;) {
400                 if (!(val & _TIF_POLLING_NRFLAG))
401                         return false;
402                 if (val & _TIF_NEED_RESCHED)
403                         return true;
404                 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
405                 if (old == val)
406                         break;
407                 val = old;
408         }
409         return true;
410 }
411
412 #else
413 static bool set_nr_and_not_polling(struct task_struct *p)
414 {
415         set_tsk_need_resched(p);
416         return true;
417 }
418
419 #ifdef CONFIG_SMP
420 static bool set_nr_if_polling(struct task_struct *p)
421 {
422         return false;
423 }
424 #endif
425 #endif
426
427 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
428 {
429         struct wake_q_node *node = &task->wake_q;
430
431         /*
432          * Atomically grab the task, if ->wake_q is !nil already it means
433          * its already queued (either by us or someone else) and will get the
434          * wakeup due to that.
435          *
436          * This cmpxchg() implies a full barrier, which pairs with the write
437          * barrier implied by the wakeup in wake_up_q().
438          */
439         if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
440                 return;
441
442         get_task_struct(task);
443
444         /*
445          * The head is context local, there can be no concurrency.
446          */
447         *head->lastp = node;
448         head->lastp = &node->next;
449 }
450
451 void wake_up_q(struct wake_q_head *head)
452 {
453         struct wake_q_node *node = head->first;
454
455         while (node != WAKE_Q_TAIL) {
456                 struct task_struct *task;
457
458                 task = container_of(node, struct task_struct, wake_q);
459                 BUG_ON(!task);
460                 /* task can safely be re-inserted now */
461                 node = node->next;
462                 task->wake_q.next = NULL;
463
464                 /*
465                  * wake_up_process() implies a wmb() to pair with the queueing
466                  * in wake_q_add() so as not to miss wakeups.
467                  */
468                 wake_up_process(task);
469                 put_task_struct(task);
470         }
471 }
472
473 /*
474  * resched_curr - mark rq's current task 'to be rescheduled now'.
475  *
476  * On UP this means the setting of the need_resched flag, on SMP it
477  * might also involve a cross-CPU call to trigger the scheduler on
478  * the target CPU.
479  */
480 void resched_curr(struct rq *rq)
481 {
482         struct task_struct *curr = rq->curr;
483         int cpu;
484
485         lockdep_assert_held(&rq->lock);
486
487         if (test_tsk_need_resched(curr))
488                 return;
489
490         cpu = cpu_of(rq);
491
492         if (cpu == smp_processor_id()) {
493                 set_tsk_need_resched(curr);
494                 set_preempt_need_resched();
495                 return;
496         }
497
498         if (set_nr_and_not_polling(curr))
499                 smp_send_reschedule(cpu);
500         else
501                 trace_sched_wake_idle_without_ipi(cpu);
502 }
503
504 void resched_cpu(int cpu)
505 {
506         struct rq *rq = cpu_rq(cpu);
507         unsigned long flags;
508
509         if (!raw_spin_trylock_irqsave(&rq->lock, flags))
510                 return;
511         resched_curr(rq);
512         raw_spin_unlock_irqrestore(&rq->lock, flags);
513 }
514
515 #ifdef CONFIG_SMP
516 #ifdef CONFIG_NO_HZ_COMMON
517 /*
518  * In the semi idle case, use the nearest busy cpu for migrating timers
519  * from an idle cpu.  This is good for power-savings.
520  *
521  * We don't do similar optimization for completely idle system, as
522  * selecting an idle cpu will add more delays to the timers than intended
523  * (as that cpu's timer base may not be uptodate wrt jiffies etc).
524  */
525 int get_nohz_timer_target(void)
526 {
527         int i, cpu = smp_processor_id();
528         struct sched_domain *sd;
529
530         if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
531                 return cpu;
532
533         rcu_read_lock();
534         for_each_domain(cpu, sd) {
535                 for_each_cpu(i, sched_domain_span(sd)) {
536                         if (!idle_cpu(i) && is_housekeeping_cpu(cpu)) {
537                                 cpu = i;
538                                 goto unlock;
539                         }
540                 }
541         }
542
543         if (!is_housekeeping_cpu(cpu))
544                 cpu = housekeeping_any_cpu();
545 unlock:
546         rcu_read_unlock();
547         return cpu;
548 }
549 /*
550  * When add_timer_on() enqueues a timer into the timer wheel of an
551  * idle CPU then this timer might expire before the next timer event
552  * which is scheduled to wake up that CPU. In case of a completely
553  * idle system the next event might even be infinite time into the
554  * future. wake_up_idle_cpu() ensures that the CPU is woken up and
555  * leaves the inner idle loop so the newly added timer is taken into
556  * account when the CPU goes back to idle and evaluates the timer
557  * wheel for the next timer event.
558  */
559 static void wake_up_idle_cpu(int cpu)
560 {
561         struct rq *rq = cpu_rq(cpu);
562
563         if (cpu == smp_processor_id())
564                 return;
565
566         if (set_nr_and_not_polling(rq->idle))
567                 smp_send_reschedule(cpu);
568         else
569                 trace_sched_wake_idle_without_ipi(cpu);
570 }
571
572 static bool wake_up_full_nohz_cpu(int cpu)
573 {
574         /*
575          * We just need the target to call irq_exit() and re-evaluate
576          * the next tick. The nohz full kick at least implies that.
577          * If needed we can still optimize that later with an
578          * empty IRQ.
579          */
580         if (tick_nohz_full_cpu(cpu)) {
581                 if (cpu != smp_processor_id() ||
582                     tick_nohz_tick_stopped())
583                         tick_nohz_full_kick_cpu(cpu);
584                 return true;
585         }
586
587         return false;
588 }
589
590 void wake_up_nohz_cpu(int cpu)
591 {
592         if (!wake_up_full_nohz_cpu(cpu))
593                 wake_up_idle_cpu(cpu);
594 }
595
596 static inline bool got_nohz_idle_kick(void)
597 {
598         int cpu = smp_processor_id();
599
600         if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
601                 return false;
602
603         if (idle_cpu(cpu) && !need_resched())
604                 return true;
605
606         /*
607          * We can't run Idle Load Balance on this CPU for this time so we
608          * cancel it and clear NOHZ_BALANCE_KICK
609          */
610         clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
611         return false;
612 }
613
614 #else /* CONFIG_NO_HZ_COMMON */
615
616 static inline bool got_nohz_idle_kick(void)
617 {
618         return false;
619 }
620
621 #endif /* CONFIG_NO_HZ_COMMON */
622
623 #ifdef CONFIG_NO_HZ_FULL
624 bool sched_can_stop_tick(struct rq *rq)
625 {
626         int fifo_nr_running;
627
628         /* Deadline tasks, even if single, need the tick */
629         if (rq->dl.dl_nr_running)
630                 return false;
631
632         /*
633          * If there are more than one RR tasks, we need the tick to effect the
634          * actual RR behaviour.
635          */
636         if (rq->rt.rr_nr_running) {
637                 if (rq->rt.rr_nr_running == 1)
638                         return true;
639                 else
640                         return false;
641         }
642
643         /*
644          * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
645          * forced preemption between FIFO tasks.
646          */
647         fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
648         if (fifo_nr_running)
649                 return true;
650
651         /*
652          * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
653          * if there's more than one we need the tick for involuntary
654          * preemption.
655          */
656         if (rq->nr_running > 1)
657                 return false;
658
659         return true;
660 }
661 #endif /* CONFIG_NO_HZ_FULL */
662
663 void sched_avg_update(struct rq *rq)
664 {
665         s64 period = sched_avg_period();
666
667         while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
668                 /*
669                  * Inline assembly required to prevent the compiler
670                  * optimising this loop into a divmod call.
671                  * See __iter_div_u64_rem() for another example of this.
672                  */
673                 asm("" : "+rm" (rq->age_stamp));
674                 rq->age_stamp += period;
675                 rq->rt_avg /= 2;
676         }
677 }
678
679 #endif /* CONFIG_SMP */
680
681 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
682                         (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
683 /*
684  * Iterate task_group tree rooted at *from, calling @down when first entering a
685  * node and @up when leaving it for the final time.
686  *
687  * Caller must hold rcu_lock or sufficient equivalent.
688  */
689 int walk_tg_tree_from(struct task_group *from,
690                              tg_visitor down, tg_visitor up, void *data)
691 {
692         struct task_group *parent, *child;
693         int ret;
694
695         parent = from;
696
697 down:
698         ret = (*down)(parent, data);
699         if (ret)
700                 goto out;
701         list_for_each_entry_rcu(child, &parent->children, siblings) {
702                 parent = child;
703                 goto down;
704
705 up:
706                 continue;
707         }
708         ret = (*up)(parent, data);
709         if (ret || parent == from)
710                 goto out;
711
712         child = parent;
713         parent = parent->parent;
714         if (parent)
715                 goto up;
716 out:
717         return ret;
718 }
719
720 int tg_nop(struct task_group *tg, void *data)
721 {
722         return 0;
723 }
724 #endif
725
726 static void set_load_weight(struct task_struct *p)
727 {
728         int prio = p->static_prio - MAX_RT_PRIO;
729         struct load_weight *load = &p->se.load;
730
731         /*
732          * SCHED_IDLE tasks get minimal weight:
733          */
734         if (idle_policy(p->policy)) {
735                 load->weight = scale_load(WEIGHT_IDLEPRIO);
736                 load->inv_weight = WMULT_IDLEPRIO;
737                 return;
738         }
739
740         load->weight = scale_load(sched_prio_to_weight[prio]);
741         load->inv_weight = sched_prio_to_wmult[prio];
742 }
743
744 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
745 {
746         update_rq_clock(rq);
747         if (!(flags & ENQUEUE_RESTORE))
748                 sched_info_queued(rq, p);
749         p->sched_class->enqueue_task(rq, p, flags);
750 }
751
752 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
753 {
754         update_rq_clock(rq);
755         if (!(flags & DEQUEUE_SAVE))
756                 sched_info_dequeued(rq, p);
757         p->sched_class->dequeue_task(rq, p, flags);
758 }
759
760 void activate_task(struct rq *rq, struct task_struct *p, int flags)
761 {
762         if (task_contributes_to_load(p))
763                 rq->nr_uninterruptible--;
764
765         enqueue_task(rq, p, flags);
766 }
767
768 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
769 {
770         if (task_contributes_to_load(p))
771                 rq->nr_uninterruptible++;
772
773         dequeue_task(rq, p, flags);
774 }
775
776 static void update_rq_clock_task(struct rq *rq, s64 delta)
777 {
778 /*
779  * In theory, the compile should just see 0 here, and optimize out the call
780  * to sched_rt_avg_update. But I don't trust it...
781  */
782 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
783         s64 steal = 0, irq_delta = 0;
784 #endif
785 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
786         irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
787
788         /*
789          * Since irq_time is only updated on {soft,}irq_exit, we might run into
790          * this case when a previous update_rq_clock() happened inside a
791          * {soft,}irq region.
792          *
793          * When this happens, we stop ->clock_task and only update the
794          * prev_irq_time stamp to account for the part that fit, so that a next
795          * update will consume the rest. This ensures ->clock_task is
796          * monotonic.
797          *
798          * It does however cause some slight miss-attribution of {soft,}irq
799          * time, a more accurate solution would be to update the irq_time using
800          * the current rq->clock timestamp, except that would require using
801          * atomic ops.
802          */
803         if (irq_delta > delta)
804                 irq_delta = delta;
805
806         rq->prev_irq_time += irq_delta;
807         delta -= irq_delta;
808 #endif
809 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
810         if (static_key_false((&paravirt_steal_rq_enabled))) {
811                 steal = paravirt_steal_clock(cpu_of(rq));
812                 steal -= rq->prev_steal_time_rq;
813
814                 if (unlikely(steal > delta))
815                         steal = delta;
816
817                 rq->prev_steal_time_rq += steal;
818                 delta -= steal;
819         }
820 #endif
821
822         rq->clock_task += delta;
823
824 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
825         if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
826                 sched_rt_avg_update(rq, irq_delta + steal);
827 #endif
828 }
829
830 void sched_set_stop_task(int cpu, struct task_struct *stop)
831 {
832         struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
833         struct task_struct *old_stop = cpu_rq(cpu)->stop;
834
835         if (stop) {
836                 /*
837                  * Make it appear like a SCHED_FIFO task, its something
838                  * userspace knows about and won't get confused about.
839                  *
840                  * Also, it will make PI more or less work without too
841                  * much confusion -- but then, stop work should not
842                  * rely on PI working anyway.
843                  */
844                 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
845
846                 stop->sched_class = &stop_sched_class;
847         }
848
849         cpu_rq(cpu)->stop = stop;
850
851         if (old_stop) {
852                 /*
853                  * Reset it back to a normal scheduling class so that
854                  * it can die in pieces.
855                  */
856                 old_stop->sched_class = &rt_sched_class;
857         }
858 }
859
860 /*
861  * __normal_prio - return the priority that is based on the static prio
862  */
863 static inline int __normal_prio(struct task_struct *p)
864 {
865         return p->static_prio;
866 }
867
868 /*
869  * Calculate the expected normal priority: i.e. priority
870  * without taking RT-inheritance into account. Might be
871  * boosted by interactivity modifiers. Changes upon fork,
872  * setprio syscalls, and whenever the interactivity
873  * estimator recalculates.
874  */
875 static inline int normal_prio(struct task_struct *p)
876 {
877         int prio;
878
879         if (task_has_dl_policy(p))
880                 prio = MAX_DL_PRIO-1;
881         else if (task_has_rt_policy(p))
882                 prio = MAX_RT_PRIO-1 - p->rt_priority;
883         else
884                 prio = __normal_prio(p);
885         return prio;
886 }
887
888 /*
889  * Calculate the current priority, i.e. the priority
890  * taken into account by the scheduler. This value might
891  * be boosted by RT tasks, or might be boosted by
892  * interactivity modifiers. Will be RT if the task got
893  * RT-boosted. If not then it returns p->normal_prio.
894  */
895 static int effective_prio(struct task_struct *p)
896 {
897         p->normal_prio = normal_prio(p);
898         /*
899          * If we are RT tasks or we were boosted to RT priority,
900          * keep the priority unchanged. Otherwise, update priority
901          * to the normal priority:
902          */
903         if (!rt_prio(p->prio))
904                 return p->normal_prio;
905         return p->prio;
906 }
907
908 /**
909  * task_curr - is this task currently executing on a CPU?
910  * @p: the task in question.
911  *
912  * Return: 1 if the task is currently executing. 0 otherwise.
913  */
914 inline int task_curr(const struct task_struct *p)
915 {
916         return cpu_curr(task_cpu(p)) == p;
917 }
918
919 /*
920  * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
921  * use the balance_callback list if you want balancing.
922  *
923  * this means any call to check_class_changed() must be followed by a call to
924  * balance_callback().
925  */
926 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
927                                        const struct sched_class *prev_class,
928                                        int oldprio)
929 {
930         if (prev_class != p->sched_class) {
931                 if (prev_class->switched_from)
932                         prev_class->switched_from(rq, p);
933
934                 p->sched_class->switched_to(rq, p);
935         } else if (oldprio != p->prio || dl_task(p))
936                 p->sched_class->prio_changed(rq, p, oldprio);
937 }
938
939 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
940 {
941         const struct sched_class *class;
942
943         if (p->sched_class == rq->curr->sched_class) {
944                 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
945         } else {
946                 for_each_class(class) {
947                         if (class == rq->curr->sched_class)
948                                 break;
949                         if (class == p->sched_class) {
950                                 resched_curr(rq);
951                                 break;
952                         }
953                 }
954         }
955
956         /*
957          * A queue event has occurred, and we're going to schedule.  In
958          * this case, we can save a useless back to back clock update.
959          */
960         if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
961                 rq_clock_skip_update(rq, true);
962 }
963
964 #ifdef CONFIG_SMP
965 /*
966  * This is how migration works:
967  *
968  * 1) we invoke migration_cpu_stop() on the target CPU using
969  *    stop_one_cpu().
970  * 2) stopper starts to run (implicitly forcing the migrated thread
971  *    off the CPU)
972  * 3) it checks whether the migrated task is still in the wrong runqueue.
973  * 4) if it's in the wrong runqueue then the migration thread removes
974  *    it and puts it into the right queue.
975  * 5) stopper completes and stop_one_cpu() returns and the migration
976  *    is done.
977  */
978
979 /*
980  * move_queued_task - move a queued task to new rq.
981  *
982  * Returns (locked) new rq. Old rq's lock is released.
983  */
984 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
985 {
986         lockdep_assert_held(&rq->lock);
987
988         p->on_rq = TASK_ON_RQ_MIGRATING;
989         dequeue_task(rq, p, 0);
990         set_task_cpu(p, new_cpu);
991         raw_spin_unlock(&rq->lock);
992
993         rq = cpu_rq(new_cpu);
994
995         raw_spin_lock(&rq->lock);
996         BUG_ON(task_cpu(p) != new_cpu);
997         enqueue_task(rq, p, 0);
998         p->on_rq = TASK_ON_RQ_QUEUED;
999         check_preempt_curr(rq, p, 0);
1000
1001         return rq;
1002 }
1003
1004 struct migration_arg {
1005         struct task_struct *task;
1006         int dest_cpu;
1007 };
1008
1009 /*
1010  * Move (not current) task off this cpu, onto dest cpu. We're doing
1011  * this because either it can't run here any more (set_cpus_allowed()
1012  * away from this CPU, or CPU going down), or because we're
1013  * attempting to rebalance this task on exec (sched_exec).
1014  *
1015  * So we race with normal scheduler movements, but that's OK, as long
1016  * as the task is no longer on this CPU.
1017  */
1018 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
1019 {
1020         if (unlikely(!cpu_active(dest_cpu)))
1021                 return rq;
1022
1023         /* Affinity changed (again). */
1024         if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1025                 return rq;
1026
1027         rq = move_queued_task(rq, p, dest_cpu);
1028
1029         return rq;
1030 }
1031
1032 /*
1033  * migration_cpu_stop - this will be executed by a highprio stopper thread
1034  * and performs thread migration by bumping thread off CPU then
1035  * 'pushing' onto another runqueue.
1036  */
1037 static int migration_cpu_stop(void *data)
1038 {
1039         struct migration_arg *arg = data;
1040         struct task_struct *p = arg->task;
1041         struct rq *rq = this_rq();
1042
1043         /*
1044          * The original target cpu might have gone down and we might
1045          * be on another cpu but it doesn't matter.
1046          */
1047         local_irq_disable();
1048         /*
1049          * We need to explicitly wake pending tasks before running
1050          * __migrate_task() such that we will not miss enforcing cpus_allowed
1051          * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1052          */
1053         sched_ttwu_pending();
1054
1055         raw_spin_lock(&p->pi_lock);
1056         raw_spin_lock(&rq->lock);
1057         /*
1058          * If task_rq(p) != rq, it cannot be migrated here, because we're
1059          * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1060          * we're holding p->pi_lock.
1061          */
1062         if (task_rq(p) == rq && task_on_rq_queued(p))
1063                 rq = __migrate_task(rq, p, arg->dest_cpu);
1064         raw_spin_unlock(&rq->lock);
1065         raw_spin_unlock(&p->pi_lock);
1066
1067         local_irq_enable();
1068         return 0;
1069 }
1070
1071 /*
1072  * sched_class::set_cpus_allowed must do the below, but is not required to
1073  * actually call this function.
1074  */
1075 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1076 {
1077         cpumask_copy(&p->cpus_allowed, new_mask);
1078         p->nr_cpus_allowed = cpumask_weight(new_mask);
1079 }
1080
1081 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1082 {
1083         struct rq *rq = task_rq(p);
1084         bool queued, running;
1085
1086         lockdep_assert_held(&p->pi_lock);
1087
1088         queued = task_on_rq_queued(p);
1089         running = task_current(rq, p);
1090
1091         if (queued) {
1092                 /*
1093                  * Because __kthread_bind() calls this on blocked tasks without
1094                  * holding rq->lock.
1095                  */
1096                 lockdep_assert_held(&rq->lock);
1097                 dequeue_task(rq, p, DEQUEUE_SAVE);
1098         }
1099         if (running)
1100                 put_prev_task(rq, p);
1101
1102         p->sched_class->set_cpus_allowed(p, new_mask);
1103
1104         if (running)
1105                 p->sched_class->set_curr_task(rq);
1106         if (queued)
1107                 enqueue_task(rq, p, ENQUEUE_RESTORE);
1108 }
1109
1110 /*
1111  * Change a given task's CPU affinity. Migrate the thread to a
1112  * proper CPU and schedule it away if the CPU it's executing on
1113  * is removed from the allowed bitmask.
1114  *
1115  * NOTE: the caller must have a valid reference to the task, the
1116  * task must not exit() & deallocate itself prematurely. The
1117  * call is not atomic; no spinlocks may be held.
1118  */
1119 static int __set_cpus_allowed_ptr(struct task_struct *p,
1120                                   const struct cpumask *new_mask, bool check)
1121 {
1122         const struct cpumask *cpu_valid_mask = cpu_active_mask;
1123         unsigned int dest_cpu;
1124         struct rq_flags rf;
1125         struct rq *rq;
1126         int ret = 0;
1127
1128         rq = task_rq_lock(p, &rf);
1129
1130         if (p->flags & PF_KTHREAD) {
1131                 /*
1132                  * Kernel threads are allowed on online && !active CPUs
1133                  */
1134                 cpu_valid_mask = cpu_online_mask;
1135         }
1136
1137         /*
1138          * Must re-check here, to close a race against __kthread_bind(),
1139          * sched_setaffinity() is not guaranteed to observe the flag.
1140          */
1141         if (check && (p->flags & PF_NO_SETAFFINITY)) {
1142                 ret = -EINVAL;
1143                 goto out;
1144         }
1145
1146         if (cpumask_equal(&p->cpus_allowed, new_mask))
1147                 goto out;
1148
1149         if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1150                 ret = -EINVAL;
1151                 goto out;
1152         }
1153
1154         do_set_cpus_allowed(p, new_mask);
1155
1156         if (p->flags & PF_KTHREAD) {
1157                 /*
1158                  * For kernel threads that do indeed end up on online &&
1159                  * !active we want to ensure they are strict per-cpu threads.
1160                  */
1161                 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1162                         !cpumask_intersects(new_mask, cpu_active_mask) &&
1163                         p->nr_cpus_allowed != 1);
1164         }
1165
1166         /* Can the task run on the task's current CPU? If so, we're done */
1167         if (cpumask_test_cpu(task_cpu(p), new_mask))
1168                 goto out;
1169
1170         dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1171         if (task_running(rq, p) || p->state == TASK_WAKING) {
1172                 struct migration_arg arg = { p, dest_cpu };
1173                 /* Need help from migration thread: drop lock and wait. */
1174                 task_rq_unlock(rq, p, &rf);
1175                 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1176                 tlb_migrate_finish(p->mm);
1177                 return 0;
1178         } else if (task_on_rq_queued(p)) {
1179                 /*
1180                  * OK, since we're going to drop the lock immediately
1181                  * afterwards anyway.
1182                  */
1183                 lockdep_unpin_lock(&rq->lock, rf.cookie);
1184                 rq = move_queued_task(rq, p, dest_cpu);
1185                 lockdep_repin_lock(&rq->lock, rf.cookie);
1186         }
1187 out:
1188         task_rq_unlock(rq, p, &rf);
1189
1190         return ret;
1191 }
1192
1193 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1194 {
1195         return __set_cpus_allowed_ptr(p, new_mask, false);
1196 }
1197 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1198
1199 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1200 {
1201 #ifdef CONFIG_SCHED_DEBUG
1202         /*
1203          * We should never call set_task_cpu() on a blocked task,
1204          * ttwu() will sort out the placement.
1205          */
1206         WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1207                         !p->on_rq);
1208
1209         /*
1210          * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1211          * because schedstat_wait_{start,end} rebase migrating task's wait_start
1212          * time relying on p->on_rq.
1213          */
1214         WARN_ON_ONCE(p->state == TASK_RUNNING &&
1215                      p->sched_class == &fair_sched_class &&
1216                      (p->on_rq && !task_on_rq_migrating(p)));
1217
1218 #ifdef CONFIG_LOCKDEP
1219         /*
1220          * The caller should hold either p->pi_lock or rq->lock, when changing
1221          * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1222          *
1223          * sched_move_task() holds both and thus holding either pins the cgroup,
1224          * see task_group().
1225          *
1226          * Furthermore, all task_rq users should acquire both locks, see
1227          * task_rq_lock().
1228          */
1229         WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1230                                       lockdep_is_held(&task_rq(p)->lock)));
1231 #endif
1232 #endif
1233
1234         trace_sched_migrate_task(p, new_cpu);
1235
1236         if (task_cpu(p) != new_cpu) {
1237                 if (p->sched_class->migrate_task_rq)
1238                         p->sched_class->migrate_task_rq(p);
1239                 p->se.nr_migrations++;
1240                 perf_event_task_migrate(p);
1241         }
1242
1243         __set_task_cpu(p, new_cpu);
1244 }
1245
1246 static void __migrate_swap_task(struct task_struct *p, int cpu)
1247 {
1248         if (task_on_rq_queued(p)) {
1249                 struct rq *src_rq, *dst_rq;
1250
1251                 src_rq = task_rq(p);
1252                 dst_rq = cpu_rq(cpu);
1253
1254                 p->on_rq = TASK_ON_RQ_MIGRATING;
1255                 deactivate_task(src_rq, p, 0);
1256                 set_task_cpu(p, cpu);
1257                 activate_task(dst_rq, p, 0);
1258                 p->on_rq = TASK_ON_RQ_QUEUED;
1259                 check_preempt_curr(dst_rq, p, 0);
1260         } else {
1261                 /*
1262                  * Task isn't running anymore; make it appear like we migrated
1263                  * it before it went to sleep. This means on wakeup we make the
1264                  * previous cpu our targer instead of where it really is.
1265                  */
1266                 p->wake_cpu = cpu;
1267         }
1268 }
1269
1270 struct migration_swap_arg {
1271         struct task_struct *src_task, *dst_task;
1272         int src_cpu, dst_cpu;
1273 };
1274
1275 static int migrate_swap_stop(void *data)
1276 {
1277         struct migration_swap_arg *arg = data;
1278         struct rq *src_rq, *dst_rq;
1279         int ret = -EAGAIN;
1280
1281         if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1282                 return -EAGAIN;
1283
1284         src_rq = cpu_rq(arg->src_cpu);
1285         dst_rq = cpu_rq(arg->dst_cpu);
1286
1287         double_raw_lock(&arg->src_task->pi_lock,
1288                         &arg->dst_task->pi_lock);
1289         double_rq_lock(src_rq, dst_rq);
1290
1291         if (task_cpu(arg->dst_task) != arg->dst_cpu)
1292                 goto unlock;
1293
1294         if (task_cpu(arg->src_task) != arg->src_cpu)
1295                 goto unlock;
1296
1297         if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1298                 goto unlock;
1299
1300         if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1301                 goto unlock;
1302
1303         __migrate_swap_task(arg->src_task, arg->dst_cpu);
1304         __migrate_swap_task(arg->dst_task, arg->src_cpu);
1305
1306         ret = 0;
1307
1308 unlock:
1309         double_rq_unlock(src_rq, dst_rq);
1310         raw_spin_unlock(&arg->dst_task->pi_lock);
1311         raw_spin_unlock(&arg->src_task->pi_lock);
1312
1313         return ret;
1314 }
1315
1316 /*
1317  * Cross migrate two tasks
1318  */
1319 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1320 {
1321         struct migration_swap_arg arg;
1322         int ret = -EINVAL;
1323
1324         arg = (struct migration_swap_arg){
1325                 .src_task = cur,
1326                 .src_cpu = task_cpu(cur),
1327                 .dst_task = p,
1328                 .dst_cpu = task_cpu(p),
1329         };
1330
1331         if (arg.src_cpu == arg.dst_cpu)
1332                 goto out;
1333
1334         /*
1335          * These three tests are all lockless; this is OK since all of them
1336          * will be re-checked with proper locks held further down the line.
1337          */
1338         if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1339                 goto out;
1340
1341         if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1342                 goto out;
1343
1344         if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1345                 goto out;
1346
1347         trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1348         ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1349
1350 out:
1351         return ret;
1352 }
1353
1354 /*
1355  * wait_task_inactive - wait for a thread to unschedule.
1356  *
1357  * If @match_state is nonzero, it's the @p->state value just checked and
1358  * not expected to change.  If it changes, i.e. @p might have woken up,
1359  * then return zero.  When we succeed in waiting for @p to be off its CPU,
1360  * we return a positive number (its total switch count).  If a second call
1361  * a short while later returns the same number, the caller can be sure that
1362  * @p has remained unscheduled the whole time.
1363  *
1364  * The caller must ensure that the task *will* unschedule sometime soon,
1365  * else this function might spin for a *long* time. This function can't
1366  * be called with interrupts off, or it may introduce deadlock with
1367  * smp_call_function() if an IPI is sent by the same process we are
1368  * waiting to become inactive.
1369  */
1370 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1371 {
1372         int running, queued;
1373         struct rq_flags rf;
1374         unsigned long ncsw;
1375         struct rq *rq;
1376
1377         for (;;) {
1378                 /*
1379                  * We do the initial early heuristics without holding
1380                  * any task-queue locks at all. We'll only try to get
1381                  * the runqueue lock when things look like they will
1382                  * work out!
1383                  */
1384                 rq = task_rq(p);
1385
1386                 /*
1387                  * If the task is actively running on another CPU
1388                  * still, just relax and busy-wait without holding
1389                  * any locks.
1390                  *
1391                  * NOTE! Since we don't hold any locks, it's not
1392                  * even sure that "rq" stays as the right runqueue!
1393                  * But we don't care, since "task_running()" will
1394                  * return false if the runqueue has changed and p
1395                  * is actually now running somewhere else!
1396                  */
1397                 while (task_running(rq, p)) {
1398                         if (match_state && unlikely(p->state != match_state))
1399                                 return 0;
1400                         cpu_relax();
1401                 }
1402
1403                 /*
1404                  * Ok, time to look more closely! We need the rq
1405                  * lock now, to be *sure*. If we're wrong, we'll
1406                  * just go back and repeat.
1407                  */
1408                 rq = task_rq_lock(p, &rf);
1409                 trace_sched_wait_task(p);
1410                 running = task_running(rq, p);
1411                 queued = task_on_rq_queued(p);
1412                 ncsw = 0;
1413                 if (!match_state || p->state == match_state)
1414                         ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1415                 task_rq_unlock(rq, p, &rf);
1416
1417                 /*
1418                  * If it changed from the expected state, bail out now.
1419                  */
1420                 if (unlikely(!ncsw))
1421                         break;
1422
1423                 /*
1424                  * Was it really running after all now that we
1425                  * checked with the proper locks actually held?
1426                  *
1427                  * Oops. Go back and try again..
1428                  */
1429                 if (unlikely(running)) {
1430                         cpu_relax();
1431                         continue;
1432                 }
1433
1434                 /*
1435                  * It's not enough that it's not actively running,
1436                  * it must be off the runqueue _entirely_, and not
1437                  * preempted!
1438                  *
1439                  * So if it was still runnable (but just not actively
1440                  * running right now), it's preempted, and we should
1441                  * yield - it could be a while.
1442                  */
1443                 if (unlikely(queued)) {
1444                         ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1445
1446                         set_current_state(TASK_UNINTERRUPTIBLE);
1447                         schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1448                         continue;
1449                 }
1450
1451                 /*
1452                  * Ahh, all good. It wasn't running, and it wasn't
1453                  * runnable, which means that it will never become
1454                  * running in the future either. We're all done!
1455                  */
1456                 break;
1457         }
1458
1459         return ncsw;
1460 }
1461
1462 /***
1463  * kick_process - kick a running thread to enter/exit the kernel
1464  * @p: the to-be-kicked thread
1465  *
1466  * Cause a process which is running on another CPU to enter
1467  * kernel-mode, without any delay. (to get signals handled.)
1468  *
1469  * NOTE: this function doesn't have to take the runqueue lock,
1470  * because all it wants to ensure is that the remote task enters
1471  * the kernel. If the IPI races and the task has been migrated
1472  * to another CPU then no harm is done and the purpose has been
1473  * achieved as well.
1474  */
1475 void kick_process(struct task_struct *p)
1476 {
1477         int cpu;
1478
1479         preempt_disable();
1480         cpu = task_cpu(p);
1481         if ((cpu != smp_processor_id()) && task_curr(p))
1482                 smp_send_reschedule(cpu);
1483         preempt_enable();
1484 }
1485 EXPORT_SYMBOL_GPL(kick_process);
1486
1487 /*
1488  * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1489  *
1490  * A few notes on cpu_active vs cpu_online:
1491  *
1492  *  - cpu_active must be a subset of cpu_online
1493  *
1494  *  - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1495  *    see __set_cpus_allowed_ptr(). At this point the newly online
1496  *    cpu isn't yet part of the sched domains, and balancing will not
1497  *    see it.
1498  *
1499  *  - on cpu-down we clear cpu_active() to mask the sched domains and
1500  *    avoid the load balancer to place new tasks on the to be removed
1501  *    cpu. Existing tasks will remain running there and will be taken
1502  *    off.
1503  *
1504  * This means that fallback selection must not select !active CPUs.
1505  * And can assume that any active CPU must be online. Conversely
1506  * select_task_rq() below may allow selection of !active CPUs in order
1507  * to satisfy the above rules.
1508  */
1509 static int select_fallback_rq(int cpu, struct task_struct *p)
1510 {
1511         int nid = cpu_to_node(cpu);
1512         const struct cpumask *nodemask = NULL;
1513         enum { cpuset, possible, fail } state = cpuset;
1514         int dest_cpu;
1515
1516         /*
1517          * If the node that the cpu is on has been offlined, cpu_to_node()
1518          * will return -1. There is no cpu on the node, and we should
1519          * select the cpu on the other node.
1520          */
1521         if (nid != -1) {
1522                 nodemask = cpumask_of_node(nid);
1523
1524                 /* Look for allowed, online CPU in same node. */
1525                 for_each_cpu(dest_cpu, nodemask) {
1526                         if (!cpu_active(dest_cpu))
1527                                 continue;
1528                         if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1529                                 return dest_cpu;
1530                 }
1531         }
1532
1533         for (;;) {
1534                 /* Any allowed, online CPU? */
1535                 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1536                         if (!cpu_active(dest_cpu))
1537                                 continue;
1538                         goto out;
1539                 }
1540
1541                 /* No more Mr. Nice Guy. */
1542                 switch (state) {
1543                 case cpuset:
1544                         if (IS_ENABLED(CONFIG_CPUSETS)) {
1545                                 cpuset_cpus_allowed_fallback(p);
1546                                 state = possible;
1547                                 break;
1548                         }
1549                         /* fall-through */
1550                 case possible:
1551                         do_set_cpus_allowed(p, cpu_possible_mask);
1552                         state = fail;
1553                         break;
1554
1555                 case fail:
1556                         BUG();
1557                         break;
1558                 }
1559         }
1560
1561 out:
1562         if (state != cpuset) {
1563                 /*
1564                  * Don't tell them about moving exiting tasks or
1565                  * kernel threads (both mm NULL), since they never
1566                  * leave kernel.
1567                  */
1568                 if (p->mm && printk_ratelimit()) {
1569                         printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1570                                         task_pid_nr(p), p->comm, cpu);
1571                 }
1572         }
1573
1574         return dest_cpu;
1575 }
1576
1577 /*
1578  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1579  */
1580 static inline
1581 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1582 {
1583         lockdep_assert_held(&p->pi_lock);
1584
1585         if (p->nr_cpus_allowed > 1)
1586                 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1587         else
1588                 cpu = cpumask_any(tsk_cpus_allowed(p));
1589
1590         /*
1591          * In order not to call set_task_cpu() on a blocking task we need
1592          * to rely on ttwu() to place the task on a valid ->cpus_allowed
1593          * cpu.
1594          *
1595          * Since this is common to all placement strategies, this lives here.
1596          *
1597          * [ this allows ->select_task() to simply return task_cpu(p) and
1598          *   not worry about this generic constraint ]
1599          */
1600         if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1601                      !cpu_online(cpu)))
1602                 cpu = select_fallback_rq(task_cpu(p), p);
1603
1604         return cpu;
1605 }
1606
1607 static void update_avg(u64 *avg, u64 sample)
1608 {
1609         s64 diff = sample - *avg;
1610         *avg += diff >> 3;
1611 }
1612
1613 #else
1614
1615 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1616                                          const struct cpumask *new_mask, bool check)
1617 {
1618         return set_cpus_allowed_ptr(p, new_mask);
1619 }
1620
1621 #endif /* CONFIG_SMP */
1622
1623 static void
1624 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1625 {
1626 #ifdef CONFIG_SCHEDSTATS
1627         struct rq *rq = this_rq();
1628
1629 #ifdef CONFIG_SMP
1630         int this_cpu = smp_processor_id();
1631
1632         if (cpu == this_cpu) {
1633                 schedstat_inc(rq, ttwu_local);
1634                 schedstat_inc(p, se.statistics.nr_wakeups_local);
1635         } else {
1636                 struct sched_domain *sd;
1637
1638                 schedstat_inc(p, se.statistics.nr_wakeups_remote);
1639                 rcu_read_lock();
1640                 for_each_domain(this_cpu, sd) {
1641                         if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1642                                 schedstat_inc(sd, ttwu_wake_remote);
1643                                 break;
1644                         }
1645                 }
1646                 rcu_read_unlock();
1647         }
1648
1649         if (wake_flags & WF_MIGRATED)
1650                 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1651
1652 #endif /* CONFIG_SMP */
1653
1654         schedstat_inc(rq, ttwu_count);
1655         schedstat_inc(p, se.statistics.nr_wakeups);
1656
1657         if (wake_flags & WF_SYNC)
1658                 schedstat_inc(p, se.statistics.nr_wakeups_sync);
1659
1660 #endif /* CONFIG_SCHEDSTATS */
1661 }
1662
1663 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1664 {
1665         activate_task(rq, p, en_flags);
1666         p->on_rq = TASK_ON_RQ_QUEUED;
1667
1668         /* if a worker is waking up, notify workqueue */
1669         if (p->flags & PF_WQ_WORKER)
1670                 wq_worker_waking_up(p, cpu_of(rq));
1671 }
1672
1673 /*
1674  * Mark the task runnable and perform wakeup-preemption.
1675  */
1676 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1677                            struct pin_cookie cookie)
1678 {
1679         check_preempt_curr(rq, p, wake_flags);
1680         p->state = TASK_RUNNING;
1681         trace_sched_wakeup(p);
1682
1683 #ifdef CONFIG_SMP
1684         if (p->sched_class->task_woken) {
1685                 /*
1686                  * Our task @p is fully woken up and running; so its safe to
1687                  * drop the rq->lock, hereafter rq is only used for statistics.
1688                  */
1689                 lockdep_unpin_lock(&rq->lock, cookie);
1690                 p->sched_class->task_woken(rq, p);
1691                 lockdep_repin_lock(&rq->lock, cookie);
1692         }
1693
1694         if (rq->idle_stamp) {
1695                 u64 delta = rq_clock(rq) - rq->idle_stamp;
1696                 u64 max = 2*rq->max_idle_balance_cost;
1697
1698                 update_avg(&rq->avg_idle, delta);
1699
1700                 if (rq->avg_idle > max)
1701                         rq->avg_idle = max;
1702
1703                 rq->idle_stamp = 0;
1704         }
1705 #endif
1706 }
1707
1708 static void
1709 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1710                  struct pin_cookie cookie)
1711 {
1712         int en_flags = ENQUEUE_WAKEUP;
1713
1714         lockdep_assert_held(&rq->lock);
1715
1716 #ifdef CONFIG_SMP
1717         if (p->sched_contributes_to_load)
1718                 rq->nr_uninterruptible--;
1719
1720         if (wake_flags & WF_MIGRATED)
1721                 en_flags |= ENQUEUE_MIGRATED;
1722 #endif
1723
1724         ttwu_activate(rq, p, en_flags);
1725         ttwu_do_wakeup(rq, p, wake_flags, cookie);
1726 }
1727
1728 /*
1729  * Called in case the task @p isn't fully descheduled from its runqueue,
1730  * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1731  * since all we need to do is flip p->state to TASK_RUNNING, since
1732  * the task is still ->on_rq.
1733  */
1734 static int ttwu_remote(struct task_struct *p, int wake_flags)
1735 {
1736         struct rq_flags rf;
1737         struct rq *rq;
1738         int ret = 0;
1739
1740         rq = __task_rq_lock(p, &rf);
1741         if (task_on_rq_queued(p)) {
1742                 /* check_preempt_curr() may use rq clock */
1743                 update_rq_clock(rq);
1744                 ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
1745                 ret = 1;
1746         }
1747         __task_rq_unlock(rq, &rf);
1748
1749         return ret;
1750 }
1751
1752 #ifdef CONFIG_SMP
1753 void sched_ttwu_pending(void)
1754 {
1755         struct rq *rq = this_rq();
1756         struct llist_node *llist = llist_del_all(&rq->wake_list);
1757         struct pin_cookie cookie;
1758         struct task_struct *p;
1759         unsigned long flags;
1760
1761         if (!llist)
1762                 return;
1763
1764         raw_spin_lock_irqsave(&rq->lock, flags);
1765         cookie = lockdep_pin_lock(&rq->lock);
1766
1767         while (llist) {
1768                 p = llist_entry(llist, struct task_struct, wake_entry);
1769                 llist = llist_next(llist);
1770                 /*
1771                  * See ttwu_queue(); we only call ttwu_queue_remote() when
1772                  * its a x-cpu wakeup.
1773                  */
1774                 ttwu_do_activate(rq, p, WF_MIGRATED, cookie);
1775         }
1776
1777         lockdep_unpin_lock(&rq->lock, cookie);
1778         raw_spin_unlock_irqrestore(&rq->lock, flags);
1779 }
1780
1781 void scheduler_ipi(void)
1782 {
1783         /*
1784          * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1785          * TIF_NEED_RESCHED remotely (for the first time) will also send
1786          * this IPI.
1787          */
1788         preempt_fold_need_resched();
1789
1790         if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1791                 return;
1792
1793         /*
1794          * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1795          * traditionally all their work was done from the interrupt return
1796          * path. Now that we actually do some work, we need to make sure
1797          * we do call them.
1798          *
1799          * Some archs already do call them, luckily irq_enter/exit nest
1800          * properly.
1801          *
1802          * Arguably we should visit all archs and update all handlers,
1803          * however a fair share of IPIs are still resched only so this would
1804          * somewhat pessimize the simple resched case.
1805          */
1806         irq_enter();
1807         sched_ttwu_pending();
1808
1809         /*
1810          * Check if someone kicked us for doing the nohz idle load balance.
1811          */
1812         if (unlikely(got_nohz_idle_kick())) {
1813                 this_rq()->idle_balance = 1;
1814                 raise_softirq_irqoff(SCHED_SOFTIRQ);
1815         }
1816         irq_exit();
1817 }
1818
1819 static void ttwu_queue_remote(struct task_struct *p, int cpu)
1820 {
1821         struct rq *rq = cpu_rq(cpu);
1822
1823         if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1824                 if (!set_nr_if_polling(rq->idle))
1825                         smp_send_reschedule(cpu);
1826                 else
1827                         trace_sched_wake_idle_without_ipi(cpu);
1828         }
1829 }
1830
1831 void wake_up_if_idle(int cpu)
1832 {
1833         struct rq *rq = cpu_rq(cpu);
1834         unsigned long flags;
1835
1836         rcu_read_lock();
1837
1838         if (!is_idle_task(rcu_dereference(rq->curr)))
1839                 goto out;
1840
1841         if (set_nr_if_polling(rq->idle)) {
1842                 trace_sched_wake_idle_without_ipi(cpu);
1843         } else {
1844                 raw_spin_lock_irqsave(&rq->lock, flags);
1845                 if (is_idle_task(rq->curr))
1846                         smp_send_reschedule(cpu);
1847                 /* Else cpu is not in idle, do nothing here */
1848                 raw_spin_unlock_irqrestore(&rq->lock, flags);
1849         }
1850
1851 out:
1852         rcu_read_unlock();
1853 }
1854
1855 bool cpus_share_cache(int this_cpu, int that_cpu)
1856 {
1857         return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1858 }
1859 #endif /* CONFIG_SMP */
1860
1861 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1862 {
1863         struct rq *rq = cpu_rq(cpu);
1864         struct pin_cookie cookie;
1865
1866 #if defined(CONFIG_SMP)
1867         if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1868                 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1869                 ttwu_queue_remote(p, cpu);
1870                 return;
1871         }
1872 #endif
1873
1874         raw_spin_lock(&rq->lock);
1875         cookie = lockdep_pin_lock(&rq->lock);
1876         ttwu_do_activate(rq, p, wake_flags, cookie);
1877         lockdep_unpin_lock(&rq->lock, cookie);
1878         raw_spin_unlock(&rq->lock);
1879 }
1880
1881 /*
1882  * Notes on Program-Order guarantees on SMP systems.
1883  *
1884  *  MIGRATION
1885  *
1886  * The basic program-order guarantee on SMP systems is that when a task [t]
1887  * migrates, all its activity on its old cpu [c0] happens-before any subsequent
1888  * execution on its new cpu [c1].
1889  *
1890  * For migration (of runnable tasks) this is provided by the following means:
1891  *
1892  *  A) UNLOCK of the rq(c0)->lock scheduling out task t
1893  *  B) migration for t is required to synchronize *both* rq(c0)->lock and
1894  *     rq(c1)->lock (if not at the same time, then in that order).
1895  *  C) LOCK of the rq(c1)->lock scheduling in task
1896  *
1897  * Transitivity guarantees that B happens after A and C after B.
1898  * Note: we only require RCpc transitivity.
1899  * Note: the cpu doing B need not be c0 or c1
1900  *
1901  * Example:
1902  *
1903  *   CPU0            CPU1            CPU2
1904  *
1905  *   LOCK rq(0)->lock
1906  *   sched-out X
1907  *   sched-in Y
1908  *   UNLOCK rq(0)->lock
1909  *
1910  *                                   LOCK rq(0)->lock // orders against CPU0
1911  *                                   dequeue X
1912  *                                   UNLOCK rq(0)->lock
1913  *
1914  *                                   LOCK rq(1)->lock
1915  *                                   enqueue X
1916  *                                   UNLOCK rq(1)->lock
1917  *
1918  *                   LOCK rq(1)->lock // orders against CPU2
1919  *                   sched-out Z
1920  *                   sched-in X
1921  *                   UNLOCK rq(1)->lock
1922  *
1923  *
1924  *  BLOCKING -- aka. SLEEP + WAKEUP
1925  *
1926  * For blocking we (obviously) need to provide the same guarantee as for
1927  * migration. However the means are completely different as there is no lock
1928  * chain to provide order. Instead we do:
1929  *
1930  *   1) smp_store_release(X->on_cpu, 0)
1931  *   2) smp_cond_acquire(!X->on_cpu)
1932  *
1933  * Example:
1934  *
1935  *   CPU0 (schedule)  CPU1 (try_to_wake_up) CPU2 (schedule)
1936  *
1937  *   LOCK rq(0)->lock LOCK X->pi_lock
1938  *   dequeue X
1939  *   sched-out X
1940  *   smp_store_release(X->on_cpu, 0);
1941  *
1942  *                    smp_cond_acquire(!X->on_cpu);
1943  *                    X->state = WAKING
1944  *                    set_task_cpu(X,2)
1945  *
1946  *                    LOCK rq(2)->lock
1947  *                    enqueue X
1948  *                    X->state = RUNNING
1949  *                    UNLOCK rq(2)->lock
1950  *
1951  *                                          LOCK rq(2)->lock // orders against CPU1
1952  *                                          sched-out Z
1953  *                                          sched-in X
1954  *                                          UNLOCK rq(2)->lock
1955  *
1956  *                    UNLOCK X->pi_lock
1957  *   UNLOCK rq(0)->lock
1958  *
1959  *
1960  * However; for wakeups there is a second guarantee we must provide, namely we
1961  * must observe the state that lead to our wakeup. That is, not only must our
1962  * task observe its own prior state, it must also observe the stores prior to
1963  * its wakeup.
1964  *
1965  * This means that any means of doing remote wakeups must order the CPU doing
1966  * the wakeup against the CPU the task is going to end up running on. This,
1967  * however, is already required for the regular Program-Order guarantee above,
1968  * since the waking CPU is the one issueing the ACQUIRE (smp_cond_acquire).
1969  *
1970  */
1971
1972 /**
1973  * try_to_wake_up - wake up a thread
1974  * @p: the thread to be awakened
1975  * @state: the mask of task states that can be woken
1976  * @wake_flags: wake modifier flags (WF_*)
1977  *
1978  * Put it on the run-queue if it's not already there. The "current"
1979  * thread is always on the run-queue (except when the actual
1980  * re-schedule is in progress), and as such you're allowed to do
1981  * the simpler "current->state = TASK_RUNNING" to mark yourself
1982  * runnable without the overhead of this.
1983  *
1984  * Return: %true if @p was woken up, %false if it was already running.
1985  * or @state didn't match @p's state.
1986  */
1987 static int
1988 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1989 {
1990         unsigned long flags;
1991         int cpu, success = 0;
1992
1993         /*
1994          * If we are going to wake up a thread waiting for CONDITION we
1995          * need to ensure that CONDITION=1 done by the caller can not be
1996          * reordered with p->state check below. This pairs with mb() in
1997          * set_current_state() the waiting thread does.
1998          */
1999         smp_mb__before_spinlock();
2000         raw_spin_lock_irqsave(&p->pi_lock, flags);
2001         if (!(p->state & state))
2002                 goto out;
2003
2004         trace_sched_waking(p);
2005
2006         success = 1; /* we're going to change ->state */
2007         cpu = task_cpu(p);
2008
2009         if (p->on_rq && ttwu_remote(p, wake_flags))
2010                 goto stat;
2011
2012 #ifdef CONFIG_SMP
2013         /*
2014          * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2015          * possible to, falsely, observe p->on_cpu == 0.
2016          *
2017          * One must be running (->on_cpu == 1) in order to remove oneself
2018          * from the runqueue.
2019          *
2020          *  [S] ->on_cpu = 1;   [L] ->on_rq
2021          *      UNLOCK rq->lock
2022          *                      RMB
2023          *      LOCK   rq->lock
2024          *  [S] ->on_rq = 0;    [L] ->on_cpu
2025          *
2026          * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2027          * from the consecutive calls to schedule(); the first switching to our
2028          * task, the second putting it to sleep.
2029          */
2030         smp_rmb();
2031
2032         /*
2033          * If the owning (remote) cpu is still in the middle of schedule() with
2034          * this task as prev, wait until its done referencing the task.
2035          *
2036          * Pairs with the smp_store_release() in finish_lock_switch().
2037          *
2038          * This ensures that tasks getting woken will be fully ordered against
2039          * their previous state and preserve Program Order.
2040          */
2041         smp_cond_acquire(!p->on_cpu);
2042
2043         p->sched_contributes_to_load = !!task_contributes_to_load(p);
2044         p->state = TASK_WAKING;
2045
2046         cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2047         if (task_cpu(p) != cpu) {
2048                 wake_flags |= WF_MIGRATED;
2049                 set_task_cpu(p, cpu);
2050         }
2051 #endif /* CONFIG_SMP */
2052
2053         ttwu_queue(p, cpu, wake_flags);
2054 stat:
2055         if (schedstat_enabled())
2056                 ttwu_stat(p, cpu, wake_flags);
2057 out:
2058         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2059
2060         return success;
2061 }
2062
2063 /**
2064  * try_to_wake_up_local - try to wake up a local task with rq lock held
2065  * @p: the thread to be awakened
2066  *
2067  * Put @p on the run-queue if it's not already there. The caller must
2068  * ensure that this_rq() is locked, @p is bound to this_rq() and not
2069  * the current task.
2070  */
2071 static void try_to_wake_up_local(struct task_struct *p, struct pin_cookie cookie)
2072 {
2073         struct rq *rq = task_rq(p);
2074
2075         if (WARN_ON_ONCE(rq != this_rq()) ||
2076             WARN_ON_ONCE(p == current))
2077                 return;
2078
2079         lockdep_assert_held(&rq->lock);
2080
2081         if (!raw_spin_trylock(&p->pi_lock)) {
2082                 /*
2083                  * This is OK, because current is on_cpu, which avoids it being
2084                  * picked for load-balance and preemption/IRQs are still
2085                  * disabled avoiding further scheduler activity on it and we've
2086                  * not yet picked a replacement task.
2087                  */
2088                 lockdep_unpin_lock(&rq->lock, cookie);
2089                 raw_spin_unlock(&rq->lock);
2090                 raw_spin_lock(&p->pi_lock);
2091                 raw_spin_lock(&rq->lock);
2092                 lockdep_repin_lock(&rq->lock, cookie);
2093         }
2094
2095         if (!(p->state & TASK_NORMAL))
2096                 goto out;
2097
2098         trace_sched_waking(p);
2099
2100         if (!task_on_rq_queued(p))
2101                 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2102
2103         ttwu_do_wakeup(rq, p, 0, cookie);
2104         if (schedstat_enabled())
2105                 ttwu_stat(p, smp_processor_id(), 0);
2106 out:
2107         raw_spin_unlock(&p->pi_lock);
2108 }
2109
2110 /**
2111  * wake_up_process - Wake up a specific process
2112  * @p: The process to be woken up.
2113  *
2114  * Attempt to wake up the nominated process and move it to the set of runnable
2115  * processes.
2116  *
2117  * Return: 1 if the process was woken up, 0 if it was already running.
2118  *
2119  * It may be assumed that this function implies a write memory barrier before
2120  * changing the task state if and only if any tasks are woken up.
2121  */
2122 int wake_up_process(struct task_struct *p)
2123 {
2124         return try_to_wake_up(p, TASK_NORMAL, 0);
2125 }
2126 EXPORT_SYMBOL(wake_up_process);
2127
2128 int wake_up_state(struct task_struct *p, unsigned int state)
2129 {
2130         return try_to_wake_up(p, state, 0);
2131 }
2132
2133 /*
2134  * This function clears the sched_dl_entity static params.
2135  */
2136 void __dl_clear_params(struct task_struct *p)
2137 {
2138         struct sched_dl_entity *dl_se = &p->dl;
2139
2140         dl_se->dl_runtime = 0;
2141         dl_se->dl_deadline = 0;
2142         dl_se->dl_period = 0;
2143         dl_se->flags = 0;
2144         dl_se->dl_bw = 0;
2145
2146         dl_se->dl_throttled = 0;
2147         dl_se->dl_yielded = 0;
2148 }
2149
2150 /*
2151  * Perform scheduler related setup for a newly forked process p.
2152  * p is forked by current.
2153  *
2154  * __sched_fork() is basic setup used by init_idle() too:
2155  */
2156 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2157 {
2158         p->on_rq                        = 0;
2159
2160         p->se.on_rq                     = 0;
2161         p->se.exec_start                = 0;
2162         p->se.sum_exec_runtime          = 0;
2163         p->se.prev_sum_exec_runtime     = 0;
2164         p->se.nr_migrations             = 0;
2165         p->se.vruntime                  = 0;
2166         INIT_LIST_HEAD(&p->se.group_node);
2167
2168 #ifdef CONFIG_FAIR_GROUP_SCHED
2169         p->se.cfs_rq                    = NULL;
2170 #endif
2171
2172 #ifdef CONFIG_SCHEDSTATS
2173         /* Even if schedstat is disabled, there should not be garbage */
2174         memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2175 #endif
2176
2177         RB_CLEAR_NODE(&p->dl.rb_node);
2178         init_dl_task_timer(&p->dl);
2179         __dl_clear_params(p);
2180
2181         INIT_LIST_HEAD(&p->rt.run_list);
2182         p->rt.timeout           = 0;
2183         p->rt.time_slice        = sched_rr_timeslice;
2184         p->rt.on_rq             = 0;
2185         p->rt.on_list           = 0;
2186
2187 #ifdef CONFIG_PREEMPT_NOTIFIERS
2188         INIT_HLIST_HEAD(&p->preempt_notifiers);
2189 #endif
2190
2191 #ifdef CONFIG_NUMA_BALANCING
2192         if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2193                 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2194                 p->mm->numa_scan_seq = 0;
2195         }
2196
2197         if (clone_flags & CLONE_VM)
2198                 p->numa_preferred_nid = current->numa_preferred_nid;
2199         else
2200                 p->numa_preferred_nid = -1;
2201
2202         p->node_stamp = 0ULL;
2203         p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2204         p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2205         p->numa_work.next = &p->numa_work;
2206         p->numa_faults = NULL;
2207         p->last_task_numa_placement = 0;
2208         p->last_sum_exec_runtime = 0;
2209
2210         p->numa_group = NULL;
2211 #endif /* CONFIG_NUMA_BALANCING */
2212 }
2213
2214 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2215
2216 #ifdef CONFIG_NUMA_BALANCING
2217
2218 void set_numabalancing_state(bool enabled)
2219 {
2220         if (enabled)
2221                 static_branch_enable(&sched_numa_balancing);
2222         else
2223                 static_branch_disable(&sched_numa_balancing);
2224 }
2225
2226 #ifdef CONFIG_PROC_SYSCTL
2227 int sysctl_numa_balancing(struct ctl_table *table, int write,
2228                          void __user *buffer, size_t *lenp, loff_t *ppos)
2229 {
2230         struct ctl_table t;
2231         int err;
2232         int state = static_branch_likely(&sched_numa_balancing);
2233
2234         if (write && !capable(CAP_SYS_ADMIN))
2235                 return -EPERM;
2236
2237         t = *table;
2238         t.data = &state;
2239         err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2240         if (err < 0)
2241                 return err;
2242         if (write)
2243                 set_numabalancing_state(state);
2244         return err;
2245 }
2246 #endif
2247 #endif
2248
2249 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2250
2251 #ifdef CONFIG_SCHEDSTATS
2252 static void set_schedstats(bool enabled)
2253 {
2254         if (enabled)
2255                 static_branch_enable(&sched_schedstats);
2256         else
2257                 static_branch_disable(&sched_schedstats);
2258 }
2259
2260 void force_schedstat_enabled(void)
2261 {
2262         if (!schedstat_enabled()) {
2263                 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2264                 static_branch_enable(&sched_schedstats);
2265         }
2266 }
2267
2268 static int __init setup_schedstats(char *str)
2269 {
2270         int ret = 0;
2271         if (!str)
2272                 goto out;
2273
2274         if (!strcmp(str, "enable")) {
2275                 set_schedstats(true);
2276                 ret = 1;
2277         } else if (!strcmp(str, "disable")) {
2278                 set_schedstats(false);
2279                 ret = 1;
2280         }
2281 out:
2282         if (!ret)
2283                 pr_warn("Unable to parse schedstats=\n");
2284
2285         return ret;
2286 }
2287 __setup("schedstats=", setup_schedstats);
2288
2289 #ifdef CONFIG_PROC_SYSCTL
2290 int sysctl_schedstats(struct ctl_table *table, int write,
2291                          void __user *buffer, size_t *lenp, loff_t *ppos)
2292 {
2293         struct ctl_table t;
2294         int err;
2295         int state = static_branch_likely(&sched_schedstats);
2296
2297         if (write && !capable(CAP_SYS_ADMIN))
2298                 return -EPERM;
2299
2300         t = *table;
2301         t.data = &state;
2302         err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2303         if (err < 0)
2304                 return err;
2305         if (write)
2306                 set_schedstats(state);
2307         return err;
2308 }
2309 #endif
2310 #endif
2311
2312 /*
2313  * fork()/clone()-time setup:
2314  */
2315 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2316 {
2317         unsigned long flags;
2318         int cpu = get_cpu();
2319
2320         __sched_fork(clone_flags, p);
2321         /*
2322          * We mark the process as running here. This guarantees that
2323          * nobody will actually run it, and a signal or other external
2324          * event cannot wake it up and insert it on the runqueue either.
2325          */
2326         p->state = TASK_RUNNING;
2327
2328         /*
2329          * Make sure we do not leak PI boosting priority to the child.
2330          */
2331         p->prio = current->normal_prio;
2332
2333         /*
2334          * Revert to default priority/policy on fork if requested.
2335          */
2336         if (unlikely(p->sched_reset_on_fork)) {
2337                 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2338                         p->policy = SCHED_NORMAL;
2339                         p->static_prio = NICE_TO_PRIO(0);
2340                         p->rt_priority = 0;
2341                 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2342                         p->static_prio = NICE_TO_PRIO(0);
2343
2344                 p->prio = p->normal_prio = __normal_prio(p);
2345                 set_load_weight(p);
2346
2347                 /*
2348                  * We don't need the reset flag anymore after the fork. It has
2349                  * fulfilled its duty:
2350                  */
2351                 p->sched_reset_on_fork = 0;
2352         }
2353
2354         if (dl_prio(p->prio)) {
2355                 put_cpu();
2356                 return -EAGAIN;
2357         } else if (rt_prio(p->prio)) {
2358                 p->sched_class = &rt_sched_class;
2359         } else {
2360                 p->sched_class = &fair_sched_class;
2361         }
2362
2363         if (p->sched_class->task_fork)
2364                 p->sched_class->task_fork(p);
2365
2366         /*
2367          * The child is not yet in the pid-hash so no cgroup attach races,
2368          * and the cgroup is pinned to this child due to cgroup_fork()
2369          * is ran before sched_fork().
2370          *
2371          * Silence PROVE_RCU.
2372          */
2373         raw_spin_lock_irqsave(&p->pi_lock, flags);
2374         set_task_cpu(p, cpu);
2375         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2376
2377 #ifdef CONFIG_SCHED_INFO
2378         if (likely(sched_info_on()))
2379                 memset(&p->sched_info, 0, sizeof(p->sched_info));
2380 #endif
2381 #if defined(CONFIG_SMP)
2382         p->on_cpu = 0;
2383 #endif
2384         init_task_preempt_count(p);
2385 #ifdef CONFIG_SMP
2386         plist_node_init(&p->pushable_tasks, MAX_PRIO);
2387         RB_CLEAR_NODE(&p->pushable_dl_tasks);
2388 #endif
2389
2390         put_cpu();
2391         return 0;
2392 }
2393
2394 unsigned long to_ratio(u64 period, u64 runtime)
2395 {
2396         if (runtime == RUNTIME_INF)
2397                 return 1ULL << 20;
2398
2399         /*
2400          * Doing this here saves a lot of checks in all
2401          * the calling paths, and returning zero seems
2402          * safe for them anyway.
2403          */
2404         if (period == 0)
2405                 return 0;
2406
2407         return div64_u64(runtime << 20, period);
2408 }
2409
2410 #ifdef CONFIG_SMP
2411 inline struct dl_bw *dl_bw_of(int i)
2412 {
2413         RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2414                          "sched RCU must be held");
2415         return &cpu_rq(i)->rd->dl_bw;
2416 }
2417
2418 static inline int dl_bw_cpus(int i)
2419 {
2420         struct root_domain *rd = cpu_rq(i)->rd;
2421         int cpus = 0;
2422
2423         RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2424                          "sched RCU must be held");
2425         for_each_cpu_and(i, rd->span, cpu_active_mask)
2426                 cpus++;
2427
2428         return cpus;
2429 }
2430 #else
2431 inline struct dl_bw *dl_bw_of(int i)
2432 {
2433         return &cpu_rq(i)->dl.dl_bw;
2434 }
2435
2436 static inline int dl_bw_cpus(int i)
2437 {
2438         return 1;
2439 }
2440 #endif
2441
2442 /*
2443  * We must be sure that accepting a new task (or allowing changing the
2444  * parameters of an existing one) is consistent with the bandwidth
2445  * constraints. If yes, this function also accordingly updates the currently
2446  * allocated bandwidth to reflect the new situation.
2447  *
2448  * This function is called while holding p's rq->lock.
2449  *
2450  * XXX we should delay bw change until the task's 0-lag point, see
2451  * __setparam_dl().
2452  */
2453 static int dl_overflow(struct task_struct *p, int policy,
2454                        const struct sched_attr *attr)
2455 {
2456
2457         struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2458         u64 period = attr->sched_period ?: attr->sched_deadline;
2459         u64 runtime = attr->sched_runtime;
2460         u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2461         int cpus, err = -1;
2462
2463         /* !deadline task may carry old deadline bandwidth */
2464         if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2465                 return 0;
2466
2467         /*
2468          * Either if a task, enters, leave, or stays -deadline but changes
2469          * its parameters, we may need to update accordingly the total
2470          * allocated bandwidth of the container.
2471          */
2472         raw_spin_lock(&dl_b->lock);
2473         cpus = dl_bw_cpus(task_cpu(p));
2474         if (dl_policy(policy) && !task_has_dl_policy(p) &&
2475             !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2476                 __dl_add(dl_b, new_bw);
2477                 err = 0;
2478         } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2479                    !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2480                 __dl_clear(dl_b, p->dl.dl_bw);
2481                 __dl_add(dl_b, new_bw);
2482                 err = 0;
2483         } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2484                 __dl_clear(dl_b, p->dl.dl_bw);
2485                 err = 0;
2486         }
2487         raw_spin_unlock(&dl_b->lock);
2488
2489         return err;
2490 }
2491
2492 extern void init_dl_bw(struct dl_bw *dl_b);
2493
2494 /*
2495  * wake_up_new_task - wake up a newly created task for the first time.
2496  *
2497  * This function will do some initial scheduler statistics housekeeping
2498  * that must be done for every newly created context, then puts the task
2499  * on the runqueue and wakes it.
2500  */
2501 void wake_up_new_task(struct task_struct *p)
2502 {
2503         struct rq_flags rf;
2504         struct rq *rq;
2505
2506         /* Initialize new task's runnable average */
2507         init_entity_runnable_average(&p->se);
2508         raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2509 #ifdef CONFIG_SMP
2510         /*
2511          * Fork balancing, do it here and not earlier because:
2512          *  - cpus_allowed can change in the fork path
2513          *  - any previously selected cpu might disappear through hotplug
2514          */
2515         set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2516 #endif
2517         /* Post initialize new task's util average when its cfs_rq is set */
2518         post_init_entity_util_avg(&p->se);
2519
2520         rq = __task_rq_lock(p, &rf);
2521         activate_task(rq, p, 0);
2522         p->on_rq = TASK_ON_RQ_QUEUED;
2523         trace_sched_wakeup_new(p);
2524         check_preempt_curr(rq, p, WF_FORK);
2525 #ifdef CONFIG_SMP
2526         if (p->sched_class->task_woken) {
2527                 /*
2528                  * Nothing relies on rq->lock after this, so its fine to
2529                  * drop it.
2530                  */
2531                 lockdep_unpin_lock(&rq->lock, rf.cookie);
2532                 p->sched_class->task_woken(rq, p);
2533                 lockdep_repin_lock(&rq->lock, rf.cookie);
2534         }
2535 #endif
2536         task_rq_unlock(rq, p, &rf);
2537 }
2538
2539 #ifdef CONFIG_PREEMPT_NOTIFIERS
2540
2541 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2542
2543 void preempt_notifier_inc(void)
2544 {
2545         static_key_slow_inc(&preempt_notifier_key);
2546 }
2547 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2548
2549 void preempt_notifier_dec(void)
2550 {
2551         static_key_slow_dec(&preempt_notifier_key);
2552 }
2553 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2554
2555 /**
2556  * preempt_notifier_register - tell me when current is being preempted & rescheduled
2557  * @notifier: notifier struct to register
2558  */
2559 void preempt_notifier_register(struct preempt_notifier *notifier)
2560 {
2561         if (!static_key_false(&preempt_notifier_key))
2562                 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2563
2564         hlist_add_head(&notifier->link, &current->preempt_notifiers);
2565 }
2566 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2567
2568 /**
2569  * preempt_notifier_unregister - no longer interested in preemption notifications
2570  * @notifier: notifier struct to unregister
2571  *
2572  * This is *not* safe to call from within a preemption notifier.
2573  */
2574 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2575 {
2576         hlist_del(&notifier->link);
2577 }
2578 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2579
2580 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2581 {
2582         struct preempt_notifier *notifier;
2583
2584         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2585                 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2586 }
2587
2588 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2589 {
2590         if (static_key_false(&preempt_notifier_key))
2591                 __fire_sched_in_preempt_notifiers(curr);
2592 }
2593
2594 static void
2595 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2596                                    struct task_struct *next)
2597 {
2598         struct preempt_notifier *notifier;
2599
2600         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2601                 notifier->ops->sched_out(notifier, next);
2602 }
2603
2604 static __always_inline void
2605 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2606                                  struct task_struct *next)
2607 {
2608         if (static_key_false(&preempt_notifier_key))
2609                 __fire_sched_out_preempt_notifiers(curr, next);
2610 }
2611
2612 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2613
2614 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2615 {
2616 }
2617
2618 static inline void
2619 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2620                                  struct task_struct *next)
2621 {
2622 }
2623
2624 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2625
2626 /**
2627  * prepare_task_switch - prepare to switch tasks
2628  * @rq: the runqueue preparing to switch
2629  * @prev: the current task that is being switched out
2630  * @next: the task we are going to switch to.
2631  *
2632  * This is called with the rq lock held and interrupts off. It must
2633  * be paired with a subsequent finish_task_switch after the context
2634  * switch.
2635  *
2636  * prepare_task_switch sets up locking and calls architecture specific
2637  * hooks.
2638  */
2639 static inline void
2640 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2641                     struct task_struct *next)
2642 {
2643         sched_info_switch(rq, prev, next);
2644         perf_event_task_sched_out(prev, next);
2645         fire_sched_out_preempt_notifiers(prev, next);
2646         prepare_lock_switch(rq, next);
2647         prepare_arch_switch(next);
2648 }
2649
2650 /**
2651  * finish_task_switch - clean up after a task-switch
2652  * @prev: the thread we just switched away from.
2653  *
2654  * finish_task_switch must be called after the context switch, paired
2655  * with a prepare_task_switch call before the context switch.
2656  * finish_task_switch will reconcile locking set up by prepare_task_switch,
2657  * and do any other architecture-specific cleanup actions.
2658  *
2659  * Note that we may have delayed dropping an mm in context_switch(). If
2660  * so, we finish that here outside of the runqueue lock. (Doing it
2661  * with the lock held can cause deadlocks; see schedule() for
2662  * details.)
2663  *
2664  * The context switch have flipped the stack from under us and restored the
2665  * local variables which were saved when this task called schedule() in the
2666  * past. prev == current is still correct but we need to recalculate this_rq
2667  * because prev may have moved to another CPU.
2668  */
2669 static struct rq *finish_task_switch(struct task_struct *prev)
2670         __releases(rq->lock)
2671 {
2672         struct rq *rq = this_rq();
2673         struct mm_struct *mm = rq->prev_mm;
2674         long prev_state;
2675
2676         /*
2677          * The previous task will have left us with a preempt_count of 2
2678          * because it left us after:
2679          *
2680          *      schedule()
2681          *        preempt_disable();                    // 1
2682          *        __schedule()
2683          *          raw_spin_lock_irq(&rq->lock)        // 2
2684          *
2685          * Also, see FORK_PREEMPT_COUNT.
2686          */
2687         if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2688                       "corrupted preempt_count: %s/%d/0x%x\n",
2689                       current->comm, current->pid, preempt_count()))
2690                 preempt_count_set(FORK_PREEMPT_COUNT);
2691
2692         rq->prev_mm = NULL;
2693
2694         /*
2695          * A task struct has one reference for the use as "current".
2696          * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2697          * schedule one last time. The schedule call will never return, and
2698          * the scheduled task must drop that reference.
2699          *
2700          * We must observe prev->state before clearing prev->on_cpu (in
2701          * finish_lock_switch), otherwise a concurrent wakeup can get prev
2702          * running on another CPU and we could rave with its RUNNING -> DEAD
2703          * transition, resulting in a double drop.
2704          */
2705         prev_state = prev->state;
2706         vtime_task_switch(prev);
2707         perf_event_task_sched_in(prev, current);
2708         finish_lock_switch(rq, prev);
2709         finish_arch_post_lock_switch();
2710
2711         fire_sched_in_preempt_notifiers(current);
2712         if (mm)
2713                 mmdrop(mm);
2714         if (unlikely(prev_state == TASK_DEAD)) {
2715                 if (prev->sched_class->task_dead)
2716                         prev->sched_class->task_dead(prev);
2717
2718                 /*
2719                  * Remove function-return probe instances associated with this
2720                  * task and put them back on the free list.
2721                  */
2722                 kprobe_flush_task(prev);
2723                 put_task_struct(prev);
2724         }
2725
2726         tick_nohz_task_switch();
2727         return rq;
2728 }
2729
2730 #ifdef CONFIG_SMP
2731
2732 /* rq->lock is NOT held, but preemption is disabled */
2733 static void __balance_callback(struct rq *rq)
2734 {
2735         struct callback_head *head, *next;
2736         void (*func)(struct rq *rq);
2737         unsigned long flags;
2738
2739         raw_spin_lock_irqsave(&rq->lock, flags);
2740         head = rq->balance_callback;
2741         rq->balance_callback = NULL;
2742         while (head) {
2743                 func = (void (*)(struct rq *))head->func;
2744                 next = head->next;
2745                 head->next = NULL;
2746                 head = next;
2747
2748                 func(rq);
2749         }
2750         raw_spin_unlock_irqrestore(&rq->lock, flags);
2751 }
2752
2753 static inline void balance_callback(struct rq *rq)
2754 {
2755         if (unlikely(rq->balance_callback))
2756                 __balance_callback(rq);
2757 }
2758
2759 #else
2760
2761 static inline void balance_callback(struct rq *rq)
2762 {
2763 }
2764
2765 #endif
2766
2767 /**
2768  * schedule_tail - first thing a freshly forked thread must call.
2769  * @prev: the thread we just switched away from.
2770  */
2771 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2772         __releases(rq->lock)
2773 {
2774         struct rq *rq;
2775
2776         /*
2777          * New tasks start with FORK_PREEMPT_COUNT, see there and
2778          * finish_task_switch() for details.
2779          *
2780          * finish_task_switch() will drop rq->lock() and lower preempt_count
2781          * and the preempt_enable() will end up enabling preemption (on
2782          * PREEMPT_COUNT kernels).
2783          */
2784
2785         rq = finish_task_switch(prev);
2786         balance_callback(rq);
2787         preempt_enable();
2788
2789         if (current->set_child_tid)
2790                 put_user(task_pid_vnr(current), current->set_child_tid);
2791 }
2792
2793 /*
2794  * context_switch - switch to the new MM and the new thread's register state.
2795  */
2796 static __always_inline struct rq *
2797 context_switch(struct rq *rq, struct task_struct *prev,
2798                struct task_struct *next, struct pin_cookie cookie)
2799 {
2800         struct mm_struct *mm, *oldmm;
2801
2802         prepare_task_switch(rq, prev, next);
2803
2804         mm = next->mm;
2805         oldmm = prev->active_mm;
2806         /*
2807          * For paravirt, this is coupled with an exit in switch_to to
2808          * combine the page table reload and the switch backend into
2809          * one hypercall.
2810          */
2811         arch_start_context_switch(prev);
2812
2813         if (!mm) {
2814                 next->active_mm = oldmm;
2815                 atomic_inc(&oldmm->mm_count);
2816                 enter_lazy_tlb(oldmm, next);
2817         } else
2818                 switch_mm_irqs_off(oldmm, mm, next);
2819
2820         if (!prev->mm) {
2821                 prev->active_mm = NULL;
2822                 rq->prev_mm = oldmm;
2823         }
2824         /*
2825          * Since the runqueue lock will be released by the next
2826          * task (which is an invalid locking op but in the case
2827          * of the scheduler it's an obvious special-case), so we
2828          * do an early lockdep release here:
2829          */
2830         lockdep_unpin_lock(&rq->lock, cookie);
2831         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2832
2833         /* Here we just switch the register state and the stack. */
2834         switch_to(prev, next, prev);
2835         barrier();
2836
2837         return finish_task_switch(prev);
2838 }
2839
2840 /*
2841  * nr_running and nr_context_switches:
2842  *
2843  * externally visible scheduler statistics: current number of runnable
2844  * threads, total number of context switches performed since bootup.
2845  */
2846 unsigned long nr_running(void)
2847 {
2848         unsigned long i, sum = 0;
2849
2850         for_each_online_cpu(i)
2851                 sum += cpu_rq(i)->nr_running;
2852
2853         return sum;
2854 }
2855
2856 /*
2857  * Check if only the current task is running on the cpu.
2858  *
2859  * Caution: this function does not check that the caller has disabled
2860  * preemption, thus the result might have a time-of-check-to-time-of-use
2861  * race.  The caller is responsible to use it correctly, for example:
2862  *
2863  * - from a non-preemptable section (of course)
2864  *
2865  * - from a thread that is bound to a single CPU
2866  *
2867  * - in a loop with very short iterations (e.g. a polling loop)
2868  */
2869 bool single_task_running(void)
2870 {
2871         return raw_rq()->nr_running == 1;
2872 }
2873 EXPORT_SYMBOL(single_task_running);
2874
2875 unsigned long long nr_context_switches(void)
2876 {
2877         int i;
2878         unsigned long long sum = 0;
2879
2880         for_each_possible_cpu(i)
2881                 sum += cpu_rq(i)->nr_switches;
2882
2883         return sum;
2884 }
2885
2886 unsigned long nr_iowait(void)
2887 {
2888         unsigned long i, sum = 0;
2889
2890         for_each_possible_cpu(i)
2891                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2892
2893         return sum;
2894 }
2895
2896 unsigned long nr_iowait_cpu(int cpu)
2897 {
2898         struct rq *this = cpu_rq(cpu);
2899         return atomic_read(&this->nr_iowait);
2900 }
2901
2902 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2903 {
2904         struct rq *rq = this_rq();
2905         *nr_waiters = atomic_read(&rq->nr_iowait);
2906         *load = rq->load.weight;
2907 }
2908
2909 #ifdef CONFIG_SMP
2910
2911 /*
2912  * sched_exec - execve() is a valuable balancing opportunity, because at
2913  * this point the task has the smallest effective memory and cache footprint.
2914  */
2915 void sched_exec(void)
2916 {
2917         struct task_struct *p = current;
2918         unsigned long flags;
2919         int dest_cpu;
2920
2921         raw_spin_lock_irqsave(&p->pi_lock, flags);
2922         dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2923         if (dest_cpu == smp_processor_id())
2924                 goto unlock;
2925
2926         if (likely(cpu_active(dest_cpu))) {
2927                 struct migration_arg arg = { p, dest_cpu };
2928
2929                 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2930                 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2931                 return;
2932         }
2933 unlock:
2934         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2935 }
2936
2937 #endif
2938
2939 DEFINE_PER_CPU(struct kernel_stat, kstat);
2940 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2941
2942 EXPORT_PER_CPU_SYMBOL(kstat);
2943 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2944
2945 /*
2946  * Return accounted runtime for the task.
2947  * In case the task is currently running, return the runtime plus current's
2948  * pending runtime that have not been accounted yet.
2949  */
2950 unsigned long long task_sched_runtime(struct task_struct *p)
2951 {
2952         struct rq_flags rf;
2953         struct rq *rq;
2954         u64 ns;
2955
2956 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2957         /*
2958          * 64-bit doesn't need locks to atomically read a 64bit value.
2959          * So we have a optimization chance when the task's delta_exec is 0.
2960          * Reading ->on_cpu is racy, but this is ok.
2961          *
2962          * If we race with it leaving cpu, we'll take a lock. So we're correct.
2963          * If we race with it entering cpu, unaccounted time is 0. This is
2964          * indistinguishable from the read occurring a few cycles earlier.
2965          * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2966          * been accounted, so we're correct here as well.
2967          */
2968         if (!p->on_cpu || !task_on_rq_queued(p))
2969                 return p->se.sum_exec_runtime;
2970 #endif
2971
2972         rq = task_rq_lock(p, &rf);
2973         /*
2974          * Must be ->curr _and_ ->on_rq.  If dequeued, we would
2975          * project cycles that may never be accounted to this
2976          * thread, breaking clock_gettime().
2977          */
2978         if (task_current(rq, p) && task_on_rq_queued(p)) {
2979                 update_rq_clock(rq);
2980                 p->sched_class->update_curr(rq);
2981         }
2982         ns = p->se.sum_exec_runtime;
2983         task_rq_unlock(rq, p, &rf);
2984
2985         return ns;
2986 }
2987
2988 /*
2989  * This function gets called by the timer code, with HZ frequency.
2990  * We call it with interrupts disabled.
2991  */
2992 void scheduler_tick(void)
2993 {
2994         int cpu = smp_processor_id();
2995         struct rq *rq = cpu_rq(cpu);
2996         struct task_struct *curr = rq->curr;
2997
2998         sched_clock_tick();
2999
3000         raw_spin_lock(&rq->lock);
3001         update_rq_clock(rq);
3002         curr->sched_class->task_tick(rq, curr, 0);
3003         cpu_load_update_active(rq);
3004         calc_global_load_tick(rq);
3005         raw_spin_unlock(&rq->lock);
3006
3007         perf_event_task_tick();
3008
3009 #ifdef CONFIG_SMP
3010         rq->idle_balance = idle_cpu(cpu);
3011         trigger_load_balance(rq);
3012 #endif
3013         rq_last_tick_reset(rq);
3014 }
3015
3016 #ifdef CONFIG_NO_HZ_FULL
3017 /**
3018  * scheduler_tick_max_deferment
3019  *
3020  * Keep at least one tick per second when a single
3021  * active task is running because the scheduler doesn't
3022  * yet completely support full dynticks environment.
3023  *
3024  * This makes sure that uptime, CFS vruntime, load
3025  * balancing, etc... continue to move forward, even
3026  * with a very low granularity.
3027  *
3028  * Return: Maximum deferment in nanoseconds.
3029  */
3030 u64 scheduler_tick_max_deferment(void)
3031 {
3032         struct rq *rq = this_rq();
3033         unsigned long next, now = READ_ONCE(jiffies);
3034
3035         next = rq->last_sched_tick + HZ;
3036
3037         if (time_before_eq(next, now))
3038                 return 0;
3039
3040         return jiffies_to_nsecs(next - now);
3041 }
3042 #endif
3043
3044 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3045                                 defined(CONFIG_PREEMPT_TRACER))
3046 /*
3047  * If the value passed in is equal to the current preempt count
3048  * then we just disabled preemption. Start timing the latency.
3049  */
3050 static inline void preempt_latency_start(int val)
3051 {
3052         if (preempt_count() == val) {
3053                 unsigned long ip = get_lock_parent_ip();
3054 #ifdef CONFIG_DEBUG_PREEMPT
3055                 current->preempt_disable_ip = ip;
3056 #endif
3057                 trace_preempt_off(CALLER_ADDR0, ip);
3058         }
3059 }
3060
3061 void preempt_count_add(int val)
3062 {
3063 #ifdef CONFIG_DEBUG_PREEMPT
3064         /*
3065          * Underflow?
3066          */
3067         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3068                 return;
3069 #endif
3070         __preempt_count_add(val);
3071 #ifdef CONFIG_DEBUG_PREEMPT
3072         /*
3073          * Spinlock count overflowing soon?
3074          */
3075         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3076                                 PREEMPT_MASK - 10);
3077 #endif
3078         preempt_latency_start(val);
3079 }
3080 EXPORT_SYMBOL(preempt_count_add);
3081 NOKPROBE_SYMBOL(preempt_count_add);
3082
3083 /*
3084  * If the value passed in equals to the current preempt count
3085  * then we just enabled preemption. Stop timing the latency.
3086  */
3087 static inline void preempt_latency_stop(int val)
3088 {
3089         if (preempt_count() == val)
3090                 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3091 }
3092
3093 void preempt_count_sub(int val)
3094 {
3095 #ifdef CONFIG_DEBUG_PREEMPT
3096         /*
3097          * Underflow?
3098          */
3099         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3100                 return;
3101         /*
3102          * Is the spinlock portion underflowing?
3103          */
3104         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3105                         !(preempt_count() & PREEMPT_MASK)))
3106                 return;
3107 #endif
3108
3109         preempt_latency_stop(val);
3110         __preempt_count_sub(val);
3111 }
3112 EXPORT_SYMBOL(preempt_count_sub);
3113 NOKPROBE_SYMBOL(preempt_count_sub);
3114
3115 #else
3116 static inline void preempt_latency_start(int val) { }
3117 static inline void preempt_latency_stop(int val) { }
3118 #endif
3119
3120 /*
3121  * Print scheduling while atomic bug:
3122  */
3123 static noinline void __schedule_bug(struct task_struct *prev)
3124 {
3125         if (oops_in_progress)
3126                 return;
3127
3128         printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3129                 prev->comm, prev->pid, preempt_count());
3130
3131         debug_show_held_locks(prev);
3132         print_modules();
3133         if (irqs_disabled())
3134                 print_irqtrace_events(prev);
3135 #ifdef CONFIG_DEBUG_PREEMPT
3136         if (in_atomic_preempt_off()) {
3137                 pr_err("Preemption disabled at:");
3138                 print_ip_sym(current->preempt_disable_ip);
3139                 pr_cont("\n");
3140         }
3141 #endif
3142         dump_stack();
3143         add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3144 }
3145
3146 /*
3147  * Various schedule()-time debugging checks and statistics:
3148  */
3149 static inline void schedule_debug(struct task_struct *prev)
3150 {
3151 #ifdef CONFIG_SCHED_STACK_END_CHECK
3152         BUG_ON(task_stack_end_corrupted(prev));
3153 #endif
3154
3155         if (unlikely(in_atomic_preempt_off())) {
3156                 __schedule_bug(prev);
3157                 preempt_count_set(PREEMPT_DISABLED);
3158         }
3159         rcu_sleep_check();
3160
3161         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3162
3163         schedstat_inc(this_rq(), sched_count);
3164 }
3165
3166 /*
3167  * Pick up the highest-prio task:
3168  */
3169 static inline struct task_struct *
3170 pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
3171 {
3172         const struct sched_class *class = &fair_sched_class;
3173         struct task_struct *p;
3174
3175         /*
3176          * Optimization: we know that if all tasks are in
3177          * the fair class we can call that function directly:
3178          */
3179         if (likely(prev->sched_class == class &&
3180                    rq->nr_running == rq->cfs.h_nr_running)) {
3181                 p = fair_sched_class.pick_next_task(rq, prev, cookie);
3182                 if (unlikely(p == RETRY_TASK))
3183                         goto again;
3184
3185                 /* assumes fair_sched_class->next == idle_sched_class */
3186                 if (unlikely(!p))
3187                         p = idle_sched_class.pick_next_task(rq, prev, cookie);
3188
3189                 return p;
3190         }
3191
3192 again:
3193         for_each_class(class) {
3194                 p = class->pick_next_task(rq, prev, cookie);
3195                 if (p) {
3196                         if (unlikely(p == RETRY_TASK))
3197                                 goto again;
3198                         return p;
3199                 }
3200         }
3201
3202         BUG(); /* the idle class will always have a runnable task */
3203 }
3204
3205 /*
3206  * __schedule() is the main scheduler function.
3207  *
3208  * The main means of driving the scheduler and thus entering this function are:
3209  *
3210  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3211  *
3212  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3213  *      paths. For example, see arch/x86/entry_64.S.
3214  *
3215  *      To drive preemption between tasks, the scheduler sets the flag in timer
3216  *      interrupt handler scheduler_tick().
3217  *
3218  *   3. Wakeups don't really cause entry into schedule(). They add a
3219  *      task to the run-queue and that's it.
3220  *
3221  *      Now, if the new task added to the run-queue preempts the current
3222  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3223  *      called on the nearest possible occasion:
3224  *
3225  *       - If the kernel is preemptible (CONFIG_PREEMPT=y):
3226  *
3227  *         - in syscall or exception context, at the next outmost
3228  *           preempt_enable(). (this might be as soon as the wake_up()'s
3229  *           spin_unlock()!)
3230  *
3231  *         - in IRQ context, return from interrupt-handler to
3232  *           preemptible context
3233  *
3234  *       - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3235  *         then at the next:
3236  *
3237  *          - cond_resched() call
3238  *          - explicit schedule() call
3239  *          - return from syscall or exception to user-space
3240  *          - return from interrupt-handler to user-space
3241  *
3242  * WARNING: must be called with preemption disabled!
3243  */
3244 static void __sched notrace __schedule(bool preempt)
3245 {
3246         struct task_struct *prev, *next;
3247         unsigned long *switch_count;
3248         struct pin_cookie cookie;
3249         struct rq *rq;
3250         int cpu;
3251
3252         cpu = smp_processor_id();
3253         rq = cpu_rq(cpu);
3254         prev = rq->curr;
3255
3256         /*
3257          * do_exit() calls schedule() with preemption disabled as an exception;
3258          * however we must fix that up, otherwise the next task will see an
3259          * inconsistent (higher) preempt count.
3260          *
3261          * It also avoids the below schedule_debug() test from complaining
3262          * about this.
3263          */
3264         if (unlikely(prev->state == TASK_DEAD))
3265                 preempt_enable_no_resched_notrace();
3266
3267         schedule_debug(prev);
3268
3269         if (sched_feat(HRTICK))
3270                 hrtick_clear(rq);
3271
3272         local_irq_disable();
3273         rcu_note_context_switch();
3274
3275         /*
3276          * Make sure that signal_pending_state()->signal_pending() below
3277          * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3278          * done by the caller to avoid the race with signal_wake_up().
3279          */
3280         smp_mb__before_spinlock();
3281         raw_spin_lock(&rq->lock);
3282         cookie = lockdep_pin_lock(&rq->lock);
3283
3284         rq->clock_skip_update <<= 1; /* promote REQ to ACT */
3285
3286         switch_count = &prev->nivcsw;
3287         if (!preempt && prev->state) {
3288                 if (unlikely(signal_pending_state(prev->state, prev))) {
3289                         prev->state = TASK_RUNNING;
3290                 } else {
3291                         deactivate_task(rq, prev, DEQUEUE_SLEEP);
3292                         prev->on_rq = 0;
3293
3294                         /*
3295                          * If a worker went to sleep, notify and ask workqueue
3296                          * whether it wants to wake up a task to maintain
3297                          * concurrency.
3298                          */
3299                         if (prev->flags & PF_WQ_WORKER) {
3300                                 struct task_struct *to_wakeup;
3301
3302                                 to_wakeup = wq_worker_sleeping(prev);
3303                                 if (to_wakeup)
3304                                         try_to_wake_up_local(to_wakeup, cookie);
3305                         }
3306                 }
3307                 switch_count = &prev->nvcsw;
3308         }
3309
3310         if (task_on_rq_queued(prev))
3311                 update_rq_clock(rq);
3312
3313         next = pick_next_task(rq, prev, cookie);
3314         clear_tsk_need_resched(prev);
3315         clear_preempt_need_resched();
3316         rq->clock_skip_update = 0;
3317
3318         if (likely(prev != next)) {
3319                 rq->nr_switches++;
3320                 rq->curr = next;
3321                 ++*switch_count;
3322
3323                 trace_sched_switch(preempt, prev, next);
3324                 rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
3325         } else {
3326                 lockdep_unpin_lock(&rq->lock, cookie);
3327                 raw_spin_unlock_irq(&rq->lock);
3328         }
3329
3330         balance_callback(rq);
3331 }
3332 STACK_FRAME_NON_STANDARD(__schedule); /* switch_to() */
3333
3334 static inline void sched_submit_work(struct task_struct *tsk)
3335 {
3336         if (!tsk->state || tsk_is_pi_blocked(tsk))
3337                 return;
3338         /*
3339          * If we are going to sleep and we have plugged IO queued,
3340          * make sure to submit it to avoid deadlocks.
3341          */
3342         if (blk_needs_flush_plug(tsk))
3343                 blk_schedule_flush_plug(tsk);
3344 }
3345
3346 asmlinkage __visible void __sched schedule(void)
3347 {
3348         struct task_struct *tsk = current;
3349
3350         sched_submit_work(tsk);
3351         do {
3352                 preempt_disable();
3353                 __schedule(false);
3354                 sched_preempt_enable_no_resched();
3355         } while (need_resched());
3356 }
3357 EXPORT_SYMBOL(schedule);
3358
3359 #ifdef CONFIG_CONTEXT_TRACKING
3360 asmlinkage __visible void __sched schedule_user(void)
3361 {
3362         /*
3363          * If we come here after a random call to set_need_resched(),
3364          * or we have been woken up remotely but the IPI has not yet arrived,
3365          * we haven't yet exited the RCU idle mode. Do it here manually until
3366          * we find a better solution.
3367          *
3368          * NB: There are buggy callers of this function.  Ideally we
3369          * should warn if prev_state != CONTEXT_USER, but that will trigger
3370          * too frequently to make sense yet.
3371          */
3372         enum ctx_state prev_state = exception_enter();
3373         schedule();
3374         exception_exit(prev_state);
3375 }
3376 #endif
3377
3378 /**
3379  * schedule_preempt_disabled - called with preemption disabled
3380  *
3381  * Returns with preemption disabled. Note: preempt_count must be 1
3382  */
3383 void __sched schedule_preempt_disabled(void)
3384 {
3385         sched_preempt_enable_no_resched();
3386         schedule();
3387         preempt_disable();
3388 }
3389
3390 static void __sched notrace preempt_schedule_common(void)
3391 {
3392         do {
3393                 /*
3394                  * Because the function tracer can trace preempt_count_sub()
3395                  * and it also uses preempt_enable/disable_notrace(), if
3396                  * NEED_RESCHED is set, the preempt_enable_notrace() called
3397                  * by the function tracer will call this function again and
3398                  * cause infinite recursion.
3399                  *
3400                  * Preemption must be disabled here before the function
3401                  * tracer can trace. Break up preempt_disable() into two
3402                  * calls. One to disable preemption without fear of being
3403                  * traced. The other to still record the preemption latency,
3404                  * which can also be traced by the function tracer.
3405                  */
3406                 preempt_disable_notrace();
3407                 preempt_latency_start(1);
3408                 __schedule(true);
3409                 preempt_latency_stop(1);
3410                 preempt_enable_no_resched_notrace();
3411
3412                 /*
3413                  * Check again in case we missed a preemption opportunity
3414                  * between schedule and now.
3415                  */
3416         } while (need_resched());
3417 }
3418
3419 #ifdef CONFIG_PREEMPT
3420 /*
3421  * this is the entry point to schedule() from in-kernel preemption
3422  * off of preempt_enable. Kernel preemptions off return from interrupt
3423  * occur there and call schedule directly.
3424  */
3425 asmlinkage __visible void __sched notrace preempt_schedule(void)
3426 {
3427         /*
3428          * If there is a non-zero preempt_count or interrupts are disabled,
3429          * we do not want to preempt the current task. Just return..
3430          */
3431         if (likely(!preemptible()))
3432                 return;
3433
3434         preempt_schedule_common();
3435 }
3436 NOKPROBE_SYMBOL(preempt_schedule);
3437 EXPORT_SYMBOL(preempt_schedule);
3438
3439 /**
3440  * preempt_schedule_notrace - preempt_schedule called by tracing
3441  *
3442  * The tracing infrastructure uses preempt_enable_notrace to prevent
3443  * recursion and tracing preempt enabling caused by the tracing
3444  * infrastructure itself. But as tracing can happen in areas coming
3445  * from userspace or just about to enter userspace, a preempt enable
3446  * can occur before user_exit() is called. This will cause the scheduler
3447  * to be called when the system is still in usermode.
3448  *
3449  * To prevent this, the preempt_enable_notrace will use this function
3450  * instead of preempt_schedule() to exit user context if needed before
3451  * calling the scheduler.
3452  */
3453 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3454 {
3455         enum ctx_state prev_ctx;
3456
3457         if (likely(!preemptible()))
3458                 return;
3459
3460         do {
3461                 /*
3462                  * Because the function tracer can trace preempt_count_sub()
3463                  * and it also uses preempt_enable/disable_notrace(), if
3464                  * NEED_RESCHED is set, the preempt_enable_notrace() called
3465                  * by the function tracer will call this function again and
3466                  * cause infinite recursion.
3467                  *
3468                  * Preemption must be disabled here before the function
3469                  * tracer can trace. Break up preempt_disable() into two
3470                  * calls. One to disable preemption without fear of being
3471                  * traced. The other to still record the preemption latency,
3472                  * which can also be traced by the function tracer.
3473                  */
3474                 preempt_disable_notrace();
3475                 preempt_latency_start(1);
3476                 /*
3477                  * Needs preempt disabled in case user_exit() is traced
3478                  * and the tracer calls preempt_enable_notrace() causing
3479                  * an infinite recursion.
3480                  */
3481                 prev_ctx = exception_enter();
3482                 __schedule(true);
3483                 exception_exit(prev_ctx);
3484
3485                 preempt_latency_stop(1);
3486                 preempt_enable_no_resched_notrace();
3487         } while (need_resched());
3488 }
3489 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3490
3491 #endif /* CONFIG_PREEMPT */
3492
3493 /*
3494  * this is the entry point to schedule() from kernel preemption
3495  * off of irq context.
3496  * Note, that this is called and return with irqs disabled. This will
3497  * protect us against recursive calling from irq.
3498  */
3499 asmlinkage __visible void __sched preempt_schedule_irq(void)
3500 {
3501         enum ctx_state prev_state;
3502
3503         /* Catch callers which need to be fixed */
3504         BUG_ON(preempt_count() || !irqs_disabled());
3505
3506         prev_state = exception_enter();
3507
3508         do {
3509                 preempt_disable();
3510                 local_irq_enable();
3511                 __schedule(true);
3512                 local_irq_disable();
3513                 sched_preempt_enable_no_resched();
3514         } while (need_resched());
3515
3516         exception_exit(prev_state);
3517 }
3518
3519 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3520                           void *key)
3521 {
3522         return try_to_wake_up(curr->private, mode, wake_flags);
3523 }
3524 EXPORT_SYMBOL(default_wake_function);
3525
3526 #ifdef CONFIG_RT_MUTEXES
3527
3528 /*
3529  * rt_mutex_setprio - set the current priority of a task
3530  * @p: task
3531  * @prio: prio value (kernel-internal form)
3532  *
3533  * This function changes the 'effective' priority of a task. It does
3534  * not touch ->normal_prio like __setscheduler().
3535  *
3536  * Used by the rt_mutex code to implement priority inheritance
3537  * logic. Call site only calls if the priority of the task changed.
3538  */
3539 void rt_mutex_setprio(struct task_struct *p, int prio)
3540 {
3541         int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3542         const struct sched_class *prev_class;
3543         struct rq_flags rf;
3544         struct rq *rq;
3545
3546         BUG_ON(prio > MAX_PRIO);
3547
3548         rq = __task_rq_lock(p, &rf);
3549
3550         /*
3551          * Idle task boosting is a nono in general. There is one
3552          * exception, when PREEMPT_RT and NOHZ is active:
3553          *
3554          * The idle task calls get_next_timer_interrupt() and holds
3555          * the timer wheel base->lock on the CPU and another CPU wants
3556          * to access the timer (probably to cancel it). We can safely
3557          * ignore the boosting request, as the idle CPU runs this code
3558          * with interrupts disabled and will complete the lock
3559          * protected section without being interrupted. So there is no
3560          * real need to boost.
3561          */
3562         if (unlikely(p == rq->idle)) {
3563                 WARN_ON(p != rq->curr);
3564                 WARN_ON(p->pi_blocked_on);
3565                 goto out_unlock;
3566         }
3567
3568         trace_sched_pi_setprio(p, prio);
3569         oldprio = p->prio;
3570
3571         if (oldprio == prio)
3572                 queue_flag &= ~DEQUEUE_MOVE;
3573
3574         prev_class = p->sched_class;
3575         queued = task_on_rq_queued(p);
3576         running = task_current(rq, p);
3577         if (queued)
3578                 dequeue_task(rq, p, queue_flag);
3579         if (running)
3580                 put_prev_task(rq, p);
3581
3582         /*
3583          * Boosting condition are:
3584          * 1. -rt task is running and holds mutex A
3585          *      --> -dl task blocks on mutex A
3586          *
3587          * 2. -dl task is running and holds mutex A
3588          *      --> -dl task blocks on mutex A and could preempt the
3589          *          running task
3590          */
3591         if (dl_prio(prio)) {
3592                 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3593                 if (!dl_prio(p->normal_prio) ||
3594                     (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3595                         p->dl.dl_boosted = 1;
3596                         queue_flag |= ENQUEUE_REPLENISH;
3597                 } else
3598                         p->dl.dl_boosted = 0;
3599                 p->sched_class = &dl_sched_class;
3600         } else if (rt_prio(prio)) {
3601                 if (dl_prio(oldprio))
3602                         p->dl.dl_boosted = 0;
3603                 if (oldprio < prio)
3604                         queue_flag |= ENQUEUE_HEAD;
3605                 p->sched_class = &rt_sched_class;
3606         } else {
3607                 if (dl_prio(oldprio))
3608                         p->dl.dl_boosted = 0;
3609                 if (rt_prio(oldprio))
3610                         p->rt.timeout = 0;
3611                 p->sched_class = &fair_sched_class;
3612         }
3613
3614         p->prio = prio;
3615
3616         if (running)
3617                 p->sched_class->set_curr_task(rq);
3618         if (queued)
3619                 enqueue_task(rq, p, queue_flag);
3620
3621         check_class_changed(rq, p, prev_class, oldprio);
3622 out_unlock:
3623         preempt_disable(); /* avoid rq from going away on us */
3624         __task_rq_unlock(rq, &rf);
3625
3626         balance_callback(rq);
3627         preempt_enable();
3628 }
3629 #endif
3630
3631 void set_user_nice(struct task_struct *p, long nice)
3632 {
3633         int old_prio, delta, queued;
3634         struct rq_flags rf;
3635         struct rq *rq;
3636
3637         if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3638                 return;
3639         /*
3640          * We have to be careful, if called from sys_setpriority(),
3641          * the task might be in the middle of scheduling on another CPU.
3642          */
3643         rq = task_rq_lock(p, &rf);
3644         /*
3645          * The RT priorities are set via sched_setscheduler(), but we still
3646          * allow the 'normal' nice value to be set - but as expected
3647          * it wont have any effect on scheduling until the task is
3648          * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3649          */
3650         if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3651                 p->static_prio = NICE_TO_PRIO(nice);
3652                 goto out_unlock;
3653         }
3654         queued = task_on_rq_queued(p);
3655         if (queued)
3656                 dequeue_task(rq, p, DEQUEUE_SAVE);
3657
3658         p->static_prio = NICE_TO_PRIO(nice);
3659         set_load_weight(p);
3660         old_prio = p->prio;
3661         p->prio = effective_prio(p);
3662         delta = p->prio - old_prio;
3663
3664         if (queued) {
3665                 enqueue_task(rq, p, ENQUEUE_RESTORE);
3666                 /*
3667                  * If the task increased its priority or is running and
3668                  * lowered its priority, then reschedule its CPU:
3669                  */
3670                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3671                         resched_curr(rq);
3672         }
3673 out_unlock:
3674         task_rq_unlock(rq, p, &rf);
3675 }
3676 EXPORT_SYMBOL(set_user_nice);
3677
3678 /*
3679  * can_nice - check if a task can reduce its nice value
3680  * @p: task
3681  * @nice: nice value
3682  */
3683 int can_nice(const struct task_struct *p, const int nice)
3684 {
3685         /* convert nice value [19,-20] to rlimit style value [1,40] */
3686         int nice_rlim = nice_to_rlimit(nice);
3687
3688         return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3689                 capable(CAP_SYS_NICE));
3690 }
3691
3692 #ifdef __ARCH_WANT_SYS_NICE
3693
3694 /*
3695  * sys_nice - change the priority of the current process.
3696  * @increment: priority increment
3697  *
3698  * sys_setpriority is a more generic, but much slower function that
3699  * does similar things.
3700  */
3701 SYSCALL_DEFINE1(nice, int, increment)
3702 {
3703         long nice, retval;
3704
3705         /*
3706          * Setpriority might change our priority at the same moment.
3707          * We don't have to worry. Conceptually one call occurs first
3708          * and we have a single winner.
3709          */
3710         increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3711         nice = task_nice(current) + increment;
3712
3713         nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3714         if (increment < 0 && !can_nice(current, nice))
3715                 return -EPERM;
3716
3717         retval = security_task_setnice(current, nice);
3718         if (retval)
3719                 return retval;
3720
3721         set_user_nice(current, nice);
3722         return 0;
3723 }
3724
3725 #endif
3726
3727 /**
3728  * task_prio - return the priority value of a given task.
3729  * @p: the task in question.
3730  *
3731  * Return: The priority value as seen by users in /proc.
3732  * RT tasks are offset by -200. Normal tasks are centered
3733  * around 0, value goes from -16 to +15.
3734  */
3735 int task_prio(const struct task_struct *p)
3736 {
3737         return p->prio - MAX_RT_PRIO;
3738 }
3739
3740 /**
3741  * idle_cpu - is a given cpu idle currently?
3742  * @cpu: the processor in question.
3743  *
3744  * Return: 1 if the CPU is currently idle. 0 otherwise.
3745  */
3746 int idle_cpu(int cpu)
3747 {
3748         struct rq *rq = cpu_rq(cpu);
3749
3750         if (rq->curr != rq->idle)
3751                 return 0;
3752
3753         if (rq->nr_running)
3754                 return 0;
3755
3756 #ifdef CONFIG_SMP
3757         if (!llist_empty(&rq->wake_list))
3758                 return 0;
3759 #endif
3760
3761         return 1;
3762 }
3763
3764 /**
3765  * idle_task - return the idle task for a given cpu.
3766  * @cpu: the processor in question.
3767  *
3768  * Return: The idle task for the cpu @cpu.
3769  */
3770 struct task_struct *idle_task(int cpu)
3771 {
3772         return cpu_rq(cpu)->idle;
3773 }
3774
3775 /**
3776  * find_process_by_pid - find a process with a matching PID value.
3777  * @pid: the pid in question.
3778  *
3779  * The task of @pid, if found. %NULL otherwise.
3780  */
3781 static struct task_struct *find_process_by_pid(pid_t pid)
3782 {
3783         return pid ? find_task_by_vpid(pid) : current;
3784 }
3785
3786 /*
3787  * This function initializes the sched_dl_entity of a newly becoming
3788  * SCHED_DEADLINE task.
3789  *
3790  * Only the static values are considered here, the actual runtime and the
3791  * absolute deadline will be properly calculated when the task is enqueued
3792  * for the first time with its new policy.
3793  */
3794 static void
3795 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3796 {
3797         struct sched_dl_entity *dl_se = &p->dl;
3798
3799         dl_se->dl_runtime = attr->sched_runtime;
3800         dl_se->dl_deadline = attr->sched_deadline;
3801         dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3802         dl_se->flags = attr->sched_flags;
3803         dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3804
3805         /*
3806          * Changing the parameters of a task is 'tricky' and we're not doing
3807          * the correct thing -- also see task_dead_dl() and switched_from_dl().
3808          *
3809          * What we SHOULD do is delay the bandwidth release until the 0-lag
3810          * point. This would include retaining the task_struct until that time
3811          * and change dl_overflow() to not immediately decrement the current
3812          * amount.
3813          *
3814          * Instead we retain the current runtime/deadline and let the new
3815          * parameters take effect after the current reservation period lapses.
3816          * This is safe (albeit pessimistic) because the 0-lag point is always
3817          * before the current scheduling deadline.
3818          *
3819          * We can still have temporary overloads because we do not delay the
3820          * change in bandwidth until that time; so admission control is
3821          * not on the safe side. It does however guarantee tasks will never
3822          * consume more than promised.
3823          */
3824 }
3825
3826 /*
3827  * sched_setparam() passes in -1 for its policy, to let the functions
3828  * it calls know not to change it.
3829  */
3830 #define SETPARAM_POLICY -1
3831
3832 static void __setscheduler_params(struct task_struct *p,
3833                 const struct sched_attr *attr)
3834 {
3835         int policy = attr->sched_policy;
3836
3837         if (policy == SETPARAM_POLICY)
3838                 policy = p->policy;
3839
3840         p->policy = policy;
3841
3842         if (dl_policy(policy))
3843                 __setparam_dl(p, attr);
3844         else if (fair_policy(policy))
3845                 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3846
3847         /*
3848          * __sched_setscheduler() ensures attr->sched_priority == 0 when
3849          * !rt_policy. Always setting this ensures that things like
3850          * getparam()/getattr() don't report silly values for !rt tasks.
3851          */
3852         p->rt_priority = attr->sched_priority;
3853         p->normal_prio = normal_prio(p);
3854         set_load_weight(p);
3855 }
3856
3857 /* Actually do priority change: must hold pi & rq lock. */
3858 static void __setscheduler(struct rq *rq, struct task_struct *p,
3859                            const struct sched_attr *attr, bool keep_boost)
3860 {
3861         __setscheduler_params(p, attr);
3862
3863         /*
3864          * Keep a potential priority boosting if called from
3865          * sched_setscheduler().
3866          */
3867         if (keep_boost)
3868                 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
3869         else
3870                 p->prio = normal_prio(p);
3871
3872         if (dl_prio(p->prio))
3873                 p->sched_class = &dl_sched_class;
3874         else if (rt_prio(p->prio))
3875                 p->sched_class = &rt_sched_class;
3876         else
3877                 p->sched_class = &fair_sched_class;
3878 }
3879
3880 static void
3881 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
3882 {
3883         struct sched_dl_entity *dl_se = &p->dl;
3884
3885         attr->sched_priority = p->rt_priority;
3886         attr->sched_runtime = dl_se->dl_runtime;
3887         attr->sched_deadline = dl_se->dl_deadline;
3888         attr->sched_period = dl_se->dl_period;
3889         attr->sched_flags = dl_se->flags;
3890 }
3891
3892 /*
3893  * This function validates the new parameters of a -deadline task.
3894  * We ask for the deadline not being zero, and greater or equal
3895  * than the runtime, as well as the period of being zero or
3896  * greater than deadline. Furthermore, we have to be sure that
3897  * user parameters are above the internal resolution of 1us (we
3898  * check sched_runtime only since it is always the smaller one) and
3899  * below 2^63 ns (we have to check both sched_deadline and
3900  * sched_period, as the latter can be zero).
3901  */
3902 static bool
3903 __checkparam_dl(const struct sched_attr *attr)
3904 {
3905         /* deadline != 0 */
3906         if (attr->sched_deadline == 0)
3907                 return false;
3908
3909         /*
3910          * Since we truncate DL_SCALE bits, make sure we're at least
3911          * that big.
3912          */
3913         if (attr->sched_runtime < (1ULL << DL_SCALE))
3914                 return false;
3915
3916         /*
3917          * Since we use the MSB for wrap-around and sign issues, make
3918          * sure it's not set (mind that period can be equal to zero).
3919          */
3920         if (attr->sched_deadline & (1ULL << 63) ||
3921             attr->sched_period & (1ULL << 63))
3922                 return false;
3923
3924         /* runtime <= deadline <= period (if period != 0) */
3925         if ((attr->sched_period != 0 &&
3926              attr->sched_period < attr->sched_deadline) ||
3927             attr->sched_deadline < attr->sched_runtime)
3928                 return false;
3929
3930         return true;
3931 }
3932
3933 /*
3934  * check the target process has a UID that matches the current process's
3935  */
3936 static bool check_same_owner(struct task_struct *p)
3937 {
3938         const struct cred *cred = current_cred(), *pcred;
3939         bool match;
3940
3941         rcu_read_lock();
3942         pcred = __task_cred(p);
3943         match = (uid_eq(cred->euid, pcred->euid) ||
3944                  uid_eq(cred->euid, pcred->uid));
3945         rcu_read_unlock();
3946         return match;
3947 }
3948
3949 static bool dl_param_changed(struct task_struct *p,
3950                 const struct sched_attr *attr)
3951 {
3952         struct sched_dl_entity *dl_se = &p->dl;
3953
3954         if (dl_se->dl_runtime != attr->sched_runtime ||
3955                 dl_se->dl_deadline != attr->sched_deadline ||
3956                 dl_se->dl_period != attr->sched_period ||
3957                 dl_se->flags != attr->sched_flags)
3958                 return true;
3959
3960         return false;
3961 }
3962
3963 static int __sched_setscheduler(struct task_struct *p,
3964                                 const struct sched_attr *attr,
3965                                 bool user, bool pi)
3966 {
3967         int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
3968                       MAX_RT_PRIO - 1 - attr->sched_priority;
3969         int retval, oldprio, oldpolicy = -1, queued, running;
3970         int new_effective_prio, policy = attr->sched_policy;
3971         const struct sched_class *prev_class;
3972         struct rq_flags rf;
3973         int reset_on_fork;
3974         int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
3975         struct rq *rq;
3976
3977         /* may grab non-irq protected spin_locks */
3978         BUG_ON(in_interrupt());
3979 recheck:
3980         /* double check policy once rq lock held */
3981         if (policy < 0) {
3982                 reset_on_fork = p->sched_reset_on_fork;
3983                 policy = oldpolicy = p->policy;
3984         } else {
3985                 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
3986
3987                 if (!valid_policy(policy))
3988                         return -EINVAL;
3989         }
3990
3991         if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
3992                 return -EINVAL;
3993
3994         /*
3995          * Valid priorities for SCHED_FIFO and SCHED_RR are
3996          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3997          * SCHED_BATCH and SCHED_IDLE is 0.
3998          */
3999         if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4000             (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4001                 return -EINVAL;
4002         if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4003             (rt_policy(policy) != (attr->sched_priority != 0)))
4004                 return -EINVAL;
4005
4006         /*
4007          * Allow unprivileged RT tasks to decrease priority:
4008          */
4009         if (user && !capable(CAP_SYS_NICE)) {
4010                 if (fair_policy(policy)) {
4011                         if (attr->sched_nice < task_nice(p) &&
4012                             !can_nice(p, attr->sched_nice))
4013                                 return -EPERM;
4014                 }
4015
4016                 if (rt_policy(policy)) {
4017                         unsigned long rlim_rtprio =
4018                                         task_rlimit(p, RLIMIT_RTPRIO);
4019
4020                         /* can't set/change the rt policy */
4021                         if (policy != p->policy && !rlim_rtprio)
4022                                 return -EPERM;
4023
4024                         /* can't increase priority */
4025                         if (attr->sched_priority > p->rt_priority &&
4026                             attr->sched_priority > rlim_rtprio)
4027                                 return -EPERM;
4028                 }
4029
4030                  /*
4031                   * Can't set/change SCHED_DEADLINE policy at all for now
4032                   * (safest behavior); in the future we would like to allow
4033                   * unprivileged DL tasks to increase their relative deadline
4034                   * or reduce their runtime (both ways reducing utilization)
4035                   */
4036                 if (dl_policy(policy))
4037                         return -EPERM;
4038
4039                 /*
4040                  * Treat SCHED_IDLE as nice 20. Only allow a switch to
4041                  * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4042                  */
4043                 if (idle_policy(p->policy) && !idle_policy(policy)) {
4044                         if (!can_nice(p, task_nice(p)))
4045                                 return -EPERM;
4046                 }
4047
4048                 /* can't change other user's priorities */
4049                 if (!check_same_owner(p))
4050                         return -EPERM;
4051
4052                 /* Normal users shall not reset the sched_reset_on_fork flag */
4053                 if (p->sched_reset_on_fork && !reset_on_fork)
4054                         return -EPERM;
4055         }
4056
4057         if (user) {
4058                 retval = security_task_setscheduler(p);
4059                 if (retval)
4060                         return retval;
4061         }
4062
4063         /*
4064          * make sure no PI-waiters arrive (or leave) while we are
4065          * changing the priority of the task:
4066          *
4067          * To be able to change p->policy safely, the appropriate
4068          * runqueue lock must be held.
4069          */
4070         rq = task_rq_lock(p, &rf);
4071
4072         /*
4073          * Changing the policy of the stop threads its a very bad idea
4074          */
4075         if (p == rq->stop) {
4076                 task_rq_unlock(rq, p, &rf);
4077                 return -EINVAL;
4078         }
4079
4080         /*
4081          * If not changing anything there's no need to proceed further,
4082          * but store a possible modification of reset_on_fork.
4083          */
4084         if (unlikely(policy == p->policy)) {
4085                 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4086                         goto change;
4087                 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4088                         goto change;
4089                 if (dl_policy(policy) && dl_param_changed(p, attr))
4090                         goto change;
4091
4092                 p->sched_reset_on_fork = reset_on_fork;
4093                 task_rq_unlock(rq, p, &rf);
4094                 return 0;
4095         }
4096 change:
4097
4098         if (user) {
4099 #ifdef CONFIG_RT_GROUP_SCHED
4100                 /*
4101                  * Do not allow realtime tasks into groups that have no runtime
4102                  * assigned.
4103                  */
4104                 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4105                                 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4106                                 !task_group_is_autogroup(task_group(p))) {
4107                         task_rq_unlock(rq, p, &rf);
4108                         return -EPERM;
4109                 }
4110 #endif
4111 #ifdef CONFIG_SMP
4112                 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4113                         cpumask_t *span = rq->rd->span;
4114
4115                         /*
4116                          * Don't allow tasks with an affinity mask smaller than
4117                          * the entire root_domain to become SCHED_DEADLINE. We
4118                          * will also fail if there's no bandwidth available.
4119                          */
4120                         if (!cpumask_subset(span, &p->cpus_allowed) ||
4121                             rq->rd->dl_bw.bw == 0) {
4122                                 task_rq_unlock(rq, p, &rf);
4123                                 return -EPERM;
4124                         }
4125                 }
4126 #endif
4127         }
4128
4129         /* recheck policy now with rq lock held */
4130         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4131                 policy = oldpolicy = -1;
4132                 task_rq_unlock(rq, p, &rf);
4133                 goto recheck;
4134         }
4135
4136         /*
4137          * If setscheduling to SCHED_DEADLINE (or changing the parameters
4138          * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4139          * is available.
4140          */
4141         if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
4142                 task_rq_unlock(rq, p, &rf);
4143                 return -EBUSY;
4144         }
4145
4146         p->sched_reset_on_fork = reset_on_fork;
4147         oldprio = p->prio;
4148
4149         if (pi) {
4150                 /*
4151                  * Take priority boosted tasks into account. If the new
4152                  * effective priority is unchanged, we just store the new
4153                  * normal parameters and do not touch the scheduler class and
4154                  * the runqueue. This will be done when the task deboost
4155                  * itself.
4156                  */
4157                 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4158                 if (new_effective_prio == oldprio)
4159                         queue_flags &= ~DEQUEUE_MOVE;
4160         }
4161
4162         queued = task_on_rq_queued(p);
4163         running = task_current(rq, p);
4164         if (queued)
4165                 dequeue_task(rq, p, queue_flags);
4166         if (running)
4167                 put_prev_task(rq, p);
4168
4169         prev_class = p->sched_class;
4170         __setscheduler(rq, p, attr, pi);
4171
4172         if (running)
4173                 p->sched_class->set_curr_task(rq);
4174         if (queued) {
4175                 /*
4176                  * We enqueue to tail when the priority of a task is
4177                  * increased (user space view).
4178                  */
4179                 if (oldprio < p->prio)
4180                         queue_flags |= ENQUEUE_HEAD;
4181
4182                 enqueue_task(rq, p, queue_flags);
4183         }
4184
4185         check_class_changed(rq, p, prev_class, oldprio);
4186         preempt_disable(); /* avoid rq from going away on us */
4187         task_rq_unlock(rq, p, &rf);
4188
4189         if (pi)
4190                 rt_mutex_adjust_pi(p);
4191
4192         /*
4193          * Run balance callbacks after we've adjusted the PI chain.
4194          */
4195         balance_callback(rq);
4196         preempt_enable();
4197
4198         return 0;
4199 }
4200
4201 static int _sched_setscheduler(struct task_struct *p, int policy,
4202                                const struct sched_param *param, bool check)
4203 {
4204         struct sched_attr attr = {
4205                 .sched_policy   = policy,
4206                 .sched_priority = param->sched_priority,
4207                 .sched_nice     = PRIO_TO_NICE(p->static_prio),
4208         };
4209
4210         /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4211         if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4212                 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4213                 policy &= ~SCHED_RESET_ON_FORK;
4214                 attr.sched_policy = policy;
4215         }
4216
4217         return __sched_setscheduler(p, &attr, check, true);
4218 }
4219 /**
4220  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4221  * @p: the task in question.
4222  * @policy: new policy.
4223  * @param: structure containing the new RT priority.
4224  *
4225  * Return: 0 on success. An error code otherwise.
4226  *
4227  * NOTE that the task may be already dead.
4228  */
4229 int sched_setscheduler(struct task_struct *p, int policy,
4230                        const struct sched_param *param)
4231 {
4232         return _sched_setscheduler(p, policy, param, true);
4233 }
4234 EXPORT_SYMBOL_GPL(sched_setscheduler);
4235
4236 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4237 {
4238         return __sched_setscheduler(p, attr, true, true);
4239 }
4240 EXPORT_SYMBOL_GPL(sched_setattr);
4241
4242 /**
4243  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4244  * @p: the task in question.
4245  * @policy: new policy.
4246  * @param: structure containing the new RT priority.
4247  *
4248  * Just like sched_setscheduler, only don't bother checking if the
4249  * current context has permission.  For example, this is needed in
4250  * stop_machine(): we create temporary high priority worker threads,
4251  * but our caller might not have that capability.
4252  *
4253  * Return: 0 on success. An error code otherwise.
4254  */
4255 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4256                                const struct sched_param *param)
4257 {
4258         return _sched_setscheduler(p, policy, param, false);
4259 }
4260 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4261
4262 static int
4263 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4264 {
4265         struct sched_param lparam;
4266         struct task_struct *p;
4267         int retval;
4268
4269         if (!param || pid < 0)
4270                 return -EINVAL;
4271         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4272                 return -EFAULT;
4273
4274         rcu_read_lock();
4275         retval = -ESRCH;
4276         p = find_process_by_pid(pid);
4277         if (p != NULL)
4278                 retval = sched_setscheduler(p, policy, &lparam);
4279         rcu_read_unlock();
4280
4281         return retval;
4282 }
4283
4284 /*
4285  * Mimics kernel/events/core.c perf_copy_attr().
4286  */
4287 static int sched_copy_attr(struct sched_attr __user *uattr,
4288                            struct sched_attr *attr)
4289 {
4290         u32 size;
4291         int ret;
4292
4293         if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4294                 return -EFAULT;
4295
4296         /*
4297          * zero the full structure, so that a short copy will be nice.
4298          */
4299         memset(attr, 0, sizeof(*attr));
4300
4301         ret = get_user(size, &uattr->size);
4302         if (ret)
4303                 return ret;
4304
4305         if (size > PAGE_SIZE)   /* silly large */
4306                 goto err_size;
4307
4308         if (!size)              /* abi compat */
4309                 size = SCHED_ATTR_SIZE_VER0;
4310
4311         if (size < SCHED_ATTR_SIZE_VER0)
4312                 goto err_size;
4313
4314         /*
4315          * If we're handed a bigger struct than we know of,
4316          * ensure all the unknown bits are 0 - i.e. new
4317          * user-space does not rely on any kernel feature
4318          * extensions we dont know about yet.
4319          */
4320         if (size > sizeof(*attr)) {
4321                 unsigned char __user *addr;
4322                 unsigned char __user *end;
4323                 unsigned char val;
4324
4325                 addr = (void __user *)uattr + sizeof(*attr);
4326                 end  = (void __user *)uattr + size;
4327
4328                 for (; addr < end; addr++) {
4329                         ret = get_user(val, addr);
4330                         if (ret)
4331                                 return ret;
4332                         if (val)
4333                                 goto err_size;
4334                 }
4335                 size = sizeof(*attr);
4336         }
4337
4338         ret = copy_from_user(attr, uattr, size);
4339         if (ret)
4340                 return -EFAULT;
4341
4342         /*
4343          * XXX: do we want to be lenient like existing syscalls; or do we want
4344          * to be strict and return an error on out-of-bounds values?
4345          */
4346         attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4347
4348         return 0;
4349
4350 err_size:
4351         put_user(sizeof(*attr), &uattr->size);
4352         return -E2BIG;
4353 }
4354
4355 /**
4356  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4357  * @pid: the pid in question.
4358  * @policy: new policy.
4359  * @param: structure containing the new RT priority.
4360  *
4361  * Return: 0 on success. An error code otherwise.
4362  */
4363 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4364                 struct sched_param __user *, param)
4365 {
4366         /* negative values for policy are not valid */
4367         if (policy < 0)
4368                 return -EINVAL;
4369
4370         return do_sched_setscheduler(pid, policy, param);
4371 }
4372
4373 /**
4374  * sys_sched_setparam - set/change the RT priority of a thread
4375  * @pid: the pid in question.
4376  * @param: structure containing the new RT priority.
4377  *
4378  * Return: 0 on success. An error code otherwise.
4379  */
4380 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4381 {
4382         return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4383 }
4384
4385 /**
4386  * sys_sched_setattr - same as above, but with extended sched_attr
4387  * @pid: the pid in question.
4388  * @uattr: structure containing the extended parameters.
4389  * @flags: for future extension.
4390  */
4391 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4392                                unsigned int, flags)
4393 {
4394         struct sched_attr attr;
4395         struct task_struct *p;
4396         int retval;
4397
4398         if (!uattr || pid < 0 || flags)
4399                 return -EINVAL;
4400
4401         retval = sched_copy_attr(uattr, &attr);
4402         if (retval)
4403                 return retval;
4404
4405         if ((int)attr.sched_policy < 0)
4406                 return -EINVAL;
4407
4408         rcu_read_lock();
4409         retval = -ESRCH;
4410         p = find_process_by_pid(pid);
4411         if (p != NULL)
4412                 retval = sched_setattr(p, &attr);
4413         rcu_read_unlock();
4414
4415         return retval;
4416 }
4417
4418 /**
4419  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4420  * @pid: the pid in question.
4421  *
4422  * Return: On success, the policy of the thread. Otherwise, a negative error
4423  * code.
4424  */
4425 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4426 {
4427         struct task_struct *p;
4428         int retval;
4429
4430         if (pid < 0)
4431                 return -EINVAL;
4432
4433         retval = -ESRCH;
4434         rcu_read_lock();
4435         p = find_process_by_pid(pid);
4436         if (p) {
4437                 retval = security_task_getscheduler(p);
4438                 if (!retval)
4439                         retval = p->policy
4440                                 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4441         }
4442         rcu_read_unlock();
4443         return retval;
4444 }
4445
4446 /**
4447  * sys_sched_getparam - get the RT priority of a thread
4448  * @pid: the pid in question.
4449  * @param: structure containing the RT priority.
4450  *
4451  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4452  * code.
4453  */
4454 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4455 {
4456         struct sched_param lp = { .sched_priority = 0 };
4457         struct task_struct *p;
4458         int retval;
4459
4460         if (!param || pid < 0)
4461                 return -EINVAL;
4462
4463         rcu_read_lock();
4464         p = find_process_by_pid(pid);
4465         retval = -ESRCH;
4466         if (!p)
4467                 goto out_unlock;
4468
4469         retval = security_task_getscheduler(p);
4470         if (retval)
4471                 goto out_unlock;
4472
4473         if (task_has_rt_policy(p))
4474                 lp.sched_priority = p->rt_priority;
4475         rcu_read_unlock();
4476
4477         /*
4478          * This one might sleep, we cannot do it with a spinlock held ...
4479          */
4480         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4481
4482         return retval;
4483
4484 out_unlock:
4485         rcu_read_unlock();
4486         return retval;
4487 }
4488
4489 static int sched_read_attr(struct sched_attr __user *uattr,
4490                            struct sched_attr *attr,
4491                            unsigned int usize)
4492 {
4493         int ret;
4494
4495         if (!access_ok(VERIFY_WRITE, uattr, usize))
4496                 return -EFAULT;
4497
4498         /*
4499          * If we're handed a smaller struct than we know of,
4500          * ensure all the unknown bits are 0 - i.e. old
4501          * user-space does not get uncomplete information.
4502          */
4503         if (usize < sizeof(*attr)) {
4504                 unsigned char *addr;
4505                 unsigned char *end;
4506
4507                 addr = (void *)attr + usize;
4508                 end  = (void *)attr + sizeof(*attr);
4509
4510                 for (; addr < end; addr++) {
4511                         if (*addr)
4512                                 return -EFBIG;
4513                 }
4514
4515                 attr->size = usize;
4516         }
4517
4518         ret = copy_to_user(uattr, attr, attr->size);
4519         if (ret)
4520                 return -EFAULT;
4521
4522         return 0;
4523 }
4524
4525 /**
4526  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4527  * @pid: the pid in question.
4528  * @uattr: structure containing the extended parameters.
4529  * @size: sizeof(attr) for fwd/bwd comp.
4530  * @flags: for future extension.
4531  */
4532 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4533                 unsigned int, size, unsigned int, flags)
4534 {
4535         struct sched_attr attr = {
4536                 .size = sizeof(struct sched_attr),
4537         };
4538         struct task_struct *p;
4539         int retval;
4540
4541         if (!uattr || pid < 0 || size > PAGE_SIZE ||
4542             size < SCHED_ATTR_SIZE_VER0 || flags)
4543                 return -EINVAL;
4544
4545         rcu_read_lock();
4546         p = find_process_by_pid(pid);
4547         retval = -ESRCH;
4548         if (!p)
4549                 goto out_unlock;
4550
4551         retval = security_task_getscheduler(p);
4552         if (retval)
4553                 goto out_unlock;
4554
4555         attr.sched_policy = p->policy;
4556         if (p->sched_reset_on_fork)
4557                 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4558         if (task_has_dl_policy(p))
4559                 __getparam_dl(p, &attr);
4560         else if (task_has_rt_policy(p))
4561                 attr.sched_priority = p->rt_priority;
4562         else
4563                 attr.sched_nice = task_nice(p);
4564
4565         rcu_read_unlock();
4566
4567         retval = sched_read_attr(uattr, &attr, size);
4568         return retval;
4569
4570 out_unlock:
4571         rcu_read_unlock();
4572         return retval;
4573 }
4574
4575 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4576 {
4577         cpumask_var_t cpus_allowed, new_mask;
4578         struct task_struct *p;
4579         int retval;
4580
4581         rcu_read_lock();
4582
4583         p = find_process_by_pid(pid);
4584         if (!p) {
4585                 rcu_read_unlock();
4586                 return -ESRCH;
4587         }
4588
4589         /* Prevent p going away */
4590         get_task_struct(p);
4591         rcu_read_unlock();
4592
4593         if (p->flags & PF_NO_SETAFFINITY) {
4594                 retval = -EINVAL;
4595                 goto out_put_task;
4596         }
4597         if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4598                 retval = -ENOMEM;
4599                 goto out_put_task;
4600         }
4601         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4602                 retval = -ENOMEM;
4603                 goto out_free_cpus_allowed;
4604         }
4605         retval = -EPERM;
4606         if (!check_same_owner(p)) {
4607                 rcu_read_lock();
4608                 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4609                         rcu_read_unlock();
4610                         goto out_free_new_mask;
4611                 }
4612                 rcu_read_unlock();
4613         }
4614
4615         retval = security_task_setscheduler(p);
4616         if (retval)
4617                 goto out_free_new_mask;
4618
4619
4620         cpuset_cpus_allowed(p, cpus_allowed);
4621         cpumask_and(new_mask, in_mask, cpus_allowed);
4622
4623         /*
4624          * Since bandwidth control happens on root_domain basis,
4625          * if admission test is enabled, we only admit -deadline
4626          * tasks allowed to run on all the CPUs in the task's
4627          * root_domain.
4628          */
4629 #ifdef CONFIG_SMP
4630         if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4631                 rcu_read_lock();
4632                 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4633                         retval = -EBUSY;
4634                         rcu_read_unlock();
4635                         goto out_free_new_mask;
4636                 }
4637                 rcu_read_unlock();
4638         }
4639 #endif
4640 again:
4641         retval = __set_cpus_allowed_ptr(p, new_mask, true);
4642
4643         if (!retval) {
4644                 cpuset_cpus_allowed(p, cpus_allowed);
4645                 if (!cpumask_subset(new_mask, cpus_allowed)) {
4646                         /*
4647                          * We must have raced with a concurrent cpuset
4648                          * update. Just reset the cpus_allowed to the
4649                          * cpuset's cpus_allowed
4650                          */
4651                         cpumask_copy(new_mask, cpus_allowed);
4652                         goto again;
4653                 }
4654         }
4655 out_free_new_mask:
4656         free_cpumask_var(new_mask);
4657 out_free_cpus_allowed:
4658         free_cpumask_var(cpus_allowed);
4659 out_put_task:
4660         put_task_struct(p);
4661         return retval;
4662 }
4663
4664 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4665                              struct cpumask *new_mask)
4666 {
4667         if (len < cpumask_size())
4668                 cpumask_clear(new_mask);
4669         else if (len > cpumask_size())
4670                 len = cpumask_size();
4671
4672         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4673 }
4674
4675 /**
4676  * sys_sched_setaffinity - set the cpu affinity of a process
4677  * @pid: pid of the process
4678  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4679  * @user_mask_ptr: user-space pointer to the new cpu mask
4680  *
4681  * Return: 0 on success. An error code otherwise.
4682  */
4683 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4684                 unsigned long __user *, user_mask_ptr)
4685 {
4686         cpumask_var_t new_mask;
4687         int retval;
4688
4689         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4690                 return -ENOMEM;
4691
4692         retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4693         if (retval == 0)
4694                 retval = sched_setaffinity(pid, new_mask);
4695         free_cpumask_var(new_mask);
4696         return retval;
4697 }
4698
4699 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4700 {
4701         struct task_struct *p;
4702         unsigned long flags;
4703         int retval;
4704
4705         rcu_read_lock();
4706
4707         retval = -ESRCH;
4708         p = find_process_by_pid(pid);
4709         if (!p)
4710                 goto out_unlock;
4711
4712         retval = security_task_getscheduler(p);
4713         if (retval)
4714                 goto out_unlock;
4715
4716         raw_spin_lock_irqsave(&p->pi_lock, flags);
4717         cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4718         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4719
4720 out_unlock:
4721         rcu_read_unlock();
4722
4723         return retval;
4724 }
4725
4726 /**
4727  * sys_sched_getaffinity - get the cpu affinity of a process
4728  * @pid: pid of the process
4729  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4730  * @user_mask_ptr: user-space pointer to hold the current cpu mask
4731  *
4732  * Return: 0 on success. An error code otherwise.
4733  */
4734 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4735                 unsigned long __user *, user_mask_ptr)
4736 {
4737         int ret;
4738         cpumask_var_t mask;
4739
4740         if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4741                 return -EINVAL;
4742         if (len & (sizeof(unsigned long)-1))
4743                 return -EINVAL;
4744
4745         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4746                 return -ENOMEM;
4747
4748         ret = sched_getaffinity(pid, mask);
4749         if (ret == 0) {
4750                 size_t retlen = min_t(size_t, len, cpumask_size());
4751
4752                 if (copy_to_user(user_mask_ptr, mask, retlen))
4753                         ret = -EFAULT;
4754                 else
4755                         ret = retlen;
4756         }
4757         free_cpumask_var(mask);
4758
4759         return ret;
4760 }
4761
4762 /**
4763  * sys_sched_yield - yield the current processor to other threads.
4764  *
4765  * This function yields the current CPU to other tasks. If there are no
4766  * other threads running on this CPU then this function will return.
4767  *
4768  * Return: 0.
4769  */
4770 SYSCALL_DEFINE0(sched_yield)
4771 {
4772         struct rq *rq = this_rq_lock();
4773
4774         schedstat_inc(rq, yld_count);
4775         current->sched_class->yield_task(rq);
4776
4777         /*
4778          * Since we are going to call schedule() anyway, there's
4779          * no need to preempt or enable interrupts:
4780          */
4781         __release(rq->lock);
4782         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4783         do_raw_spin_unlock(&rq->lock);
4784         sched_preempt_enable_no_resched();
4785
4786         schedule();
4787
4788         return 0;
4789 }
4790
4791 int __sched _cond_resched(void)
4792 {
4793         if (should_resched(0)) {
4794                 preempt_schedule_common();
4795                 return 1;
4796         }
4797         return 0;
4798 }
4799 EXPORT_SYMBOL(_cond_resched);
4800
4801 /*
4802  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4803  * call schedule, and on return reacquire the lock.
4804  *
4805  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4806  * operations here to prevent schedule() from being called twice (once via
4807  * spin_unlock(), once by hand).
4808  */
4809 int __cond_resched_lock(spinlock_t *lock)
4810 {
4811         int resched = should_resched(PREEMPT_LOCK_OFFSET);
4812         int ret = 0;
4813
4814         lockdep_assert_held(lock);
4815
4816         if (spin_needbreak(lock) || resched) {
4817                 spin_unlock(lock);
4818                 if (resched)
4819                         preempt_schedule_common();
4820                 else
4821                         cpu_relax();
4822                 ret = 1;
4823                 spin_lock(lock);
4824         }
4825         return ret;
4826 }
4827 EXPORT_SYMBOL(__cond_resched_lock);
4828
4829 int __sched __cond_resched_softirq(void)
4830 {
4831         BUG_ON(!in_softirq());
4832
4833         if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
4834                 local_bh_enable();
4835                 preempt_schedule_common();
4836                 local_bh_disable();
4837                 return 1;
4838         }
4839         return 0;
4840 }
4841 EXPORT_SYMBOL(__cond_resched_softirq);
4842
4843 /**
4844  * yield - yield the current processor to other threads.
4845  *
4846  * Do not ever use this function, there's a 99% chance you're doing it wrong.
4847  *
4848  * The scheduler is at all times free to pick the calling task as the most
4849  * eligible task to run, if removing the yield() call from your code breaks
4850  * it, its already broken.
4851  *
4852  * Typical broken usage is:
4853  *
4854  * while (!event)
4855  *      yield();
4856  *
4857  * where one assumes that yield() will let 'the other' process run that will
4858  * make event true. If the current task is a SCHED_FIFO task that will never
4859  * happen. Never use yield() as a progress guarantee!!
4860  *
4861  * If you want to use yield() to wait for something, use wait_event().
4862  * If you want to use yield() to be 'nice' for others, use cond_resched().
4863  * If you still want to use yield(), do not!
4864  */
4865 void __sched yield(void)
4866 {
4867         set_current_state(TASK_RUNNING);
4868         sys_sched_yield();
4869 }
4870 EXPORT_SYMBOL(yield);
4871
4872 /**
4873  * yield_to - yield the current processor to another thread in
4874  * your thread group, or accelerate that thread toward the
4875  * processor it's on.
4876  * @p: target task
4877  * @preempt: whether task preemption is allowed or not
4878  *
4879  * It's the caller's job to ensure that the target task struct
4880  * can't go away on us before we can do any checks.
4881  *
4882  * Return:
4883  *      true (>0) if we indeed boosted the target task.
4884  *      false (0) if we failed to boost the target.
4885  *      -ESRCH if there's no task to yield to.
4886  */
4887 int __sched yield_to(struct task_struct *p, bool preempt)
4888 {
4889         struct task_struct *curr = current;
4890         struct rq *rq, *p_rq;
4891         unsigned long flags;
4892         int yielded = 0;
4893
4894         local_irq_save(flags);
4895         rq = this_rq();
4896
4897 again:
4898         p_rq = task_rq(p);
4899         /*
4900          * If we're the only runnable task on the rq and target rq also
4901          * has only one task, there's absolutely no point in yielding.
4902          */
4903         if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4904                 yielded = -ESRCH;
4905                 goto out_irq;
4906         }
4907
4908         double_rq_lock(rq, p_rq);
4909         if (task_rq(p) != p_rq) {
4910                 double_rq_unlock(rq, p_rq);
4911                 goto again;
4912         }
4913
4914         if (!curr->sched_class->yield_to_task)
4915                 goto out_unlock;
4916
4917         if (curr->sched_class != p->sched_class)
4918                 goto out_unlock;
4919
4920         if (task_running(p_rq, p) || p->state)
4921                 goto out_unlock;
4922
4923         yielded = curr->sched_class->yield_to_task(rq, p, preempt);
4924         if (yielded) {
4925                 schedstat_inc(rq, yld_count);
4926                 /*
4927                  * Make p's CPU reschedule; pick_next_entity takes care of
4928                  * fairness.
4929                  */
4930                 if (preempt && rq != p_rq)
4931                         resched_curr(p_rq);
4932         }
4933
4934 out_unlock:
4935         double_rq_unlock(rq, p_rq);
4936 out_irq:
4937         local_irq_restore(flags);
4938
4939         if (yielded > 0)
4940                 schedule();
4941
4942         return yielded;
4943 }
4944 EXPORT_SYMBOL_GPL(yield_to);
4945
4946 /*
4947  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4948  * that process accounting knows that this is a task in IO wait state.
4949  */
4950 long __sched io_schedule_timeout(long timeout)
4951 {
4952         int old_iowait = current->in_iowait;
4953         struct rq *rq;
4954         long ret;
4955
4956         current->in_iowait = 1;
4957         blk_schedule_flush_plug(current);
4958
4959         delayacct_blkio_start();
4960         rq = raw_rq();
4961         atomic_inc(&rq->nr_iowait);
4962         ret = schedule_timeout(timeout);
4963         current->in_iowait = old_iowait;
4964         atomic_dec(&rq->nr_iowait);
4965         delayacct_blkio_end();
4966
4967         return ret;
4968 }
4969 EXPORT_SYMBOL(io_schedule_timeout);
4970
4971 /**
4972  * sys_sched_get_priority_max - return maximum RT priority.
4973  * @policy: scheduling class.
4974  *
4975  * Return: On success, this syscall returns the maximum
4976  * rt_priority that can be used by a given scheduling class.
4977  * On failure, a negative error code is returned.
4978  */
4979 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
4980 {
4981         int ret = -EINVAL;
4982
4983         switch (policy) {
4984         case SCHED_FIFO:
4985         case SCHED_RR:
4986                 ret = MAX_USER_RT_PRIO-1;
4987                 break;
4988         case SCHED_DEADLINE:
4989         case SCHED_NORMAL:
4990         case SCHED_BATCH:
4991         case SCHED_IDLE:
4992                 ret = 0;
4993                 break;
4994         }
4995         return ret;
4996 }
4997
4998 /**
4999  * sys_sched_get_priority_min - return minimum RT priority.
5000  * @policy: scheduling class.
5001  *
5002  * Return: On success, this syscall returns the minimum
5003  * rt_priority that can be used by a given scheduling class.
5004  * On failure, a negative error code is returned.
5005  */
5006 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5007 {
5008         int ret = -EINVAL;
5009
5010         switch (policy) {
5011         case SCHED_FIFO:
5012         case SCHED_RR:
5013                 ret = 1;
5014                 break;
5015         case SCHED_DEADLINE:
5016         case SCHED_NORMAL:
5017         case SCHED_BATCH:
5018         case SCHED_IDLE:
5019                 ret = 0;
5020         }
5021         return ret;
5022 }
5023
5024 /**
5025  * sys_sched_rr_get_interval - return the default timeslice of a process.
5026  * @pid: pid of the process.
5027  * @interval: userspace pointer to the timeslice value.
5028  *
5029  * this syscall writes the default timeslice value of a given process
5030  * into the user-space timespec buffer. A value of '0' means infinity.
5031  *
5032  * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5033  * an error code.
5034  */
5035 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5036                 struct timespec __user *, interval)
5037 {
5038         struct task_struct *p;
5039         unsigned int time_slice;
5040         struct rq_flags rf;
5041         struct timespec t;
5042         struct rq *rq;
5043         int retval;
5044
5045         if (pid < 0)
5046                 return -EINVAL;
5047
5048         retval = -ESRCH;
5049         rcu_read_lock();
5050         p = find_process_by_pid(pid);
5051         if (!p)
5052                 goto out_unlock;
5053
5054         retval = security_task_getscheduler(p);
5055         if (retval)
5056                 goto out_unlock;
5057
5058         rq = task_rq_lock(p, &rf);
5059         time_slice = 0;
5060         if (p->sched_class->get_rr_interval)
5061                 time_slice = p->sched_class->get_rr_interval(rq, p);
5062         task_rq_unlock(rq, p, &rf);
5063
5064         rcu_read_unlock();
5065         jiffies_to_timespec(time_slice, &t);
5066         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5067         return retval;
5068
5069 out_unlock:
5070         rcu_read_unlock();
5071         return retval;
5072 }
5073
5074 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5075
5076 void sched_show_task(struct task_struct *p)
5077 {
5078         unsigned long free = 0;
5079         int ppid;
5080         unsigned long state = p->state;
5081
5082         if (state)
5083                 state = __ffs(state) + 1;
5084         printk(KERN_INFO "%-15.15s %c", p->comm,
5085                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5086 #if BITS_PER_LONG == 32
5087         if (state == TASK_RUNNING)
5088                 printk(KERN_CONT " running  ");
5089         else
5090                 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5091 #else
5092         if (state == TASK_RUNNING)
5093                 printk(KERN_CONT "  running task    ");
5094         else
5095                 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5096 #endif
5097 #ifdef CONFIG_DEBUG_STACK_USAGE
5098         free = stack_not_used(p);
5099 #endif
5100         ppid = 0;
5101         rcu_read_lock();
5102         if (pid_alive(p))
5103                 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5104         rcu_read_unlock();
5105         printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5106                 task_pid_nr(p), ppid,
5107                 (unsigned long)task_thread_info(p)->flags);
5108
5109         print_worker_info(KERN_INFO, p);
5110         show_stack(p, NULL);
5111 }
5112
5113 void show_state_filter(unsigned long state_filter)
5114 {
5115         struct task_struct *g, *p;
5116
5117 #if BITS_PER_LONG == 32
5118         printk(KERN_INFO
5119                 "  task                PC stack   pid father\n");
5120 #else
5121         printk(KERN_INFO
5122                 "  task                        PC stack   pid father\n");
5123 #endif
5124         rcu_read_lock();
5125         for_each_process_thread(g, p) {
5126                 /*
5127                  * reset the NMI-timeout, listing all files on a slow
5128                  * console might take a lot of time:
5129                  */
5130                 touch_nmi_watchdog();
5131                 if (!state_filter || (p->state & state_filter))
5132                         sched_show_task(p);
5133         }
5134
5135         touch_all_softlockup_watchdogs();
5136
5137 #ifdef CONFIG_SCHED_DEBUG
5138         if (!state_filter)
5139                 sysrq_sched_debug_show();
5140 #endif
5141         rcu_read_unlock();
5142         /*
5143          * Only show locks if all tasks are dumped:
5144          */
5145         if (!state_filter)
5146                 debug_show_all_locks();
5147 }
5148
5149 void init_idle_bootup_task(struct task_struct *idle)
5150 {
5151         idle->sched_class = &idle_sched_class;
5152 }
5153
5154 /**
5155  * init_idle - set up an idle thread for a given CPU
5156  * @idle: task in question
5157  * @cpu: cpu the idle task belongs to
5158  *
5159  * NOTE: this function does not set the idle thread's NEED_RESCHED
5160  * flag, to make booting more robust.
5161  */
5162 void init_idle(struct task_struct *idle, int cpu)
5163 {
5164         struct rq *rq = cpu_rq(cpu);
5165         unsigned long flags;
5166
5167         raw_spin_lock_irqsave(&idle->pi_lock, flags);
5168         raw_spin_lock(&rq->lock);
5169
5170         __sched_fork(0, idle);
5171         idle->state = TASK_RUNNING;
5172         idle->se.exec_start = sched_clock();
5173
5174         kasan_unpoison_task_stack(idle);
5175
5176 #ifdef CONFIG_SMP
5177         /*
5178          * Its possible that init_idle() gets called multiple times on a task,
5179          * in that case do_set_cpus_allowed() will not do the right thing.
5180          *
5181          * And since this is boot we can forgo the serialization.
5182          */
5183         set_cpus_allowed_common(idle, cpumask_of(cpu));
5184 #endif
5185         /*
5186          * We're having a chicken and egg problem, even though we are
5187          * holding rq->lock, the cpu isn't yet set to this cpu so the
5188          * lockdep check in task_group() will fail.
5189          *
5190          * Similar case to sched_fork(). / Alternatively we could
5191          * use task_rq_lock() here and obtain the other rq->lock.
5192          *
5193          * Silence PROVE_RCU
5194          */
5195         rcu_read_lock();
5196         __set_task_cpu(idle, cpu);
5197         rcu_read_unlock();
5198
5199         rq->curr = rq->idle = idle;
5200         idle->on_rq = TASK_ON_RQ_QUEUED;
5201 #ifdef CONFIG_SMP
5202         idle->on_cpu = 1;
5203 #endif
5204         raw_spin_unlock(&rq->lock);
5205         raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5206
5207         /* Set the preempt count _outside_ the spinlocks! */
5208         init_idle_preempt_count(idle, cpu);
5209
5210         /*
5211          * The idle tasks have their own, simple scheduling class:
5212          */
5213         idle->sched_class = &idle_sched_class;
5214         ftrace_graph_init_idle_task(idle, cpu);
5215         vtime_init_idle(idle, cpu);
5216 #ifdef CONFIG_SMP
5217         sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5218 #endif
5219 }
5220
5221 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5222                               const struct cpumask *trial)
5223 {
5224         int ret = 1, trial_cpus;
5225         struct dl_bw *cur_dl_b;
5226         unsigned long flags;
5227
5228         if (!cpumask_weight(cur))
5229                 return ret;
5230
5231         rcu_read_lock_sched();
5232         cur_dl_b = dl_bw_of(cpumask_any(cur));
5233         trial_cpus = cpumask_weight(trial);
5234
5235         raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5236         if (cur_dl_b->bw != -1 &&
5237             cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5238                 ret = 0;
5239         raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5240         rcu_read_unlock_sched();
5241
5242         return ret;
5243 }
5244
5245 int task_can_attach(struct task_struct *p,
5246                     const struct cpumask *cs_cpus_allowed)
5247 {
5248         int ret = 0;
5249
5250         /*
5251          * Kthreads which disallow setaffinity shouldn't be moved
5252          * to a new cpuset; we don't want to change their cpu
5253          * affinity and isolating such threads by their set of
5254          * allowed nodes is unnecessary.  Thus, cpusets are not
5255          * applicable for such threads.  This prevents checking for
5256          * success of set_cpus_allowed_ptr() on all attached tasks
5257          * before cpus_allowed may be changed.
5258          */
5259         if (p->flags & PF_NO_SETAFFINITY) {
5260                 ret = -EINVAL;
5261                 goto out;
5262         }
5263
5264 #ifdef CONFIG_SMP
5265         if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5266                                               cs_cpus_allowed)) {
5267                 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5268                                                         cs_cpus_allowed);
5269                 struct dl_bw *dl_b;
5270                 bool overflow;
5271                 int cpus;
5272                 unsigned long flags;
5273
5274                 rcu_read_lock_sched();
5275                 dl_b = dl_bw_of(dest_cpu);
5276                 raw_spin_lock_irqsave(&dl_b->lock, flags);
5277                 cpus = dl_bw_cpus(dest_cpu);
5278                 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5279                 if (overflow)
5280                         ret = -EBUSY;
5281                 else {
5282                         /*
5283                          * We reserve space for this task in the destination
5284                          * root_domain, as we can't fail after this point.
5285                          * We will free resources in the source root_domain
5286                          * later on (see set_cpus_allowed_dl()).
5287                          */
5288                         __dl_add(dl_b, p->dl.dl_bw);
5289                 }
5290                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5291                 rcu_read_unlock_sched();
5292
5293         }
5294 #endif
5295 out:
5296         return ret;
5297 }
5298
5299 #ifdef CONFIG_SMP
5300
5301 static bool sched_smp_initialized __read_mostly;
5302
5303 #ifdef CONFIG_NUMA_BALANCING
5304 /* Migrate current task p to target_cpu */
5305 int migrate_task_to(struct task_struct *p, int target_cpu)
5306 {
5307         struct migration_arg arg = { p, target_cpu };
5308         int curr_cpu = task_cpu(p);
5309
5310         if (curr_cpu == target_cpu)
5311                 return 0;
5312
5313         if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
5314                 return -EINVAL;
5315
5316         /* TODO: This is not properly updating schedstats */
5317
5318         trace_sched_move_numa(p, curr_cpu, target_cpu);
5319         return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5320 }
5321
5322 /*
5323  * Requeue a task on a given node and accurately track the number of NUMA
5324  * tasks on the runqueues
5325  */
5326 void sched_setnuma(struct task_struct *p, int nid)
5327 {
5328         bool queued, running;
5329         struct rq_flags rf;
5330         struct rq *rq;
5331
5332         rq = task_rq_lock(p, &rf);
5333         queued = task_on_rq_queued(p);
5334         running = task_current(rq, p);
5335
5336         if (queued)
5337                 dequeue_task(rq, p, DEQUEUE_SAVE);
5338         if (running)
5339                 put_prev_task(rq, p);
5340
5341         p->numa_preferred_nid = nid;
5342
5343         if (running)
5344                 p->sched_class->set_curr_task(rq);
5345         if (queued)
5346                 enqueue_task(rq, p, ENQUEUE_RESTORE);
5347         task_rq_unlock(rq, p, &rf);
5348 }
5349 #endif /* CONFIG_NUMA_BALANCING */
5350
5351 #ifdef CONFIG_HOTPLUG_CPU
5352 /*
5353  * Ensures that the idle task is using init_mm right before its cpu goes
5354  * offline.
5355  */
5356 void idle_task_exit(void)
5357 {
5358         struct mm_struct *mm = current->active_mm;
5359
5360         BUG_ON(cpu_online(smp_processor_id()));
5361
5362         if (mm != &init_mm) {
5363                 switch_mm_irqs_off(mm, &init_mm, current);
5364                 finish_arch_post_lock_switch();
5365         }
5366         mmdrop(mm);
5367 }
5368
5369 /*
5370  * Since this CPU is going 'away' for a while, fold any nr_active delta
5371  * we might have. Assumes we're called after migrate_tasks() so that the
5372  * nr_active count is stable.
5373  *
5374  * Also see the comment "Global load-average calculations".
5375  */
5376 static void calc_load_migrate(struct rq *rq)
5377 {
5378         long delta = calc_load_fold_active(rq);
5379         if (delta)
5380                 atomic_long_add(delta, &calc_load_tasks);
5381 }
5382
5383 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5384 {
5385 }
5386
5387 static const struct sched_class fake_sched_class = {
5388         .put_prev_task = put_prev_task_fake,
5389 };
5390
5391 static struct task_struct fake_task = {
5392         /*
5393          * Avoid pull_{rt,dl}_task()
5394          */
5395         .prio = MAX_PRIO + 1,
5396         .sched_class = &fake_sched_class,
5397 };
5398
5399 /*
5400  * Migrate all tasks from the rq, sleeping tasks will be migrated by
5401  * try_to_wake_up()->select_task_rq().
5402  *
5403  * Called with rq->lock held even though we'er in stop_machine() and
5404  * there's no concurrency possible, we hold the required locks anyway
5405  * because of lock validation efforts.
5406  */
5407 static void migrate_tasks(struct rq *dead_rq)
5408 {
5409         struct rq *rq = dead_rq;
5410         struct task_struct *next, *stop = rq->stop;
5411         struct pin_cookie cookie;
5412         int dest_cpu;
5413
5414         /*
5415          * Fudge the rq selection such that the below task selection loop
5416          * doesn't get stuck on the currently eligible stop task.
5417          *
5418          * We're currently inside stop_machine() and the rq is either stuck
5419          * in the stop_machine_cpu_stop() loop, or we're executing this code,
5420          * either way we should never end up calling schedule() until we're
5421          * done here.
5422          */
5423         rq->stop = NULL;
5424
5425         /*
5426          * put_prev_task() and pick_next_task() sched
5427          * class method both need to have an up-to-date
5428          * value of rq->clock[_task]
5429          */
5430         update_rq_clock(rq);
5431
5432         for (;;) {
5433                 /*
5434                  * There's this thread running, bail when that's the only
5435                  * remaining thread.
5436                  */
5437                 if (rq->nr_running == 1)
5438                         break;
5439
5440                 /*
5441                  * pick_next_task assumes pinned rq->lock.
5442                  */
5443                 cookie = lockdep_pin_lock(&rq->lock);
5444                 next = pick_next_task(rq, &fake_task, cookie);
5445                 BUG_ON(!next);
5446                 next->sched_class->put_prev_task(rq, next);
5447
5448                 /*
5449                  * Rules for changing task_struct::cpus_allowed are holding
5450                  * both pi_lock and rq->lock, such that holding either
5451                  * stabilizes the mask.
5452                  *
5453                  * Drop rq->lock is not quite as disastrous as it usually is
5454                  * because !cpu_active at this point, which means load-balance
5455                  * will not interfere. Also, stop-machine.
5456                  */
5457                 lockdep_unpin_lock(&rq->lock, cookie);
5458                 raw_spin_unlock(&rq->lock);
5459                 raw_spin_lock(&next->pi_lock);
5460                 raw_spin_lock(&rq->lock);
5461
5462                 /*
5463                  * Since we're inside stop-machine, _nothing_ should have
5464                  * changed the task, WARN if weird stuff happened, because in
5465                  * that case the above rq->lock drop is a fail too.
5466                  */
5467                 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5468                         raw_spin_unlock(&next->pi_lock);
5469                         continue;
5470                 }
5471
5472                 /* Find suitable destination for @next, with force if needed. */
5473                 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5474
5475                 rq = __migrate_task(rq, next, dest_cpu);
5476                 if (rq != dead_rq) {
5477                         raw_spin_unlock(&rq->lock);
5478                         rq = dead_rq;
5479                         raw_spin_lock(&rq->lock);
5480                 }
5481                 raw_spin_unlock(&next->pi_lock);
5482         }
5483
5484         rq->stop = stop;
5485 }
5486 #endif /* CONFIG_HOTPLUG_CPU */
5487
5488 static void set_rq_online(struct rq *rq)
5489 {
5490         if (!rq->online) {
5491                 const struct sched_class *class;
5492
5493                 cpumask_set_cpu(rq->cpu, rq->rd->online);
5494                 rq->online = 1;
5495
5496                 for_each_class(class) {
5497                         if (class->rq_online)
5498                                 class->rq_online(rq);
5499                 }
5500         }
5501 }
5502
5503 static void set_rq_offline(struct rq *rq)
5504 {
5505         if (rq->online) {
5506                 const struct sched_class *class;
5507
5508                 for_each_class(class) {
5509                         if (class->rq_offline)
5510                                 class->rq_offline(rq);
5511                 }
5512
5513                 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5514                 rq->online = 0;
5515         }
5516 }
5517
5518 static void set_cpu_rq_start_time(unsigned int cpu)
5519 {
5520         struct rq *rq = cpu_rq(cpu);
5521
5522         rq->age_stamp = sched_clock_cpu(cpu);
5523 }
5524
5525 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5526
5527 #ifdef CONFIG_SCHED_DEBUG
5528
5529 static __read_mostly int sched_debug_enabled;
5530
5531 static int __init sched_debug_setup(char *str)
5532 {
5533         sched_debug_enabled = 1;
5534
5535         return 0;
5536 }
5537 early_param("sched_debug", sched_debug_setup);
5538
5539 static inline bool sched_debug(void)
5540 {
5541         return sched_debug_enabled;
5542 }
5543
5544 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5545                                   struct cpumask *groupmask)
5546 {
5547         struct sched_group *group = sd->groups;
5548
5549         cpumask_clear(groupmask);
5550
5551         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5552
5553         if (!(sd->flags & SD_LOAD_BALANCE)) {
5554                 printk("does not load-balance\n");
5555                 if (sd->parent)
5556                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5557                                         " has parent");
5558                 return -1;
5559         }
5560
5561         printk(KERN_CONT "span %*pbl level %s\n",
5562                cpumask_pr_args(sched_domain_span(sd)), sd->name);
5563
5564         if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5565                 printk(KERN_ERR "ERROR: domain->span does not contain "
5566                                 "CPU%d\n", cpu);
5567         }
5568         if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5569                 printk(KERN_ERR "ERROR: domain->groups does not contain"
5570                                 " CPU%d\n", cpu);
5571         }
5572
5573         printk(KERN_DEBUG "%*s groups:", level + 1, "");
5574         do {
5575                 if (!group) {
5576                         printk("\n");
5577                         printk(KERN_ERR "ERROR: group is NULL\n");
5578                         break;
5579                 }
5580
5581                 if (!cpumask_weight(sched_group_cpus(group))) {
5582                         printk(KERN_CONT "\n");
5583                         printk(KERN_ERR "ERROR: empty group\n");
5584                         break;
5585                 }
5586
5587                 if (!(sd->flags & SD_OVERLAP) &&
5588                     cpumask_intersects(groupmask, sched_group_cpus(group))) {
5589                         printk(KERN_CONT "\n");
5590                         printk(KERN_ERR "ERROR: repeated CPUs\n");
5591                         break;
5592                 }
5593
5594                 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5595
5596                 printk(KERN_CONT " %*pbl",
5597                        cpumask_pr_args(sched_group_cpus(group)));
5598                 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5599                         printk(KERN_CONT " (cpu_capacity = %d)",
5600                                 group->sgc->capacity);
5601                 }
5602
5603                 group = group->next;
5604         } while (group != sd->groups);
5605         printk(KERN_CONT "\n");
5606
5607         if (!cpumask_equal(sched_domain_span(sd), groupmask))
5608                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5609
5610         if (sd->parent &&
5611             !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5612                 printk(KERN_ERR "ERROR: parent span is not a superset "
5613                         "of domain->span\n");
5614         return 0;
5615 }
5616
5617 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5618 {
5619         int level = 0;
5620
5621         if (!sched_debug_enabled)
5622                 return;
5623
5624         if (!sd) {
5625                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5626                 return;
5627         }
5628
5629         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5630
5631         for (;;) {
5632                 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5633                         break;
5634                 level++;
5635                 sd = sd->parent;
5636                 if (!sd)
5637                         break;
5638         }
5639 }
5640 #else /* !CONFIG_SCHED_DEBUG */
5641 # define sched_domain_debug(sd, cpu) do { } while (0)
5642 static inline bool sched_debug(void)
5643 {
5644         return false;
5645 }
5646 #endif /* CONFIG_SCHED_DEBUG */
5647
5648 static int sd_degenerate(struct sched_domain *sd)
5649 {
5650         if (cpumask_weight(sched_domain_span(sd)) == 1)
5651                 return 1;
5652
5653         /* Following flags need at least 2 groups */
5654         if (sd->flags & (SD_LOAD_BALANCE |
5655                          SD_BALANCE_NEWIDLE |
5656                          SD_BALANCE_FORK |
5657                          SD_BALANCE_EXEC |
5658                          SD_SHARE_CPUCAPACITY |
5659                          SD_SHARE_PKG_RESOURCES |
5660                          SD_SHARE_POWERDOMAIN)) {
5661                 if (sd->groups != sd->groups->next)
5662                         return 0;
5663         }
5664
5665         /* Following flags don't use groups */
5666         if (sd->flags & (SD_WAKE_AFFINE))
5667                 return 0;
5668
5669         return 1;
5670 }
5671
5672 static int
5673 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5674 {
5675         unsigned long cflags = sd->flags, pflags = parent->flags;
5676
5677         if (sd_degenerate(parent))
5678                 return 1;
5679
5680         if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5681                 return 0;
5682
5683         /* Flags needing groups don't count if only 1 group in parent */
5684         if (parent->groups == parent->groups->next) {
5685                 pflags &= ~(SD_LOAD_BALANCE |
5686                                 SD_BALANCE_NEWIDLE |
5687                                 SD_BALANCE_FORK |
5688                                 SD_BALANCE_EXEC |
5689                                 SD_SHARE_CPUCAPACITY |
5690                                 SD_SHARE_PKG_RESOURCES |
5691                                 SD_PREFER_SIBLING |
5692                                 SD_SHARE_POWERDOMAIN);
5693                 if (nr_node_ids == 1)
5694                         pflags &= ~SD_SERIALIZE;
5695         }
5696         if (~cflags & pflags)
5697                 return 0;
5698
5699         return 1;
5700 }
5701
5702 static void free_rootdomain(struct rcu_head *rcu)
5703 {
5704         struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5705
5706         cpupri_cleanup(&rd->cpupri);
5707         cpudl_cleanup(&rd->cpudl);
5708         free_cpumask_var(rd->dlo_mask);
5709         free_cpumask_var(rd->rto_mask);
5710         free_cpumask_var(rd->online);
5711         free_cpumask_var(rd->span);
5712         kfree(rd);
5713 }
5714
5715 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5716 {
5717         struct root_domain *old_rd = NULL;
5718         unsigned long flags;
5719
5720         raw_spin_lock_irqsave(&rq->lock, flags);
5721
5722         if (rq->rd) {
5723                 old_rd = rq->rd;
5724
5725                 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5726                         set_rq_offline(rq);
5727
5728                 cpumask_clear_cpu(rq->cpu, old_rd->span);
5729
5730                 /*
5731                  * If we dont want to free the old_rd yet then
5732                  * set old_rd to NULL to skip the freeing later
5733                  * in this function:
5734                  */
5735                 if (!atomic_dec_and_test(&old_rd->refcount))
5736                         old_rd = NULL;
5737         }
5738
5739         atomic_inc(&rd->refcount);
5740         rq->rd = rd;
5741
5742         cpumask_set_cpu(rq->cpu, rd->span);
5743         if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5744                 set_rq_online(rq);
5745
5746         raw_spin_unlock_irqrestore(&rq->lock, flags);
5747
5748         if (old_rd)
5749                 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5750 }
5751
5752 static int init_rootdomain(struct root_domain *rd)
5753 {
5754         memset(rd, 0, sizeof(*rd));
5755
5756         if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
5757                 goto out;
5758         if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
5759                 goto free_span;
5760         if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
5761                 goto free_online;
5762         if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5763                 goto free_dlo_mask;
5764
5765         init_dl_bw(&rd->dl_bw);
5766         if (cpudl_init(&rd->cpudl) != 0)
5767                 goto free_dlo_mask;
5768
5769         if (cpupri_init(&rd->cpupri) != 0)
5770                 goto free_rto_mask;
5771         return 0;
5772
5773 free_rto_mask:
5774         free_cpumask_var(rd->rto_mask);
5775 free_dlo_mask:
5776         free_cpumask_var(rd->dlo_mask);
5777 free_online:
5778         free_cpumask_var(rd->online);
5779 free_span:
5780         free_cpumask_var(rd->span);
5781 out:
5782         return -ENOMEM;
5783 }
5784
5785 /*
5786  * By default the system creates a single root-domain with all cpus as
5787  * members (mimicking the global state we have today).
5788  */
5789 struct root_domain def_root_domain;
5790
5791 static void init_defrootdomain(void)
5792 {
5793         init_rootdomain(&def_root_domain);
5794
5795         atomic_set(&def_root_domain.refcount, 1);
5796 }
5797
5798 static struct root_domain *alloc_rootdomain(void)
5799 {
5800         struct root_domain *rd;
5801
5802         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5803         if (!rd)
5804                 return NULL;
5805
5806         if (init_rootdomain(rd) != 0) {
5807                 kfree(rd);
5808                 return NULL;
5809         }
5810
5811         return rd;
5812 }
5813
5814 static void free_sched_groups(struct sched_group *sg, int free_sgc)
5815 {
5816         struct sched_group *tmp, *first;
5817
5818         if (!sg)
5819                 return;
5820
5821         first = sg;
5822         do {
5823                 tmp = sg->next;
5824
5825                 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
5826                         kfree(sg->sgc);
5827
5828                 kfree(sg);
5829                 sg = tmp;
5830         } while (sg != first);
5831 }
5832
5833 static void free_sched_domain(struct rcu_head *rcu)
5834 {
5835         struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5836
5837         /*
5838          * If its an overlapping domain it has private groups, iterate and
5839          * nuke them all.
5840          */
5841         if (sd->flags & SD_OVERLAP) {
5842                 free_sched_groups(sd->groups, 1);
5843         } else if (atomic_dec_and_test(&sd->groups->ref)) {
5844                 kfree(sd->groups->sgc);
5845                 kfree(sd->groups);
5846         }
5847         kfree(sd);
5848 }
5849
5850 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5851 {
5852         call_rcu(&sd->rcu, free_sched_domain);
5853 }
5854
5855 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5856 {
5857         for (; sd; sd = sd->parent)
5858                 destroy_sched_domain(sd, cpu);
5859 }
5860
5861 /*
5862  * Keep a special pointer to the highest sched_domain that has
5863  * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5864  * allows us to avoid some pointer chasing select_idle_sibling().
5865  *
5866  * Also keep a unique ID per domain (we use the first cpu number in
5867  * the cpumask of the domain), this allows us to quickly tell if
5868  * two cpus are in the same cache domain, see cpus_share_cache().
5869  */
5870 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5871 DEFINE_PER_CPU(int, sd_llc_size);
5872 DEFINE_PER_CPU(int, sd_llc_id);
5873 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
5874 DEFINE_PER_CPU(struct sched_domain *, sd_busy);
5875 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
5876
5877 static void update_top_cache_domain(int cpu)
5878 {
5879         struct sched_domain *sd;
5880         struct sched_domain *busy_sd = NULL;
5881         int id = cpu;
5882         int size = 1;
5883
5884         sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
5885         if (sd) {
5886                 id = cpumask_first(sched_domain_span(sd));
5887                 size = cpumask_weight(sched_domain_span(sd));
5888                 busy_sd = sd->parent; /* sd_busy */
5889         }
5890         rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
5891
5892         rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5893         per_cpu(sd_llc_size, cpu) = size;
5894         per_cpu(sd_llc_id, cpu) = id;
5895
5896         sd = lowest_flag_domain(cpu, SD_NUMA);
5897         rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
5898
5899         sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
5900         rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
5901 }
5902
5903 /*
5904  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5905  * hold the hotplug lock.
5906  */
5907 static void
5908 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5909 {
5910         struct rq *rq = cpu_rq(cpu);
5911         struct sched_domain *tmp;
5912
5913         /* Remove the sched domains which do not contribute to scheduling. */
5914         for (tmp = sd; tmp; ) {
5915                 struct sched_domain *parent = tmp->parent;
5916                 if (!parent)
5917                         break;
5918
5919                 if (sd_parent_degenerate(tmp, parent)) {
5920                         tmp->parent = parent->parent;
5921                         if (parent->parent)
5922                                 parent->parent->child = tmp;
5923                         /*
5924                          * Transfer SD_PREFER_SIBLING down in case of a
5925                          * degenerate parent; the spans match for this
5926                          * so the property transfers.
5927                          */
5928                         if (parent->flags & SD_PREFER_SIBLING)
5929                                 tmp->flags |= SD_PREFER_SIBLING;
5930                         destroy_sched_domain(parent, cpu);
5931                 } else
5932                         tmp = tmp->parent;
5933         }
5934
5935         if (sd && sd_degenerate(sd)) {
5936                 tmp = sd;
5937                 sd = sd->parent;
5938                 destroy_sched_domain(tmp, cpu);
5939                 if (sd)
5940                         sd->child = NULL;
5941         }
5942
5943         sched_domain_debug(sd, cpu);
5944
5945         rq_attach_root(rq, rd);
5946         tmp = rq->sd;
5947         rcu_assign_pointer(rq->sd, sd);
5948         destroy_sched_domains(tmp, cpu);
5949
5950         update_top_cache_domain(cpu);
5951 }
5952
5953 /* Setup the mask of cpus configured for isolated domains */
5954 static int __init isolated_cpu_setup(char *str)
5955 {
5956         int ret;
5957
5958         alloc_bootmem_cpumask_var(&cpu_isolated_map);
5959         ret = cpulist_parse(str, cpu_isolated_map);
5960         if (ret) {
5961                 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
5962                 return 0;
5963         }
5964         return 1;
5965 }
5966 __setup("isolcpus=", isolated_cpu_setup);
5967
5968 struct s_data {
5969         struct sched_domain ** __percpu sd;
5970         struct root_domain      *rd;
5971 };
5972
5973 enum s_alloc {
5974         sa_rootdomain,
5975         sa_sd,
5976         sa_sd_storage,
5977         sa_none,
5978 };
5979
5980 /*
5981  * Build an iteration mask that can exclude certain CPUs from the upwards
5982  * domain traversal.
5983  *
5984  * Asymmetric node setups can result in situations where the domain tree is of
5985  * unequal depth, make sure to skip domains that already cover the entire
5986  * range.
5987  *
5988  * In that case build_sched_domains() will have terminated the iteration early
5989  * and our sibling sd spans will be empty. Domains should always include the
5990  * cpu they're built on, so check that.
5991  *
5992  */
5993 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5994 {
5995         const struct cpumask *span = sched_domain_span(sd);
5996         struct sd_data *sdd = sd->private;
5997         struct sched_domain *sibling;
5998         int i;
5999
6000         for_each_cpu(i, span) {
6001                 sibling = *per_cpu_ptr(sdd->sd, i);
6002                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6003                         continue;
6004
6005                 cpumask_set_cpu(i, sched_group_mask(sg));
6006         }
6007 }
6008
6009 /*
6010  * Return the canonical balance cpu for this group, this is the first cpu
6011  * of this group that's also in the iteration mask.
6012  */
6013 int group_balance_cpu(struct sched_group *sg)
6014 {
6015         return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6016 }
6017
6018 static int
6019 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6020 {
6021         struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6022         const struct cpumask *span = sched_domain_span(sd);
6023         struct cpumask *covered = sched_domains_tmpmask;
6024         struct sd_data *sdd = sd->private;
6025         struct sched_domain *sibling;
6026         int i;
6027
6028         cpumask_clear(covered);
6029
6030         for_each_cpu(i, span) {
6031                 struct cpumask *sg_span;
6032
6033                 if (cpumask_test_cpu(i, covered))
6034                         continue;
6035
6036                 sibling = *per_cpu_ptr(sdd->sd, i);
6037
6038                 /* See the comment near build_group_mask(). */
6039                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6040                         continue;
6041
6042                 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6043                                 GFP_KERNEL, cpu_to_node(cpu));
6044
6045                 if (!sg)
6046                         goto fail;
6047
6048                 sg_span = sched_group_cpus(sg);
6049                 if (sibling->child)
6050                         cpumask_copy(sg_span, sched_domain_span(sibling->child));
6051                 else
6052                         cpumask_set_cpu(i, sg_span);
6053
6054                 cpumask_or(covered, covered, sg_span);
6055
6056                 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6057                 if (atomic_inc_return(&sg->sgc->ref) == 1)
6058                         build_group_mask(sd, sg);
6059
6060                 /*
6061                  * Initialize sgc->capacity such that even if we mess up the
6062                  * domains and no possible iteration will get us here, we won't
6063                  * die on a /0 trap.
6064                  */
6065                 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6066
6067                 /*
6068                  * Make sure the first group of this domain contains the
6069                  * canonical balance cpu. Otherwise the sched_domain iteration
6070                  * breaks. See update_sg_lb_stats().
6071                  */
6072                 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6073                     group_balance_cpu(sg) == cpu)
6074                         groups = sg;
6075
6076                 if (!first)
6077                         first = sg;
6078                 if (last)
6079                         last->next = sg;
6080                 last = sg;
6081                 last->next = first;
6082         }
6083         sd->groups = groups;
6084
6085         return 0;
6086
6087 fail:
6088         free_sched_groups(first, 0);
6089
6090         return -ENOMEM;
6091 }
6092
6093 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6094 {
6095         struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6096         struct sched_domain *child = sd->child;
6097
6098         if (child)
6099                 cpu = cpumask_first(sched_domain_span(child));
6100
6101         if (sg) {
6102                 *sg = *per_cpu_ptr(sdd->sg, cpu);
6103                 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6104                 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6105         }
6106
6107         return cpu;
6108 }
6109
6110 /*
6111  * build_sched_groups will build a circular linked list of the groups
6112  * covered by the given span, and will set each group's ->cpumask correctly,
6113  * and ->cpu_capacity to 0.
6114  *
6115  * Assumes the sched_domain tree is fully constructed
6116  */
6117 static int
6118 build_sched_groups(struct sched_domain *sd, int cpu)
6119 {
6120         struct sched_group *first = NULL, *last = NULL;
6121         struct sd_data *sdd = sd->private;
6122         const struct cpumask *span = sched_domain_span(sd);
6123         struct cpumask *covered;
6124         int i;
6125
6126         get_group(cpu, sdd, &sd->groups);
6127         atomic_inc(&sd->groups->ref);
6128
6129         if (cpu != cpumask_first(span))
6130                 return 0;
6131
6132         lockdep_assert_held(&sched_domains_mutex);
6133         covered = sched_domains_tmpmask;
6134
6135         cpumask_clear(covered);
6136
6137         for_each_cpu(i, span) {
6138                 struct sched_group *sg;
6139                 int group, j;
6140
6141                 if (cpumask_test_cpu(i, covered))
6142                         continue;
6143
6144                 group = get_group(i, sdd, &sg);
6145                 cpumask_setall(sched_group_mask(sg));
6146
6147                 for_each_cpu(j, span) {
6148                         if (get_group(j, sdd, NULL) != group)
6149                                 continue;
6150
6151                         cpumask_set_cpu(j, covered);
6152                         cpumask_set_cpu(j, sched_group_cpus(sg));
6153                 }
6154
6155                 if (!first)
6156                         first = sg;
6157                 if (last)
6158                         last->next = sg;
6159                 last = sg;
6160         }
6161         last->next = first;
6162
6163         return 0;
6164 }
6165
6166 /*
6167  * Initialize sched groups cpu_capacity.
6168  *
6169  * cpu_capacity indicates the capacity of sched group, which is used while
6170  * distributing the load between different sched groups in a sched domain.
6171  * Typically cpu_capacity for all the groups in a sched domain will be same
6172  * unless there are asymmetries in the topology. If there are asymmetries,
6173  * group having more cpu_capacity will pickup more load compared to the
6174  * group having less cpu_capacity.
6175  */
6176 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6177 {
6178         struct sched_group *sg = sd->groups;
6179
6180         WARN_ON(!sg);
6181
6182         do {
6183                 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6184                 sg = sg->next;
6185         } while (sg != sd->groups);
6186
6187         if (cpu != group_balance_cpu(sg))
6188                 return;
6189
6190         update_group_capacity(sd, cpu);
6191         atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
6192 }
6193
6194 /*
6195  * Initializers for schedule domains
6196  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6197  */
6198
6199 static int default_relax_domain_level = -1;
6200 int sched_domain_level_max;
6201
6202 static int __init setup_relax_domain_level(char *str)
6203 {
6204         if (kstrtoint(str, 0, &default_relax_domain_level))
6205                 pr_warn("Unable to set relax_domain_level\n");
6206
6207         return 1;
6208 }
6209 __setup("relax_domain_level=", setup_relax_domain_level);
6210
6211 static void set_domain_attribute(struct sched_domain *sd,
6212                                  struct sched_domain_attr *attr)
6213 {
6214         int request;
6215
6216         if (!attr || attr->relax_domain_level < 0) {
6217                 if (default_relax_domain_level < 0)
6218                         return;
6219                 else
6220                         request = default_relax_domain_level;
6221         } else
6222                 request = attr->relax_domain_level;
6223         if (request < sd->level) {
6224                 /* turn off idle balance on this domain */
6225                 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6226         } else {
6227                 /* turn on idle balance on this domain */
6228                 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6229         }
6230 }
6231
6232 static void __sdt_free(const struct cpumask *cpu_map);
6233 static int __sdt_alloc(const struct cpumask *cpu_map);
6234
6235 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6236                                  const struct cpumask *cpu_map)
6237 {
6238         switch (what) {
6239         case sa_rootdomain:
6240                 if (!atomic_read(&d->rd->refcount))
6241                         free_rootdomain(&d->rd->rcu); /* fall through */
6242         case sa_sd:
6243                 free_percpu(d->sd); /* fall through */
6244         case sa_sd_storage:
6245                 __sdt_free(cpu_map); /* fall through */
6246         case sa_none:
6247                 break;
6248         }
6249 }
6250
6251 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6252                                                    const struct cpumask *cpu_map)
6253 {
6254         memset(d, 0, sizeof(*d));
6255
6256         if (__sdt_alloc(cpu_map))
6257                 return sa_sd_storage;
6258         d->sd = alloc_percpu(struct sched_domain *);
6259         if (!d->sd)
6260                 return sa_sd_storage;
6261         d->rd = alloc_rootdomain();
6262         if (!d->rd)
6263                 return sa_sd;
6264         return sa_rootdomain;
6265 }
6266
6267 /*
6268  * NULL the sd_data elements we've used to build the sched_domain and
6269  * sched_group structure so that the subsequent __free_domain_allocs()
6270  * will not free the data we're using.
6271  */
6272 static void claim_allocations(int cpu, struct sched_domain *sd)
6273 {
6274         struct sd_data *sdd = sd->private;
6275
6276         WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6277         *per_cpu_ptr(sdd->sd, cpu) = NULL;
6278
6279         if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6280                 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6281
6282         if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6283                 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6284 }
6285
6286 #ifdef CONFIG_NUMA
6287 static int sched_domains_numa_levels;
6288 enum numa_topology_type sched_numa_topology_type;
6289 static int *sched_domains_numa_distance;
6290 int sched_max_numa_distance;
6291 static struct cpumask ***sched_domains_numa_masks;
6292 static int sched_domains_curr_level;
6293 #endif
6294
6295 /*
6296  * SD_flags allowed in topology descriptions.
6297  *
6298  * SD_SHARE_CPUCAPACITY      - describes SMT topologies
6299  * SD_SHARE_PKG_RESOURCES - describes shared caches
6300  * SD_NUMA                - describes NUMA topologies
6301  * SD_SHARE_POWERDOMAIN   - describes shared power domain
6302  *
6303  * Odd one out:
6304  * SD_ASYM_PACKING        - describes SMT quirks
6305  */
6306 #define TOPOLOGY_SD_FLAGS               \
6307         (SD_SHARE_CPUCAPACITY |         \
6308          SD_SHARE_PKG_RESOURCES |       \
6309          SD_NUMA |                      \
6310          SD_ASYM_PACKING |              \
6311          SD_SHARE_POWERDOMAIN)
6312
6313 static struct sched_domain *
6314 sd_init(struct sched_domain_topology_level *tl, int cpu)
6315 {
6316         struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6317         int sd_weight, sd_flags = 0;
6318
6319 #ifdef CONFIG_NUMA
6320         /*
6321          * Ugly hack to pass state to sd_numa_mask()...
6322          */
6323         sched_domains_curr_level = tl->numa_level;
6324 #endif
6325
6326         sd_weight = cpumask_weight(tl->mask(cpu));
6327
6328         if (tl->sd_flags)
6329                 sd_flags = (*tl->sd_flags)();
6330         if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6331                         "wrong sd_flags in topology description\n"))
6332                 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6333
6334         *sd = (struct sched_domain){
6335                 .min_interval           = sd_weight,
6336                 .max_interval           = 2*sd_weight,
6337                 .busy_factor            = 32,
6338                 .imbalance_pct          = 125,
6339
6340                 .cache_nice_tries       = 0,
6341                 .busy_idx               = 0,
6342                 .idle_idx               = 0,
6343                 .newidle_idx            = 0,
6344                 .wake_idx               = 0,
6345                 .forkexec_idx           = 0,
6346
6347                 .flags                  = 1*SD_LOAD_BALANCE
6348                                         | 1*SD_BALANCE_NEWIDLE
6349                                         | 1*SD_BALANCE_EXEC
6350                                         | 1*SD_BALANCE_FORK
6351                                         | 0*SD_BALANCE_WAKE
6352                                         | 1*SD_WAKE_AFFINE
6353                                         | 0*SD_SHARE_CPUCAPACITY
6354                                         | 0*SD_SHARE_PKG_RESOURCES
6355                                         | 0*SD_SERIALIZE
6356                                         | 0*SD_PREFER_SIBLING
6357                                         | 0*SD_NUMA
6358                                         | sd_flags
6359                                         ,
6360
6361                 .last_balance           = jiffies,
6362                 .balance_interval       = sd_weight,
6363                 .smt_gain               = 0,
6364                 .max_newidle_lb_cost    = 0,
6365                 .next_decay_max_lb_cost = jiffies,
6366 #ifdef CONFIG_SCHED_DEBUG
6367                 .name                   = tl->name,
6368 #endif
6369         };
6370
6371         /*
6372          * Convert topological properties into behaviour.
6373          */
6374
6375         if (sd->flags & SD_SHARE_CPUCAPACITY) {
6376                 sd->flags |= SD_PREFER_SIBLING;
6377                 sd->imbalance_pct = 110;
6378                 sd->smt_gain = 1178; /* ~15% */
6379
6380         } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6381                 sd->imbalance_pct = 117;
6382                 sd->cache_nice_tries = 1;
6383                 sd->busy_idx = 2;
6384
6385 #ifdef CONFIG_NUMA
6386         } else if (sd->flags & SD_NUMA) {
6387                 sd->cache_nice_tries = 2;
6388                 sd->busy_idx = 3;
6389                 sd->idle_idx = 2;
6390
6391                 sd->flags |= SD_SERIALIZE;
6392                 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6393                         sd->flags &= ~(SD_BALANCE_EXEC |
6394                                        SD_BALANCE_FORK |
6395                                        SD_WAKE_AFFINE);
6396                 }
6397
6398 #endif
6399         } else {
6400                 sd->flags |= SD_PREFER_SIBLING;
6401                 sd->cache_nice_tries = 1;
6402                 sd->busy_idx = 2;
6403                 sd->idle_idx = 1;
6404         }
6405
6406         sd->private = &tl->data;
6407
6408         return sd;
6409 }
6410
6411 /*
6412  * Topology list, bottom-up.
6413  */
6414 static struct sched_domain_topology_level default_topology[] = {
6415 #ifdef CONFIG_SCHED_SMT
6416         { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6417 #endif
6418 #ifdef CONFIG_SCHED_MC
6419         { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6420 #endif
6421         { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6422         { NULL, },
6423 };
6424
6425 static struct sched_domain_topology_level *sched_domain_topology =
6426         default_topology;
6427
6428 #define for_each_sd_topology(tl)                        \
6429         for (tl = sched_domain_topology; tl->mask; tl++)
6430
6431 void set_sched_topology(struct sched_domain_topology_level *tl)
6432 {
6433         sched_domain_topology = tl;
6434 }
6435
6436 #ifdef CONFIG_NUMA
6437
6438 static const struct cpumask *sd_numa_mask(int cpu)
6439 {
6440         return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6441 }
6442
6443 static void sched_numa_warn(const char *str)
6444 {
6445         static int done = false;
6446         int i,j;
6447
6448         if (done)
6449                 return;
6450
6451         done = true;
6452
6453         printk(KERN_WARNING "ERROR: %s\n\n", str);
6454
6455         for (i = 0; i < nr_node_ids; i++) {
6456                 printk(KERN_WARNING "  ");
6457                 for (j = 0; j < nr_node_ids; j++)
6458                         printk(KERN_CONT "%02d ", node_distance(i,j));
6459                 printk(KERN_CONT "\n");
6460         }
6461         printk(KERN_WARNING "\n");
6462 }
6463
6464 bool find_numa_distance(int distance)
6465 {
6466         int i;
6467
6468         if (distance == node_distance(0, 0))
6469                 return true;
6470
6471         for (i = 0; i < sched_domains_numa_levels; i++) {
6472                 if (sched_domains_numa_distance[i] == distance)
6473                         return true;
6474         }
6475
6476         return false;
6477 }
6478
6479 /*
6480  * A system can have three types of NUMA topology:
6481  * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6482  * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6483  * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6484  *
6485  * The difference between a glueless mesh topology and a backplane
6486  * topology lies in whether communication between not directly
6487  * connected nodes goes through intermediary nodes (where programs
6488  * could run), or through backplane controllers. This affects
6489  * placement of programs.
6490  *
6491  * The type of topology can be discerned with the following tests:
6492  * - If the maximum distance between any nodes is 1 hop, the system
6493  *   is directly connected.
6494  * - If for two nodes A and B, located N > 1 hops away from each other,
6495  *   there is an intermediary node C, which is < N hops away from both
6496  *   nodes A and B, the system is a glueless mesh.
6497  */
6498 static void init_numa_topology_type(void)
6499 {
6500         int a, b, c, n;
6501
6502         n = sched_max_numa_distance;
6503
6504         if (sched_domains_numa_levels <= 1) {
6505                 sched_numa_topology_type = NUMA_DIRECT;
6506                 return;
6507         }
6508
6509         for_each_online_node(a) {
6510                 for_each_online_node(b) {
6511                         /* Find two nodes furthest removed from each other. */
6512                         if (node_distance(a, b) < n)
6513                                 continue;
6514
6515                         /* Is there an intermediary node between a and b? */
6516                         for_each_online_node(c) {
6517                                 if (node_distance(a, c) < n &&
6518                                     node_distance(b, c) < n) {
6519                                         sched_numa_topology_type =
6520                                                         NUMA_GLUELESS_MESH;
6521                                         return;
6522                                 }
6523                         }
6524
6525                         sched_numa_topology_type = NUMA_BACKPLANE;
6526                         return;
6527                 }
6528         }
6529 }
6530
6531 static void sched_init_numa(void)
6532 {
6533         int next_distance, curr_distance = node_distance(0, 0);
6534         struct sched_domain_topology_level *tl;
6535         int level = 0;
6536         int i, j, k;
6537
6538         sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6539         if (!sched_domains_numa_distance)
6540                 return;
6541
6542         /*
6543          * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6544          * unique distances in the node_distance() table.
6545          *
6546          * Assumes node_distance(0,j) includes all distances in
6547          * node_distance(i,j) in order to avoid cubic time.
6548          */
6549         next_distance = curr_distance;
6550         for (i = 0; i < nr_node_ids; i++) {
6551                 for (j = 0; j < nr_node_ids; j++) {
6552                         for (k = 0; k < nr_node_ids; k++) {
6553                                 int distance = node_distance(i, k);
6554
6555                                 if (distance > curr_distance &&
6556                                     (distance < next_distance ||
6557                                      next_distance == curr_distance))
6558                                         next_distance = distance;
6559
6560                                 /*
6561                                  * While not a strong assumption it would be nice to know
6562                                  * about cases where if node A is connected to B, B is not
6563                                  * equally connected to A.
6564                                  */
6565                                 if (sched_debug() && node_distance(k, i) != distance)
6566                                         sched_numa_warn("Node-distance not symmetric");
6567
6568                                 if (sched_debug() && i && !find_numa_distance(distance))
6569                                         sched_numa_warn("Node-0 not representative");
6570                         }
6571                         if (next_distance != curr_distance) {
6572                                 sched_domains_numa_distance[level++] = next_distance;
6573                                 sched_domains_numa_levels = level;
6574                                 curr_distance = next_distance;
6575                         } else break;
6576                 }
6577
6578                 /*
6579                  * In case of sched_debug() we verify the above assumption.
6580                  */
6581                 if (!sched_debug())
6582                         break;
6583         }
6584
6585         if (!level)
6586                 return;
6587
6588         /*
6589          * 'level' contains the number of unique distances, excluding the
6590          * identity distance node_distance(i,i).
6591          *
6592          * The sched_domains_numa_distance[] array includes the actual distance
6593          * numbers.
6594          */
6595
6596         /*
6597          * Here, we should temporarily reset sched_domains_numa_levels to 0.
6598          * If it fails to allocate memory for array sched_domains_numa_masks[][],
6599          * the array will contain less then 'level' members. This could be
6600          * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6601          * in other functions.
6602          *
6603          * We reset it to 'level' at the end of this function.
6604          */
6605         sched_domains_numa_levels = 0;
6606
6607         sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6608         if (!sched_domains_numa_masks)
6609                 return;
6610
6611         /*
6612          * Now for each level, construct a mask per node which contains all
6613          * cpus of nodes that are that many hops away from us.
6614          */
6615         for (i = 0; i < level; i++) {
6616                 sched_domains_numa_masks[i] =
6617                         kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6618                 if (!sched_domains_numa_masks[i])
6619                         return;
6620
6621                 for (j = 0; j < nr_node_ids; j++) {
6622                         struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6623                         if (!mask)
6624                                 return;
6625
6626                         sched_domains_numa_masks[i][j] = mask;
6627
6628                         for_each_node(k) {
6629                                 if (node_distance(j, k) > sched_domains_numa_distance[i])
6630                                         continue;
6631
6632                                 cpumask_or(mask, mask, cpumask_of_node(k));
6633                         }
6634                 }
6635         }
6636
6637         /* Compute default topology size */
6638         for (i = 0; sched_domain_topology[i].mask; i++);
6639
6640         tl = kzalloc((i + level + 1) *
6641                         sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6642         if (!tl)
6643                 return;
6644
6645         /*
6646          * Copy the default topology bits..
6647          */
6648         for (i = 0; sched_domain_topology[i].mask; i++)
6649                 tl[i] = sched_domain_topology[i];
6650
6651         /*
6652          * .. and append 'j' levels of NUMA goodness.
6653          */
6654         for (j = 0; j < level; i++, j++) {
6655                 tl[i] = (struct sched_domain_topology_level){
6656                         .mask = sd_numa_mask,
6657                         .sd_flags = cpu_numa_flags,
6658                         .flags = SDTL_OVERLAP,
6659                         .numa_level = j,
6660                         SD_INIT_NAME(NUMA)
6661                 };
6662         }
6663
6664         sched_domain_topology = tl;
6665
6666         sched_domains_numa_levels = level;
6667         sched_max_numa_distance = sched_domains_numa_distance[level - 1];
6668
6669         init_numa_topology_type();
6670 }
6671
6672 static void sched_domains_numa_masks_set(unsigned int cpu)
6673 {
6674         int node = cpu_to_node(cpu);
6675         int i, j;
6676
6677         for (i = 0; i < sched_domains_numa_levels; i++) {
6678                 for (j = 0; j < nr_node_ids; j++) {
6679                         if (node_distance(j, node) <= sched_domains_numa_distance[i])
6680                                 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6681                 }
6682         }
6683 }
6684
6685 static void sched_domains_numa_masks_clear(unsigned int cpu)
6686 {
6687         int i, j;
6688
6689         for (i = 0; i < sched_domains_numa_levels; i++) {
6690                 for (j = 0; j < nr_node_ids; j++)
6691                         cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6692         }
6693 }
6694
6695 #else
6696 static inline void sched_init_numa(void) { }
6697 static void sched_domains_numa_masks_set(unsigned int cpu) { }
6698 static void sched_domains_numa_masks_clear(unsigned int cpu) { }
6699 #endif /* CONFIG_NUMA */
6700
6701 static int __sdt_alloc(const struct cpumask *cpu_map)
6702 {
6703         struct sched_domain_topology_level *tl;
6704         int j;
6705
6706         for_each_sd_topology(tl) {
6707                 struct sd_data *sdd = &tl->data;
6708
6709                 sdd->sd = alloc_percpu(struct sched_domain *);
6710                 if (!sdd->sd)
6711                         return -ENOMEM;
6712
6713                 sdd->sg = alloc_percpu(struct sched_group *);
6714                 if (!sdd->sg)
6715                         return -ENOMEM;
6716
6717                 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
6718                 if (!sdd->sgc)
6719                         return -ENOMEM;
6720
6721                 for_each_cpu(j, cpu_map) {
6722                         struct sched_domain *sd;
6723                         struct sched_group *sg;
6724                         struct sched_group_capacity *sgc;
6725
6726                         sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6727                                         GFP_KERNEL, cpu_to_node(j));
6728                         if (!sd)
6729                                 return -ENOMEM;
6730
6731                         *per_cpu_ptr(sdd->sd, j) = sd;
6732
6733                         sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6734                                         GFP_KERNEL, cpu_to_node(j));
6735                         if (!sg)
6736                                 return -ENOMEM;
6737
6738                         sg->next = sg;
6739
6740                         *per_cpu_ptr(sdd->sg, j) = sg;
6741
6742                         sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
6743                                         GFP_KERNEL, cpu_to_node(j));
6744                         if (!sgc)
6745                                 return -ENOMEM;
6746
6747                         *per_cpu_ptr(sdd->sgc, j) = sgc;
6748                 }
6749         }
6750
6751         return 0;
6752 }
6753
6754 static void __sdt_free(const struct cpumask *cpu_map)
6755 {
6756         struct sched_domain_topology_level *tl;
6757         int j;
6758
6759         for_each_sd_topology(tl) {
6760                 struct sd_data *sdd = &tl->data;
6761
6762                 for_each_cpu(j, cpu_map) {
6763                         struct sched_domain *sd;
6764
6765                         if (sdd->sd) {
6766                                 sd = *per_cpu_ptr(sdd->sd, j);
6767                                 if (sd && (sd->flags & SD_OVERLAP))
6768                                         free_sched_groups(sd->groups, 0);
6769                                 kfree(*per_cpu_ptr(sdd->sd, j));
6770                         }
6771
6772                         if (sdd->sg)
6773                                 kfree(*per_cpu_ptr(sdd->sg, j));
6774                         if (sdd->sgc)
6775                                 kfree(*per_cpu_ptr(sdd->sgc, j));
6776                 }
6777                 free_percpu(sdd->sd);
6778                 sdd->sd = NULL;
6779                 free_percpu(sdd->sg);
6780                 sdd->sg = NULL;
6781                 free_percpu(sdd->sgc);
6782                 sdd->sgc = NULL;
6783         }
6784 }
6785
6786 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6787                 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6788                 struct sched_domain *child, int cpu)
6789 {
6790         struct sched_domain *sd = sd_init(tl, cpu);
6791         if (!sd)
6792                 return child;
6793
6794         cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6795         if (child) {
6796                 sd->level = child->level + 1;
6797                 sched_domain_level_max = max(sched_domain_level_max, sd->level);
6798                 child->parent = sd;
6799                 sd->child = child;
6800
6801                 if (!cpumask_subset(sched_domain_span(child),
6802                                     sched_domain_span(sd))) {
6803                         pr_err("BUG: arch topology borken\n");
6804 #ifdef CONFIG_SCHED_DEBUG
6805                         pr_err("     the %s domain not a subset of the %s domain\n",
6806                                         child->name, sd->name);
6807 #endif
6808                         /* Fixup, ensure @sd has at least @child cpus. */
6809                         cpumask_or(sched_domain_span(sd),
6810                                    sched_domain_span(sd),
6811                                    sched_domain_span(child));
6812                 }
6813
6814         }
6815         set_domain_attribute(sd, attr);
6816
6817         return sd;
6818 }
6819
6820 /*
6821  * Build sched domains for a given set of cpus and attach the sched domains
6822  * to the individual cpus
6823  */
6824 static int build_sched_domains(const struct cpumask *cpu_map,
6825                                struct sched_domain_attr *attr)
6826 {
6827         enum s_alloc alloc_state;
6828         struct sched_domain *sd;
6829         struct s_data d;
6830         int i, ret = -ENOMEM;
6831
6832         alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6833         if (alloc_state != sa_rootdomain)
6834                 goto error;
6835
6836         /* Set up domains for cpus specified by the cpu_map. */
6837         for_each_cpu(i, cpu_map) {
6838                 struct sched_domain_topology_level *tl;
6839
6840                 sd = NULL;
6841                 for_each_sd_topology(tl) {
6842                         sd = build_sched_domain(tl, cpu_map, attr, sd, i);
6843                         if (tl == sched_domain_topology)
6844                                 *per_cpu_ptr(d.sd, i) = sd;
6845                         if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6846                                 sd->flags |= SD_OVERLAP;
6847                         if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6848                                 break;
6849                 }
6850         }
6851
6852         /* Build the groups for the domains */
6853         for_each_cpu(i, cpu_map) {
6854                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6855                         sd->span_weight = cpumask_weight(sched_domain_span(sd));
6856                         if (sd->flags & SD_OVERLAP) {
6857                                 if (build_overlap_sched_groups(sd, i))
6858                                         goto error;
6859                         } else {
6860                                 if (build_sched_groups(sd, i))
6861                                         goto error;
6862                         }
6863                 }
6864         }
6865
6866         /* Calculate CPU capacity for physical packages and nodes */
6867         for (i = nr_cpumask_bits-1; i >= 0; i--) {
6868                 if (!cpumask_test_cpu(i, cpu_map))
6869                         continue;
6870
6871                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6872                         claim_allocations(i, sd);
6873                         init_sched_groups_capacity(i, sd);
6874                 }
6875         }
6876
6877         /* Attach the domains */
6878         rcu_read_lock();
6879         for_each_cpu(i, cpu_map) {
6880                 sd = *per_cpu_ptr(d.sd, i);
6881                 cpu_attach_domain(sd, d.rd, i);
6882         }
6883         rcu_read_unlock();
6884
6885         ret = 0;
6886 error:
6887         __free_domain_allocs(&d, alloc_state, cpu_map);
6888         return ret;
6889 }
6890
6891 static cpumask_var_t *doms_cur; /* current sched domains */
6892 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
6893 static struct sched_domain_attr *dattr_cur;
6894                                 /* attribues of custom domains in 'doms_cur' */
6895
6896 /*
6897  * Special case: If a kmalloc of a doms_cur partition (array of
6898  * cpumask) fails, then fallback to a single sched domain,
6899  * as determined by the single cpumask fallback_doms.
6900  */
6901 static cpumask_var_t fallback_doms;
6902
6903 /*
6904  * arch_update_cpu_topology lets virtualized architectures update the
6905  * cpu core maps. It is supposed to return 1 if the topology changed
6906  * or 0 if it stayed the same.
6907  */
6908 int __weak arch_update_cpu_topology(void)
6909 {
6910         return 0;
6911 }
6912
6913 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6914 {
6915         int i;
6916         cpumask_var_t *doms;
6917
6918         doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6919         if (!doms)
6920                 return NULL;
6921         for (i = 0; i < ndoms; i++) {
6922                 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6923                         free_sched_domains(doms, i);
6924                         return NULL;
6925                 }
6926         }
6927         return doms;
6928 }
6929
6930 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6931 {
6932         unsigned int i;
6933         for (i = 0; i < ndoms; i++)
6934                 free_cpumask_var(doms[i]);
6935         kfree(doms);
6936 }
6937
6938 /*
6939  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6940  * For now this just excludes isolated cpus, but could be used to
6941  * exclude other special cases in the future.
6942  */
6943 static int init_sched_domains(const struct cpumask *cpu_map)
6944 {
6945         int err;
6946
6947         arch_update_cpu_topology();
6948         ndoms_cur = 1;
6949         doms_cur = alloc_sched_domains(ndoms_cur);
6950         if (!doms_cur)
6951                 doms_cur = &fallback_doms;
6952         cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
6953         err = build_sched_domains(doms_cur[0], NULL);
6954         register_sched_domain_sysctl();
6955
6956         return err;
6957 }
6958
6959 /*
6960  * Detach sched domains from a group of cpus specified in cpu_map
6961  * These cpus will now be attached to the NULL domain
6962  */
6963 static void detach_destroy_domains(const struct cpumask *cpu_map)
6964 {
6965         int i;
6966
6967         rcu_read_lock();
6968         for_each_cpu(i, cpu_map)
6969                 cpu_attach_domain(NULL, &def_root_domain, i);
6970         rcu_read_unlock();
6971 }
6972
6973 /* handle null as "default" */
6974 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6975                         struct sched_domain_attr *new, int idx_new)
6976 {
6977         struct sched_domain_attr tmp;
6978
6979         /* fast path */
6980         if (!new && !cur)
6981                 return 1;
6982
6983         tmp = SD_ATTR_INIT;
6984         return !memcmp(cur ? (cur + idx_cur) : &tmp,
6985                         new ? (new + idx_new) : &tmp,
6986                         sizeof(struct sched_domain_attr));
6987 }
6988
6989 /*
6990  * Partition sched domains as specified by the 'ndoms_new'
6991  * cpumasks in the array doms_new[] of cpumasks. This compares
6992  * doms_new[] to the current sched domain partitioning, doms_cur[].
6993  * It destroys each deleted domain and builds each new domain.
6994  *
6995  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
6996  * The masks don't intersect (don't overlap.) We should setup one
6997  * sched domain for each mask. CPUs not in any of the cpumasks will
6998  * not be load balanced. If the same cpumask appears both in the
6999  * current 'doms_cur' domains and in the new 'doms_new', we can leave
7000  * it as it is.
7001  *
7002  * The passed in 'doms_new' should be allocated using
7003  * alloc_sched_domains.  This routine takes ownership of it and will
7004  * free_sched_domains it when done with it. If the caller failed the
7005  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7006  * and partition_sched_domains() will fallback to the single partition
7007  * 'fallback_doms', it also forces the domains to be rebuilt.
7008  *
7009  * If doms_new == NULL it will be replaced with cpu_online_mask.
7010  * ndoms_new == 0 is a special case for destroying existing domains,
7011  * and it will not create the default domain.
7012  *
7013  * Call with hotplug lock held
7014  */
7015 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7016                              struct sched_domain_attr *dattr_new)
7017 {
7018         int i, j, n;
7019         int new_topology;
7020
7021         mutex_lock(&sched_domains_mutex);
7022
7023         /* always unregister in case we don't destroy any domains */
7024         unregister_sched_domain_sysctl();
7025
7026         /* Let architecture update cpu core mappings. */
7027         new_topology = arch_update_cpu_topology();
7028
7029         n = doms_new ? ndoms_new : 0;
7030
7031         /* Destroy deleted domains */
7032         for (i = 0; i < ndoms_cur; i++) {
7033                 for (j = 0; j < n && !new_topology; j++) {
7034                         if (cpumask_equal(doms_cur[i], doms_new[j])
7035                             && dattrs_equal(dattr_cur, i, dattr_new, j))
7036                                 goto match1;
7037                 }
7038                 /* no match - a current sched domain not in new doms_new[] */
7039                 detach_destroy_domains(doms_cur[i]);
7040 match1:
7041                 ;
7042         }
7043
7044         n = ndoms_cur;
7045         if (doms_new == NULL) {
7046                 n = 0;
7047                 doms_new = &fallback_doms;
7048                 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7049                 WARN_ON_ONCE(dattr_new);
7050         }
7051
7052         /* Build new domains */
7053         for (i = 0; i < ndoms_new; i++) {
7054                 for (j = 0; j < n && !new_topology; j++) {
7055                         if (cpumask_equal(doms_new[i], doms_cur[j])
7056                             && dattrs_equal(dattr_new, i, dattr_cur, j))
7057                                 goto match2;
7058                 }
7059                 /* no match - add a new doms_new */
7060                 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7061 match2:
7062                 ;
7063         }
7064
7065         /* Remember the new sched domains */
7066         if (doms_cur != &fallback_doms)
7067                 free_sched_domains(doms_cur, ndoms_cur);
7068         kfree(dattr_cur);       /* kfree(NULL) is safe */
7069         doms_cur = doms_new;
7070         dattr_cur = dattr_new;
7071         ndoms_cur = ndoms_new;
7072
7073         register_sched_domain_sysctl();
7074
7075         mutex_unlock(&sched_domains_mutex);
7076 }
7077
7078 static int num_cpus_frozen;     /* used to mark begin/end of suspend/resume */
7079
7080 /*
7081  * Update cpusets according to cpu_active mask.  If cpusets are
7082  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7083  * around partition_sched_domains().
7084  *
7085  * If we come here as part of a suspend/resume, don't touch cpusets because we
7086  * want to restore it back to its original state upon resume anyway.
7087  */
7088 static void cpuset_cpu_active(void)
7089 {
7090         if (cpuhp_tasks_frozen) {
7091                 /*
7092                  * num_cpus_frozen tracks how many CPUs are involved in suspend
7093                  * resume sequence. As long as this is not the last online
7094                  * operation in the resume sequence, just build a single sched
7095                  * domain, ignoring cpusets.
7096                  */
7097                 num_cpus_frozen--;
7098                 if (likely(num_cpus_frozen)) {
7099                         partition_sched_domains(1, NULL, NULL);
7100                         return;
7101                 }
7102                 /*
7103                  * This is the last CPU online operation. So fall through and
7104                  * restore the original sched domains by considering the
7105                  * cpuset configurations.
7106                  */
7107         }
7108         cpuset_update_active_cpus(true);
7109 }
7110
7111 static int cpuset_cpu_inactive(unsigned int cpu)
7112 {
7113         unsigned long flags;
7114         struct dl_bw *dl_b;
7115         bool overflow;
7116         int cpus;
7117
7118         if (!cpuhp_tasks_frozen) {
7119                 rcu_read_lock_sched();
7120                 dl_b = dl_bw_of(cpu);
7121
7122                 raw_spin_lock_irqsave(&dl_b->lock, flags);
7123                 cpus = dl_bw_cpus(cpu);
7124                 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7125                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7126
7127                 rcu_read_unlock_sched();
7128
7129                 if (overflow)
7130                         return -EBUSY;
7131                 cpuset_update_active_cpus(false);
7132         } else {
7133                 num_cpus_frozen++;
7134                 partition_sched_domains(1, NULL, NULL);
7135         }
7136         return 0;
7137 }
7138
7139 int sched_cpu_activate(unsigned int cpu)
7140 {
7141         struct rq *rq = cpu_rq(cpu);
7142         unsigned long flags;
7143
7144         set_cpu_active(cpu, true);
7145
7146         if (sched_smp_initialized) {
7147                 sched_domains_numa_masks_set(cpu);
7148                 cpuset_cpu_active();
7149         }
7150
7151         /*
7152          * Put the rq online, if not already. This happens:
7153          *
7154          * 1) In the early boot process, because we build the real domains
7155          *    after all cpus have been brought up.
7156          *
7157          * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7158          *    domains.
7159          */
7160         raw_spin_lock_irqsave(&rq->lock, flags);
7161         if (rq->rd) {
7162                 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7163                 set_rq_online(rq);
7164         }
7165         raw_spin_unlock_irqrestore(&rq->lock, flags);
7166
7167         update_max_interval();
7168
7169         return 0;
7170 }
7171
7172 int sched_cpu_deactivate(unsigned int cpu)
7173 {
7174         int ret;
7175
7176         set_cpu_active(cpu, false);
7177         /*
7178          * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
7179          * users of this state to go away such that all new such users will
7180          * observe it.
7181          *
7182          * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
7183          * not imply sync_sched(), so wait for both.
7184          *
7185          * Do sync before park smpboot threads to take care the rcu boost case.
7186          */
7187         if (IS_ENABLED(CONFIG_PREEMPT))
7188                 synchronize_rcu_mult(call_rcu, call_rcu_sched);
7189         else
7190                 synchronize_rcu();
7191
7192         if (!sched_smp_initialized)
7193                 return 0;
7194
7195         ret = cpuset_cpu_inactive(cpu);
7196         if (ret) {
7197                 set_cpu_active(cpu, true);
7198                 return ret;
7199         }
7200         sched_domains_numa_masks_clear(cpu);
7201         return 0;
7202 }
7203
7204 static void sched_rq_cpu_starting(unsigned int cpu)
7205 {
7206         struct rq *rq = cpu_rq(cpu);
7207
7208         rq->calc_load_update = calc_load_update;
7209         account_reset_rq(rq);
7210         update_max_interval();
7211 }
7212
7213 int sched_cpu_starting(unsigned int cpu)
7214 {
7215         set_cpu_rq_start_time(cpu);
7216         sched_rq_cpu_starting(cpu);
7217         return 0;
7218 }
7219
7220 #ifdef CONFIG_HOTPLUG_CPU
7221 int sched_cpu_dying(unsigned int cpu)
7222 {
7223         struct rq *rq = cpu_rq(cpu);
7224         unsigned long flags;
7225
7226         /* Handle pending wakeups and then migrate everything off */
7227         sched_ttwu_pending();
7228         raw_spin_lock_irqsave(&rq->lock, flags);
7229         if (rq->rd) {
7230                 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7231                 set_rq_offline(rq);
7232         }
7233         migrate_tasks(rq);
7234         BUG_ON(rq->nr_running != 1);
7235         raw_spin_unlock_irqrestore(&rq->lock, flags);
7236         calc_load_migrate(rq);
7237         update_max_interval();
7238         nohz_balance_exit_idle(cpu);
7239         hrtick_clear(rq);
7240         return 0;
7241 }
7242 #endif
7243
7244 void __init sched_init_smp(void)
7245 {
7246         cpumask_var_t non_isolated_cpus;
7247
7248         alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7249         alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7250
7251         sched_init_numa();
7252
7253         /*
7254          * There's no userspace yet to cause hotplug operations; hence all the
7255          * cpu masks are stable and all blatant races in the below code cannot
7256          * happen.
7257          */
7258         mutex_lock(&sched_domains_mutex);
7259         init_sched_domains(cpu_active_mask);
7260         cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7261         if (cpumask_empty(non_isolated_cpus))
7262                 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7263         mutex_unlock(&sched_domains_mutex);
7264
7265         /* Move init over to a non-isolated CPU */
7266         if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7267                 BUG();
7268         sched_init_granularity();
7269         free_cpumask_var(non_isolated_cpus);
7270
7271         init_sched_rt_class();
7272         init_sched_dl_class();
7273         sched_smp_initialized = true;
7274 }
7275
7276 static int __init migration_init(void)
7277 {
7278         sched_rq_cpu_starting(smp_processor_id());
7279         return 0;
7280 }
7281 early_initcall(migration_init);
7282
7283 #else
7284 void __init sched_init_smp(void)
7285 {
7286         sched_init_granularity();
7287 }
7288 #endif /* CONFIG_SMP */
7289
7290 int in_sched_functions(unsigned long addr)
7291 {
7292         return in_lock_functions(addr) ||
7293                 (addr >= (unsigned long)__sched_text_start
7294                 && addr < (unsigned long)__sched_text_end);
7295 }
7296
7297 #ifdef CONFIG_CGROUP_SCHED
7298 /*
7299  * Default task group.
7300  * Every task in system belongs to this group at bootup.
7301  */
7302 struct task_group root_task_group;
7303 LIST_HEAD(task_groups);
7304
7305 /* Cacheline aligned slab cache for task_group */
7306 static struct kmem_cache *task_group_cache __read_mostly;
7307 #endif
7308
7309 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7310
7311 void __init sched_init(void)
7312 {
7313         int i, j;
7314         unsigned long alloc_size = 0, ptr;
7315
7316 #ifdef CONFIG_FAIR_GROUP_SCHED
7317         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7318 #endif
7319 #ifdef CONFIG_RT_GROUP_SCHED
7320         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7321 #endif
7322         if (alloc_size) {
7323                 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7324
7325 #ifdef CONFIG_FAIR_GROUP_SCHED
7326                 root_task_group.se = (struct sched_entity **)ptr;
7327                 ptr += nr_cpu_ids * sizeof(void **);
7328
7329                 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7330                 ptr += nr_cpu_ids * sizeof(void **);
7331
7332 #endif /* CONFIG_FAIR_GROUP_SCHED */
7333 #ifdef CONFIG_RT_GROUP_SCHED
7334                 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7335                 ptr += nr_cpu_ids * sizeof(void **);
7336
7337                 root_task_group.rt_rq = (struct rt_rq **)ptr;
7338                 ptr += nr_cpu_ids * sizeof(void **);
7339
7340 #endif /* CONFIG_RT_GROUP_SCHED */
7341         }
7342 #ifdef CONFIG_CPUMASK_OFFSTACK
7343         for_each_possible_cpu(i) {
7344                 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7345                         cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7346         }
7347 #endif /* CONFIG_CPUMASK_OFFSTACK */
7348
7349         init_rt_bandwidth(&def_rt_bandwidth,
7350                         global_rt_period(), global_rt_runtime());
7351         init_dl_bandwidth(&def_dl_bandwidth,
7352                         global_rt_period(), global_rt_runtime());
7353
7354 #ifdef CONFIG_SMP
7355         init_defrootdomain();
7356 #endif
7357
7358 #ifdef CONFIG_RT_GROUP_SCHED
7359         init_rt_bandwidth(&root_task_group.rt_bandwidth,
7360                         global_rt_period(), global_rt_runtime());
7361 #endif /* CONFIG_RT_GROUP_SCHED */
7362
7363 #ifdef CONFIG_CGROUP_SCHED
7364         task_group_cache = KMEM_CACHE(task_group, 0);
7365
7366         list_add(&root_task_group.list, &task_groups);
7367         INIT_LIST_HEAD(&root_task_group.children);
7368         INIT_LIST_HEAD(&root_task_group.siblings);
7369         autogroup_init(&init_task);
7370 #endif /* CONFIG_CGROUP_SCHED */
7371
7372         for_each_possible_cpu(i) {
7373                 struct rq *rq;
7374
7375                 rq = cpu_rq(i);
7376                 raw_spin_lock_init(&rq->lock);
7377                 rq->nr_running = 0;
7378                 rq->calc_load_active = 0;
7379                 rq->calc_load_update = jiffies + LOAD_FREQ;
7380                 init_cfs_rq(&rq->cfs);
7381                 init_rt_rq(&rq->rt);
7382                 init_dl_rq(&rq->dl);
7383 #ifdef CONFIG_FAIR_GROUP_SCHED
7384                 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7385                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7386                 /*
7387                  * How much cpu bandwidth does root_task_group get?
7388                  *
7389                  * In case of task-groups formed thr' the cgroup filesystem, it
7390                  * gets 100% of the cpu resources in the system. This overall
7391                  * system cpu resource is divided among the tasks of
7392                  * root_task_group and its child task-groups in a fair manner,
7393                  * based on each entity's (task or task-group's) weight
7394                  * (se->load.weight).
7395                  *
7396                  * In other words, if root_task_group has 10 tasks of weight
7397                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
7398                  * then A0's share of the cpu resource is:
7399                  *
7400                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7401                  *
7402                  * We achieve this by letting root_task_group's tasks sit
7403                  * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7404                  */
7405                 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7406                 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7407 #endif /* CONFIG_FAIR_GROUP_SCHED */
7408
7409                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7410 #ifdef CONFIG_RT_GROUP_SCHED
7411                 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7412 #endif
7413
7414                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7415                         rq->cpu_load[j] = 0;
7416
7417 #ifdef CONFIG_SMP
7418                 rq->sd = NULL;
7419                 rq->rd = NULL;
7420                 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7421                 rq->balance_callback = NULL;
7422                 rq->active_balance = 0;
7423                 rq->next_balance = jiffies;
7424                 rq->push_cpu = 0;
7425                 rq->cpu = i;
7426                 rq->online = 0;
7427                 rq->idle_stamp = 0;
7428                 rq->avg_idle = 2*sysctl_sched_migration_cost;
7429                 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7430
7431                 INIT_LIST_HEAD(&rq->cfs_tasks);
7432
7433                 rq_attach_root(rq, &def_root_domain);
7434 #ifdef CONFIG_NO_HZ_COMMON
7435                 rq->last_load_update_tick = jiffies;
7436                 rq->nohz_flags = 0;
7437 #endif
7438 #ifdef CONFIG_NO_HZ_FULL
7439                 rq->last_sched_tick = 0;
7440 #endif
7441 #endif /* CONFIG_SMP */
7442                 init_rq_hrtick(rq);
7443                 atomic_set(&rq->nr_iowait, 0);
7444         }
7445
7446         set_load_weight(&init_task);
7447
7448 #ifdef CONFIG_PREEMPT_NOTIFIERS
7449         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7450 #endif
7451
7452         /*
7453          * The boot idle thread does lazy MMU switching as well:
7454          */
7455         atomic_inc(&init_mm.mm_count);
7456         enter_lazy_tlb(&init_mm, current);
7457
7458         /*
7459          * During early bootup we pretend to be a normal task:
7460          */
7461         current->sched_class = &fair_sched_class;
7462
7463         /*
7464          * Make us the idle thread. Technically, schedule() should not be
7465          * called from this thread, however somewhere below it might be,
7466          * but because we are the idle thread, we just pick up running again
7467          * when this runqueue becomes "idle".
7468          */
7469         init_idle(current, smp_processor_id());
7470
7471         calc_load_update = jiffies + LOAD_FREQ;
7472
7473 #ifdef CONFIG_SMP
7474         zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7475         /* May be allocated at isolcpus cmdline parse time */
7476         if (cpu_isolated_map == NULL)
7477                 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7478         idle_thread_set_boot_cpu();
7479         set_cpu_rq_start_time(smp_processor_id());
7480 #endif
7481         init_sched_fair_class();
7482
7483         scheduler_running = 1;
7484 }
7485
7486 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7487 static inline int preempt_count_equals(int preempt_offset)
7488 {
7489         int nested = preempt_count() + rcu_preempt_depth();
7490
7491         return (nested == preempt_offset);
7492 }
7493
7494 void __might_sleep(const char *file, int line, int preempt_offset)
7495 {
7496         /*
7497          * Blocking primitives will set (and therefore destroy) current->state,
7498          * since we will exit with TASK_RUNNING make sure we enter with it,
7499          * otherwise we will destroy state.
7500          */
7501         WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7502                         "do not call blocking ops when !TASK_RUNNING; "
7503                         "state=%lx set at [<%p>] %pS\n",
7504                         current->state,
7505                         (void *)current->task_state_change,
7506                         (void *)current->task_state_change);
7507
7508         ___might_sleep(file, line, preempt_offset);
7509 }
7510 EXPORT_SYMBOL(__might_sleep);
7511
7512 void ___might_sleep(const char *file, int line, int preempt_offset)
7513 {
7514         static unsigned long prev_jiffy;        /* ratelimiting */
7515
7516         rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7517         if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7518              !is_idle_task(current)) ||
7519             system_state != SYSTEM_RUNNING || oops_in_progress)
7520                 return;
7521         if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7522                 return;
7523         prev_jiffy = jiffies;
7524
7525         printk(KERN_ERR
7526                 "BUG: sleeping function called from invalid context at %s:%d\n",
7527                         file, line);
7528         printk(KERN_ERR
7529                 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7530                         in_atomic(), irqs_disabled(),
7531                         current->pid, current->comm);
7532
7533         if (task_stack_end_corrupted(current))
7534                 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7535
7536         debug_show_held_locks(current);
7537         if (irqs_disabled())
7538                 print_irqtrace_events(current);
7539 #ifdef CONFIG_DEBUG_PREEMPT
7540         if (!preempt_count_equals(preempt_offset)) {
7541                 pr_err("Preemption disabled at:");
7542                 print_ip_sym(current->preempt_disable_ip);
7543                 pr_cont("\n");
7544         }
7545 #endif
7546         dump_stack();
7547 }
7548 EXPORT_SYMBOL(___might_sleep);
7549 #endif
7550
7551 #ifdef CONFIG_MAGIC_SYSRQ
7552 void normalize_rt_tasks(void)
7553 {
7554         struct task_struct *g, *p;
7555         struct sched_attr attr = {
7556                 .sched_policy = SCHED_NORMAL,
7557         };
7558
7559         read_lock(&tasklist_lock);
7560         for_each_process_thread(g, p) {
7561                 /*
7562                  * Only normalize user tasks:
7563                  */
7564                 if (p->flags & PF_KTHREAD)
7565                         continue;
7566
7567                 p->se.exec_start                = 0;
7568 #ifdef CONFIG_SCHEDSTATS
7569                 p->se.statistics.wait_start     = 0;
7570                 p->se.statistics.sleep_start    = 0;
7571                 p->se.statistics.block_start    = 0;
7572 #endif
7573
7574                 if (!dl_task(p) && !rt_task(p)) {
7575                         /*
7576                          * Renice negative nice level userspace
7577                          * tasks back to 0:
7578                          */
7579                         if (task_nice(p) < 0)
7580                                 set_user_nice(p, 0);
7581                         continue;
7582                 }
7583
7584                 __sched_setscheduler(p, &attr, false, false);
7585         }
7586         read_unlock(&tasklist_lock);
7587 }
7588
7589 #endif /* CONFIG_MAGIC_SYSRQ */
7590
7591 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7592 /*
7593  * These functions are only useful for the IA64 MCA handling, or kdb.
7594  *
7595  * They can only be called when the whole system has been
7596  * stopped - every CPU needs to be quiescent, and no scheduling
7597  * activity can take place. Using them for anything else would
7598  * be a serious bug, and as a result, they aren't even visible
7599  * under any other configuration.
7600  */
7601
7602 /**
7603  * curr_task - return the current task for a given cpu.
7604  * @cpu: the processor in question.
7605  *
7606  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7607  *
7608  * Return: The current task for @cpu.
7609  */
7610 struct task_struct *curr_task(int cpu)
7611 {
7612         return cpu_curr(cpu);
7613 }
7614
7615 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7616
7617 #ifdef CONFIG_IA64
7618 /**
7619  * set_curr_task - set the current task for a given cpu.
7620  * @cpu: the processor in question.
7621  * @p: the task pointer to set.
7622  *
7623  * Description: This function must only be used when non-maskable interrupts
7624  * are serviced on a separate stack. It allows the architecture to switch the
7625  * notion of the current task on a cpu in a non-blocking manner. This function
7626  * must be called with all CPU's synchronized, and interrupts disabled, the
7627  * and caller must save the original value of the current task (see
7628  * curr_task() above) and restore that value before reenabling interrupts and
7629  * re-starting the system.
7630  *
7631  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7632  */
7633 void set_curr_task(int cpu, struct task_struct *p)
7634 {
7635         cpu_curr(cpu) = p;
7636 }
7637
7638 #endif
7639
7640 #ifdef CONFIG_CGROUP_SCHED
7641 /* task_group_lock serializes the addition/removal of task groups */
7642 static DEFINE_SPINLOCK(task_group_lock);
7643
7644 static void sched_free_group(struct task_group *tg)
7645 {
7646         free_fair_sched_group(tg);
7647         free_rt_sched_group(tg);
7648         autogroup_free(tg);
7649         kmem_cache_free(task_group_cache, tg);
7650 }
7651
7652 /* allocate runqueue etc for a new task group */
7653 struct task_group *sched_create_group(struct task_group *parent)
7654 {
7655         struct task_group *tg;
7656
7657         tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
7658         if (!tg)
7659                 return ERR_PTR(-ENOMEM);
7660
7661         if (!alloc_fair_sched_group(tg, parent))
7662                 goto err;
7663
7664         if (!alloc_rt_sched_group(tg, parent))
7665                 goto err;
7666
7667         return tg;
7668
7669 err:
7670         sched_free_group(tg);
7671         return ERR_PTR(-ENOMEM);
7672 }
7673
7674 void sched_online_group(struct task_group *tg, struct task_group *parent)
7675 {
7676         unsigned long flags;
7677
7678         spin_lock_irqsave(&task_group_lock, flags);
7679         list_add_rcu(&tg->list, &task_groups);
7680
7681         WARN_ON(!parent); /* root should already exist */
7682
7683         tg->parent = parent;
7684         INIT_LIST_HEAD(&tg->children);
7685         list_add_rcu(&tg->siblings, &parent->children);
7686         spin_unlock_irqrestore(&task_group_lock, flags);
7687 }
7688
7689 /* rcu callback to free various structures associated with a task group */
7690 static void sched_free_group_rcu(struct rcu_head *rhp)
7691 {
7692         /* now it should be safe to free those cfs_rqs */
7693         sched_free_group(container_of(rhp, struct task_group, rcu));
7694 }
7695
7696 void sched_destroy_group(struct task_group *tg)
7697 {
7698         /* wait for possible concurrent references to cfs_rqs complete */
7699         call_rcu(&tg->rcu, sched_free_group_rcu);
7700 }
7701
7702 void sched_offline_group(struct task_group *tg)
7703 {
7704         unsigned long flags;
7705
7706         /* end participation in shares distribution */
7707         unregister_fair_sched_group(tg);
7708
7709         spin_lock_irqsave(&task_group_lock, flags);
7710         list_del_rcu(&tg->list);
7711         list_del_rcu(&tg->siblings);
7712         spin_unlock_irqrestore(&task_group_lock, flags);
7713 }
7714
7715 /* change task's runqueue when it moves between groups.
7716  *      The caller of this function should have put the task in its new group
7717  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7718  *      reflect its new group.
7719  */
7720 void sched_move_task(struct task_struct *tsk)
7721 {
7722         struct task_group *tg;
7723         int queued, running;
7724         struct rq_flags rf;
7725         struct rq *rq;
7726
7727         rq = task_rq_lock(tsk, &rf);
7728
7729         running = task_current(rq, tsk);
7730         queued = task_on_rq_queued(tsk);
7731
7732         if (queued)
7733                 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
7734         if (unlikely(running))
7735                 put_prev_task(rq, tsk);
7736
7737         /*
7738          * All callers are synchronized by task_rq_lock(); we do not use RCU
7739          * which is pointless here. Thus, we pass "true" to task_css_check()
7740          * to prevent lockdep warnings.
7741          */
7742         tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7743                           struct task_group, css);
7744         tg = autogroup_task_group(tsk, tg);
7745         tsk->sched_task_group = tg;
7746
7747 #ifdef CONFIG_FAIR_GROUP_SCHED
7748         if (tsk->sched_class->task_move_group)
7749                 tsk->sched_class->task_move_group(tsk);
7750         else
7751 #endif
7752                 set_task_rq(tsk, task_cpu(tsk));
7753
7754         if (unlikely(running))
7755                 tsk->sched_class->set_curr_task(rq);
7756         if (queued)
7757                 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
7758
7759         task_rq_unlock(rq, tsk, &rf);
7760 }
7761 #endif /* CONFIG_CGROUP_SCHED */
7762
7763 #ifdef CONFIG_RT_GROUP_SCHED
7764 /*
7765  * Ensure that the real time constraints are schedulable.
7766  */
7767 static DEFINE_MUTEX(rt_constraints_mutex);
7768
7769 /* Must be called with tasklist_lock held */
7770 static inline int tg_has_rt_tasks(struct task_group *tg)
7771 {
7772         struct task_struct *g, *p;
7773
7774         /*
7775          * Autogroups do not have RT tasks; see autogroup_create().
7776          */
7777         if (task_group_is_autogroup(tg))
7778                 return 0;
7779
7780         for_each_process_thread(g, p) {
7781                 if (rt_task(p) && task_group(p) == tg)
7782                         return 1;
7783         }
7784
7785         return 0;
7786 }
7787
7788 struct rt_schedulable_data {
7789         struct task_group *tg;
7790         u64 rt_period;
7791         u64 rt_runtime;
7792 };
7793
7794 static int tg_rt_schedulable(struct task_group *tg, void *data)
7795 {
7796         struct rt_schedulable_data *d = data;
7797         struct task_group *child;
7798         unsigned long total, sum = 0;
7799         u64 period, runtime;
7800
7801         period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7802         runtime = tg->rt_bandwidth.rt_runtime;
7803
7804         if (tg == d->tg) {
7805                 period = d->rt_period;
7806                 runtime = d->rt_runtime;
7807         }
7808
7809         /*
7810          * Cannot have more runtime than the period.
7811          */
7812         if (runtime > period && runtime != RUNTIME_INF)
7813                 return -EINVAL;
7814
7815         /*
7816          * Ensure we don't starve existing RT tasks.
7817          */
7818         if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7819                 return -EBUSY;
7820
7821         total = to_ratio(period, runtime);
7822
7823         /*
7824          * Nobody can have more than the global setting allows.
7825          */
7826         if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7827                 return -EINVAL;
7828
7829         /*
7830          * The sum of our children's runtime should not exceed our own.
7831          */
7832         list_for_each_entry_rcu(child, &tg->children, siblings) {
7833                 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7834                 runtime = child->rt_bandwidth.rt_runtime;
7835
7836                 if (child == d->tg) {
7837                         period = d->rt_period;
7838                         runtime = d->rt_runtime;
7839                 }
7840
7841                 sum += to_ratio(period, runtime);
7842         }
7843
7844         if (sum > total)
7845                 return -EINVAL;
7846
7847         return 0;
7848 }
7849
7850 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7851 {
7852         int ret;
7853
7854         struct rt_schedulable_data data = {
7855                 .tg = tg,
7856                 .rt_period = period,
7857                 .rt_runtime = runtime,
7858         };
7859
7860         rcu_read_lock();
7861         ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7862         rcu_read_unlock();
7863
7864         return ret;
7865 }
7866
7867 static int tg_set_rt_bandwidth(struct task_group *tg,
7868                 u64 rt_period, u64 rt_runtime)
7869 {
7870         int i, err = 0;
7871
7872         /*
7873          * Disallowing the root group RT runtime is BAD, it would disallow the
7874          * kernel creating (and or operating) RT threads.
7875          */
7876         if (tg == &root_task_group && rt_runtime == 0)
7877                 return -EINVAL;
7878
7879         /* No period doesn't make any sense. */
7880         if (rt_period == 0)
7881                 return -EINVAL;
7882
7883         mutex_lock(&rt_constraints_mutex);
7884         read_lock(&tasklist_lock);
7885         err = __rt_schedulable(tg, rt_period, rt_runtime);
7886         if (err)
7887                 goto unlock;
7888
7889         raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7890         tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7891         tg->rt_bandwidth.rt_runtime = rt_runtime;
7892
7893         for_each_possible_cpu(i) {
7894                 struct rt_rq *rt_rq = tg->rt_rq[i];
7895
7896                 raw_spin_lock(&rt_rq->rt_runtime_lock);
7897                 rt_rq->rt_runtime = rt_runtime;
7898                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7899         }
7900         raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7901 unlock:
7902         read_unlock(&tasklist_lock);
7903         mutex_unlock(&rt_constraints_mutex);
7904
7905         return err;
7906 }
7907
7908 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7909 {
7910         u64 rt_runtime, rt_period;
7911
7912         rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7913         rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7914         if (rt_runtime_us < 0)
7915                 rt_runtime = RUNTIME_INF;
7916
7917         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7918 }
7919
7920 static long sched_group_rt_runtime(struct task_group *tg)
7921 {
7922         u64 rt_runtime_us;
7923
7924         if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
7925                 return -1;
7926
7927         rt_runtime_us = tg->rt_bandwidth.rt_runtime;
7928         do_div(rt_runtime_us, NSEC_PER_USEC);
7929         return rt_runtime_us;
7930 }
7931
7932 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
7933 {
7934         u64 rt_runtime, rt_period;
7935
7936         rt_period = rt_period_us * NSEC_PER_USEC;
7937         rt_runtime = tg->rt_bandwidth.rt_runtime;
7938
7939         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7940 }
7941
7942 static long sched_group_rt_period(struct task_group *tg)
7943 {
7944         u64 rt_period_us;
7945
7946         rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7947         do_div(rt_period_us, NSEC_PER_USEC);
7948         return rt_period_us;
7949 }
7950 #endif /* CONFIG_RT_GROUP_SCHED */
7951
7952 #ifdef CONFIG_RT_GROUP_SCHED
7953 static int sched_rt_global_constraints(void)
7954 {
7955         int ret = 0;
7956
7957         mutex_lock(&rt_constraints_mutex);
7958         read_lock(&tasklist_lock);
7959         ret = __rt_schedulable(NULL, 0, 0);
7960         read_unlock(&tasklist_lock);
7961         mutex_unlock(&rt_constraints_mutex);
7962
7963         return ret;
7964 }
7965
7966 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
7967 {
7968         /* Don't accept realtime tasks when there is no way for them to run */
7969         if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7970                 return 0;
7971
7972         return 1;
7973 }
7974
7975 #else /* !CONFIG_RT_GROUP_SCHED */
7976 static int sched_rt_global_constraints(void)
7977 {
7978         unsigned long flags;
7979         int i;
7980
7981         raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
7982         for_each_possible_cpu(i) {
7983                 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7984
7985                 raw_spin_lock(&rt_rq->rt_runtime_lock);
7986                 rt_rq->rt_runtime = global_rt_runtime();
7987                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7988         }
7989         raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
7990
7991         return 0;
7992 }
7993 #endif /* CONFIG_RT_GROUP_SCHED */
7994
7995 static int sched_dl_global_validate(void)
7996 {
7997         u64 runtime = global_rt_runtime();
7998         u64 period = global_rt_period();
7999         u64 new_bw = to_ratio(period, runtime);
8000         struct dl_bw *dl_b;
8001         int cpu, ret = 0;
8002         unsigned long flags;
8003
8004         /*
8005          * Here we want to check the bandwidth not being set to some
8006          * value smaller than the currently allocated bandwidth in
8007          * any of the root_domains.
8008          *
8009          * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8010          * cycling on root_domains... Discussion on different/better
8011          * solutions is welcome!
8012          */
8013         for_each_possible_cpu(cpu) {
8014                 rcu_read_lock_sched();
8015                 dl_b = dl_bw_of(cpu);
8016
8017                 raw_spin_lock_irqsave(&dl_b->lock, flags);
8018                 if (new_bw < dl_b->total_bw)
8019                         ret = -EBUSY;
8020                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8021
8022                 rcu_read_unlock_sched();
8023
8024                 if (ret)
8025                         break;
8026         }
8027
8028         return ret;
8029 }
8030
8031 static void sched_dl_do_global(void)
8032 {
8033         u64 new_bw = -1;
8034         struct dl_bw *dl_b;
8035         int cpu;
8036         unsigned long flags;
8037
8038         def_dl_bandwidth.dl_period = global_rt_period();
8039         def_dl_bandwidth.dl_runtime = global_rt_runtime();
8040
8041         if (global_rt_runtime() != RUNTIME_INF)
8042                 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
8043
8044         /*
8045          * FIXME: As above...
8046          */
8047         for_each_possible_cpu(cpu) {
8048                 rcu_read_lock_sched();
8049                 dl_b = dl_bw_of(cpu);
8050
8051                 raw_spin_lock_irqsave(&dl_b->lock, flags);
8052                 dl_b->bw = new_bw;
8053                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8054
8055                 rcu_read_unlock_sched();
8056         }
8057 }
8058
8059 static int sched_rt_global_validate(void)
8060 {
8061         if (sysctl_sched_rt_period <= 0)
8062                 return -EINVAL;
8063
8064         if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
8065                 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
8066                 return -EINVAL;
8067
8068         return 0;
8069 }
8070
8071 static void sched_rt_do_global(void)
8072 {
8073         def_rt_bandwidth.rt_runtime = global_rt_runtime();
8074         def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
8075 }
8076
8077 int sched_rt_handler(struct ctl_table *table, int write,
8078                 void __user *buffer, size_t *lenp,
8079                 loff_t *ppos)
8080 {
8081         int old_period, old_runtime;
8082         static DEFINE_MUTEX(mutex);
8083         int ret;
8084
8085         mutex_lock(&mutex);
8086         old_period = sysctl_sched_rt_period;
8087         old_runtime = sysctl_sched_rt_runtime;
8088
8089         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8090
8091         if (!ret && write) {
8092                 ret = sched_rt_global_validate();
8093                 if (ret)
8094                         goto undo;
8095
8096                 ret = sched_dl_global_validate();
8097                 if (ret)
8098                         goto undo;
8099
8100                 ret = sched_rt_global_constraints();
8101                 if (ret)
8102                         goto undo;
8103
8104                 sched_rt_do_global();
8105                 sched_dl_do_global();
8106         }
8107         if (0) {
8108 undo:
8109                 sysctl_sched_rt_period = old_period;
8110                 sysctl_sched_rt_runtime = old_runtime;
8111         }
8112         mutex_unlock(&mutex);
8113
8114         return ret;
8115 }
8116
8117 int sched_rr_handler(struct ctl_table *table, int write,
8118                 void __user *buffer, size_t *lenp,
8119                 loff_t *ppos)
8120 {
8121         int ret;
8122         static DEFINE_MUTEX(mutex);
8123
8124         mutex_lock(&mutex);
8125         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8126         /* make sure that internally we keep jiffies */
8127         /* also, writing zero resets timeslice to default */
8128         if (!ret && write) {
8129                 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8130                         RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8131         }
8132         mutex_unlock(&mutex);
8133         return ret;
8134 }
8135
8136 #ifdef CONFIG_CGROUP_SCHED
8137
8138 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8139 {
8140         return css ? container_of(css, struct task_group, css) : NULL;
8141 }
8142
8143 static struct cgroup_subsys_state *
8144 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8145 {
8146         struct task_group *parent = css_tg(parent_css);
8147         struct task_group *tg;
8148
8149         if (!parent) {
8150                 /* This is early initialization for the top cgroup */
8151                 return &root_task_group.css;
8152         }
8153
8154         tg = sched_create_group(parent);
8155         if (IS_ERR(tg))
8156                 return ERR_PTR(-ENOMEM);
8157
8158         sched_online_group(tg, parent);
8159
8160         return &tg->css;
8161 }
8162
8163 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8164 {
8165         struct task_group *tg = css_tg(css);
8166
8167         sched_offline_group(tg);
8168 }
8169
8170 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8171 {
8172         struct task_group *tg = css_tg(css);
8173
8174         /*
8175          * Relies on the RCU grace period between css_released() and this.
8176          */
8177         sched_free_group(tg);
8178 }
8179
8180 static void cpu_cgroup_fork(struct task_struct *task)
8181 {
8182         sched_move_task(task);
8183 }
8184
8185 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8186 {
8187         struct task_struct *task;
8188         struct cgroup_subsys_state *css;
8189
8190         cgroup_taskset_for_each(task, css, tset) {
8191 #ifdef CONFIG_RT_GROUP_SCHED
8192                 if (!sched_rt_can_attach(css_tg(css), task))
8193                         return -EINVAL;
8194 #else
8195                 /* We don't support RT-tasks being in separate groups */
8196                 if (task->sched_class != &fair_sched_class)
8197                         return -EINVAL;
8198 #endif
8199         }
8200         return 0;
8201 }
8202
8203 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8204 {
8205         struct task_struct *task;
8206         struct cgroup_subsys_state *css;
8207
8208         cgroup_taskset_for_each(task, css, tset)
8209                 sched_move_task(task);
8210 }
8211
8212 #ifdef CONFIG_FAIR_GROUP_SCHED
8213 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8214                                 struct cftype *cftype, u64 shareval)
8215 {
8216         return sched_group_set_shares(css_tg(css), scale_load(shareval));
8217 }
8218
8219 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8220                                struct cftype *cft)
8221 {
8222         struct task_group *tg = css_tg(css);
8223
8224         return (u64) scale_load_down(tg->shares);
8225 }
8226
8227 #ifdef CONFIG_CFS_BANDWIDTH
8228 static DEFINE_MUTEX(cfs_constraints_mutex);
8229
8230 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8231 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8232
8233 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8234
8235 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8236 {
8237         int i, ret = 0, runtime_enabled, runtime_was_enabled;
8238         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8239
8240         if (tg == &root_task_group)
8241                 return -EINVAL;
8242
8243         /*
8244          * Ensure we have at some amount of bandwidth every period.  This is
8245          * to prevent reaching a state of large arrears when throttled via
8246          * entity_tick() resulting in prolonged exit starvation.
8247          */
8248         if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8249                 return -EINVAL;
8250
8251         /*
8252          * Likewise, bound things on the otherside by preventing insane quota
8253          * periods.  This also allows us to normalize in computing quota
8254          * feasibility.
8255          */
8256         if (period > max_cfs_quota_period)
8257                 return -EINVAL;
8258
8259         /*
8260          * Prevent race between setting of cfs_rq->runtime_enabled and
8261          * unthrottle_offline_cfs_rqs().
8262          */
8263         get_online_cpus();
8264         mutex_lock(&cfs_constraints_mutex);
8265         ret = __cfs_schedulable(tg, period, quota);
8266         if (ret)
8267                 goto out_unlock;
8268
8269         runtime_enabled = quota != RUNTIME_INF;
8270         runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8271         /*
8272          * If we need to toggle cfs_bandwidth_used, off->on must occur
8273          * before making related changes, and on->off must occur afterwards
8274          */
8275         if (runtime_enabled && !runtime_was_enabled)
8276                 cfs_bandwidth_usage_inc();
8277         raw_spin_lock_irq(&cfs_b->lock);
8278         cfs_b->period = ns_to_ktime(period);
8279         cfs_b->quota = quota;
8280
8281         __refill_cfs_bandwidth_runtime(cfs_b);
8282         /* restart the period timer (if active) to handle new period expiry */
8283         if (runtime_enabled)
8284                 start_cfs_bandwidth(cfs_b);
8285         raw_spin_unlock_irq(&cfs_b->lock);
8286
8287         for_each_online_cpu(i) {
8288                 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8289                 struct rq *rq = cfs_rq->rq;
8290
8291                 raw_spin_lock_irq(&rq->lock);
8292                 cfs_rq->runtime_enabled = runtime_enabled;
8293                 cfs_rq->runtime_remaining = 0;
8294
8295                 if (cfs_rq->throttled)
8296                         unthrottle_cfs_rq(cfs_rq);
8297                 raw_spin_unlock_irq(&rq->lock);
8298         }
8299         if (runtime_was_enabled && !runtime_enabled)
8300                 cfs_bandwidth_usage_dec();
8301 out_unlock:
8302         mutex_unlock(&cfs_constraints_mutex);
8303         put_online_cpus();
8304
8305         return ret;
8306 }
8307
8308 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8309 {
8310         u64 quota, period;
8311
8312         period = ktime_to_ns(tg->cfs_bandwidth.period);
8313         if (cfs_quota_us < 0)
8314                 quota = RUNTIME_INF;
8315         else
8316                 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8317
8318         return tg_set_cfs_bandwidth(tg, period, quota);
8319 }
8320
8321 long tg_get_cfs_quota(struct task_group *tg)
8322 {
8323         u64 quota_us;
8324
8325         if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8326                 return -1;
8327
8328         quota_us = tg->cfs_bandwidth.quota;
8329         do_div(quota_us, NSEC_PER_USEC);
8330
8331         return quota_us;
8332 }
8333
8334 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8335 {
8336         u64 quota, period;
8337
8338         period = (u64)cfs_period_us * NSEC_PER_USEC;
8339         quota = tg->cfs_bandwidth.quota;
8340
8341         return tg_set_cfs_bandwidth(tg, period, quota);
8342 }
8343
8344 long tg_get_cfs_period(struct task_group *tg)
8345 {
8346         u64 cfs_period_us;
8347
8348         cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8349         do_div(cfs_period_us, NSEC_PER_USEC);
8350
8351         return cfs_period_us;
8352 }
8353
8354 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8355                                   struct cftype *cft)
8356 {
8357         return tg_get_cfs_quota(css_tg(css));
8358 }
8359
8360 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8361                                    struct cftype *cftype, s64 cfs_quota_us)
8362 {
8363         return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8364 }
8365
8366 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8367                                    struct cftype *cft)
8368 {
8369         return tg_get_cfs_period(css_tg(css));
8370 }
8371
8372 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8373                                     struct cftype *cftype, u64 cfs_period_us)
8374 {
8375         return tg_set_cfs_period(css_tg(css), cfs_period_us);
8376 }
8377
8378 struct cfs_schedulable_data {
8379         struct task_group *tg;
8380         u64 period, quota;
8381 };
8382
8383 /*
8384  * normalize group quota/period to be quota/max_period
8385  * note: units are usecs
8386  */
8387 static u64 normalize_cfs_quota(struct task_group *tg,
8388                                struct cfs_schedulable_data *d)
8389 {
8390         u64 quota, period;
8391
8392         if (tg == d->tg) {
8393                 period = d->period;
8394                 quota = d->quota;
8395         } else {
8396                 period = tg_get_cfs_period(tg);
8397                 quota = tg_get_cfs_quota(tg);
8398         }
8399
8400         /* note: these should typically be equivalent */
8401         if (quota == RUNTIME_INF || quota == -1)
8402                 return RUNTIME_INF;
8403
8404         return to_ratio(period, quota);
8405 }
8406
8407 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8408 {
8409         struct cfs_schedulable_data *d = data;
8410         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8411         s64 quota = 0, parent_quota = -1;
8412
8413         if (!tg->parent) {
8414                 quota = RUNTIME_INF;
8415         } else {
8416                 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8417
8418                 quota = normalize_cfs_quota(tg, d);
8419                 parent_quota = parent_b->hierarchical_quota;
8420
8421                 /*
8422                  * ensure max(child_quota) <= parent_quota, inherit when no
8423                  * limit is set
8424                  */
8425                 if (quota == RUNTIME_INF)
8426                         quota = parent_quota;
8427                 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8428                         return -EINVAL;
8429         }
8430         cfs_b->hierarchical_quota = quota;
8431
8432         return 0;
8433 }
8434
8435 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8436 {
8437         int ret;
8438         struct cfs_schedulable_data data = {
8439                 .tg = tg,
8440                 .period = period,
8441                 .quota = quota,
8442         };
8443
8444         if (quota != RUNTIME_INF) {
8445                 do_div(data.period, NSEC_PER_USEC);
8446                 do_div(data.quota, NSEC_PER_USEC);
8447         }
8448
8449         rcu_read_lock();
8450         ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8451         rcu_read_unlock();
8452
8453         return ret;
8454 }
8455
8456 static int cpu_stats_show(struct seq_file *sf, void *v)
8457 {
8458         struct task_group *tg = css_tg(seq_css(sf));
8459         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8460
8461         seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8462         seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8463         seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8464
8465         return 0;
8466 }
8467 #endif /* CONFIG_CFS_BANDWIDTH */
8468 #endif /* CONFIG_FAIR_GROUP_SCHED */
8469
8470 #ifdef CONFIG_RT_GROUP_SCHED
8471 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8472                                 struct cftype *cft, s64 val)
8473 {
8474         return sched_group_set_rt_runtime(css_tg(css), val);
8475 }
8476
8477 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8478                                struct cftype *cft)
8479 {
8480         return sched_group_rt_runtime(css_tg(css));
8481 }
8482
8483 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8484                                     struct cftype *cftype, u64 rt_period_us)
8485 {
8486         return sched_group_set_rt_period(css_tg(css), rt_period_us);
8487 }
8488
8489 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8490                                    struct cftype *cft)
8491 {
8492         return sched_group_rt_period(css_tg(css));
8493 }
8494 #endif /* CONFIG_RT_GROUP_SCHED */
8495
8496 static struct cftype cpu_files[] = {
8497 #ifdef CONFIG_FAIR_GROUP_SCHED
8498         {
8499                 .name = "shares",
8500                 .read_u64 = cpu_shares_read_u64,
8501                 .write_u64 = cpu_shares_write_u64,
8502         },
8503 #endif
8504 #ifdef CONFIG_CFS_BANDWIDTH
8505         {
8506                 .name = "cfs_quota_us",
8507                 .read_s64 = cpu_cfs_quota_read_s64,
8508                 .write_s64 = cpu_cfs_quota_write_s64,
8509         },
8510         {
8511                 .name = "cfs_period_us",
8512                 .read_u64 = cpu_cfs_period_read_u64,
8513                 .write_u64 = cpu_cfs_period_write_u64,
8514         },
8515         {
8516                 .name = "stat",
8517                 .seq_show = cpu_stats_show,
8518         },
8519 #endif
8520 #ifdef CONFIG_RT_GROUP_SCHED
8521         {
8522                 .name = "rt_runtime_us",
8523                 .read_s64 = cpu_rt_runtime_read,
8524                 .write_s64 = cpu_rt_runtime_write,
8525         },
8526         {
8527                 .name = "rt_period_us",
8528                 .read_u64 = cpu_rt_period_read_uint,
8529                 .write_u64 = cpu_rt_period_write_uint,
8530         },
8531 #endif
8532         { }     /* terminate */
8533 };
8534
8535 struct cgroup_subsys cpu_cgrp_subsys = {
8536         .css_alloc      = cpu_cgroup_css_alloc,
8537         .css_released   = cpu_cgroup_css_released,
8538         .css_free       = cpu_cgroup_css_free,
8539         .fork           = cpu_cgroup_fork,
8540         .can_attach     = cpu_cgroup_can_attach,
8541         .attach         = cpu_cgroup_attach,
8542         .legacy_cftypes = cpu_files,
8543         .early_init     = true,
8544 };
8545
8546 #endif  /* CONFIG_CGROUP_SCHED */
8547
8548 void dump_cpu_task(int cpu)
8549 {
8550         pr_info("Task dump for CPU %d:\n", cpu);
8551         sched_show_task(cpu_curr(cpu));
8552 }
8553
8554 /*
8555  * Nice levels are multiplicative, with a gentle 10% change for every
8556  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8557  * nice 1, it will get ~10% less CPU time than another CPU-bound task
8558  * that remained on nice 0.
8559  *
8560  * The "10% effect" is relative and cumulative: from _any_ nice level,
8561  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8562  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8563  * If a task goes up by ~10% and another task goes down by ~10% then
8564  * the relative distance between them is ~25%.)
8565  */
8566 const int sched_prio_to_weight[40] = {
8567  /* -20 */     88761,     71755,     56483,     46273,     36291,
8568  /* -15 */     29154,     23254,     18705,     14949,     11916,
8569  /* -10 */      9548,      7620,      6100,      4904,      3906,
8570  /*  -5 */      3121,      2501,      1991,      1586,      1277,
8571  /*   0 */      1024,       820,       655,       526,       423,
8572  /*   5 */       335,       272,       215,       172,       137,
8573  /*  10 */       110,        87,        70,        56,        45,
8574  /*  15 */        36,        29,        23,        18,        15,
8575 };
8576
8577 /*
8578  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8579  *
8580  * In cases where the weight does not change often, we can use the
8581  * precalculated inverse to speed up arithmetics by turning divisions
8582  * into multiplications:
8583  */
8584 const u32 sched_prio_to_wmult[40] = {
8585  /* -20 */     48388,     59856,     76040,     92818,    118348,
8586  /* -15 */    147320,    184698,    229616,    287308,    360437,
8587  /* -10 */    449829,    563644,    704093,    875809,   1099582,
8588  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
8589  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
8590  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
8591  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
8592  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
8593 };