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