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