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