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