OSDN Git Service

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