These changes are a raw update to a vanilla kernel 4.1.10, with the
[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_ONLINE:
5676                 /*
5677                  * At this point a starting CPU has marked itself as online via
5678                  * set_cpu_online(). But it might not yet have marked itself
5679                  * as active, which is essential from here on.
5680                  *
5681                  * Thus, fall-through and help the starting CPU along.
5682                  */
5683         case CPU_DOWN_FAILED:
5684                 set_cpu_active((long)hcpu, true);
5685                 return NOTIFY_OK;
5686         default:
5687                 return NOTIFY_DONE;
5688         }
5689 }
5690
5691 static int sched_cpu_inactive(struct notifier_block *nfb,
5692                                         unsigned long action, void *hcpu)
5693 {
5694         switch (action & ~CPU_TASKS_FROZEN) {
5695         case CPU_DOWN_PREPARE:
5696                 set_cpu_active((long)hcpu, false);
5697                 return NOTIFY_OK;
5698         default:
5699                 return NOTIFY_DONE;
5700         }
5701 }
5702
5703 static int __init migration_init(void)
5704 {
5705         void *cpu = (void *)(long)smp_processor_id();
5706         int err;
5707
5708         /* Initialize migration for the boot CPU */
5709         err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5710         BUG_ON(err == NOTIFY_BAD);
5711         migration_call(&migration_notifier, CPU_ONLINE, cpu);
5712         register_cpu_notifier(&migration_notifier);
5713
5714         /* Register cpu active notifiers */
5715         cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5716         cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5717
5718         return 0;
5719 }
5720 early_initcall(migration_init);
5721 #endif
5722
5723 #ifdef CONFIG_SMP
5724
5725 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5726
5727 #ifdef CONFIG_SCHED_DEBUG
5728
5729 static __read_mostly int sched_debug_enabled;
5730
5731 static int __init sched_debug_setup(char *str)
5732 {
5733         sched_debug_enabled = 1;
5734
5735         return 0;
5736 }
5737 early_param("sched_debug", sched_debug_setup);
5738
5739 static inline bool sched_debug(void)
5740 {
5741         return sched_debug_enabled;
5742 }
5743
5744 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5745                                   struct cpumask *groupmask)
5746 {
5747         struct sched_group *group = sd->groups;
5748
5749         cpumask_clear(groupmask);
5750
5751         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5752
5753         if (!(sd->flags & SD_LOAD_BALANCE)) {
5754                 printk("does not load-balance\n");
5755                 if (sd->parent)
5756                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5757                                         " has parent");
5758                 return -1;
5759         }
5760
5761         printk(KERN_CONT "span %*pbl level %s\n",
5762                cpumask_pr_args(sched_domain_span(sd)), sd->name);
5763
5764         if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5765                 printk(KERN_ERR "ERROR: domain->span does not contain "
5766                                 "CPU%d\n", cpu);
5767         }
5768         if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5769                 printk(KERN_ERR "ERROR: domain->groups does not contain"
5770                                 " CPU%d\n", cpu);
5771         }
5772
5773         printk(KERN_DEBUG "%*s groups:", level + 1, "");
5774         do {
5775                 if (!group) {
5776                         printk("\n");
5777                         printk(KERN_ERR "ERROR: group is NULL\n");
5778                         break;
5779                 }
5780
5781                 if (!cpumask_weight(sched_group_cpus(group))) {
5782                         printk(KERN_CONT "\n");
5783                         printk(KERN_ERR "ERROR: empty group\n");
5784                         break;
5785                 }
5786
5787                 if (!(sd->flags & SD_OVERLAP) &&
5788                     cpumask_intersects(groupmask, sched_group_cpus(group))) {
5789                         printk(KERN_CONT "\n");
5790                         printk(KERN_ERR "ERROR: repeated CPUs\n");
5791                         break;
5792                 }
5793
5794                 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5795
5796                 printk(KERN_CONT " %*pbl",
5797                        cpumask_pr_args(sched_group_cpus(group)));
5798                 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5799                         printk(KERN_CONT " (cpu_capacity = %d)",
5800                                 group->sgc->capacity);
5801                 }
5802
5803                 group = group->next;
5804         } while (group != sd->groups);
5805         printk(KERN_CONT "\n");
5806
5807         if (!cpumask_equal(sched_domain_span(sd), groupmask))
5808                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5809
5810         if (sd->parent &&
5811             !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5812                 printk(KERN_ERR "ERROR: parent span is not a superset "
5813                         "of domain->span\n");
5814         return 0;
5815 }
5816
5817 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5818 {
5819         int level = 0;
5820
5821         if (!sched_debug_enabled)
5822                 return;
5823
5824         if (!sd) {
5825                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5826                 return;
5827         }
5828
5829         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5830
5831         for (;;) {
5832                 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5833                         break;
5834                 level++;
5835                 sd = sd->parent;
5836                 if (!sd)
5837                         break;
5838         }
5839 }
5840 #else /* !CONFIG_SCHED_DEBUG */
5841 # define sched_domain_debug(sd, cpu) do { } while (0)
5842 static inline bool sched_debug(void)
5843 {
5844         return false;
5845 }
5846 #endif /* CONFIG_SCHED_DEBUG */
5847
5848 static int sd_degenerate(struct sched_domain *sd)
5849 {
5850         if (cpumask_weight(sched_domain_span(sd)) == 1)
5851                 return 1;
5852
5853         /* Following flags need at least 2 groups */
5854         if (sd->flags & (SD_LOAD_BALANCE |
5855                          SD_BALANCE_NEWIDLE |
5856                          SD_BALANCE_FORK |
5857                          SD_BALANCE_EXEC |
5858                          SD_SHARE_CPUCAPACITY |
5859                          SD_SHARE_PKG_RESOURCES |
5860                          SD_SHARE_POWERDOMAIN)) {
5861                 if (sd->groups != sd->groups->next)
5862                         return 0;
5863         }
5864
5865         /* Following flags don't use groups */
5866         if (sd->flags & (SD_WAKE_AFFINE))
5867                 return 0;
5868
5869         return 1;
5870 }
5871
5872 static int
5873 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5874 {
5875         unsigned long cflags = sd->flags, pflags = parent->flags;
5876
5877         if (sd_degenerate(parent))
5878                 return 1;
5879
5880         if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5881                 return 0;
5882
5883         /* Flags needing groups don't count if only 1 group in parent */
5884         if (parent->groups == parent->groups->next) {
5885                 pflags &= ~(SD_LOAD_BALANCE |
5886                                 SD_BALANCE_NEWIDLE |
5887                                 SD_BALANCE_FORK |
5888                                 SD_BALANCE_EXEC |
5889                                 SD_SHARE_CPUCAPACITY |
5890                                 SD_SHARE_PKG_RESOURCES |
5891                                 SD_PREFER_SIBLING |
5892                                 SD_SHARE_POWERDOMAIN);
5893                 if (nr_node_ids == 1)
5894                         pflags &= ~SD_SERIALIZE;
5895         }
5896         if (~cflags & pflags)
5897                 return 0;
5898
5899         return 1;
5900 }
5901
5902 static void free_rootdomain(struct rcu_head *rcu)
5903 {
5904         struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5905
5906         cpupri_cleanup(&rd->cpupri);
5907         cpudl_cleanup(&rd->cpudl);
5908         free_cpumask_var(rd->dlo_mask);
5909         free_cpumask_var(rd->rto_mask);
5910         free_cpumask_var(rd->online);
5911         free_cpumask_var(rd->span);
5912         kfree(rd);
5913 }
5914
5915 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5916 {
5917         struct root_domain *old_rd = NULL;
5918         unsigned long flags;
5919
5920         raw_spin_lock_irqsave(&rq->lock, flags);
5921
5922         if (rq->rd) {
5923                 old_rd = rq->rd;
5924
5925                 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5926                         set_rq_offline(rq);
5927
5928                 cpumask_clear_cpu(rq->cpu, old_rd->span);
5929
5930                 /*
5931                  * If we dont want to free the old_rd yet then
5932                  * set old_rd to NULL to skip the freeing later
5933                  * in this function:
5934                  */
5935                 if (!atomic_dec_and_test(&old_rd->refcount))
5936                         old_rd = NULL;
5937         }
5938
5939         atomic_inc(&rd->refcount);
5940         rq->rd = rd;
5941
5942         cpumask_set_cpu(rq->cpu, rd->span);
5943         if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5944                 set_rq_online(rq);
5945
5946         raw_spin_unlock_irqrestore(&rq->lock, flags);
5947
5948         if (old_rd)
5949                 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5950 }
5951
5952 static int init_rootdomain(struct root_domain *rd)
5953 {
5954         memset(rd, 0, sizeof(*rd));
5955
5956         if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
5957                 goto out;
5958         if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
5959                 goto free_span;
5960         if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
5961                 goto free_online;
5962         if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5963                 goto free_dlo_mask;
5964
5965         init_dl_bw(&rd->dl_bw);
5966         if (cpudl_init(&rd->cpudl) != 0)
5967                 goto free_dlo_mask;
5968
5969         if (cpupri_init(&rd->cpupri) != 0)
5970                 goto free_rto_mask;
5971         return 0;
5972
5973 free_rto_mask:
5974         free_cpumask_var(rd->rto_mask);
5975 free_dlo_mask:
5976         free_cpumask_var(rd->dlo_mask);
5977 free_online:
5978         free_cpumask_var(rd->online);
5979 free_span:
5980         free_cpumask_var(rd->span);
5981 out:
5982         return -ENOMEM;
5983 }
5984
5985 /*
5986  * By default the system creates a single root-domain with all cpus as
5987  * members (mimicking the global state we have today).
5988  */
5989 struct root_domain def_root_domain;
5990
5991 static void init_defrootdomain(void)
5992 {
5993         init_rootdomain(&def_root_domain);
5994
5995         atomic_set(&def_root_domain.refcount, 1);
5996 }
5997
5998 static struct root_domain *alloc_rootdomain(void)
5999 {
6000         struct root_domain *rd;
6001
6002         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6003         if (!rd)
6004                 return NULL;
6005
6006         if (init_rootdomain(rd) != 0) {
6007                 kfree(rd);
6008                 return NULL;
6009         }
6010
6011         return rd;
6012 }
6013
6014 static void free_sched_groups(struct sched_group *sg, int free_sgc)
6015 {
6016         struct sched_group *tmp, *first;
6017
6018         if (!sg)
6019                 return;
6020
6021         first = sg;
6022         do {
6023                 tmp = sg->next;
6024
6025                 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
6026                         kfree(sg->sgc);
6027
6028                 kfree(sg);
6029                 sg = tmp;
6030         } while (sg != first);
6031 }
6032
6033 static void free_sched_domain(struct rcu_head *rcu)
6034 {
6035         struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
6036
6037         /*
6038          * If its an overlapping domain it has private groups, iterate and
6039          * nuke them all.
6040          */
6041         if (sd->flags & SD_OVERLAP) {
6042                 free_sched_groups(sd->groups, 1);
6043         } else if (atomic_dec_and_test(&sd->groups->ref)) {
6044                 kfree(sd->groups->sgc);
6045                 kfree(sd->groups);
6046         }
6047         kfree(sd);
6048 }
6049
6050 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
6051 {
6052         call_rcu(&sd->rcu, free_sched_domain);
6053 }
6054
6055 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
6056 {
6057         for (; sd; sd = sd->parent)
6058                 destroy_sched_domain(sd, cpu);
6059 }
6060
6061 /*
6062  * Keep a special pointer to the highest sched_domain that has
6063  * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
6064  * allows us to avoid some pointer chasing select_idle_sibling().
6065  *
6066  * Also keep a unique ID per domain (we use the first cpu number in
6067  * the cpumask of the domain), this allows us to quickly tell if
6068  * two cpus are in the same cache domain, see cpus_share_cache().
6069  */
6070 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
6071 DEFINE_PER_CPU(int, sd_llc_size);
6072 DEFINE_PER_CPU(int, sd_llc_id);
6073 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
6074 DEFINE_PER_CPU(struct sched_domain *, sd_busy);
6075 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
6076
6077 static void update_top_cache_domain(int cpu)
6078 {
6079         struct sched_domain *sd;
6080         struct sched_domain *busy_sd = NULL;
6081         int id = cpu;
6082         int size = 1;
6083
6084         sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
6085         if (sd) {
6086                 id = cpumask_first(sched_domain_span(sd));
6087                 size = cpumask_weight(sched_domain_span(sd));
6088                 busy_sd = sd->parent; /* sd_busy */
6089         }
6090         rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
6091
6092         rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
6093         per_cpu(sd_llc_size, cpu) = size;
6094         per_cpu(sd_llc_id, cpu) = id;
6095
6096         sd = lowest_flag_domain(cpu, SD_NUMA);
6097         rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
6098
6099         sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
6100         rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
6101 }
6102
6103 /*
6104  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6105  * hold the hotplug lock.
6106  */
6107 static void
6108 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6109 {
6110         struct rq *rq = cpu_rq(cpu);
6111         struct sched_domain *tmp;
6112
6113         /* Remove the sched domains which do not contribute to scheduling. */
6114         for (tmp = sd; tmp; ) {
6115                 struct sched_domain *parent = tmp->parent;
6116                 if (!parent)
6117                         break;
6118
6119                 if (sd_parent_degenerate(tmp, parent)) {
6120                         tmp->parent = parent->parent;
6121                         if (parent->parent)
6122                                 parent->parent->child = tmp;
6123                         /*
6124                          * Transfer SD_PREFER_SIBLING down in case of a
6125                          * degenerate parent; the spans match for this
6126                          * so the property transfers.
6127                          */
6128                         if (parent->flags & SD_PREFER_SIBLING)
6129                                 tmp->flags |= SD_PREFER_SIBLING;
6130                         destroy_sched_domain(parent, cpu);
6131                 } else
6132                         tmp = tmp->parent;
6133         }
6134
6135         if (sd && sd_degenerate(sd)) {
6136                 tmp = sd;
6137                 sd = sd->parent;
6138                 destroy_sched_domain(tmp, cpu);
6139                 if (sd)
6140                         sd->child = NULL;
6141         }
6142
6143         sched_domain_debug(sd, cpu);
6144
6145         rq_attach_root(rq, rd);
6146         tmp = rq->sd;
6147         rcu_assign_pointer(rq->sd, sd);
6148         destroy_sched_domains(tmp, cpu);
6149
6150         update_top_cache_domain(cpu);
6151 }
6152
6153 /* Setup the mask of cpus configured for isolated domains */
6154 static int __init isolated_cpu_setup(char *str)
6155 {
6156         alloc_bootmem_cpumask_var(&cpu_isolated_map);
6157         cpulist_parse(str, cpu_isolated_map);
6158         return 1;
6159 }
6160
6161 __setup("isolcpus=", isolated_cpu_setup);
6162
6163 struct s_data {
6164         struct sched_domain ** __percpu sd;
6165         struct root_domain      *rd;
6166 };
6167
6168 enum s_alloc {
6169         sa_rootdomain,
6170         sa_sd,
6171         sa_sd_storage,
6172         sa_none,
6173 };
6174
6175 /*
6176  * Build an iteration mask that can exclude certain CPUs from the upwards
6177  * domain traversal.
6178  *
6179  * Asymmetric node setups can result in situations where the domain tree is of
6180  * unequal depth, make sure to skip domains that already cover the entire
6181  * range.
6182  *
6183  * In that case build_sched_domains() will have terminated the iteration early
6184  * and our sibling sd spans will be empty. Domains should always include the
6185  * cpu they're built on, so check that.
6186  *
6187  */
6188 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
6189 {
6190         const struct cpumask *span = sched_domain_span(sd);
6191         struct sd_data *sdd = sd->private;
6192         struct sched_domain *sibling;
6193         int i;
6194
6195         for_each_cpu(i, span) {
6196                 sibling = *per_cpu_ptr(sdd->sd, i);
6197                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6198                         continue;
6199
6200                 cpumask_set_cpu(i, sched_group_mask(sg));
6201         }
6202 }
6203
6204 /*
6205  * Return the canonical balance cpu for this group, this is the first cpu
6206  * of this group that's also in the iteration mask.
6207  */
6208 int group_balance_cpu(struct sched_group *sg)
6209 {
6210         return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6211 }
6212
6213 static int
6214 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6215 {
6216         struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6217         const struct cpumask *span = sched_domain_span(sd);
6218         struct cpumask *covered = sched_domains_tmpmask;
6219         struct sd_data *sdd = sd->private;
6220         struct sched_domain *sibling;
6221         int i;
6222
6223         cpumask_clear(covered);
6224
6225         for_each_cpu(i, span) {
6226                 struct cpumask *sg_span;
6227
6228                 if (cpumask_test_cpu(i, covered))
6229                         continue;
6230
6231                 sibling = *per_cpu_ptr(sdd->sd, i);
6232
6233                 /* See the comment near build_group_mask(). */
6234                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6235                         continue;
6236
6237                 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6238                                 GFP_KERNEL, cpu_to_node(cpu));
6239
6240                 if (!sg)
6241                         goto fail;
6242
6243                 sg_span = sched_group_cpus(sg);
6244                 if (sibling->child)
6245                         cpumask_copy(sg_span, sched_domain_span(sibling->child));
6246                 else
6247                         cpumask_set_cpu(i, sg_span);
6248
6249                 cpumask_or(covered, covered, sg_span);
6250
6251                 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6252                 if (atomic_inc_return(&sg->sgc->ref) == 1)
6253                         build_group_mask(sd, sg);
6254
6255                 /*
6256                  * Initialize sgc->capacity such that even if we mess up the
6257                  * domains and no possible iteration will get us here, we won't
6258                  * die on a /0 trap.
6259                  */
6260                 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6261
6262                 /*
6263                  * Make sure the first group of this domain contains the
6264                  * canonical balance cpu. Otherwise the sched_domain iteration
6265                  * breaks. See update_sg_lb_stats().
6266                  */
6267                 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6268                     group_balance_cpu(sg) == cpu)
6269                         groups = sg;
6270
6271                 if (!first)
6272                         first = sg;
6273                 if (last)
6274                         last->next = sg;
6275                 last = sg;
6276                 last->next = first;
6277         }
6278         sd->groups = groups;
6279
6280         return 0;
6281
6282 fail:
6283         free_sched_groups(first, 0);
6284
6285         return -ENOMEM;
6286 }
6287
6288 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6289 {
6290         struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6291         struct sched_domain *child = sd->child;
6292
6293         if (child)
6294                 cpu = cpumask_first(sched_domain_span(child));
6295
6296         if (sg) {
6297                 *sg = *per_cpu_ptr(sdd->sg, cpu);
6298                 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6299                 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6300         }
6301
6302         return cpu;
6303 }
6304
6305 /*
6306  * build_sched_groups will build a circular linked list of the groups
6307  * covered by the given span, and will set each group's ->cpumask correctly,
6308  * and ->cpu_capacity to 0.
6309  *
6310  * Assumes the sched_domain tree is fully constructed
6311  */
6312 static int
6313 build_sched_groups(struct sched_domain *sd, int cpu)
6314 {
6315         struct sched_group *first = NULL, *last = NULL;
6316         struct sd_data *sdd = sd->private;
6317         const struct cpumask *span = sched_domain_span(sd);
6318         struct cpumask *covered;
6319         int i;
6320
6321         get_group(cpu, sdd, &sd->groups);
6322         atomic_inc(&sd->groups->ref);
6323
6324         if (cpu != cpumask_first(span))
6325                 return 0;
6326
6327         lockdep_assert_held(&sched_domains_mutex);
6328         covered = sched_domains_tmpmask;
6329
6330         cpumask_clear(covered);
6331
6332         for_each_cpu(i, span) {
6333                 struct sched_group *sg;
6334                 int group, j;
6335
6336                 if (cpumask_test_cpu(i, covered))
6337                         continue;
6338
6339                 group = get_group(i, sdd, &sg);
6340                 cpumask_setall(sched_group_mask(sg));
6341
6342                 for_each_cpu(j, span) {
6343                         if (get_group(j, sdd, NULL) != group)
6344                                 continue;
6345
6346                         cpumask_set_cpu(j, covered);
6347                         cpumask_set_cpu(j, sched_group_cpus(sg));
6348                 }
6349
6350                 if (!first)
6351                         first = sg;
6352                 if (last)
6353                         last->next = sg;
6354                 last = sg;
6355         }
6356         last->next = first;
6357
6358         return 0;
6359 }
6360
6361 /*
6362  * Initialize sched groups cpu_capacity.
6363  *
6364  * cpu_capacity indicates the capacity of sched group, which is used while
6365  * distributing the load between different sched groups in a sched domain.
6366  * Typically cpu_capacity for all the groups in a sched domain will be same
6367  * unless there are asymmetries in the topology. If there are asymmetries,
6368  * group having more cpu_capacity will pickup more load compared to the
6369  * group having less cpu_capacity.
6370  */
6371 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6372 {
6373         struct sched_group *sg = sd->groups;
6374
6375         WARN_ON(!sg);
6376
6377         do {
6378                 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6379                 sg = sg->next;
6380         } while (sg != sd->groups);
6381
6382         if (cpu != group_balance_cpu(sg))
6383                 return;
6384
6385         update_group_capacity(sd, cpu);
6386         atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
6387 }
6388
6389 /*
6390  * Initializers for schedule domains
6391  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6392  */
6393
6394 static int default_relax_domain_level = -1;
6395 int sched_domain_level_max;
6396
6397 static int __init setup_relax_domain_level(char *str)
6398 {
6399         if (kstrtoint(str, 0, &default_relax_domain_level))
6400                 pr_warn("Unable to set relax_domain_level\n");
6401
6402         return 1;
6403 }
6404 __setup("relax_domain_level=", setup_relax_domain_level);
6405
6406 static void set_domain_attribute(struct sched_domain *sd,
6407                                  struct sched_domain_attr *attr)
6408 {
6409         int request;
6410
6411         if (!attr || attr->relax_domain_level < 0) {
6412                 if (default_relax_domain_level < 0)
6413                         return;
6414                 else
6415                         request = default_relax_domain_level;
6416         } else
6417                 request = attr->relax_domain_level;
6418         if (request < sd->level) {
6419                 /* turn off idle balance on this domain */
6420                 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6421         } else {
6422                 /* turn on idle balance on this domain */
6423                 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6424         }
6425 }
6426
6427 static void __sdt_free(const struct cpumask *cpu_map);
6428 static int __sdt_alloc(const struct cpumask *cpu_map);
6429
6430 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6431                                  const struct cpumask *cpu_map)
6432 {
6433         switch (what) {
6434         case sa_rootdomain:
6435                 if (!atomic_read(&d->rd->refcount))
6436                         free_rootdomain(&d->rd->rcu); /* fall through */
6437         case sa_sd:
6438                 free_percpu(d->sd); /* fall through */
6439         case sa_sd_storage:
6440                 __sdt_free(cpu_map); /* fall through */
6441         case sa_none:
6442                 break;
6443         }
6444 }
6445
6446 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6447                                                    const struct cpumask *cpu_map)
6448 {
6449         memset(d, 0, sizeof(*d));
6450
6451         if (__sdt_alloc(cpu_map))
6452                 return sa_sd_storage;
6453         d->sd = alloc_percpu(struct sched_domain *);
6454         if (!d->sd)
6455                 return sa_sd_storage;
6456         d->rd = alloc_rootdomain();
6457         if (!d->rd)
6458                 return sa_sd;
6459         return sa_rootdomain;
6460 }
6461
6462 /*
6463  * NULL the sd_data elements we've used to build the sched_domain and
6464  * sched_group structure so that the subsequent __free_domain_allocs()
6465  * will not free the data we're using.
6466  */
6467 static void claim_allocations(int cpu, struct sched_domain *sd)
6468 {
6469         struct sd_data *sdd = sd->private;
6470
6471         WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6472         *per_cpu_ptr(sdd->sd, cpu) = NULL;
6473
6474         if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6475                 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6476
6477         if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6478                 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6479 }
6480
6481 #ifdef CONFIG_NUMA
6482 static int sched_domains_numa_levels;
6483 enum numa_topology_type sched_numa_topology_type;
6484 static int *sched_domains_numa_distance;
6485 int sched_max_numa_distance;
6486 static struct cpumask ***sched_domains_numa_masks;
6487 static int sched_domains_curr_level;
6488 #endif
6489
6490 /*
6491  * SD_flags allowed in topology descriptions.
6492  *
6493  * SD_SHARE_CPUCAPACITY      - describes SMT topologies
6494  * SD_SHARE_PKG_RESOURCES - describes shared caches
6495  * SD_NUMA                - describes NUMA topologies
6496  * SD_SHARE_POWERDOMAIN   - describes shared power domain
6497  *
6498  * Odd one out:
6499  * SD_ASYM_PACKING        - describes SMT quirks
6500  */
6501 #define TOPOLOGY_SD_FLAGS               \
6502         (SD_SHARE_CPUCAPACITY |         \
6503          SD_SHARE_PKG_RESOURCES |       \
6504          SD_NUMA |                      \
6505          SD_ASYM_PACKING |              \
6506          SD_SHARE_POWERDOMAIN)
6507
6508 static struct sched_domain *
6509 sd_init(struct sched_domain_topology_level *tl, int cpu)
6510 {
6511         struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6512         int sd_weight, sd_flags = 0;
6513
6514 #ifdef CONFIG_NUMA
6515         /*
6516          * Ugly hack to pass state to sd_numa_mask()...
6517          */
6518         sched_domains_curr_level = tl->numa_level;
6519 #endif
6520
6521         sd_weight = cpumask_weight(tl->mask(cpu));
6522
6523         if (tl->sd_flags)
6524                 sd_flags = (*tl->sd_flags)();
6525         if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6526                         "wrong sd_flags in topology description\n"))
6527                 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6528
6529         *sd = (struct sched_domain){
6530                 .min_interval           = sd_weight,
6531                 .max_interval           = 2*sd_weight,
6532                 .busy_factor            = 32,
6533                 .imbalance_pct          = 125,
6534
6535                 .cache_nice_tries       = 0,
6536                 .busy_idx               = 0,
6537                 .idle_idx               = 0,
6538                 .newidle_idx            = 0,
6539                 .wake_idx               = 0,
6540                 .forkexec_idx           = 0,
6541
6542                 .flags                  = 1*SD_LOAD_BALANCE
6543                                         | 1*SD_BALANCE_NEWIDLE
6544                                         | 1*SD_BALANCE_EXEC
6545                                         | 1*SD_BALANCE_FORK
6546                                         | 0*SD_BALANCE_WAKE
6547                                         | 1*SD_WAKE_AFFINE
6548                                         | 0*SD_SHARE_CPUCAPACITY
6549                                         | 0*SD_SHARE_PKG_RESOURCES
6550                                         | 0*SD_SERIALIZE
6551                                         | 0*SD_PREFER_SIBLING
6552                                         | 0*SD_NUMA
6553                                         | sd_flags
6554                                         ,
6555
6556                 .last_balance           = jiffies,
6557                 .balance_interval       = sd_weight,
6558                 .smt_gain               = 0,
6559                 .max_newidle_lb_cost    = 0,
6560                 .next_decay_max_lb_cost = jiffies,
6561 #ifdef CONFIG_SCHED_DEBUG
6562                 .name                   = tl->name,
6563 #endif
6564         };
6565
6566         /*
6567          * Convert topological properties into behaviour.
6568          */
6569
6570         if (sd->flags & SD_SHARE_CPUCAPACITY) {
6571                 sd->flags |= SD_PREFER_SIBLING;
6572                 sd->imbalance_pct = 110;
6573                 sd->smt_gain = 1178; /* ~15% */
6574
6575         } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6576                 sd->imbalance_pct = 117;
6577                 sd->cache_nice_tries = 1;
6578                 sd->busy_idx = 2;
6579
6580 #ifdef CONFIG_NUMA
6581         } else if (sd->flags & SD_NUMA) {
6582                 sd->cache_nice_tries = 2;
6583                 sd->busy_idx = 3;
6584                 sd->idle_idx = 2;
6585
6586                 sd->flags |= SD_SERIALIZE;
6587                 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6588                         sd->flags &= ~(SD_BALANCE_EXEC |
6589                                        SD_BALANCE_FORK |
6590                                        SD_WAKE_AFFINE);
6591                 }
6592
6593 #endif
6594         } else {
6595                 sd->flags |= SD_PREFER_SIBLING;
6596                 sd->cache_nice_tries = 1;
6597                 sd->busy_idx = 2;
6598                 sd->idle_idx = 1;
6599         }
6600
6601         sd->private = &tl->data;
6602
6603         return sd;
6604 }
6605
6606 /*
6607  * Topology list, bottom-up.
6608  */
6609 static struct sched_domain_topology_level default_topology[] = {
6610 #ifdef CONFIG_SCHED_SMT
6611         { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6612 #endif
6613 #ifdef CONFIG_SCHED_MC
6614         { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6615 #endif
6616         { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6617         { NULL, },
6618 };
6619
6620 struct sched_domain_topology_level *sched_domain_topology = default_topology;
6621
6622 #define for_each_sd_topology(tl)                        \
6623         for (tl = sched_domain_topology; tl->mask; tl++)
6624
6625 void set_sched_topology(struct sched_domain_topology_level *tl)
6626 {
6627         sched_domain_topology = tl;
6628 }
6629
6630 #ifdef CONFIG_NUMA
6631
6632 static const struct cpumask *sd_numa_mask(int cpu)
6633 {
6634         return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6635 }
6636
6637 static void sched_numa_warn(const char *str)
6638 {
6639         static int done = false;
6640         int i,j;
6641
6642         if (done)
6643                 return;
6644
6645         done = true;
6646
6647         printk(KERN_WARNING "ERROR: %s\n\n", str);
6648
6649         for (i = 0; i < nr_node_ids; i++) {
6650                 printk(KERN_WARNING "  ");
6651                 for (j = 0; j < nr_node_ids; j++)
6652                         printk(KERN_CONT "%02d ", node_distance(i,j));
6653                 printk(KERN_CONT "\n");
6654         }
6655         printk(KERN_WARNING "\n");
6656 }
6657
6658 bool find_numa_distance(int distance)
6659 {
6660         int i;
6661
6662         if (distance == node_distance(0, 0))
6663                 return true;
6664
6665         for (i = 0; i < sched_domains_numa_levels; i++) {
6666                 if (sched_domains_numa_distance[i] == distance)
6667                         return true;
6668         }
6669
6670         return false;
6671 }
6672
6673 /*
6674  * A system can have three types of NUMA topology:
6675  * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6676  * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6677  * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6678  *
6679  * The difference between a glueless mesh topology and a backplane
6680  * topology lies in whether communication between not directly
6681  * connected nodes goes through intermediary nodes (where programs
6682  * could run), or through backplane controllers. This affects
6683  * placement of programs.
6684  *
6685  * The type of topology can be discerned with the following tests:
6686  * - If the maximum distance between any nodes is 1 hop, the system
6687  *   is directly connected.
6688  * - If for two nodes A and B, located N > 1 hops away from each other,
6689  *   there is an intermediary node C, which is < N hops away from both
6690  *   nodes A and B, the system is a glueless mesh.
6691  */
6692 static void init_numa_topology_type(void)
6693 {
6694         int a, b, c, n;
6695
6696         n = sched_max_numa_distance;
6697
6698         if (n <= 1)
6699                 sched_numa_topology_type = NUMA_DIRECT;
6700
6701         for_each_online_node(a) {
6702                 for_each_online_node(b) {
6703                         /* Find two nodes furthest removed from each other. */
6704                         if (node_distance(a, b) < n)
6705                                 continue;
6706
6707                         /* Is there an intermediary node between a and b? */
6708                         for_each_online_node(c) {
6709                                 if (node_distance(a, c) < n &&
6710                                     node_distance(b, c) < n) {
6711                                         sched_numa_topology_type =
6712                                                         NUMA_GLUELESS_MESH;
6713                                         return;
6714                                 }
6715                         }
6716
6717                         sched_numa_topology_type = NUMA_BACKPLANE;
6718                         return;
6719                 }
6720         }
6721 }
6722
6723 static void sched_init_numa(void)
6724 {
6725         int next_distance, curr_distance = node_distance(0, 0);
6726         struct sched_domain_topology_level *tl;
6727         int level = 0;
6728         int i, j, k;
6729
6730         sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6731         if (!sched_domains_numa_distance)
6732                 return;
6733
6734         /*
6735          * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6736          * unique distances in the node_distance() table.
6737          *
6738          * Assumes node_distance(0,j) includes all distances in
6739          * node_distance(i,j) in order to avoid cubic time.
6740          */
6741         next_distance = curr_distance;
6742         for (i = 0; i < nr_node_ids; i++) {
6743                 for (j = 0; j < nr_node_ids; j++) {
6744                         for (k = 0; k < nr_node_ids; k++) {
6745                                 int distance = node_distance(i, k);
6746
6747                                 if (distance > curr_distance &&
6748                                     (distance < next_distance ||
6749                                      next_distance == curr_distance))
6750                                         next_distance = distance;
6751
6752                                 /*
6753                                  * While not a strong assumption it would be nice to know
6754                                  * about cases where if node A is connected to B, B is not
6755                                  * equally connected to A.
6756                                  */
6757                                 if (sched_debug() && node_distance(k, i) != distance)
6758                                         sched_numa_warn("Node-distance not symmetric");
6759
6760                                 if (sched_debug() && i && !find_numa_distance(distance))
6761                                         sched_numa_warn("Node-0 not representative");
6762                         }
6763                         if (next_distance != curr_distance) {
6764                                 sched_domains_numa_distance[level++] = next_distance;
6765                                 sched_domains_numa_levels = level;
6766                                 curr_distance = next_distance;
6767                         } else break;
6768                 }
6769
6770                 /*
6771                  * In case of sched_debug() we verify the above assumption.
6772                  */
6773                 if (!sched_debug())
6774                         break;
6775         }
6776
6777         if (!level)
6778                 return;
6779
6780         /*
6781          * 'level' contains the number of unique distances, excluding the
6782          * identity distance node_distance(i,i).
6783          *
6784          * The sched_domains_numa_distance[] array includes the actual distance
6785          * numbers.
6786          */
6787
6788         /*
6789          * Here, we should temporarily reset sched_domains_numa_levels to 0.
6790          * If it fails to allocate memory for array sched_domains_numa_masks[][],
6791          * the array will contain less then 'level' members. This could be
6792          * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6793          * in other functions.
6794          *
6795          * We reset it to 'level' at the end of this function.
6796          */
6797         sched_domains_numa_levels = 0;
6798
6799         sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6800         if (!sched_domains_numa_masks)
6801                 return;
6802
6803         /*
6804          * Now for each level, construct a mask per node which contains all
6805          * cpus of nodes that are that many hops away from us.
6806          */
6807         for (i = 0; i < level; i++) {
6808                 sched_domains_numa_masks[i] =
6809                         kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6810                 if (!sched_domains_numa_masks[i])
6811                         return;
6812
6813                 for (j = 0; j < nr_node_ids; j++) {
6814                         struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6815                         if (!mask)
6816                                 return;
6817
6818                         sched_domains_numa_masks[i][j] = mask;
6819
6820                         for (k = 0; k < nr_node_ids; k++) {
6821                                 if (node_distance(j, k) > sched_domains_numa_distance[i])
6822                                         continue;
6823
6824                                 cpumask_or(mask, mask, cpumask_of_node(k));
6825                         }
6826                 }
6827         }
6828
6829         /* Compute default topology size */
6830         for (i = 0; sched_domain_topology[i].mask; i++);
6831
6832         tl = kzalloc((i + level + 1) *
6833                         sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6834         if (!tl)
6835                 return;
6836
6837         /*
6838          * Copy the default topology bits..
6839          */
6840         for (i = 0; sched_domain_topology[i].mask; i++)
6841                 tl[i] = sched_domain_topology[i];
6842
6843         /*
6844          * .. and append 'j' levels of NUMA goodness.
6845          */
6846         for (j = 0; j < level; i++, j++) {
6847                 tl[i] = (struct sched_domain_topology_level){
6848                         .mask = sd_numa_mask,
6849                         .sd_flags = cpu_numa_flags,
6850                         .flags = SDTL_OVERLAP,
6851                         .numa_level = j,
6852                         SD_INIT_NAME(NUMA)
6853                 };
6854         }
6855
6856         sched_domain_topology = tl;
6857
6858         sched_domains_numa_levels = level;
6859         sched_max_numa_distance = sched_domains_numa_distance[level - 1];
6860
6861         init_numa_topology_type();
6862 }
6863
6864 static void sched_domains_numa_masks_set(int cpu)
6865 {
6866         int i, j;
6867         int node = cpu_to_node(cpu);
6868
6869         for (i = 0; i < sched_domains_numa_levels; i++) {
6870                 for (j = 0; j < nr_node_ids; j++) {
6871                         if (node_distance(j, node) <= sched_domains_numa_distance[i])
6872                                 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6873                 }
6874         }
6875 }
6876
6877 static void sched_domains_numa_masks_clear(int cpu)
6878 {
6879         int i, j;
6880         for (i = 0; i < sched_domains_numa_levels; i++) {
6881                 for (j = 0; j < nr_node_ids; j++)
6882                         cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6883         }
6884 }
6885
6886 /*
6887  * Update sched_domains_numa_masks[level][node] array when new cpus
6888  * are onlined.
6889  */
6890 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6891                                            unsigned long action,
6892                                            void *hcpu)
6893 {
6894         int cpu = (long)hcpu;
6895
6896         switch (action & ~CPU_TASKS_FROZEN) {
6897         case CPU_ONLINE:
6898                 sched_domains_numa_masks_set(cpu);
6899                 break;
6900
6901         case CPU_DEAD:
6902                 sched_domains_numa_masks_clear(cpu);
6903                 break;
6904
6905         default:
6906                 return NOTIFY_DONE;
6907         }
6908
6909         return NOTIFY_OK;
6910 }
6911 #else
6912 static inline void sched_init_numa(void)
6913 {
6914 }
6915
6916 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6917                                            unsigned long action,
6918                                            void *hcpu)
6919 {
6920         return 0;
6921 }
6922 #endif /* CONFIG_NUMA */
6923
6924 static int __sdt_alloc(const struct cpumask *cpu_map)
6925 {
6926         struct sched_domain_topology_level *tl;
6927         int j;
6928
6929         for_each_sd_topology(tl) {
6930                 struct sd_data *sdd = &tl->data;
6931
6932                 sdd->sd = alloc_percpu(struct sched_domain *);
6933                 if (!sdd->sd)
6934                         return -ENOMEM;
6935
6936                 sdd->sg = alloc_percpu(struct sched_group *);
6937                 if (!sdd->sg)
6938                         return -ENOMEM;
6939
6940                 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
6941                 if (!sdd->sgc)
6942                         return -ENOMEM;
6943
6944                 for_each_cpu(j, cpu_map) {
6945                         struct sched_domain *sd;
6946                         struct sched_group *sg;
6947                         struct sched_group_capacity *sgc;
6948
6949                         sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6950                                         GFP_KERNEL, cpu_to_node(j));
6951                         if (!sd)
6952                                 return -ENOMEM;
6953
6954                         *per_cpu_ptr(sdd->sd, j) = sd;
6955
6956                         sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6957                                         GFP_KERNEL, cpu_to_node(j));
6958                         if (!sg)
6959                                 return -ENOMEM;
6960
6961                         sg->next = sg;
6962
6963                         *per_cpu_ptr(sdd->sg, j) = sg;
6964
6965                         sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
6966                                         GFP_KERNEL, cpu_to_node(j));
6967                         if (!sgc)
6968                                 return -ENOMEM;
6969
6970                         *per_cpu_ptr(sdd->sgc, j) = sgc;
6971                 }
6972         }
6973
6974         return 0;
6975 }
6976
6977 static void __sdt_free(const struct cpumask *cpu_map)
6978 {
6979         struct sched_domain_topology_level *tl;
6980         int j;
6981
6982         for_each_sd_topology(tl) {
6983                 struct sd_data *sdd = &tl->data;
6984
6985                 for_each_cpu(j, cpu_map) {
6986                         struct sched_domain *sd;
6987
6988                         if (sdd->sd) {
6989                                 sd = *per_cpu_ptr(sdd->sd, j);
6990                                 if (sd && (sd->flags & SD_OVERLAP))
6991                                         free_sched_groups(sd->groups, 0);
6992                                 kfree(*per_cpu_ptr(sdd->sd, j));
6993                         }
6994
6995                         if (sdd->sg)
6996                                 kfree(*per_cpu_ptr(sdd->sg, j));
6997                         if (sdd->sgc)
6998                                 kfree(*per_cpu_ptr(sdd->sgc, j));
6999                 }
7000                 free_percpu(sdd->sd);
7001                 sdd->sd = NULL;
7002                 free_percpu(sdd->sg);
7003                 sdd->sg = NULL;
7004                 free_percpu(sdd->sgc);
7005                 sdd->sgc = NULL;
7006         }
7007 }
7008
7009 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
7010                 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7011                 struct sched_domain *child, int cpu)
7012 {
7013         struct sched_domain *sd = sd_init(tl, cpu);
7014         if (!sd)
7015                 return child;
7016
7017         cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
7018         if (child) {
7019                 sd->level = child->level + 1;
7020                 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7021                 child->parent = sd;
7022                 sd->child = child;
7023
7024                 if (!cpumask_subset(sched_domain_span(child),
7025                                     sched_domain_span(sd))) {
7026                         pr_err("BUG: arch topology borken\n");
7027 #ifdef CONFIG_SCHED_DEBUG
7028                         pr_err("     the %s domain not a subset of the %s domain\n",
7029                                         child->name, sd->name);
7030 #endif
7031                         /* Fixup, ensure @sd has at least @child cpus. */
7032                         cpumask_or(sched_domain_span(sd),
7033                                    sched_domain_span(sd),
7034                                    sched_domain_span(child));
7035                 }
7036
7037         }
7038         set_domain_attribute(sd, attr);
7039
7040         return sd;
7041 }
7042
7043 /*
7044  * Build sched domains for a given set of cpus and attach the sched domains
7045  * to the individual cpus
7046  */
7047 static int build_sched_domains(const struct cpumask *cpu_map,
7048                                struct sched_domain_attr *attr)
7049 {
7050         enum s_alloc alloc_state;
7051         struct sched_domain *sd;
7052         struct s_data d;
7053         int i, ret = -ENOMEM;
7054
7055         alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7056         if (alloc_state != sa_rootdomain)
7057                 goto error;
7058
7059         /* Set up domains for cpus specified by the cpu_map. */
7060         for_each_cpu(i, cpu_map) {
7061                 struct sched_domain_topology_level *tl;
7062
7063                 sd = NULL;
7064                 for_each_sd_topology(tl) {
7065                         sd = build_sched_domain(tl, cpu_map, attr, sd, i);
7066                         if (tl == sched_domain_topology)
7067                                 *per_cpu_ptr(d.sd, i) = sd;
7068                         if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7069                                 sd->flags |= SD_OVERLAP;
7070                         if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7071                                 break;
7072                 }
7073         }
7074
7075         /* Build the groups for the domains */
7076         for_each_cpu(i, cpu_map) {
7077                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7078                         sd->span_weight = cpumask_weight(sched_domain_span(sd));
7079                         if (sd->flags & SD_OVERLAP) {
7080                                 if (build_overlap_sched_groups(sd, i))
7081                                         goto error;
7082                         } else {
7083                                 if (build_sched_groups(sd, i))
7084                                         goto error;
7085                         }
7086                 }
7087         }
7088
7089         /* Calculate CPU capacity for physical packages and nodes */
7090         for (i = nr_cpumask_bits-1; i >= 0; i--) {
7091                 if (!cpumask_test_cpu(i, cpu_map))
7092                         continue;
7093
7094                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7095                         claim_allocations(i, sd);
7096                         init_sched_groups_capacity(i, sd);
7097                 }
7098         }
7099
7100         /* Attach the domains */
7101         rcu_read_lock();
7102         for_each_cpu(i, cpu_map) {
7103                 sd = *per_cpu_ptr(d.sd, i);
7104                 cpu_attach_domain(sd, d.rd, i);
7105         }
7106         rcu_read_unlock();
7107
7108         ret = 0;
7109 error:
7110         __free_domain_allocs(&d, alloc_state, cpu_map);
7111         return ret;
7112 }
7113
7114 static cpumask_var_t *doms_cur; /* current sched domains */
7115 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
7116 static struct sched_domain_attr *dattr_cur;
7117                                 /* attribues of custom domains in 'doms_cur' */
7118
7119 /*
7120  * Special case: If a kmalloc of a doms_cur partition (array of
7121  * cpumask) fails, then fallback to a single sched domain,
7122  * as determined by the single cpumask fallback_doms.
7123  */
7124 static cpumask_var_t fallback_doms;
7125
7126 /*
7127  * arch_update_cpu_topology lets virtualized architectures update the
7128  * cpu core maps. It is supposed to return 1 if the topology changed
7129  * or 0 if it stayed the same.
7130  */
7131 int __weak arch_update_cpu_topology(void)
7132 {
7133         return 0;
7134 }
7135
7136 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7137 {
7138         int i;
7139         cpumask_var_t *doms;
7140
7141         doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7142         if (!doms)
7143                 return NULL;
7144         for (i = 0; i < ndoms; i++) {
7145                 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7146                         free_sched_domains(doms, i);
7147                         return NULL;
7148                 }
7149         }
7150         return doms;
7151 }
7152
7153 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7154 {
7155         unsigned int i;
7156         for (i = 0; i < ndoms; i++)
7157                 free_cpumask_var(doms[i]);
7158         kfree(doms);
7159 }
7160
7161 /*
7162  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7163  * For now this just excludes isolated cpus, but could be used to
7164  * exclude other special cases in the future.
7165  */
7166 static int init_sched_domains(const struct cpumask *cpu_map)
7167 {
7168         int err;
7169
7170         arch_update_cpu_topology();
7171         ndoms_cur = 1;
7172         doms_cur = alloc_sched_domains(ndoms_cur);
7173         if (!doms_cur)
7174                 doms_cur = &fallback_doms;
7175         cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7176         err = build_sched_domains(doms_cur[0], NULL);
7177         register_sched_domain_sysctl();
7178
7179         return err;
7180 }
7181
7182 /*
7183  * Detach sched domains from a group of cpus specified in cpu_map
7184  * These cpus will now be attached to the NULL domain
7185  */
7186 static void detach_destroy_domains(const struct cpumask *cpu_map)
7187 {
7188         int i;
7189
7190         rcu_read_lock();
7191         for_each_cpu(i, cpu_map)
7192                 cpu_attach_domain(NULL, &def_root_domain, i);
7193         rcu_read_unlock();
7194 }
7195
7196 /* handle null as "default" */
7197 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7198                         struct sched_domain_attr *new, int idx_new)
7199 {
7200         struct sched_domain_attr tmp;
7201
7202         /* fast path */
7203         if (!new && !cur)
7204                 return 1;
7205
7206         tmp = SD_ATTR_INIT;
7207         return !memcmp(cur ? (cur + idx_cur) : &tmp,
7208                         new ? (new + idx_new) : &tmp,
7209                         sizeof(struct sched_domain_attr));
7210 }
7211
7212 /*
7213  * Partition sched domains as specified by the 'ndoms_new'
7214  * cpumasks in the array doms_new[] of cpumasks. This compares
7215  * doms_new[] to the current sched domain partitioning, doms_cur[].
7216  * It destroys each deleted domain and builds each new domain.
7217  *
7218  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7219  * The masks don't intersect (don't overlap.) We should setup one
7220  * sched domain for each mask. CPUs not in any of the cpumasks will
7221  * not be load balanced. If the same cpumask appears both in the
7222  * current 'doms_cur' domains and in the new 'doms_new', we can leave
7223  * it as it is.
7224  *
7225  * The passed in 'doms_new' should be allocated using
7226  * alloc_sched_domains.  This routine takes ownership of it and will
7227  * free_sched_domains it when done with it. If the caller failed the
7228  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7229  * and partition_sched_domains() will fallback to the single partition
7230  * 'fallback_doms', it also forces the domains to be rebuilt.
7231  *
7232  * If doms_new == NULL it will be replaced with cpu_online_mask.
7233  * ndoms_new == 0 is a special case for destroying existing domains,
7234  * and it will not create the default domain.
7235  *
7236  * Call with hotplug lock held
7237  */
7238 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7239                              struct sched_domain_attr *dattr_new)
7240 {
7241         int i, j, n;
7242         int new_topology;
7243
7244         mutex_lock(&sched_domains_mutex);
7245
7246         /* always unregister in case we don't destroy any domains */
7247         unregister_sched_domain_sysctl();
7248
7249         /* Let architecture update cpu core mappings. */
7250         new_topology = arch_update_cpu_topology();
7251
7252         n = doms_new ? ndoms_new : 0;
7253
7254         /* Destroy deleted domains */
7255         for (i = 0; i < ndoms_cur; i++) {
7256                 for (j = 0; j < n && !new_topology; j++) {
7257                         if (cpumask_equal(doms_cur[i], doms_new[j])
7258                             && dattrs_equal(dattr_cur, i, dattr_new, j))
7259                                 goto match1;
7260                 }
7261                 /* no match - a current sched domain not in new doms_new[] */
7262                 detach_destroy_domains(doms_cur[i]);
7263 match1:
7264                 ;
7265         }
7266
7267         n = ndoms_cur;
7268         if (doms_new == NULL) {
7269                 n = 0;
7270                 doms_new = &fallback_doms;
7271                 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7272                 WARN_ON_ONCE(dattr_new);
7273         }
7274
7275         /* Build new domains */
7276         for (i = 0; i < ndoms_new; i++) {
7277                 for (j = 0; j < n && !new_topology; j++) {
7278                         if (cpumask_equal(doms_new[i], doms_cur[j])
7279                             && dattrs_equal(dattr_new, i, dattr_cur, j))
7280                                 goto match2;
7281                 }
7282                 /* no match - add a new doms_new */
7283                 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7284 match2:
7285                 ;
7286         }
7287
7288         /* Remember the new sched domains */
7289         if (doms_cur != &fallback_doms)
7290                 free_sched_domains(doms_cur, ndoms_cur);
7291         kfree(dattr_cur);       /* kfree(NULL) is safe */
7292         doms_cur = doms_new;
7293         dattr_cur = dattr_new;
7294         ndoms_cur = ndoms_new;
7295
7296         register_sched_domain_sysctl();
7297
7298         mutex_unlock(&sched_domains_mutex);
7299 }
7300
7301 static int num_cpus_frozen;     /* used to mark begin/end of suspend/resume */
7302
7303 /*
7304  * Update cpusets according to cpu_active mask.  If cpusets are
7305  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7306  * around partition_sched_domains().
7307  *
7308  * If we come here as part of a suspend/resume, don't touch cpusets because we
7309  * want to restore it back to its original state upon resume anyway.
7310  */
7311 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7312                              void *hcpu)
7313 {
7314         switch (action) {
7315         case CPU_ONLINE_FROZEN:
7316         case CPU_DOWN_FAILED_FROZEN:
7317
7318                 /*
7319                  * num_cpus_frozen tracks how many CPUs are involved in suspend
7320                  * resume sequence. As long as this is not the last online
7321                  * operation in the resume sequence, just build a single sched
7322                  * domain, ignoring cpusets.
7323                  */
7324                 num_cpus_frozen--;
7325                 if (likely(num_cpus_frozen)) {
7326                         partition_sched_domains(1, NULL, NULL);
7327                         break;
7328                 }
7329
7330                 /*
7331                  * This is the last CPU online operation. So fall through and
7332                  * restore the original sched domains by considering the
7333                  * cpuset configurations.
7334                  */
7335
7336         case CPU_ONLINE:
7337                 cpuset_update_active_cpus(true);
7338                 break;
7339         default:
7340                 return NOTIFY_DONE;
7341         }
7342         return NOTIFY_OK;
7343 }
7344
7345 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7346                                void *hcpu)
7347 {
7348         unsigned long flags;
7349         long cpu = (long)hcpu;
7350         struct dl_bw *dl_b;
7351         bool overflow;
7352         int cpus;
7353
7354         switch (action) {
7355         case CPU_DOWN_PREPARE:
7356                 rcu_read_lock_sched();
7357                 dl_b = dl_bw_of(cpu);
7358
7359                 raw_spin_lock_irqsave(&dl_b->lock, flags);
7360                 cpus = dl_bw_cpus(cpu);
7361                 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7362                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7363
7364                 rcu_read_unlock_sched();
7365
7366                 if (overflow)
7367                         return notifier_from_errno(-EBUSY);
7368                 cpuset_update_active_cpus(false);
7369                 break;
7370         case CPU_DOWN_PREPARE_FROZEN:
7371                 num_cpus_frozen++;
7372                 partition_sched_domains(1, NULL, NULL);
7373                 break;
7374         default:
7375                 return NOTIFY_DONE;
7376         }
7377         return NOTIFY_OK;
7378 }
7379
7380 void __init sched_init_smp(void)
7381 {
7382         cpumask_var_t non_isolated_cpus;
7383
7384         alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7385         alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7386
7387         sched_init_numa();
7388
7389         /*
7390          * There's no userspace yet to cause hotplug operations; hence all the
7391          * cpu masks are stable and all blatant races in the below code cannot
7392          * happen.
7393          */
7394         mutex_lock(&sched_domains_mutex);
7395         init_sched_domains(cpu_active_mask);
7396         cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7397         if (cpumask_empty(non_isolated_cpus))
7398                 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7399         mutex_unlock(&sched_domains_mutex);
7400
7401         hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
7402         hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7403         hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7404
7405         init_hrtick();
7406
7407         /* Move init over to a non-isolated CPU */
7408         if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7409                 BUG();
7410         sched_init_granularity();
7411         free_cpumask_var(non_isolated_cpus);
7412
7413         init_sched_rt_class();
7414         init_sched_dl_class();
7415 }
7416 #else
7417 void __init sched_init_smp(void)
7418 {
7419         sched_init_granularity();
7420 }
7421 #endif /* CONFIG_SMP */
7422
7423 const_debug unsigned int sysctl_timer_migration = 1;
7424
7425 int in_sched_functions(unsigned long addr)
7426 {
7427         return in_lock_functions(addr) ||
7428                 (addr >= (unsigned long)__sched_text_start
7429                 && addr < (unsigned long)__sched_text_end);
7430 }
7431
7432 #ifdef CONFIG_CGROUP_SCHED
7433 /*
7434  * Default task group.
7435  * Every task in system belongs to this group at bootup.
7436  */
7437 struct task_group root_task_group;
7438 LIST_HEAD(task_groups);
7439 #endif
7440
7441 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7442
7443 void __init sched_init(void)
7444 {
7445         int i, j;
7446         unsigned long alloc_size = 0, ptr;
7447
7448 #ifdef CONFIG_FAIR_GROUP_SCHED
7449         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7450 #endif
7451 #ifdef CONFIG_RT_GROUP_SCHED
7452         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7453 #endif
7454         if (alloc_size) {
7455                 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7456
7457 #ifdef CONFIG_FAIR_GROUP_SCHED
7458                 root_task_group.se = (struct sched_entity **)ptr;
7459                 ptr += nr_cpu_ids * sizeof(void **);
7460
7461                 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7462                 ptr += nr_cpu_ids * sizeof(void **);
7463
7464 #endif /* CONFIG_FAIR_GROUP_SCHED */
7465 #ifdef CONFIG_RT_GROUP_SCHED
7466                 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7467                 ptr += nr_cpu_ids * sizeof(void **);
7468
7469                 root_task_group.rt_rq = (struct rt_rq **)ptr;
7470                 ptr += nr_cpu_ids * sizeof(void **);
7471
7472 #endif /* CONFIG_RT_GROUP_SCHED */
7473         }
7474 #ifdef CONFIG_CPUMASK_OFFSTACK
7475         for_each_possible_cpu(i) {
7476                 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7477                         cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7478         }
7479 #endif /* CONFIG_CPUMASK_OFFSTACK */
7480
7481         init_rt_bandwidth(&def_rt_bandwidth,
7482                         global_rt_period(), global_rt_runtime());
7483         init_dl_bandwidth(&def_dl_bandwidth,
7484                         global_rt_period(), global_rt_runtime());
7485
7486 #ifdef CONFIG_SMP
7487         init_defrootdomain();
7488 #endif
7489
7490 #ifdef CONFIG_RT_GROUP_SCHED
7491         init_rt_bandwidth(&root_task_group.rt_bandwidth,
7492                         global_rt_period(), global_rt_runtime());
7493 #endif /* CONFIG_RT_GROUP_SCHED */
7494
7495 #ifdef CONFIG_CGROUP_SCHED
7496         list_add(&root_task_group.list, &task_groups);
7497         INIT_LIST_HEAD(&root_task_group.children);
7498         INIT_LIST_HEAD(&root_task_group.siblings);
7499         autogroup_init(&init_task);
7500
7501 #endif /* CONFIG_CGROUP_SCHED */
7502
7503         for_each_possible_cpu(i) {
7504                 struct rq *rq;
7505
7506                 rq = cpu_rq(i);
7507                 raw_spin_lock_init(&rq->lock);
7508                 rq->nr_running = 0;
7509                 rq->calc_load_active = 0;
7510                 rq->calc_load_update = jiffies + LOAD_FREQ;
7511                 init_cfs_rq(&rq->cfs);
7512                 init_rt_rq(&rq->rt);
7513                 init_dl_rq(&rq->dl);
7514 #ifdef CONFIG_FAIR_GROUP_SCHED
7515                 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7516                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7517                 /*
7518                  * How much cpu bandwidth does root_task_group get?
7519                  *
7520                  * In case of task-groups formed thr' the cgroup filesystem, it
7521                  * gets 100% of the cpu resources in the system. This overall
7522                  * system cpu resource is divided among the tasks of
7523                  * root_task_group and its child task-groups in a fair manner,
7524                  * based on each entity's (task or task-group's) weight
7525                  * (se->load.weight).
7526                  *
7527                  * In other words, if root_task_group has 10 tasks of weight
7528                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
7529                  * then A0's share of the cpu resource is:
7530                  *
7531                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7532                  *
7533                  * We achieve this by letting root_task_group's tasks sit
7534                  * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7535                  */
7536                 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7537                 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7538 #endif /* CONFIG_FAIR_GROUP_SCHED */
7539
7540                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7541 #ifdef CONFIG_RT_GROUP_SCHED
7542                 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7543 #endif
7544
7545                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7546                         rq->cpu_load[j] = 0;
7547
7548                 rq->last_load_update_tick = jiffies;
7549
7550 #ifdef CONFIG_SMP
7551                 rq->sd = NULL;
7552                 rq->rd = NULL;
7553                 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7554                 rq->post_schedule = 0;
7555                 rq->active_balance = 0;
7556                 rq->next_balance = jiffies;
7557                 rq->push_cpu = 0;
7558                 rq->cpu = i;
7559                 rq->online = 0;
7560                 rq->idle_stamp = 0;
7561                 rq->avg_idle = 2*sysctl_sched_migration_cost;
7562                 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7563
7564                 INIT_LIST_HEAD(&rq->cfs_tasks);
7565
7566                 rq_attach_root(rq, &def_root_domain);
7567 #ifdef CONFIG_NO_HZ_COMMON
7568                 rq->nohz_flags = 0;
7569 #endif
7570 #ifdef CONFIG_NO_HZ_FULL
7571                 rq->last_sched_tick = 0;
7572 #endif
7573 #endif
7574                 init_rq_hrtick(rq);
7575                 atomic_set(&rq->nr_iowait, 0);
7576         }
7577
7578         set_load_weight(&init_task);
7579
7580 #ifdef CONFIG_PREEMPT_NOTIFIERS
7581         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7582 #endif
7583
7584         /*
7585          * The boot idle thread does lazy MMU switching as well:
7586          */
7587         atomic_inc(&init_mm.mm_count);
7588         enter_lazy_tlb(&init_mm, current);
7589
7590         /*
7591          * During early bootup we pretend to be a normal task:
7592          */
7593         current->sched_class = &fair_sched_class;
7594
7595         /*
7596          * Make us the idle thread. Technically, schedule() should not be
7597          * called from this thread, however somewhere below it might be,
7598          * but because we are the idle thread, we just pick up running again
7599          * when this runqueue becomes "idle".
7600          */
7601         init_idle(current, smp_processor_id());
7602
7603         calc_load_update = jiffies + LOAD_FREQ;
7604
7605 #ifdef CONFIG_SMP
7606         zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7607         /* May be allocated at isolcpus cmdline parse time */
7608         if (cpu_isolated_map == NULL)
7609                 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7610         idle_thread_set_boot_cpu();
7611         set_cpu_rq_start_time();
7612 #endif
7613         init_sched_fair_class();
7614
7615         scheduler_running = 1;
7616 }
7617
7618 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7619 static inline int preempt_count_equals(int preempt_offset)
7620 {
7621         int nested = (preempt_count() & ~PREEMPT_ACTIVE) +
7622                 sched_rcu_preempt_depth();
7623
7624         return (nested == preempt_offset);
7625 }
7626
7627 void __might_sleep(const char *file, int line, int preempt_offset)
7628 {
7629         /*
7630          * Blocking primitives will set (and therefore destroy) current->state,
7631          * since we will exit with TASK_RUNNING make sure we enter with it,
7632          * otherwise we will destroy state.
7633          */
7634         WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7635                         "do not call blocking ops when !TASK_RUNNING; "
7636                         "state=%lx set at [<%p>] %pS\n",
7637                         current->state,
7638                         (void *)current->task_state_change,
7639                         (void *)current->task_state_change);
7640
7641         ___might_sleep(file, line, preempt_offset);
7642 }
7643 EXPORT_SYMBOL(__might_sleep);
7644
7645 void ___might_sleep(const char *file, int line, int preempt_offset)
7646 {
7647         static unsigned long prev_jiffy;        /* ratelimiting */
7648
7649         rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7650         if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7651              !is_idle_task(current)) ||
7652             system_state != SYSTEM_RUNNING || oops_in_progress)
7653                 return;
7654         if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7655                 return;
7656         prev_jiffy = jiffies;
7657
7658         printk(KERN_ERR
7659                 "BUG: sleeping function called from invalid context at %s:%d\n",
7660                         file, line);
7661         printk(KERN_ERR
7662                 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7663                         in_atomic(), irqs_disabled(),
7664                         current->pid, current->comm);
7665
7666         if (task_stack_end_corrupted(current))
7667                 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7668
7669         debug_show_held_locks(current);
7670         if (irqs_disabled())
7671                 print_irqtrace_events(current);
7672 #ifdef CONFIG_DEBUG_PREEMPT
7673         if (!preempt_count_equals(preempt_offset)) {
7674                 pr_err("Preemption disabled at:");
7675                 print_ip_sym(current->preempt_disable_ip);
7676                 pr_cont("\n");
7677         }
7678 #endif
7679         dump_stack();
7680 }
7681 EXPORT_SYMBOL(___might_sleep);
7682 #endif
7683
7684 #ifdef CONFIG_MAGIC_SYSRQ
7685 static void normalize_task(struct rq *rq, struct task_struct *p)
7686 {
7687         const struct sched_class *prev_class = p->sched_class;
7688         struct sched_attr attr = {
7689                 .sched_policy = SCHED_NORMAL,
7690         };
7691         int old_prio = p->prio;
7692         int queued;
7693
7694         queued = task_on_rq_queued(p);
7695         if (queued)
7696                 dequeue_task(rq, p, 0);
7697         __setscheduler(rq, p, &attr, false);
7698         if (queued) {
7699                 enqueue_task(rq, p, 0);
7700                 resched_curr(rq);
7701         }
7702
7703         check_class_changed(rq, p, prev_class, old_prio);
7704 }
7705
7706 void normalize_rt_tasks(void)
7707 {
7708         struct task_struct *g, *p;
7709         unsigned long flags;
7710         struct rq *rq;
7711
7712         read_lock(&tasklist_lock);
7713         for_each_process_thread(g, p) {
7714                 /*
7715                  * Only normalize user tasks:
7716                  */
7717                 if (p->flags & PF_KTHREAD)
7718                         continue;
7719
7720                 p->se.exec_start                = 0;
7721 #ifdef CONFIG_SCHEDSTATS
7722                 p->se.statistics.wait_start     = 0;
7723                 p->se.statistics.sleep_start    = 0;
7724                 p->se.statistics.block_start    = 0;
7725 #endif
7726
7727                 if (!dl_task(p) && !rt_task(p)) {
7728                         /*
7729                          * Renice negative nice level userspace
7730                          * tasks back to 0:
7731                          */
7732                         if (task_nice(p) < 0)
7733                                 set_user_nice(p, 0);
7734                         continue;
7735                 }
7736
7737                 rq = task_rq_lock(p, &flags);
7738                 normalize_task(rq, p);
7739                 task_rq_unlock(rq, p, &flags);
7740         }
7741         read_unlock(&tasklist_lock);
7742 }
7743
7744 #endif /* CONFIG_MAGIC_SYSRQ */
7745
7746 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7747 /*
7748  * These functions are only useful for the IA64 MCA handling, or kdb.
7749  *
7750  * They can only be called when the whole system has been
7751  * stopped - every CPU needs to be quiescent, and no scheduling
7752  * activity can take place. Using them for anything else would
7753  * be a serious bug, and as a result, they aren't even visible
7754  * under any other configuration.
7755  */
7756
7757 /**
7758  * curr_task - return the current task for a given cpu.
7759  * @cpu: the processor in question.
7760  *
7761  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7762  *
7763  * Return: The current task for @cpu.
7764  */
7765 struct task_struct *curr_task(int cpu)
7766 {
7767         return cpu_curr(cpu);
7768 }
7769
7770 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7771
7772 #ifdef CONFIG_IA64
7773 /**
7774  * set_curr_task - set the current task for a given cpu.
7775  * @cpu: the processor in question.
7776  * @p: the task pointer to set.
7777  *
7778  * Description: This function must only be used when non-maskable interrupts
7779  * are serviced on a separate stack. It allows the architecture to switch the
7780  * notion of the current task on a cpu in a non-blocking manner. This function
7781  * must be called with all CPU's synchronized, and interrupts disabled, the
7782  * and caller must save the original value of the current task (see
7783  * curr_task() above) and restore that value before reenabling interrupts and
7784  * re-starting the system.
7785  *
7786  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7787  */
7788 void set_curr_task(int cpu, struct task_struct *p)
7789 {
7790         cpu_curr(cpu) = p;
7791 }
7792
7793 #endif
7794
7795 #ifdef CONFIG_CGROUP_SCHED
7796 /* task_group_lock serializes the addition/removal of task groups */
7797 static DEFINE_SPINLOCK(task_group_lock);
7798
7799 static void free_sched_group(struct task_group *tg)
7800 {
7801         free_fair_sched_group(tg);
7802         free_rt_sched_group(tg);
7803         autogroup_free(tg);
7804         kfree(tg);
7805 }
7806
7807 /* allocate runqueue etc for a new task group */
7808 struct task_group *sched_create_group(struct task_group *parent)
7809 {
7810         struct task_group *tg;
7811
7812         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7813         if (!tg)
7814                 return ERR_PTR(-ENOMEM);
7815
7816         if (!alloc_fair_sched_group(tg, parent))
7817                 goto err;
7818
7819         if (!alloc_rt_sched_group(tg, parent))
7820                 goto err;
7821
7822         return tg;
7823
7824 err:
7825         free_sched_group(tg);
7826         return ERR_PTR(-ENOMEM);
7827 }
7828
7829 void sched_online_group(struct task_group *tg, struct task_group *parent)
7830 {
7831         unsigned long flags;
7832
7833         spin_lock_irqsave(&task_group_lock, flags);
7834         list_add_rcu(&tg->list, &task_groups);
7835
7836         WARN_ON(!parent); /* root should already exist */
7837
7838         tg->parent = parent;
7839         INIT_LIST_HEAD(&tg->children);
7840         list_add_rcu(&tg->siblings, &parent->children);
7841         spin_unlock_irqrestore(&task_group_lock, flags);
7842 }
7843
7844 /* rcu callback to free various structures associated with a task group */
7845 static void free_sched_group_rcu(struct rcu_head *rhp)
7846 {
7847         /* now it should be safe to free those cfs_rqs */
7848         free_sched_group(container_of(rhp, struct task_group, rcu));
7849 }
7850
7851 /* Destroy runqueue etc associated with a task group */
7852 void sched_destroy_group(struct task_group *tg)
7853 {
7854         /* wait for possible concurrent references to cfs_rqs complete */
7855         call_rcu(&tg->rcu, free_sched_group_rcu);
7856 }
7857
7858 void sched_offline_group(struct task_group *tg)
7859 {
7860         unsigned long flags;
7861         int i;
7862
7863         /* end participation in shares distribution */
7864         for_each_possible_cpu(i)
7865                 unregister_fair_sched_group(tg, i);
7866
7867         spin_lock_irqsave(&task_group_lock, flags);
7868         list_del_rcu(&tg->list);
7869         list_del_rcu(&tg->siblings);
7870         spin_unlock_irqrestore(&task_group_lock, flags);
7871 }
7872
7873 /* change task's runqueue when it moves between groups.
7874  *      The caller of this function should have put the task in its new group
7875  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7876  *      reflect its new group.
7877  */
7878 void sched_move_task(struct task_struct *tsk)
7879 {
7880         struct task_group *tg;
7881         int queued, running;
7882         unsigned long flags;
7883         struct rq *rq;
7884
7885         rq = task_rq_lock(tsk, &flags);
7886
7887         running = task_current(rq, tsk);
7888         queued = task_on_rq_queued(tsk);
7889
7890         if (queued)
7891                 dequeue_task(rq, tsk, 0);
7892         if (unlikely(running))
7893                 put_prev_task(rq, tsk);
7894
7895         /*
7896          * All callers are synchronized by task_rq_lock(); we do not use RCU
7897          * which is pointless here. Thus, we pass "true" to task_css_check()
7898          * to prevent lockdep warnings.
7899          */
7900         tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7901                           struct task_group, css);
7902         tg = autogroup_task_group(tsk, tg);
7903         tsk->sched_task_group = tg;
7904
7905 #ifdef CONFIG_FAIR_GROUP_SCHED
7906         if (tsk->sched_class->task_move_group)
7907                 tsk->sched_class->task_move_group(tsk, queued);
7908         else
7909 #endif
7910                 set_task_rq(tsk, task_cpu(tsk));
7911
7912         if (unlikely(running))
7913                 tsk->sched_class->set_curr_task(rq);
7914         if (queued)
7915                 enqueue_task(rq, tsk, 0);
7916
7917         task_rq_unlock(rq, tsk, &flags);
7918 }
7919 #endif /* CONFIG_CGROUP_SCHED */
7920
7921 #ifdef CONFIG_RT_GROUP_SCHED
7922 /*
7923  * Ensure that the real time constraints are schedulable.
7924  */
7925 static DEFINE_MUTEX(rt_constraints_mutex);
7926
7927 /* Must be called with tasklist_lock held */
7928 static inline int tg_has_rt_tasks(struct task_group *tg)
7929 {
7930         struct task_struct *g, *p;
7931
7932         /*
7933          * Autogroups do not have RT tasks; see autogroup_create().
7934          */
7935         if (task_group_is_autogroup(tg))
7936                 return 0;
7937
7938         for_each_process_thread(g, p) {
7939                 if (rt_task(p) && task_group(p) == tg)
7940                         return 1;
7941         }
7942
7943         return 0;
7944 }
7945
7946 struct rt_schedulable_data {
7947         struct task_group *tg;
7948         u64 rt_period;
7949         u64 rt_runtime;
7950 };
7951
7952 static int tg_rt_schedulable(struct task_group *tg, void *data)
7953 {
7954         struct rt_schedulable_data *d = data;
7955         struct task_group *child;
7956         unsigned long total, sum = 0;
7957         u64 period, runtime;
7958
7959         period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7960         runtime = tg->rt_bandwidth.rt_runtime;
7961
7962         if (tg == d->tg) {
7963                 period = d->rt_period;
7964                 runtime = d->rt_runtime;
7965         }
7966
7967         /*
7968          * Cannot have more runtime than the period.
7969          */
7970         if (runtime > period && runtime != RUNTIME_INF)
7971                 return -EINVAL;
7972
7973         /*
7974          * Ensure we don't starve existing RT tasks.
7975          */
7976         if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7977                 return -EBUSY;
7978
7979         total = to_ratio(period, runtime);
7980
7981         /*
7982          * Nobody can have more than the global setting allows.
7983          */
7984         if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7985                 return -EINVAL;
7986
7987         /*
7988          * The sum of our children's runtime should not exceed our own.
7989          */
7990         list_for_each_entry_rcu(child, &tg->children, siblings) {
7991                 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7992                 runtime = child->rt_bandwidth.rt_runtime;
7993
7994                 if (child == d->tg) {
7995                         period = d->rt_period;
7996                         runtime = d->rt_runtime;
7997                 }
7998
7999                 sum += to_ratio(period, runtime);
8000         }
8001
8002         if (sum > total)
8003                 return -EINVAL;
8004
8005         return 0;
8006 }
8007
8008 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8009 {
8010         int ret;
8011
8012         struct rt_schedulable_data data = {
8013                 .tg = tg,
8014                 .rt_period = period,
8015                 .rt_runtime = runtime,
8016         };
8017
8018         rcu_read_lock();
8019         ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
8020         rcu_read_unlock();
8021
8022         return ret;
8023 }
8024
8025 static int tg_set_rt_bandwidth(struct task_group *tg,
8026                 u64 rt_period, u64 rt_runtime)
8027 {
8028         int i, err = 0;
8029
8030         /*
8031          * Disallowing the root group RT runtime is BAD, it would disallow the
8032          * kernel creating (and or operating) RT threads.
8033          */
8034         if (tg == &root_task_group && rt_runtime == 0)
8035                 return -EINVAL;
8036
8037         /* No period doesn't make any sense. */
8038         if (rt_period == 0)
8039                 return -EINVAL;
8040
8041         mutex_lock(&rt_constraints_mutex);
8042         read_lock(&tasklist_lock);
8043         err = __rt_schedulable(tg, rt_period, rt_runtime);
8044         if (err)
8045                 goto unlock;
8046
8047         raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8048         tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8049         tg->rt_bandwidth.rt_runtime = rt_runtime;
8050
8051         for_each_possible_cpu(i) {
8052                 struct rt_rq *rt_rq = tg->rt_rq[i];
8053
8054                 raw_spin_lock(&rt_rq->rt_runtime_lock);
8055                 rt_rq->rt_runtime = rt_runtime;
8056                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8057         }
8058         raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8059 unlock:
8060         read_unlock(&tasklist_lock);
8061         mutex_unlock(&rt_constraints_mutex);
8062
8063         return err;
8064 }
8065
8066 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8067 {
8068         u64 rt_runtime, rt_period;
8069
8070         rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8071         rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8072         if (rt_runtime_us < 0)
8073                 rt_runtime = RUNTIME_INF;
8074
8075         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8076 }
8077
8078 static long sched_group_rt_runtime(struct task_group *tg)
8079 {
8080         u64 rt_runtime_us;
8081
8082         if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8083                 return -1;
8084
8085         rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8086         do_div(rt_runtime_us, NSEC_PER_USEC);
8087         return rt_runtime_us;
8088 }
8089
8090 static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8091 {
8092         u64 rt_runtime, rt_period;
8093
8094         rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8095         rt_runtime = tg->rt_bandwidth.rt_runtime;
8096
8097         return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8098 }
8099
8100 static long sched_group_rt_period(struct task_group *tg)
8101 {
8102         u64 rt_period_us;
8103
8104         rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8105         do_div(rt_period_us, NSEC_PER_USEC);
8106         return rt_period_us;
8107 }
8108 #endif /* CONFIG_RT_GROUP_SCHED */
8109
8110 #ifdef CONFIG_RT_GROUP_SCHED
8111 static int sched_rt_global_constraints(void)
8112 {
8113         int ret = 0;
8114
8115         mutex_lock(&rt_constraints_mutex);
8116         read_lock(&tasklist_lock);
8117         ret = __rt_schedulable(NULL, 0, 0);
8118         read_unlock(&tasklist_lock);
8119         mutex_unlock(&rt_constraints_mutex);
8120
8121         return ret;
8122 }
8123
8124 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8125 {
8126         /* Don't accept realtime tasks when there is no way for them to run */
8127         if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8128                 return 0;
8129
8130         return 1;
8131 }
8132
8133 #else /* !CONFIG_RT_GROUP_SCHED */
8134 static int sched_rt_global_constraints(void)
8135 {
8136         unsigned long flags;
8137         int i, ret = 0;
8138
8139         raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8140         for_each_possible_cpu(i) {
8141                 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8142
8143                 raw_spin_lock(&rt_rq->rt_runtime_lock);
8144                 rt_rq->rt_runtime = global_rt_runtime();
8145                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8146         }
8147         raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8148
8149         return ret;
8150 }
8151 #endif /* CONFIG_RT_GROUP_SCHED */
8152
8153 static int sched_dl_global_validate(void)
8154 {
8155         u64 runtime = global_rt_runtime();
8156         u64 period = global_rt_period();
8157         u64 new_bw = to_ratio(period, runtime);
8158         struct dl_bw *dl_b;
8159         int cpu, ret = 0;
8160         unsigned long flags;
8161
8162         /*
8163          * Here we want to check the bandwidth not being set to some
8164          * value smaller than the currently allocated bandwidth in
8165          * any of the root_domains.
8166          *
8167          * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8168          * cycling on root_domains... Discussion on different/better
8169          * solutions is welcome!
8170          */
8171         for_each_possible_cpu(cpu) {
8172                 rcu_read_lock_sched();
8173                 dl_b = dl_bw_of(cpu);
8174
8175                 raw_spin_lock_irqsave(&dl_b->lock, flags);
8176                 if (new_bw < dl_b->total_bw)
8177                         ret = -EBUSY;
8178                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8179
8180                 rcu_read_unlock_sched();
8181
8182                 if (ret)
8183                         break;
8184         }
8185
8186         return ret;
8187 }
8188
8189 static void sched_dl_do_global(void)
8190 {
8191         u64 new_bw = -1;
8192         struct dl_bw *dl_b;
8193         int cpu;
8194         unsigned long flags;
8195
8196         def_dl_bandwidth.dl_period = global_rt_period();
8197         def_dl_bandwidth.dl_runtime = global_rt_runtime();
8198
8199         if (global_rt_runtime() != RUNTIME_INF)
8200                 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
8201
8202         /*
8203          * FIXME: As above...
8204          */
8205         for_each_possible_cpu(cpu) {
8206                 rcu_read_lock_sched();
8207                 dl_b = dl_bw_of(cpu);
8208
8209                 raw_spin_lock_irqsave(&dl_b->lock, flags);
8210                 dl_b->bw = new_bw;
8211                 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8212
8213                 rcu_read_unlock_sched();
8214         }
8215 }
8216
8217 static int sched_rt_global_validate(void)
8218 {
8219         if (sysctl_sched_rt_period <= 0)
8220                 return -EINVAL;
8221
8222         if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
8223                 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
8224                 return -EINVAL;
8225
8226         return 0;
8227 }
8228
8229 static void sched_rt_do_global(void)
8230 {
8231         def_rt_bandwidth.rt_runtime = global_rt_runtime();
8232         def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
8233 }
8234
8235 int sched_rt_handler(struct ctl_table *table, int write,
8236                 void __user *buffer, size_t *lenp,
8237                 loff_t *ppos)
8238 {
8239         int old_period, old_runtime;
8240         static DEFINE_MUTEX(mutex);
8241         int ret;
8242
8243         mutex_lock(&mutex);
8244         old_period = sysctl_sched_rt_period;
8245         old_runtime = sysctl_sched_rt_runtime;
8246
8247         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8248
8249         if (!ret && write) {
8250                 ret = sched_rt_global_validate();
8251                 if (ret)
8252                         goto undo;
8253
8254                 ret = sched_dl_global_validate();
8255                 if (ret)
8256                         goto undo;
8257
8258                 ret = sched_rt_global_constraints();
8259                 if (ret)
8260                         goto undo;
8261
8262                 sched_rt_do_global();
8263                 sched_dl_do_global();
8264         }
8265         if (0) {
8266 undo:
8267                 sysctl_sched_rt_period = old_period;
8268                 sysctl_sched_rt_runtime = old_runtime;
8269         }
8270         mutex_unlock(&mutex);
8271
8272         return ret;
8273 }
8274
8275 int sched_rr_handler(struct ctl_table *table, int write,
8276                 void __user *buffer, size_t *lenp,
8277                 loff_t *ppos)
8278 {
8279         int ret;
8280         static DEFINE_MUTEX(mutex);
8281
8282         mutex_lock(&mutex);
8283         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8284         /* make sure that internally we keep jiffies */
8285         /* also, writing zero resets timeslice to default */
8286         if (!ret && write) {
8287                 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8288                         RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8289         }
8290         mutex_unlock(&mutex);
8291         return ret;
8292 }
8293
8294 #ifdef CONFIG_CGROUP_SCHED
8295
8296 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8297 {
8298         return css ? container_of(css, struct task_group, css) : NULL;
8299 }
8300
8301 static struct cgroup_subsys_state *
8302 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8303 {
8304         struct task_group *parent = css_tg(parent_css);
8305         struct task_group *tg;
8306
8307         if (!parent) {
8308                 /* This is early initialization for the top cgroup */
8309                 return &root_task_group.css;
8310         }
8311
8312         tg = sched_create_group(parent);
8313         if (IS_ERR(tg))
8314                 return ERR_PTR(-ENOMEM);
8315
8316         return &tg->css;
8317 }
8318
8319 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
8320 {
8321         struct task_group *tg = css_tg(css);
8322         struct task_group *parent = css_tg(css->parent);
8323
8324         if (parent)
8325                 sched_online_group(tg, parent);
8326         return 0;
8327 }
8328
8329 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8330 {
8331         struct task_group *tg = css_tg(css);
8332
8333         sched_destroy_group(tg);
8334 }
8335
8336 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
8337 {
8338         struct task_group *tg = css_tg(css);
8339
8340         sched_offline_group(tg);
8341 }
8342
8343 static void cpu_cgroup_fork(struct task_struct *task)
8344 {
8345         sched_move_task(task);
8346 }
8347
8348 static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css,
8349                                  struct cgroup_taskset *tset)
8350 {
8351         struct task_struct *task;
8352
8353         cgroup_taskset_for_each(task, tset) {
8354 #ifdef CONFIG_RT_GROUP_SCHED
8355                 if (!sched_rt_can_attach(css_tg(css), task))
8356                         return -EINVAL;
8357 #else
8358                 /* We don't support RT-tasks being in separate groups */
8359                 if (task->sched_class != &fair_sched_class)
8360                         return -EINVAL;
8361 #endif
8362         }
8363         return 0;
8364 }
8365
8366 static void cpu_cgroup_attach(struct cgroup_subsys_state *css,
8367                               struct cgroup_taskset *tset)
8368 {
8369         struct task_struct *task;
8370
8371         cgroup_taskset_for_each(task, tset)
8372                 sched_move_task(task);
8373 }
8374
8375 static void cpu_cgroup_exit(struct cgroup_subsys_state *css,
8376                             struct cgroup_subsys_state *old_css,
8377                             struct task_struct *task)
8378 {
8379         /*
8380          * cgroup_exit() is called in the copy_process() failure path.
8381          * Ignore this case since the task hasn't ran yet, this avoids
8382          * trying to poke a half freed task state from generic code.
8383          */
8384         if (!(task->flags & PF_EXITING))
8385                 return;
8386
8387         sched_move_task(task);
8388 }
8389
8390 #ifdef CONFIG_FAIR_GROUP_SCHED
8391 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8392                                 struct cftype *cftype, u64 shareval)
8393 {
8394         return sched_group_set_shares(css_tg(css), scale_load(shareval));
8395 }
8396
8397 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8398                                struct cftype *cft)
8399 {
8400         struct task_group *tg = css_tg(css);
8401
8402         return (u64) scale_load_down(tg->shares);
8403 }
8404
8405 #ifdef CONFIG_CFS_BANDWIDTH
8406 static DEFINE_MUTEX(cfs_constraints_mutex);
8407
8408 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8409 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8410
8411 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8412
8413 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8414 {
8415         int i, ret = 0, runtime_enabled, runtime_was_enabled;
8416         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8417
8418         if (tg == &root_task_group)
8419                 return -EINVAL;
8420
8421         /*
8422          * Ensure we have at some amount of bandwidth every period.  This is
8423          * to prevent reaching a state of large arrears when throttled via
8424          * entity_tick() resulting in prolonged exit starvation.
8425          */
8426         if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8427                 return -EINVAL;
8428
8429         /*
8430          * Likewise, bound things on the otherside by preventing insane quota
8431          * periods.  This also allows us to normalize in computing quota
8432          * feasibility.
8433          */
8434         if (period > max_cfs_quota_period)
8435                 return -EINVAL;
8436
8437         /*
8438          * Prevent race between setting of cfs_rq->runtime_enabled and
8439          * unthrottle_offline_cfs_rqs().
8440          */
8441         get_online_cpus();
8442         mutex_lock(&cfs_constraints_mutex);
8443         ret = __cfs_schedulable(tg, period, quota);
8444         if (ret)
8445                 goto out_unlock;
8446
8447         runtime_enabled = quota != RUNTIME_INF;
8448         runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8449         /*
8450          * If we need to toggle cfs_bandwidth_used, off->on must occur
8451          * before making related changes, and on->off must occur afterwards
8452          */
8453         if (runtime_enabled && !runtime_was_enabled)
8454                 cfs_bandwidth_usage_inc();
8455         raw_spin_lock_irq(&cfs_b->lock);
8456         cfs_b->period = ns_to_ktime(period);
8457         cfs_b->quota = quota;
8458
8459         __refill_cfs_bandwidth_runtime(cfs_b);
8460         /* restart the period timer (if active) to handle new period expiry */
8461         if (runtime_enabled && cfs_b->timer_active) {
8462                 /* force a reprogram */
8463                 __start_cfs_bandwidth(cfs_b, true);
8464         }
8465         raw_spin_unlock_irq(&cfs_b->lock);
8466
8467         for_each_online_cpu(i) {
8468                 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8469                 struct rq *rq = cfs_rq->rq;
8470
8471                 raw_spin_lock_irq(&rq->lock);
8472                 cfs_rq->runtime_enabled = runtime_enabled;
8473                 cfs_rq->runtime_remaining = 0;
8474
8475                 if (cfs_rq->throttled)
8476                         unthrottle_cfs_rq(cfs_rq);
8477                 raw_spin_unlock_irq(&rq->lock);
8478         }
8479         if (runtime_was_enabled && !runtime_enabled)
8480                 cfs_bandwidth_usage_dec();
8481 out_unlock:
8482         mutex_unlock(&cfs_constraints_mutex);
8483         put_online_cpus();
8484
8485         return ret;
8486 }
8487
8488 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8489 {
8490         u64 quota, period;
8491
8492         period = ktime_to_ns(tg->cfs_bandwidth.period);
8493         if (cfs_quota_us < 0)
8494                 quota = RUNTIME_INF;
8495         else
8496                 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8497
8498         return tg_set_cfs_bandwidth(tg, period, quota);
8499 }
8500
8501 long tg_get_cfs_quota(struct task_group *tg)
8502 {
8503         u64 quota_us;
8504
8505         if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8506                 return -1;
8507
8508         quota_us = tg->cfs_bandwidth.quota;
8509         do_div(quota_us, NSEC_PER_USEC);
8510
8511         return quota_us;
8512 }
8513
8514 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8515 {
8516         u64 quota, period;
8517
8518         period = (u64)cfs_period_us * NSEC_PER_USEC;
8519         quota = tg->cfs_bandwidth.quota;
8520
8521         return tg_set_cfs_bandwidth(tg, period, quota);
8522 }
8523
8524 long tg_get_cfs_period(struct task_group *tg)
8525 {
8526         u64 cfs_period_us;
8527
8528         cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8529         do_div(cfs_period_us, NSEC_PER_USEC);
8530
8531         return cfs_period_us;
8532 }
8533
8534 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8535                                   struct cftype *cft)
8536 {
8537         return tg_get_cfs_quota(css_tg(css));
8538 }
8539
8540 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8541                                    struct cftype *cftype, s64 cfs_quota_us)
8542 {
8543         return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8544 }
8545
8546 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8547                                    struct cftype *cft)
8548 {
8549         return tg_get_cfs_period(css_tg(css));
8550 }
8551
8552 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8553                                     struct cftype *cftype, u64 cfs_period_us)
8554 {
8555         return tg_set_cfs_period(css_tg(css), cfs_period_us);
8556 }
8557
8558 struct cfs_schedulable_data {
8559         struct task_group *tg;
8560         u64 period, quota;
8561 };
8562
8563 /*
8564  * normalize group quota/period to be quota/max_period
8565  * note: units are usecs
8566  */
8567 static u64 normalize_cfs_quota(struct task_group *tg,
8568                                struct cfs_schedulable_data *d)
8569 {
8570         u64 quota, period;
8571
8572         if (tg == d->tg) {
8573                 period = d->period;
8574                 quota = d->quota;
8575         } else {
8576                 period = tg_get_cfs_period(tg);
8577                 quota = tg_get_cfs_quota(tg);
8578         }
8579
8580         /* note: these should typically be equivalent */
8581         if (quota == RUNTIME_INF || quota == -1)
8582                 return RUNTIME_INF;
8583
8584         return to_ratio(period, quota);
8585 }
8586
8587 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8588 {
8589         struct cfs_schedulable_data *d = data;
8590         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8591         s64 quota = 0, parent_quota = -1;
8592
8593         if (!tg->parent) {
8594                 quota = RUNTIME_INF;
8595         } else {
8596                 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8597
8598                 quota = normalize_cfs_quota(tg, d);
8599                 parent_quota = parent_b->hierarchical_quota;
8600
8601                 /*
8602                  * ensure max(child_quota) <= parent_quota, inherit when no
8603                  * limit is set
8604                  */
8605                 if (quota == RUNTIME_INF)
8606                         quota = parent_quota;
8607                 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8608                         return -EINVAL;
8609         }
8610         cfs_b->hierarchical_quota = quota;
8611
8612         return 0;
8613 }
8614
8615 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8616 {
8617         int ret;
8618         struct cfs_schedulable_data data = {
8619                 .tg = tg,
8620                 .period = period,
8621                 .quota = quota,
8622         };
8623
8624         if (quota != RUNTIME_INF) {
8625                 do_div(data.period, NSEC_PER_USEC);
8626                 do_div(data.quota, NSEC_PER_USEC);
8627         }
8628
8629         rcu_read_lock();
8630         ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8631         rcu_read_unlock();
8632
8633         return ret;
8634 }
8635
8636 static int cpu_stats_show(struct seq_file *sf, void *v)
8637 {
8638         struct task_group *tg = css_tg(seq_css(sf));
8639         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8640
8641         seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8642         seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8643         seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8644
8645         return 0;
8646 }
8647 #endif /* CONFIG_CFS_BANDWIDTH */
8648 #endif /* CONFIG_FAIR_GROUP_SCHED */
8649
8650 #ifdef CONFIG_RT_GROUP_SCHED
8651 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8652                                 struct cftype *cft, s64 val)
8653 {
8654         return sched_group_set_rt_runtime(css_tg(css), val);
8655 }
8656
8657 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8658                                struct cftype *cft)
8659 {
8660         return sched_group_rt_runtime(css_tg(css));
8661 }
8662
8663 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8664                                     struct cftype *cftype, u64 rt_period_us)
8665 {
8666         return sched_group_set_rt_period(css_tg(css), rt_period_us);
8667 }
8668
8669 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8670                                    struct cftype *cft)
8671 {
8672         return sched_group_rt_period(css_tg(css));
8673 }
8674 #endif /* CONFIG_RT_GROUP_SCHED */
8675
8676 static struct cftype cpu_files[] = {
8677 #ifdef CONFIG_FAIR_GROUP_SCHED
8678         {
8679                 .name = "shares",
8680                 .read_u64 = cpu_shares_read_u64,
8681                 .write_u64 = cpu_shares_write_u64,
8682         },
8683 #endif
8684 #ifdef CONFIG_CFS_BANDWIDTH
8685         {
8686                 .name = "cfs_quota_us",
8687                 .read_s64 = cpu_cfs_quota_read_s64,
8688                 .write_s64 = cpu_cfs_quota_write_s64,
8689         },
8690         {
8691                 .name = "cfs_period_us",
8692                 .read_u64 = cpu_cfs_period_read_u64,
8693                 .write_u64 = cpu_cfs_period_write_u64,
8694         },
8695         {
8696                 .name = "stat",
8697                 .seq_show = cpu_stats_show,
8698         },
8699 #endif
8700 #ifdef CONFIG_RT_GROUP_SCHED
8701         {
8702                 .name = "rt_runtime_us",
8703                 .read_s64 = cpu_rt_runtime_read,
8704                 .write_s64 = cpu_rt_runtime_write,
8705         },
8706         {
8707                 .name = "rt_period_us",
8708                 .read_u64 = cpu_rt_period_read_uint,
8709                 .write_u64 = cpu_rt_period_write_uint,
8710         },
8711 #endif
8712         { }     /* terminate */
8713 };
8714
8715 struct cgroup_subsys cpu_cgrp_subsys = {
8716         .css_alloc      = cpu_cgroup_css_alloc,
8717         .css_free       = cpu_cgroup_css_free,
8718         .css_online     = cpu_cgroup_css_online,
8719         .css_offline    = cpu_cgroup_css_offline,
8720         .fork           = cpu_cgroup_fork,
8721         .can_attach     = cpu_cgroup_can_attach,
8722         .attach         = cpu_cgroup_attach,
8723         .exit           = cpu_cgroup_exit,
8724         .legacy_cftypes = cpu_files,
8725         .early_init     = 1,
8726 };
8727
8728 #endif  /* CONFIG_CGROUP_SCHED */
8729
8730 void dump_cpu_task(int cpu)
8731 {
8732         pr_info("Task dump for CPU %d:\n", cpu);
8733         sched_show_task(cpu_curr(cpu));
8734 }