]> asedeno.scripts.mit.edu Git - linux.git/blob - kernel/sched/core.c
sched/wake_q: Reduce reference counting for special users
[linux.git] / kernel / sched / core.c
1 /*
2  *  kernel/sched/core.c
3  *
4  *  Core kernel scheduler code and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  */
8 #include "sched.h"
9
10 #include <linux/nospec.h>
11
12 #include <linux/kcov.h>
13
14 #include <asm/switch_to.h>
15 #include <asm/tlb.h>
16
17 #include "../workqueue_internal.h"
18 #include "../smpboot.h"
19
20 #include "pelt.h"
21
22 #define CREATE_TRACE_POINTS
23 #include <trace/events/sched.h>
24
25 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
26
27 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_JUMP_LABEL)
28 /*
29  * Debugging: various feature bits
30  *
31  * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
32  * sysctl_sched_features, defined in sched.h, to allow constants propagation
33  * at compile time and compiler optimization based on features default.
34  */
35 #define SCHED_FEAT(name, enabled)       \
36         (1UL << __SCHED_FEAT_##name) * enabled |
37 const_debug unsigned int sysctl_sched_features =
38 #include "features.h"
39         0;
40 #undef SCHED_FEAT
41 #endif
42
43 /*
44  * Number of tasks to iterate in a single balance run.
45  * Limited because this is done with IRQs disabled.
46  */
47 const_debug unsigned int sysctl_sched_nr_migrate = 32;
48
49 /*
50  * period over which we measure -rt task CPU usage in us.
51  * default: 1s
52  */
53 unsigned int sysctl_sched_rt_period = 1000000;
54
55 __read_mostly int scheduler_running;
56
57 /*
58  * part of the period that we allow rt tasks to run in us.
59  * default: 0.95s
60  */
61 int sysctl_sched_rt_runtime = 950000;
62
63 /*
64  * __task_rq_lock - lock the rq @p resides on.
65  */
66 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
67         __acquires(rq->lock)
68 {
69         struct rq *rq;
70
71         lockdep_assert_held(&p->pi_lock);
72
73         for (;;) {
74                 rq = task_rq(p);
75                 raw_spin_lock(&rq->lock);
76                 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
77                         rq_pin_lock(rq, rf);
78                         return rq;
79                 }
80                 raw_spin_unlock(&rq->lock);
81
82                 while (unlikely(task_on_rq_migrating(p)))
83                         cpu_relax();
84         }
85 }
86
87 /*
88  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
89  */
90 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
91         __acquires(p->pi_lock)
92         __acquires(rq->lock)
93 {
94         struct rq *rq;
95
96         for (;;) {
97                 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
98                 rq = task_rq(p);
99                 raw_spin_lock(&rq->lock);
100                 /*
101                  *      move_queued_task()              task_rq_lock()
102                  *
103                  *      ACQUIRE (rq->lock)
104                  *      [S] ->on_rq = MIGRATING         [L] rq = task_rq()
105                  *      WMB (__set_task_cpu())          ACQUIRE (rq->lock);
106                  *      [S] ->cpu = new_cpu             [L] task_rq()
107                  *                                      [L] ->on_rq
108                  *      RELEASE (rq->lock)
109                  *
110                  * If we observe the old CPU in task_rq_lock, the acquire of
111                  * the old rq->lock will fully serialize against the stores.
112                  *
113                  * If we observe the new CPU in task_rq_lock, the acquire will
114                  * pair with the WMB to ensure we must then also see migrating.
115                  */
116                 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
117                         rq_pin_lock(rq, rf);
118                         return rq;
119                 }
120                 raw_spin_unlock(&rq->lock);
121                 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
122
123                 while (unlikely(task_on_rq_migrating(p)))
124                         cpu_relax();
125         }
126 }
127
128 /*
129  * RQ-clock updating methods:
130  */
131
132 static void update_rq_clock_task(struct rq *rq, s64 delta)
133 {
134 /*
135  * In theory, the compile should just see 0 here, and optimize out the call
136  * to sched_rt_avg_update. But I don't trust it...
137  */
138         s64 __maybe_unused steal = 0, irq_delta = 0;
139
140 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
141         irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
142
143         /*
144          * Since irq_time is only updated on {soft,}irq_exit, we might run into
145          * this case when a previous update_rq_clock() happened inside a
146          * {soft,}irq region.
147          *
148          * When this happens, we stop ->clock_task and only update the
149          * prev_irq_time stamp to account for the part that fit, so that a next
150          * update will consume the rest. This ensures ->clock_task is
151          * monotonic.
152          *
153          * It does however cause some slight miss-attribution of {soft,}irq
154          * time, a more accurate solution would be to update the irq_time using
155          * the current rq->clock timestamp, except that would require using
156          * atomic ops.
157          */
158         if (irq_delta > delta)
159                 irq_delta = delta;
160
161         rq->prev_irq_time += irq_delta;
162         delta -= irq_delta;
163 #endif
164 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
165         if (static_key_false((&paravirt_steal_rq_enabled))) {
166                 steal = paravirt_steal_clock(cpu_of(rq));
167                 steal -= rq->prev_steal_time_rq;
168
169                 if (unlikely(steal > delta))
170                         steal = delta;
171
172                 rq->prev_steal_time_rq += steal;
173                 delta -= steal;
174         }
175 #endif
176
177         rq->clock_task += delta;
178
179 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
180         if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
181                 update_irq_load_avg(rq, irq_delta + steal);
182 #endif
183 }
184
185 void update_rq_clock(struct rq *rq)
186 {
187         s64 delta;
188
189         lockdep_assert_held(&rq->lock);
190
191         if (rq->clock_update_flags & RQCF_ACT_SKIP)
192                 return;
193
194 #ifdef CONFIG_SCHED_DEBUG
195         if (sched_feat(WARN_DOUBLE_CLOCK))
196                 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
197         rq->clock_update_flags |= RQCF_UPDATED;
198 #endif
199
200         delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
201         if (delta < 0)
202                 return;
203         rq->clock += delta;
204         update_rq_clock_task(rq, delta);
205 }
206
207
208 #ifdef CONFIG_SCHED_HRTICK
209 /*
210  * Use HR-timers to deliver accurate preemption points.
211  */
212
213 static void hrtick_clear(struct rq *rq)
214 {
215         if (hrtimer_active(&rq->hrtick_timer))
216                 hrtimer_cancel(&rq->hrtick_timer);
217 }
218
219 /*
220  * High-resolution timer tick.
221  * Runs from hardirq context with interrupts disabled.
222  */
223 static enum hrtimer_restart hrtick(struct hrtimer *timer)
224 {
225         struct rq *rq = container_of(timer, struct rq, hrtick_timer);
226         struct rq_flags rf;
227
228         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
229
230         rq_lock(rq, &rf);
231         update_rq_clock(rq);
232         rq->curr->sched_class->task_tick(rq, rq->curr, 1);
233         rq_unlock(rq, &rf);
234
235         return HRTIMER_NORESTART;
236 }
237
238 #ifdef CONFIG_SMP
239
240 static void __hrtick_restart(struct rq *rq)
241 {
242         struct hrtimer *timer = &rq->hrtick_timer;
243
244         hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
245 }
246
247 /*
248  * called from hardirq (IPI) context
249  */
250 static void __hrtick_start(void *arg)
251 {
252         struct rq *rq = arg;
253         struct rq_flags rf;
254
255         rq_lock(rq, &rf);
256         __hrtick_restart(rq);
257         rq->hrtick_csd_pending = 0;
258         rq_unlock(rq, &rf);
259 }
260
261 /*
262  * Called to set the hrtick timer state.
263  *
264  * called with rq->lock held and irqs disabled
265  */
266 void hrtick_start(struct rq *rq, u64 delay)
267 {
268         struct hrtimer *timer = &rq->hrtick_timer;
269         ktime_t time;
270         s64 delta;
271
272         /*
273          * Don't schedule slices shorter than 10000ns, that just
274          * doesn't make sense and can cause timer DoS.
275          */
276         delta = max_t(s64, delay, 10000LL);
277         time = ktime_add_ns(timer->base->get_time(), delta);
278
279         hrtimer_set_expires(timer, time);
280
281         if (rq == this_rq()) {
282                 __hrtick_restart(rq);
283         } else if (!rq->hrtick_csd_pending) {
284                 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
285                 rq->hrtick_csd_pending = 1;
286         }
287 }
288
289 #else
290 /*
291  * Called to set the hrtick timer state.
292  *
293  * called with rq->lock held and irqs disabled
294  */
295 void hrtick_start(struct rq *rq, u64 delay)
296 {
297         /*
298          * Don't schedule slices shorter than 10000ns, that just
299          * doesn't make sense. Rely on vruntime for fairness.
300          */
301         delay = max_t(u64, delay, 10000LL);
302         hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
303                       HRTIMER_MODE_REL_PINNED);
304 }
305 #endif /* CONFIG_SMP */
306
307 static void hrtick_rq_init(struct rq *rq)
308 {
309 #ifdef CONFIG_SMP
310         rq->hrtick_csd_pending = 0;
311
312         rq->hrtick_csd.flags = 0;
313         rq->hrtick_csd.func = __hrtick_start;
314         rq->hrtick_csd.info = rq;
315 #endif
316
317         hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
318         rq->hrtick_timer.function = hrtick;
319 }
320 #else   /* CONFIG_SCHED_HRTICK */
321 static inline void hrtick_clear(struct rq *rq)
322 {
323 }
324
325 static inline void hrtick_rq_init(struct rq *rq)
326 {
327 }
328 #endif  /* CONFIG_SCHED_HRTICK */
329
330 /*
331  * cmpxchg based fetch_or, macro so it works for different integer types
332  */
333 #define fetch_or(ptr, mask)                                             \
334         ({                                                              \
335                 typeof(ptr) _ptr = (ptr);                               \
336                 typeof(mask) _mask = (mask);                            \
337                 typeof(*_ptr) _old, _val = *_ptr;                       \
338                                                                         \
339                 for (;;) {                                              \
340                         _old = cmpxchg(_ptr, _val, _val | _mask);       \
341                         if (_old == _val)                               \
342                                 break;                                  \
343                         _val = _old;                                    \
344                 }                                                       \
345         _old;                                                           \
346 })
347
348 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
349 /*
350  * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
351  * this avoids any races wrt polling state changes and thereby avoids
352  * spurious IPIs.
353  */
354 static bool set_nr_and_not_polling(struct task_struct *p)
355 {
356         struct thread_info *ti = task_thread_info(p);
357         return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
358 }
359
360 /*
361  * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
362  *
363  * If this returns true, then the idle task promises to call
364  * sched_ttwu_pending() and reschedule soon.
365  */
366 static bool set_nr_if_polling(struct task_struct *p)
367 {
368         struct thread_info *ti = task_thread_info(p);
369         typeof(ti->flags) old, val = READ_ONCE(ti->flags);
370
371         for (;;) {
372                 if (!(val & _TIF_POLLING_NRFLAG))
373                         return false;
374                 if (val & _TIF_NEED_RESCHED)
375                         return true;
376                 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
377                 if (old == val)
378                         break;
379                 val = old;
380         }
381         return true;
382 }
383
384 #else
385 static bool set_nr_and_not_polling(struct task_struct *p)
386 {
387         set_tsk_need_resched(p);
388         return true;
389 }
390
391 #ifdef CONFIG_SMP
392 static bool set_nr_if_polling(struct task_struct *p)
393 {
394         return false;
395 }
396 #endif
397 #endif
398
399 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
400 {
401         struct wake_q_node *node = &task->wake_q;
402
403         /*
404          * Atomically grab the task, if ->wake_q is !nil already it means
405          * its already queued (either by us or someone else) and will get the
406          * wakeup due to that.
407          *
408          * In order to ensure that a pending wakeup will observe our pending
409          * state, even in the failed case, an explicit smp_mb() must be used.
410          */
411         smp_mb__before_atomic();
412         if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
413                 return false;
414
415         /*
416          * The head is context local, there can be no concurrency.
417          */
418         *head->lastp = node;
419         head->lastp = &node->next;
420         return true;
421 }
422
423 /**
424  * wake_q_add() - queue a wakeup for 'later' waking.
425  * @head: the wake_q_head to add @task to
426  * @task: the task to queue for 'later' wakeup
427  *
428  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
429  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
430  * instantly.
431  *
432  * This function must be used as-if it were wake_up_process(); IOW the task
433  * must be ready to be woken at this location.
434  */
435 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
436 {
437         if (__wake_q_add(head, task))
438                 get_task_struct(task);
439 }
440
441 /**
442  * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
443  * @head: the wake_q_head to add @task to
444  * @task: the task to queue for 'later' wakeup
445  *
446  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
447  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
448  * instantly.
449  *
450  * This function must be used as-if it were wake_up_process(); IOW the task
451  * must be ready to be woken at this location.
452  *
453  * This function is essentially a task-safe equivalent to wake_q_add(). Callers
454  * that already hold reference to @task can call the 'safe' version and trust
455  * wake_q to do the right thing depending whether or not the @task is already
456  * queued for wakeup.
457  */
458 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
459 {
460         if (!__wake_q_add(head, task))
461                 put_task_struct(task);
462 }
463
464 void wake_up_q(struct wake_q_head *head)
465 {
466         struct wake_q_node *node = head->first;
467
468         while (node != WAKE_Q_TAIL) {
469                 struct task_struct *task;
470
471                 task = container_of(node, struct task_struct, wake_q);
472                 BUG_ON(!task);
473                 /* Task can safely be re-inserted now: */
474                 node = node->next;
475                 task->wake_q.next = NULL;
476
477                 /*
478                  * wake_up_process() executes a full barrier, which pairs with
479                  * the queueing in wake_q_add() so as not to miss wakeups.
480                  */
481                 wake_up_process(task);
482                 put_task_struct(task);
483         }
484 }
485
486 /*
487  * resched_curr - mark rq's current task 'to be rescheduled now'.
488  *
489  * On UP this means the setting of the need_resched flag, on SMP it
490  * might also involve a cross-CPU call to trigger the scheduler on
491  * the target CPU.
492  */
493 void resched_curr(struct rq *rq)
494 {
495         struct task_struct *curr = rq->curr;
496         int cpu;
497
498         lockdep_assert_held(&rq->lock);
499
500         if (test_tsk_need_resched(curr))
501                 return;
502
503         cpu = cpu_of(rq);
504
505         if (cpu == smp_processor_id()) {
506                 set_tsk_need_resched(curr);
507                 set_preempt_need_resched();
508                 return;
509         }
510
511         if (set_nr_and_not_polling(curr))
512                 smp_send_reschedule(cpu);
513         else
514                 trace_sched_wake_idle_without_ipi(cpu);
515 }
516
517 void resched_cpu(int cpu)
518 {
519         struct rq *rq = cpu_rq(cpu);
520         unsigned long flags;
521
522         raw_spin_lock_irqsave(&rq->lock, flags);
523         if (cpu_online(cpu) || cpu == smp_processor_id())
524                 resched_curr(rq);
525         raw_spin_unlock_irqrestore(&rq->lock, flags);
526 }
527
528 #ifdef CONFIG_SMP
529 #ifdef CONFIG_NO_HZ_COMMON
530 /*
531  * In the semi idle case, use the nearest busy CPU for migrating timers
532  * from an idle CPU.  This is good for power-savings.
533  *
534  * We don't do similar optimization for completely idle system, as
535  * selecting an idle CPU will add more delays to the timers than intended
536  * (as that CPU's timer base may not be uptodate wrt jiffies etc).
537  */
538 int get_nohz_timer_target(void)
539 {
540         int i, cpu = smp_processor_id();
541         struct sched_domain *sd;
542
543         if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
544                 return cpu;
545
546         rcu_read_lock();
547         for_each_domain(cpu, sd) {
548                 for_each_cpu(i, sched_domain_span(sd)) {
549                         if (cpu == i)
550                                 continue;
551
552                         if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
553                                 cpu = i;
554                                 goto unlock;
555                         }
556                 }
557         }
558
559         if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
560                 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
561 unlock:
562         rcu_read_unlock();
563         return cpu;
564 }
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 (!(atomic_read(nohz_flags(cpu)) & NOHZ_KICK_MASK))
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         atomic_andnot(NOHZ_KICK_MASK, 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 #endif /* CONFIG_SMP */
687
688 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
689                         (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
690 /*
691  * Iterate task_group tree rooted at *from, calling @down when first entering a
692  * node and @up when leaving it for the final time.
693  *
694  * Caller must hold rcu_lock or sufficient equivalent.
695  */
696 int walk_tg_tree_from(struct task_group *from,
697                              tg_visitor down, tg_visitor up, void *data)
698 {
699         struct task_group *parent, *child;
700         int ret;
701
702         parent = from;
703
704 down:
705         ret = (*down)(parent, data);
706         if (ret)
707                 goto out;
708         list_for_each_entry_rcu(child, &parent->children, siblings) {
709                 parent = child;
710                 goto down;
711
712 up:
713                 continue;
714         }
715         ret = (*up)(parent, data);
716         if (ret || parent == from)
717                 goto out;
718
719         child = parent;
720         parent = parent->parent;
721         if (parent)
722                 goto up;
723 out:
724         return ret;
725 }
726
727 int tg_nop(struct task_group *tg, void *data)
728 {
729         return 0;
730 }
731 #endif
732
733 static void set_load_weight(struct task_struct *p, bool update_load)
734 {
735         int prio = p->static_prio - MAX_RT_PRIO;
736         struct load_weight *load = &p->se.load;
737
738         /*
739          * SCHED_IDLE tasks get minimal weight:
740          */
741         if (task_has_idle_policy(p)) {
742                 load->weight = scale_load(WEIGHT_IDLEPRIO);
743                 load->inv_weight = WMULT_IDLEPRIO;
744                 p->se.runnable_weight = load->weight;
745                 return;
746         }
747
748         /*
749          * SCHED_OTHER tasks have to update their load when changing their
750          * weight
751          */
752         if (update_load && p->sched_class == &fair_sched_class) {
753                 reweight_task(p, prio);
754         } else {
755                 load->weight = scale_load(sched_prio_to_weight[prio]);
756                 load->inv_weight = sched_prio_to_wmult[prio];
757                 p->se.runnable_weight = load->weight;
758         }
759 }
760
761 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
762 {
763         if (!(flags & ENQUEUE_NOCLOCK))
764                 update_rq_clock(rq);
765
766         if (!(flags & ENQUEUE_RESTORE)) {
767                 sched_info_queued(rq, p);
768                 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
769         }
770
771         p->sched_class->enqueue_task(rq, p, flags);
772 }
773
774 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
775 {
776         if (!(flags & DEQUEUE_NOCLOCK))
777                 update_rq_clock(rq);
778
779         if (!(flags & DEQUEUE_SAVE)) {
780                 sched_info_dequeued(rq, p);
781                 psi_dequeue(p, flags & DEQUEUE_SLEEP);
782         }
783
784         p->sched_class->dequeue_task(rq, p, flags);
785 }
786
787 void activate_task(struct rq *rq, struct task_struct *p, int flags)
788 {
789         if (task_contributes_to_load(p))
790                 rq->nr_uninterruptible--;
791
792         enqueue_task(rq, p, flags);
793 }
794
795 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
796 {
797         if (task_contributes_to_load(p))
798                 rq->nr_uninterruptible++;
799
800         dequeue_task(rq, p, flags);
801 }
802
803 /*
804  * __normal_prio - return the priority that is based on the static prio
805  */
806 static inline int __normal_prio(struct task_struct *p)
807 {
808         return p->static_prio;
809 }
810
811 /*
812  * Calculate the expected normal priority: i.e. priority
813  * without taking RT-inheritance into account. Might be
814  * boosted by interactivity modifiers. Changes upon fork,
815  * setprio syscalls, and whenever the interactivity
816  * estimator recalculates.
817  */
818 static inline int normal_prio(struct task_struct *p)
819 {
820         int prio;
821
822         if (task_has_dl_policy(p))
823                 prio = MAX_DL_PRIO-1;
824         else if (task_has_rt_policy(p))
825                 prio = MAX_RT_PRIO-1 - p->rt_priority;
826         else
827                 prio = __normal_prio(p);
828         return prio;
829 }
830
831 /*
832  * Calculate the current priority, i.e. the priority
833  * taken into account by the scheduler. This value might
834  * be boosted by RT tasks, or might be boosted by
835  * interactivity modifiers. Will be RT if the task got
836  * RT-boosted. If not then it returns p->normal_prio.
837  */
838 static int effective_prio(struct task_struct *p)
839 {
840         p->normal_prio = normal_prio(p);
841         /*
842          * If we are RT tasks or we were boosted to RT priority,
843          * keep the priority unchanged. Otherwise, update priority
844          * to the normal priority:
845          */
846         if (!rt_prio(p->prio))
847                 return p->normal_prio;
848         return p->prio;
849 }
850
851 /**
852  * task_curr - is this task currently executing on a CPU?
853  * @p: the task in question.
854  *
855  * Return: 1 if the task is currently executing. 0 otherwise.
856  */
857 inline int task_curr(const struct task_struct *p)
858 {
859         return cpu_curr(task_cpu(p)) == p;
860 }
861
862 /*
863  * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
864  * use the balance_callback list if you want balancing.
865  *
866  * this means any call to check_class_changed() must be followed by a call to
867  * balance_callback().
868  */
869 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
870                                        const struct sched_class *prev_class,
871                                        int oldprio)
872 {
873         if (prev_class != p->sched_class) {
874                 if (prev_class->switched_from)
875                         prev_class->switched_from(rq, p);
876
877                 p->sched_class->switched_to(rq, p);
878         } else if (oldprio != p->prio || dl_task(p))
879                 p->sched_class->prio_changed(rq, p, oldprio);
880 }
881
882 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
883 {
884         const struct sched_class *class;
885
886         if (p->sched_class == rq->curr->sched_class) {
887                 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
888         } else {
889                 for_each_class(class) {
890                         if (class == rq->curr->sched_class)
891                                 break;
892                         if (class == p->sched_class) {
893                                 resched_curr(rq);
894                                 break;
895                         }
896                 }
897         }
898
899         /*
900          * A queue event has occurred, and we're going to schedule.  In
901          * this case, we can save a useless back to back clock update.
902          */
903         if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
904                 rq_clock_skip_update(rq);
905 }
906
907 #ifdef CONFIG_SMP
908
909 static inline bool is_per_cpu_kthread(struct task_struct *p)
910 {
911         if (!(p->flags & PF_KTHREAD))
912                 return false;
913
914         if (p->nr_cpus_allowed != 1)
915                 return false;
916
917         return true;
918 }
919
920 /*
921  * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
922  * __set_cpus_allowed_ptr() and select_fallback_rq().
923  */
924 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
925 {
926         if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
927                 return false;
928
929         if (is_per_cpu_kthread(p))
930                 return cpu_online(cpu);
931
932         return cpu_active(cpu);
933 }
934
935 /*
936  * This is how migration works:
937  *
938  * 1) we invoke migration_cpu_stop() on the target CPU using
939  *    stop_one_cpu().
940  * 2) stopper starts to run (implicitly forcing the migrated thread
941  *    off the CPU)
942  * 3) it checks whether the migrated task is still in the wrong runqueue.
943  * 4) if it's in the wrong runqueue then the migration thread removes
944  *    it and puts it into the right queue.
945  * 5) stopper completes and stop_one_cpu() returns and the migration
946  *    is done.
947  */
948
949 /*
950  * move_queued_task - move a queued task to new rq.
951  *
952  * Returns (locked) new rq. Old rq's lock is released.
953  */
954 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
955                                    struct task_struct *p, int new_cpu)
956 {
957         lockdep_assert_held(&rq->lock);
958
959         p->on_rq = TASK_ON_RQ_MIGRATING;
960         dequeue_task(rq, p, DEQUEUE_NOCLOCK);
961         set_task_cpu(p, new_cpu);
962         rq_unlock(rq, rf);
963
964         rq = cpu_rq(new_cpu);
965
966         rq_lock(rq, rf);
967         BUG_ON(task_cpu(p) != new_cpu);
968         enqueue_task(rq, p, 0);
969         p->on_rq = TASK_ON_RQ_QUEUED;
970         check_preempt_curr(rq, p, 0);
971
972         return rq;
973 }
974
975 struct migration_arg {
976         struct task_struct *task;
977         int dest_cpu;
978 };
979
980 /*
981  * Move (not current) task off this CPU, onto the destination CPU. We're doing
982  * this because either it can't run here any more (set_cpus_allowed()
983  * away from this CPU, or CPU going down), or because we're
984  * attempting to rebalance this task on exec (sched_exec).
985  *
986  * So we race with normal scheduler movements, but that's OK, as long
987  * as the task is no longer on this CPU.
988  */
989 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
990                                  struct task_struct *p, int dest_cpu)
991 {
992         /* Affinity changed (again). */
993         if (!is_cpu_allowed(p, dest_cpu))
994                 return rq;
995
996         update_rq_clock(rq);
997         rq = move_queued_task(rq, rf, p, dest_cpu);
998
999         return rq;
1000 }
1001
1002 /*
1003  * migration_cpu_stop - this will be executed by a highprio stopper thread
1004  * and performs thread migration by bumping thread off CPU then
1005  * 'pushing' onto another runqueue.
1006  */
1007 static int migration_cpu_stop(void *data)
1008 {
1009         struct migration_arg *arg = data;
1010         struct task_struct *p = arg->task;
1011         struct rq *rq = this_rq();
1012         struct rq_flags rf;
1013
1014         /*
1015          * The original target CPU might have gone down and we might
1016          * be on another CPU but it doesn't matter.
1017          */
1018         local_irq_disable();
1019         /*
1020          * We need to explicitly wake pending tasks before running
1021          * __migrate_task() such that we will not miss enforcing cpus_allowed
1022          * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1023          */
1024         sched_ttwu_pending();
1025
1026         raw_spin_lock(&p->pi_lock);
1027         rq_lock(rq, &rf);
1028         /*
1029          * If task_rq(p) != rq, it cannot be migrated here, because we're
1030          * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1031          * we're holding p->pi_lock.
1032          */
1033         if (task_rq(p) == rq) {
1034                 if (task_on_rq_queued(p))
1035                         rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1036                 else
1037                         p->wake_cpu = arg->dest_cpu;
1038         }
1039         rq_unlock(rq, &rf);
1040         raw_spin_unlock(&p->pi_lock);
1041
1042         local_irq_enable();
1043         return 0;
1044 }
1045
1046 /*
1047  * sched_class::set_cpus_allowed must do the below, but is not required to
1048  * actually call this function.
1049  */
1050 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1051 {
1052         cpumask_copy(&p->cpus_allowed, new_mask);
1053         p->nr_cpus_allowed = cpumask_weight(new_mask);
1054 }
1055
1056 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1057 {
1058         struct rq *rq = task_rq(p);
1059         bool queued, running;
1060
1061         lockdep_assert_held(&p->pi_lock);
1062
1063         queued = task_on_rq_queued(p);
1064         running = task_current(rq, p);
1065
1066         if (queued) {
1067                 /*
1068                  * Because __kthread_bind() calls this on blocked tasks without
1069                  * holding rq->lock.
1070                  */
1071                 lockdep_assert_held(&rq->lock);
1072                 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1073         }
1074         if (running)
1075                 put_prev_task(rq, p);
1076
1077         p->sched_class->set_cpus_allowed(p, new_mask);
1078
1079         if (queued)
1080                 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1081         if (running)
1082                 set_curr_task(rq, p);
1083 }
1084
1085 /*
1086  * Change a given task's CPU affinity. Migrate the thread to a
1087  * proper CPU and schedule it away if the CPU it's executing on
1088  * is removed from the allowed bitmask.
1089  *
1090  * NOTE: the caller must have a valid reference to the task, the
1091  * task must not exit() & deallocate itself prematurely. The
1092  * call is not atomic; no spinlocks may be held.
1093  */
1094 static int __set_cpus_allowed_ptr(struct task_struct *p,
1095                                   const struct cpumask *new_mask, bool check)
1096 {
1097         const struct cpumask *cpu_valid_mask = cpu_active_mask;
1098         unsigned int dest_cpu;
1099         struct rq_flags rf;
1100         struct rq *rq;
1101         int ret = 0;
1102
1103         rq = task_rq_lock(p, &rf);
1104         update_rq_clock(rq);
1105
1106         if (p->flags & PF_KTHREAD) {
1107                 /*
1108                  * Kernel threads are allowed on online && !active CPUs
1109                  */
1110                 cpu_valid_mask = cpu_online_mask;
1111         }
1112
1113         /*
1114          * Must re-check here, to close a race against __kthread_bind(),
1115          * sched_setaffinity() is not guaranteed to observe the flag.
1116          */
1117         if (check && (p->flags & PF_NO_SETAFFINITY)) {
1118                 ret = -EINVAL;
1119                 goto out;
1120         }
1121
1122         if (cpumask_equal(&p->cpus_allowed, new_mask))
1123                 goto out;
1124
1125         if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1126                 ret = -EINVAL;
1127                 goto out;
1128         }
1129
1130         do_set_cpus_allowed(p, new_mask);
1131
1132         if (p->flags & PF_KTHREAD) {
1133                 /*
1134                  * For kernel threads that do indeed end up on online &&
1135                  * !active we want to ensure they are strict per-CPU threads.
1136                  */
1137                 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1138                         !cpumask_intersects(new_mask, cpu_active_mask) &&
1139                         p->nr_cpus_allowed != 1);
1140         }
1141
1142         /* Can the task run on the task's current CPU? If so, we're done */
1143         if (cpumask_test_cpu(task_cpu(p), new_mask))
1144                 goto out;
1145
1146         dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1147         if (task_running(rq, p) || p->state == TASK_WAKING) {
1148                 struct migration_arg arg = { p, dest_cpu };
1149                 /* Need help from migration thread: drop lock and wait. */
1150                 task_rq_unlock(rq, p, &rf);
1151                 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1152                 tlb_migrate_finish(p->mm);
1153                 return 0;
1154         } else if (task_on_rq_queued(p)) {
1155                 /*
1156                  * OK, since we're going to drop the lock immediately
1157                  * afterwards anyway.
1158                  */
1159                 rq = move_queued_task(rq, &rf, p, dest_cpu);
1160         }
1161 out:
1162         task_rq_unlock(rq, p, &rf);
1163
1164         return ret;
1165 }
1166
1167 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1168 {
1169         return __set_cpus_allowed_ptr(p, new_mask, false);
1170 }
1171 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1172
1173 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1174 {
1175 #ifdef CONFIG_SCHED_DEBUG
1176         /*
1177          * We should never call set_task_cpu() on a blocked task,
1178          * ttwu() will sort out the placement.
1179          */
1180         WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1181                         !p->on_rq);
1182
1183         /*
1184          * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1185          * because schedstat_wait_{start,end} rebase migrating task's wait_start
1186          * time relying on p->on_rq.
1187          */
1188         WARN_ON_ONCE(p->state == TASK_RUNNING &&
1189                      p->sched_class == &fair_sched_class &&
1190                      (p->on_rq && !task_on_rq_migrating(p)));
1191
1192 #ifdef CONFIG_LOCKDEP
1193         /*
1194          * The caller should hold either p->pi_lock or rq->lock, when changing
1195          * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1196          *
1197          * sched_move_task() holds both and thus holding either pins the cgroup,
1198          * see task_group().
1199          *
1200          * Furthermore, all task_rq users should acquire both locks, see
1201          * task_rq_lock().
1202          */
1203         WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1204                                       lockdep_is_held(&task_rq(p)->lock)));
1205 #endif
1206         /*
1207          * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1208          */
1209         WARN_ON_ONCE(!cpu_online(new_cpu));
1210 #endif
1211
1212         trace_sched_migrate_task(p, new_cpu);
1213
1214         if (task_cpu(p) != new_cpu) {
1215                 if (p->sched_class->migrate_task_rq)
1216                         p->sched_class->migrate_task_rq(p, new_cpu);
1217                 p->se.nr_migrations++;
1218                 rseq_migrate(p);
1219                 perf_event_task_migrate(p);
1220         }
1221
1222         __set_task_cpu(p, new_cpu);
1223 }
1224
1225 #ifdef CONFIG_NUMA_BALANCING
1226 static void __migrate_swap_task(struct task_struct *p, int cpu)
1227 {
1228         if (task_on_rq_queued(p)) {
1229                 struct rq *src_rq, *dst_rq;
1230                 struct rq_flags srf, drf;
1231
1232                 src_rq = task_rq(p);
1233                 dst_rq = cpu_rq(cpu);
1234
1235                 rq_pin_lock(src_rq, &srf);
1236                 rq_pin_lock(dst_rq, &drf);
1237
1238                 p->on_rq = TASK_ON_RQ_MIGRATING;
1239                 deactivate_task(src_rq, p, 0);
1240                 set_task_cpu(p, cpu);
1241                 activate_task(dst_rq, p, 0);
1242                 p->on_rq = TASK_ON_RQ_QUEUED;
1243                 check_preempt_curr(dst_rq, p, 0);
1244
1245                 rq_unpin_lock(dst_rq, &drf);
1246                 rq_unpin_lock(src_rq, &srf);
1247
1248         } else {
1249                 /*
1250                  * Task isn't running anymore; make it appear like we migrated
1251                  * it before it went to sleep. This means on wakeup we make the
1252                  * previous CPU our target instead of where it really is.
1253                  */
1254                 p->wake_cpu = cpu;
1255         }
1256 }
1257
1258 struct migration_swap_arg {
1259         struct task_struct *src_task, *dst_task;
1260         int src_cpu, dst_cpu;
1261 };
1262
1263 static int migrate_swap_stop(void *data)
1264 {
1265         struct migration_swap_arg *arg = data;
1266         struct rq *src_rq, *dst_rq;
1267         int ret = -EAGAIN;
1268
1269         if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1270                 return -EAGAIN;
1271
1272         src_rq = cpu_rq(arg->src_cpu);
1273         dst_rq = cpu_rq(arg->dst_cpu);
1274
1275         double_raw_lock(&arg->src_task->pi_lock,
1276                         &arg->dst_task->pi_lock);
1277         double_rq_lock(src_rq, dst_rq);
1278
1279         if (task_cpu(arg->dst_task) != arg->dst_cpu)
1280                 goto unlock;
1281
1282         if (task_cpu(arg->src_task) != arg->src_cpu)
1283                 goto unlock;
1284
1285         if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1286                 goto unlock;
1287
1288         if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1289                 goto unlock;
1290
1291         __migrate_swap_task(arg->src_task, arg->dst_cpu);
1292         __migrate_swap_task(arg->dst_task, arg->src_cpu);
1293
1294         ret = 0;
1295
1296 unlock:
1297         double_rq_unlock(src_rq, dst_rq);
1298         raw_spin_unlock(&arg->dst_task->pi_lock);
1299         raw_spin_unlock(&arg->src_task->pi_lock);
1300
1301         return ret;
1302 }
1303
1304 /*
1305  * Cross migrate two tasks
1306  */
1307 int migrate_swap(struct task_struct *cur, struct task_struct *p,
1308                 int target_cpu, int curr_cpu)
1309 {
1310         struct migration_swap_arg arg;
1311         int ret = -EINVAL;
1312
1313         arg = (struct migration_swap_arg){
1314                 .src_task = cur,
1315                 .src_cpu = curr_cpu,
1316                 .dst_task = p,
1317                 .dst_cpu = target_cpu,
1318         };
1319
1320         if (arg.src_cpu == arg.dst_cpu)
1321                 goto out;
1322
1323         /*
1324          * These three tests are all lockless; this is OK since all of them
1325          * will be re-checked with proper locks held further down the line.
1326          */
1327         if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1328                 goto out;
1329
1330         if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1331                 goto out;
1332
1333         if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1334                 goto out;
1335
1336         trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1337         ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1338
1339 out:
1340         return ret;
1341 }
1342 #endif /* CONFIG_NUMA_BALANCING */
1343
1344 /*
1345  * wait_task_inactive - wait for a thread to unschedule.
1346  *
1347  * If @match_state is nonzero, it's the @p->state value just checked and
1348  * not expected to change.  If it changes, i.e. @p might have woken up,
1349  * then return zero.  When we succeed in waiting for @p to be off its CPU,
1350  * we return a positive number (its total switch count).  If a second call
1351  * a short while later returns the same number, the caller can be sure that
1352  * @p has remained unscheduled the whole time.
1353  *
1354  * The caller must ensure that the task *will* unschedule sometime soon,
1355  * else this function might spin for a *long* time. This function can't
1356  * be called with interrupts off, or it may introduce deadlock with
1357  * smp_call_function() if an IPI is sent by the same process we are
1358  * waiting to become inactive.
1359  */
1360 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1361 {
1362         int running, queued;
1363         struct rq_flags rf;
1364         unsigned long ncsw;
1365         struct rq *rq;
1366
1367         for (;;) {
1368                 /*
1369                  * We do the initial early heuristics without holding
1370                  * any task-queue locks at all. We'll only try to get
1371                  * the runqueue lock when things look like they will
1372                  * work out!
1373                  */
1374                 rq = task_rq(p);
1375
1376                 /*
1377                  * If the task is actively running on another CPU
1378                  * still, just relax and busy-wait without holding
1379                  * any locks.
1380                  *
1381                  * NOTE! Since we don't hold any locks, it's not
1382                  * even sure that "rq" stays as the right runqueue!
1383                  * But we don't care, since "task_running()" will
1384                  * return false if the runqueue has changed and p
1385                  * is actually now running somewhere else!
1386                  */
1387                 while (task_running(rq, p)) {
1388                         if (match_state && unlikely(p->state != match_state))
1389                                 return 0;
1390                         cpu_relax();
1391                 }
1392
1393                 /*
1394                  * Ok, time to look more closely! We need the rq
1395                  * lock now, to be *sure*. If we're wrong, we'll
1396                  * just go back and repeat.
1397                  */
1398                 rq = task_rq_lock(p, &rf);
1399                 trace_sched_wait_task(p);
1400                 running = task_running(rq, p);
1401                 queued = task_on_rq_queued(p);
1402                 ncsw = 0;
1403                 if (!match_state || p->state == match_state)
1404                         ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1405                 task_rq_unlock(rq, p, &rf);
1406
1407                 /*
1408                  * If it changed from the expected state, bail out now.
1409                  */
1410                 if (unlikely(!ncsw))
1411                         break;
1412
1413                 /*
1414                  * Was it really running after all now that we
1415                  * checked with the proper locks actually held?
1416                  *
1417                  * Oops. Go back and try again..
1418                  */
1419                 if (unlikely(running)) {
1420                         cpu_relax();
1421                         continue;
1422                 }
1423
1424                 /*
1425                  * It's not enough that it's not actively running,
1426                  * it must be off the runqueue _entirely_, and not
1427                  * preempted!
1428                  *
1429                  * So if it was still runnable (but just not actively
1430                  * running right now), it's preempted, and we should
1431                  * yield - it could be a while.
1432                  */
1433                 if (unlikely(queued)) {
1434                         ktime_t to = NSEC_PER_SEC / HZ;
1435
1436                         set_current_state(TASK_UNINTERRUPTIBLE);
1437                         schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1438                         continue;
1439                 }
1440
1441                 /*
1442                  * Ahh, all good. It wasn't running, and it wasn't
1443                  * runnable, which means that it will never become
1444                  * running in the future either. We're all done!
1445                  */
1446                 break;
1447         }
1448
1449         return ncsw;
1450 }
1451
1452 /***
1453  * kick_process - kick a running thread to enter/exit the kernel
1454  * @p: the to-be-kicked thread
1455  *
1456  * Cause a process which is running on another CPU to enter
1457  * kernel-mode, without any delay. (to get signals handled.)
1458  *
1459  * NOTE: this function doesn't have to take the runqueue lock,
1460  * because all it wants to ensure is that the remote task enters
1461  * the kernel. If the IPI races and the task has been migrated
1462  * to another CPU then no harm is done and the purpose has been
1463  * achieved as well.
1464  */
1465 void kick_process(struct task_struct *p)
1466 {
1467         int cpu;
1468
1469         preempt_disable();
1470         cpu = task_cpu(p);
1471         if ((cpu != smp_processor_id()) && task_curr(p))
1472                 smp_send_reschedule(cpu);
1473         preempt_enable();
1474 }
1475 EXPORT_SYMBOL_GPL(kick_process);
1476
1477 /*
1478  * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1479  *
1480  * A few notes on cpu_active vs cpu_online:
1481  *
1482  *  - cpu_active must be a subset of cpu_online
1483  *
1484  *  - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
1485  *    see __set_cpus_allowed_ptr(). At this point the newly online
1486  *    CPU isn't yet part of the sched domains, and balancing will not
1487  *    see it.
1488  *
1489  *  - on CPU-down we clear cpu_active() to mask the sched domains and
1490  *    avoid the load balancer to place new tasks on the to be removed
1491  *    CPU. Existing tasks will remain running there and will be taken
1492  *    off.
1493  *
1494  * This means that fallback selection must not select !active CPUs.
1495  * And can assume that any active CPU must be online. Conversely
1496  * select_task_rq() below may allow selection of !active CPUs in order
1497  * to satisfy the above rules.
1498  */
1499 static int select_fallback_rq(int cpu, struct task_struct *p)
1500 {
1501         int nid = cpu_to_node(cpu);
1502         const struct cpumask *nodemask = NULL;
1503         enum { cpuset, possible, fail } state = cpuset;
1504         int dest_cpu;
1505
1506         /*
1507          * If the node that the CPU is on has been offlined, cpu_to_node()
1508          * will return -1. There is no CPU on the node, and we should
1509          * select the CPU on the other node.
1510          */
1511         if (nid != -1) {
1512                 nodemask = cpumask_of_node(nid);
1513
1514                 /* Look for allowed, online CPU in same node. */
1515                 for_each_cpu(dest_cpu, nodemask) {
1516                         if (!cpu_active(dest_cpu))
1517                                 continue;
1518                         if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
1519                                 return dest_cpu;
1520                 }
1521         }
1522
1523         for (;;) {
1524                 /* Any allowed, online CPU? */
1525                 for_each_cpu(dest_cpu, &p->cpus_allowed) {
1526                         if (!is_cpu_allowed(p, dest_cpu))
1527                                 continue;
1528
1529                         goto out;
1530                 }
1531
1532                 /* No more Mr. Nice Guy. */
1533                 switch (state) {
1534                 case cpuset:
1535                         if (IS_ENABLED(CONFIG_CPUSETS)) {
1536                                 cpuset_cpus_allowed_fallback(p);
1537                                 state = possible;
1538                                 break;
1539                         }
1540                         /* Fall-through */
1541                 case possible:
1542                         do_set_cpus_allowed(p, cpu_possible_mask);
1543                         state = fail;
1544                         break;
1545
1546                 case fail:
1547                         BUG();
1548                         break;
1549                 }
1550         }
1551
1552 out:
1553         if (state != cpuset) {
1554                 /*
1555                  * Don't tell them about moving exiting tasks or
1556                  * kernel threads (both mm NULL), since they never
1557                  * leave kernel.
1558                  */
1559                 if (p->mm && printk_ratelimit()) {
1560                         printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1561                                         task_pid_nr(p), p->comm, cpu);
1562                 }
1563         }
1564
1565         return dest_cpu;
1566 }
1567
1568 /*
1569  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1570  */
1571 static inline
1572 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1573 {
1574         lockdep_assert_held(&p->pi_lock);
1575
1576         if (p->nr_cpus_allowed > 1)
1577                 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1578         else
1579                 cpu = cpumask_any(&p->cpus_allowed);
1580
1581         /*
1582          * In order not to call set_task_cpu() on a blocking task we need
1583          * to rely on ttwu() to place the task on a valid ->cpus_allowed
1584          * CPU.
1585          *
1586          * Since this is common to all placement strategies, this lives here.
1587          *
1588          * [ this allows ->select_task() to simply return task_cpu(p) and
1589          *   not worry about this generic constraint ]
1590          */
1591         if (unlikely(!is_cpu_allowed(p, cpu)))
1592                 cpu = select_fallback_rq(task_cpu(p), p);
1593
1594         return cpu;
1595 }
1596
1597 static void update_avg(u64 *avg, u64 sample)
1598 {
1599         s64 diff = sample - *avg;
1600         *avg += diff >> 3;
1601 }
1602
1603 void sched_set_stop_task(int cpu, struct task_struct *stop)
1604 {
1605         struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1606         struct task_struct *old_stop = cpu_rq(cpu)->stop;
1607
1608         if (stop) {
1609                 /*
1610                  * Make it appear like a SCHED_FIFO task, its something
1611                  * userspace knows about and won't get confused about.
1612                  *
1613                  * Also, it will make PI more or less work without too
1614                  * much confusion -- but then, stop work should not
1615                  * rely on PI working anyway.
1616                  */
1617                 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1618
1619                 stop->sched_class = &stop_sched_class;
1620         }
1621
1622         cpu_rq(cpu)->stop = stop;
1623
1624         if (old_stop) {
1625                 /*
1626                  * Reset it back to a normal scheduling class so that
1627                  * it can die in pieces.
1628                  */
1629                 old_stop->sched_class = &rt_sched_class;
1630         }
1631 }
1632
1633 #else
1634
1635 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1636                                          const struct cpumask *new_mask, bool check)
1637 {
1638         return set_cpus_allowed_ptr(p, new_mask);
1639 }
1640
1641 #endif /* CONFIG_SMP */
1642
1643 static void
1644 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1645 {
1646         struct rq *rq;
1647
1648         if (!schedstat_enabled())
1649                 return;
1650
1651         rq = this_rq();
1652
1653 #ifdef CONFIG_SMP
1654         if (cpu == rq->cpu) {
1655                 __schedstat_inc(rq->ttwu_local);
1656                 __schedstat_inc(p->se.statistics.nr_wakeups_local);
1657         } else {
1658                 struct sched_domain *sd;
1659
1660                 __schedstat_inc(p->se.statistics.nr_wakeups_remote);
1661                 rcu_read_lock();
1662                 for_each_domain(rq->cpu, sd) {
1663                         if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1664                                 __schedstat_inc(sd->ttwu_wake_remote);
1665                                 break;
1666                         }
1667                 }
1668                 rcu_read_unlock();
1669         }
1670
1671         if (wake_flags & WF_MIGRATED)
1672                 __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1673 #endif /* CONFIG_SMP */
1674
1675         __schedstat_inc(rq->ttwu_count);
1676         __schedstat_inc(p->se.statistics.nr_wakeups);
1677
1678         if (wake_flags & WF_SYNC)
1679                 __schedstat_inc(p->se.statistics.nr_wakeups_sync);
1680 }
1681
1682 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1683 {
1684         activate_task(rq, p, en_flags);
1685         p->on_rq = TASK_ON_RQ_QUEUED;
1686
1687         /* If a worker is waking up, notify the workqueue: */
1688         if (p->flags & PF_WQ_WORKER)
1689                 wq_worker_waking_up(p, cpu_of(rq));
1690 }
1691
1692 /*
1693  * Mark the task runnable and perform wakeup-preemption.
1694  */
1695 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1696                            struct rq_flags *rf)
1697 {
1698         check_preempt_curr(rq, p, wake_flags);
1699         p->state = TASK_RUNNING;
1700         trace_sched_wakeup(p);
1701
1702 #ifdef CONFIG_SMP
1703         if (p->sched_class->task_woken) {
1704                 /*
1705                  * Our task @p is fully woken up and running; so its safe to
1706                  * drop the rq->lock, hereafter rq is only used for statistics.
1707                  */
1708                 rq_unpin_lock(rq, rf);
1709                 p->sched_class->task_woken(rq, p);
1710                 rq_repin_lock(rq, rf);
1711         }
1712
1713         if (rq->idle_stamp) {
1714                 u64 delta = rq_clock(rq) - rq->idle_stamp;
1715                 u64 max = 2*rq->max_idle_balance_cost;
1716
1717                 update_avg(&rq->avg_idle, delta);
1718
1719                 if (rq->avg_idle > max)
1720                         rq->avg_idle = max;
1721
1722                 rq->idle_stamp = 0;
1723         }
1724 #endif
1725 }
1726
1727 static void
1728 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1729                  struct rq_flags *rf)
1730 {
1731         int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
1732
1733         lockdep_assert_held(&rq->lock);
1734
1735 #ifdef CONFIG_SMP
1736         if (p->sched_contributes_to_load)
1737                 rq->nr_uninterruptible--;
1738
1739         if (wake_flags & WF_MIGRATED)
1740                 en_flags |= ENQUEUE_MIGRATED;
1741 #endif
1742
1743         ttwu_activate(rq, p, en_flags);
1744         ttwu_do_wakeup(rq, p, wake_flags, rf);
1745 }
1746
1747 /*
1748  * Called in case the task @p isn't fully descheduled from its runqueue,
1749  * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1750  * since all we need to do is flip p->state to TASK_RUNNING, since
1751  * the task is still ->on_rq.
1752  */
1753 static int ttwu_remote(struct task_struct *p, int wake_flags)
1754 {
1755         struct rq_flags rf;
1756         struct rq *rq;
1757         int ret = 0;
1758
1759         rq = __task_rq_lock(p, &rf);
1760         if (task_on_rq_queued(p)) {
1761                 /* check_preempt_curr() may use rq clock */
1762                 update_rq_clock(rq);
1763                 ttwu_do_wakeup(rq, p, wake_flags, &rf);
1764                 ret = 1;
1765         }
1766         __task_rq_unlock(rq, &rf);
1767
1768         return ret;
1769 }
1770
1771 #ifdef CONFIG_SMP
1772 void sched_ttwu_pending(void)
1773 {
1774         struct rq *rq = this_rq();
1775         struct llist_node *llist = llist_del_all(&rq->wake_list);
1776         struct task_struct *p, *t;
1777         struct rq_flags rf;
1778
1779         if (!llist)
1780                 return;
1781
1782         rq_lock_irqsave(rq, &rf);
1783         update_rq_clock(rq);
1784
1785         llist_for_each_entry_safe(p, t, llist, wake_entry)
1786                 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
1787
1788         rq_unlock_irqrestore(rq, &rf);
1789 }
1790
1791 void scheduler_ipi(void)
1792 {
1793         /*
1794          * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1795          * TIF_NEED_RESCHED remotely (for the first time) will also send
1796          * this IPI.
1797          */
1798         preempt_fold_need_resched();
1799
1800         if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1801                 return;
1802
1803         /*
1804          * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1805          * traditionally all their work was done from the interrupt return
1806          * path. Now that we actually do some work, we need to make sure
1807          * we do call them.
1808          *
1809          * Some archs already do call them, luckily irq_enter/exit nest
1810          * properly.
1811          *
1812          * Arguably we should visit all archs and update all handlers,
1813          * however a fair share of IPIs are still resched only so this would
1814          * somewhat pessimize the simple resched case.
1815          */
1816         irq_enter();
1817         sched_ttwu_pending();
1818
1819         /*
1820          * Check if someone kicked us for doing the nohz idle load balance.
1821          */
1822         if (unlikely(got_nohz_idle_kick())) {
1823                 this_rq()->idle_balance = 1;
1824                 raise_softirq_irqoff(SCHED_SOFTIRQ);
1825         }
1826         irq_exit();
1827 }
1828
1829 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1830 {
1831         struct rq *rq = cpu_rq(cpu);
1832
1833         p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1834
1835         if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1836                 if (!set_nr_if_polling(rq->idle))
1837                         smp_send_reschedule(cpu);
1838                 else
1839                         trace_sched_wake_idle_without_ipi(cpu);
1840         }
1841 }
1842
1843 void wake_up_if_idle(int cpu)
1844 {
1845         struct rq *rq = cpu_rq(cpu);
1846         struct rq_flags rf;
1847
1848         rcu_read_lock();
1849
1850         if (!is_idle_task(rcu_dereference(rq->curr)))
1851                 goto out;
1852
1853         if (set_nr_if_polling(rq->idle)) {
1854                 trace_sched_wake_idle_without_ipi(cpu);
1855         } else {
1856                 rq_lock_irqsave(rq, &rf);
1857                 if (is_idle_task(rq->curr))
1858                         smp_send_reschedule(cpu);
1859                 /* Else CPU is not idle, do nothing here: */
1860                 rq_unlock_irqrestore(rq, &rf);
1861         }
1862
1863 out:
1864         rcu_read_unlock();
1865 }
1866
1867 bool cpus_share_cache(int this_cpu, int that_cpu)
1868 {
1869         return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1870 }
1871 #endif /* CONFIG_SMP */
1872
1873 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1874 {
1875         struct rq *rq = cpu_rq(cpu);
1876         struct rq_flags rf;
1877
1878 #if defined(CONFIG_SMP)
1879         if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1880                 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
1881                 ttwu_queue_remote(p, cpu, wake_flags);
1882                 return;
1883         }
1884 #endif
1885
1886         rq_lock(rq, &rf);
1887         update_rq_clock(rq);
1888         ttwu_do_activate(rq, p, wake_flags, &rf);
1889         rq_unlock(rq, &rf);
1890 }
1891
1892 /*
1893  * Notes on Program-Order guarantees on SMP systems.
1894  *
1895  *  MIGRATION
1896  *
1897  * The basic program-order guarantee on SMP systems is that when a task [t]
1898  * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1899  * execution on its new CPU [c1].
1900  *
1901  * For migration (of runnable tasks) this is provided by the following means:
1902  *
1903  *  A) UNLOCK of the rq(c0)->lock scheduling out task t
1904  *  B) migration for t is required to synchronize *both* rq(c0)->lock and
1905  *     rq(c1)->lock (if not at the same time, then in that order).
1906  *  C) LOCK of the rq(c1)->lock scheduling in task
1907  *
1908  * Release/acquire chaining guarantees that B happens after A and C after B.
1909  * Note: the CPU doing B need not be c0 or c1
1910  *
1911  * Example:
1912  *
1913  *   CPU0            CPU1            CPU2
1914  *
1915  *   LOCK rq(0)->lock
1916  *   sched-out X
1917  *   sched-in Y
1918  *   UNLOCK rq(0)->lock
1919  *
1920  *                                   LOCK rq(0)->lock // orders against CPU0
1921  *                                   dequeue X
1922  *                                   UNLOCK rq(0)->lock
1923  *
1924  *                                   LOCK rq(1)->lock
1925  *                                   enqueue X
1926  *                                   UNLOCK rq(1)->lock
1927  *
1928  *                   LOCK rq(1)->lock // orders against CPU2
1929  *                   sched-out Z
1930  *                   sched-in X
1931  *                   UNLOCK rq(1)->lock
1932  *
1933  *
1934  *  BLOCKING -- aka. SLEEP + WAKEUP
1935  *
1936  * For blocking we (obviously) need to provide the same guarantee as for
1937  * migration. However the means are completely different as there is no lock
1938  * chain to provide order. Instead we do:
1939  *
1940  *   1) smp_store_release(X->on_cpu, 0)
1941  *   2) smp_cond_load_acquire(!X->on_cpu)
1942  *
1943  * Example:
1944  *
1945  *   CPU0 (schedule)  CPU1 (try_to_wake_up) CPU2 (schedule)
1946  *
1947  *   LOCK rq(0)->lock LOCK X->pi_lock
1948  *   dequeue X
1949  *   sched-out X
1950  *   smp_store_release(X->on_cpu, 0);
1951  *
1952  *                    smp_cond_load_acquire(&X->on_cpu, !VAL);
1953  *                    X->state = WAKING
1954  *                    set_task_cpu(X,2)
1955  *
1956  *                    LOCK rq(2)->lock
1957  *                    enqueue X
1958  *                    X->state = RUNNING
1959  *                    UNLOCK rq(2)->lock
1960  *
1961  *                                          LOCK rq(2)->lock // orders against CPU1
1962  *                                          sched-out Z
1963  *                                          sched-in X
1964  *                                          UNLOCK rq(2)->lock
1965  *
1966  *                    UNLOCK X->pi_lock
1967  *   UNLOCK rq(0)->lock
1968  *
1969  *
1970  * However, for wakeups there is a second guarantee we must provide, namely we
1971  * must ensure that CONDITION=1 done by the caller can not be reordered with
1972  * accesses to the task state; see try_to_wake_up() and set_current_state().
1973  */
1974
1975 /**
1976  * try_to_wake_up - wake up a thread
1977  * @p: the thread to be awakened
1978  * @state: the mask of task states that can be woken
1979  * @wake_flags: wake modifier flags (WF_*)
1980  *
1981  * If (@state & @p->state) @p->state = TASK_RUNNING.
1982  *
1983  * If the task was not queued/runnable, also place it back on a runqueue.
1984  *
1985  * Atomic against schedule() which would dequeue a task, also see
1986  * set_current_state().
1987  *
1988  * This function executes a full memory barrier before accessing the task
1989  * state; see set_current_state().
1990  *
1991  * Return: %true if @p->state changes (an actual wakeup was done),
1992  *         %false otherwise.
1993  */
1994 static int
1995 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1996 {
1997         unsigned long flags;
1998         int cpu, success = 0;
1999
2000         /*
2001          * If we are going to wake up a thread waiting for CONDITION we
2002          * need to ensure that CONDITION=1 done by the caller can not be
2003          * reordered with p->state check below. This pairs with mb() in
2004          * set_current_state() the waiting thread does.
2005          */
2006         raw_spin_lock_irqsave(&p->pi_lock, flags);
2007         smp_mb__after_spinlock();
2008         if (!(p->state & state))
2009                 goto out;
2010
2011         trace_sched_waking(p);
2012
2013         /* We're going to change ->state: */
2014         success = 1;
2015         cpu = task_cpu(p);
2016
2017         /*
2018          * Ensure we load p->on_rq _after_ p->state, otherwise it would
2019          * be possible to, falsely, observe p->on_rq == 0 and get stuck
2020          * in smp_cond_load_acquire() below.
2021          *
2022          * sched_ttwu_pending()                 try_to_wake_up()
2023          *   STORE p->on_rq = 1                   LOAD p->state
2024          *   UNLOCK rq->lock
2025          *
2026          * __schedule() (switch to task 'p')
2027          *   LOCK rq->lock                        smp_rmb();
2028          *   smp_mb__after_spinlock();
2029          *   UNLOCK rq->lock
2030          *
2031          * [task p]
2032          *   STORE p->state = UNINTERRUPTIBLE     LOAD p->on_rq
2033          *
2034          * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2035          * __schedule().  See the comment for smp_mb__after_spinlock().
2036          */
2037         smp_rmb();
2038         if (p->on_rq && ttwu_remote(p, wake_flags))
2039                 goto stat;
2040
2041 #ifdef CONFIG_SMP
2042         /*
2043          * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2044          * possible to, falsely, observe p->on_cpu == 0.
2045          *
2046          * One must be running (->on_cpu == 1) in order to remove oneself
2047          * from the runqueue.
2048          *
2049          * __schedule() (switch to task 'p')    try_to_wake_up()
2050          *   STORE p->on_cpu = 1                  LOAD p->on_rq
2051          *   UNLOCK rq->lock
2052          *
2053          * __schedule() (put 'p' to sleep)
2054          *   LOCK rq->lock                        smp_rmb();
2055          *   smp_mb__after_spinlock();
2056          *   STORE p->on_rq = 0                   LOAD p->on_cpu
2057          *
2058          * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2059          * __schedule().  See the comment for smp_mb__after_spinlock().
2060          */
2061         smp_rmb();
2062
2063         /*
2064          * If the owning (remote) CPU is still in the middle of schedule() with
2065          * this task as prev, wait until its done referencing the task.
2066          *
2067          * Pairs with the smp_store_release() in finish_task().
2068          *
2069          * This ensures that tasks getting woken will be fully ordered against
2070          * their previous state and preserve Program Order.
2071          */
2072         smp_cond_load_acquire(&p->on_cpu, !VAL);
2073
2074         p->sched_contributes_to_load = !!task_contributes_to_load(p);
2075         p->state = TASK_WAKING;
2076
2077         if (p->in_iowait) {
2078                 delayacct_blkio_end(p);
2079                 atomic_dec(&task_rq(p)->nr_iowait);
2080         }
2081
2082         cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2083         if (task_cpu(p) != cpu) {
2084                 wake_flags |= WF_MIGRATED;
2085                 psi_ttwu_dequeue(p);
2086                 set_task_cpu(p, cpu);
2087         }
2088
2089 #else /* CONFIG_SMP */
2090
2091         if (p->in_iowait) {
2092                 delayacct_blkio_end(p);
2093                 atomic_dec(&task_rq(p)->nr_iowait);
2094         }
2095
2096 #endif /* CONFIG_SMP */
2097
2098         ttwu_queue(p, cpu, wake_flags);
2099 stat:
2100         ttwu_stat(p, cpu, wake_flags);
2101 out:
2102         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2103
2104         return success;
2105 }
2106
2107 /**
2108  * try_to_wake_up_local - try to wake up a local task with rq lock held
2109  * @p: the thread to be awakened
2110  * @rf: request-queue flags for pinning
2111  *
2112  * Put @p on the run-queue if it's not already there. The caller must
2113  * ensure that this_rq() is locked, @p is bound to this_rq() and not
2114  * the current task.
2115  */
2116 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2117 {
2118         struct rq *rq = task_rq(p);
2119
2120         if (WARN_ON_ONCE(rq != this_rq()) ||
2121             WARN_ON_ONCE(p == current))
2122                 return;
2123
2124         lockdep_assert_held(&rq->lock);
2125
2126         if (!raw_spin_trylock(&p->pi_lock)) {
2127                 /*
2128                  * This is OK, because current is on_cpu, which avoids it being
2129                  * picked for load-balance and preemption/IRQs are still
2130                  * disabled avoiding further scheduler activity on it and we've
2131                  * not yet picked a replacement task.
2132                  */
2133                 rq_unlock(rq, rf);
2134                 raw_spin_lock(&p->pi_lock);
2135                 rq_relock(rq, rf);
2136         }
2137
2138         if (!(p->state & TASK_NORMAL))
2139                 goto out;
2140
2141         trace_sched_waking(p);
2142
2143         if (!task_on_rq_queued(p)) {
2144                 if (p->in_iowait) {
2145                         delayacct_blkio_end(p);
2146                         atomic_dec(&rq->nr_iowait);
2147                 }
2148                 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
2149         }
2150
2151         ttwu_do_wakeup(rq, p, 0, rf);
2152         ttwu_stat(p, smp_processor_id(), 0);
2153 out:
2154         raw_spin_unlock(&p->pi_lock);
2155 }
2156
2157 /**
2158  * wake_up_process - Wake up a specific process
2159  * @p: The process to be woken up.
2160  *
2161  * Attempt to wake up the nominated process and move it to the set of runnable
2162  * processes.
2163  *
2164  * Return: 1 if the process was woken up, 0 if it was already running.
2165  *
2166  * This function executes a full memory barrier before accessing the task state.
2167  */
2168 int wake_up_process(struct task_struct *p)
2169 {
2170         return try_to_wake_up(p, TASK_NORMAL, 0);
2171 }
2172 EXPORT_SYMBOL(wake_up_process);
2173
2174 int wake_up_state(struct task_struct *p, unsigned int state)
2175 {
2176         return try_to_wake_up(p, state, 0);
2177 }
2178
2179 /*
2180  * Perform scheduler related setup for a newly forked process p.
2181  * p is forked by current.
2182  *
2183  * __sched_fork() is basic setup used by init_idle() too:
2184  */
2185 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2186 {
2187         p->on_rq                        = 0;
2188
2189         p->se.on_rq                     = 0;
2190         p->se.exec_start                = 0;
2191         p->se.sum_exec_runtime          = 0;
2192         p->se.prev_sum_exec_runtime     = 0;
2193         p->se.nr_migrations             = 0;
2194         p->se.vruntime                  = 0;
2195         INIT_LIST_HEAD(&p->se.group_node);
2196
2197 #ifdef CONFIG_FAIR_GROUP_SCHED
2198         p->se.cfs_rq                    = NULL;
2199 #endif
2200
2201 #ifdef CONFIG_SCHEDSTATS
2202         /* Even if schedstat is disabled, there should not be garbage */
2203         memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2204 #endif
2205
2206         RB_CLEAR_NODE(&p->dl.rb_node);
2207         init_dl_task_timer(&p->dl);
2208         init_dl_inactive_task_timer(&p->dl);
2209         __dl_clear_params(p);
2210
2211         INIT_LIST_HEAD(&p->rt.run_list);
2212         p->rt.timeout           = 0;
2213         p->rt.time_slice        = sched_rr_timeslice;
2214         p->rt.on_rq             = 0;
2215         p->rt.on_list           = 0;
2216
2217 #ifdef CONFIG_PREEMPT_NOTIFIERS
2218         INIT_HLIST_HEAD(&p->preempt_notifiers);
2219 #endif
2220
2221         init_numa_balancing(clone_flags, p);
2222 }
2223
2224 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2225
2226 #ifdef CONFIG_NUMA_BALANCING
2227
2228 void set_numabalancing_state(bool enabled)
2229 {
2230         if (enabled)
2231                 static_branch_enable(&sched_numa_balancing);
2232         else
2233                 static_branch_disable(&sched_numa_balancing);
2234 }
2235
2236 #ifdef CONFIG_PROC_SYSCTL
2237 int sysctl_numa_balancing(struct ctl_table *table, int write,
2238                          void __user *buffer, size_t *lenp, loff_t *ppos)
2239 {
2240         struct ctl_table t;
2241         int err;
2242         int state = static_branch_likely(&sched_numa_balancing);
2243
2244         if (write && !capable(CAP_SYS_ADMIN))
2245                 return -EPERM;
2246
2247         t = *table;
2248         t.data = &state;
2249         err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2250         if (err < 0)
2251                 return err;
2252         if (write)
2253                 set_numabalancing_state(state);
2254         return err;
2255 }
2256 #endif
2257 #endif
2258
2259 #ifdef CONFIG_SCHEDSTATS
2260
2261 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2262 static bool __initdata __sched_schedstats = false;
2263
2264 static void set_schedstats(bool enabled)
2265 {
2266         if (enabled)
2267                 static_branch_enable(&sched_schedstats);
2268         else
2269                 static_branch_disable(&sched_schedstats);
2270 }
2271
2272 void force_schedstat_enabled(void)
2273 {
2274         if (!schedstat_enabled()) {
2275                 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2276                 static_branch_enable(&sched_schedstats);
2277         }
2278 }
2279
2280 static int __init setup_schedstats(char *str)
2281 {
2282         int ret = 0;
2283         if (!str)
2284                 goto out;
2285
2286         /*
2287          * This code is called before jump labels have been set up, so we can't
2288          * change the static branch directly just yet.  Instead set a temporary
2289          * variable so init_schedstats() can do it later.
2290          */
2291         if (!strcmp(str, "enable")) {
2292                 __sched_schedstats = true;
2293                 ret = 1;
2294         } else if (!strcmp(str, "disable")) {
2295                 __sched_schedstats = false;
2296                 ret = 1;
2297         }
2298 out:
2299         if (!ret)
2300                 pr_warn("Unable to parse schedstats=\n");
2301
2302         return ret;
2303 }
2304 __setup("schedstats=", setup_schedstats);
2305
2306 static void __init init_schedstats(void)
2307 {
2308         set_schedstats(__sched_schedstats);
2309 }
2310
2311 #ifdef CONFIG_PROC_SYSCTL
2312 int sysctl_schedstats(struct ctl_table *table, int write,
2313                          void __user *buffer, size_t *lenp, loff_t *ppos)
2314 {
2315         struct ctl_table t;
2316         int err;
2317         int state = static_branch_likely(&sched_schedstats);
2318
2319         if (write && !capable(CAP_SYS_ADMIN))
2320                 return -EPERM;
2321
2322         t = *table;
2323         t.data = &state;
2324         err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2325         if (err < 0)
2326                 return err;
2327         if (write)
2328                 set_schedstats(state);
2329         return err;
2330 }
2331 #endif /* CONFIG_PROC_SYSCTL */
2332 #else  /* !CONFIG_SCHEDSTATS */
2333 static inline void init_schedstats(void) {}
2334 #endif /* CONFIG_SCHEDSTATS */
2335
2336 /*
2337  * fork()/clone()-time setup:
2338  */
2339 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2340 {
2341         unsigned long flags;
2342
2343         __sched_fork(clone_flags, p);
2344         /*
2345          * We mark the process as NEW here. This guarantees that
2346          * nobody will actually run it, and a signal or other external
2347          * event cannot wake it up and insert it on the runqueue either.
2348          */
2349         p->state = TASK_NEW;
2350
2351         /*
2352          * Make sure we do not leak PI boosting priority to the child.
2353          */
2354         p->prio = current->normal_prio;
2355
2356         /*
2357          * Revert to default priority/policy on fork if requested.
2358          */
2359         if (unlikely(p->sched_reset_on_fork)) {
2360                 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2361                         p->policy = SCHED_NORMAL;
2362                         p->static_prio = NICE_TO_PRIO(0);
2363                         p->rt_priority = 0;
2364                 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2365                         p->static_prio = NICE_TO_PRIO(0);
2366
2367                 p->prio = p->normal_prio = __normal_prio(p);
2368                 set_load_weight(p, false);
2369
2370                 /*
2371                  * We don't need the reset flag anymore after the fork. It has
2372                  * fulfilled its duty:
2373                  */
2374                 p->sched_reset_on_fork = 0;
2375         }
2376
2377         if (dl_prio(p->prio))
2378                 return -EAGAIN;
2379         else if (rt_prio(p->prio))
2380                 p->sched_class = &rt_sched_class;
2381         else
2382                 p->sched_class = &fair_sched_class;
2383
2384         init_entity_runnable_average(&p->se);
2385
2386         /*
2387          * The child is not yet in the pid-hash so no cgroup attach races,
2388          * and the cgroup is pinned to this child due to cgroup_fork()
2389          * is ran before sched_fork().
2390          *
2391          * Silence PROVE_RCU.
2392          */
2393         raw_spin_lock_irqsave(&p->pi_lock, flags);
2394         /*
2395          * We're setting the CPU for the first time, we don't migrate,
2396          * so use __set_task_cpu().
2397          */
2398         __set_task_cpu(p, smp_processor_id());
2399         if (p->sched_class->task_fork)
2400                 p->sched_class->task_fork(p);
2401         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2402
2403 #ifdef CONFIG_SCHED_INFO
2404         if (likely(sched_info_on()))
2405                 memset(&p->sched_info, 0, sizeof(p->sched_info));
2406 #endif
2407 #if defined(CONFIG_SMP)
2408         p->on_cpu = 0;
2409 #endif
2410         init_task_preempt_count(p);
2411 #ifdef CONFIG_SMP
2412         plist_node_init(&p->pushable_tasks, MAX_PRIO);
2413         RB_CLEAR_NODE(&p->pushable_dl_tasks);
2414 #endif
2415         return 0;
2416 }
2417
2418 unsigned long to_ratio(u64 period, u64 runtime)
2419 {
2420         if (runtime == RUNTIME_INF)
2421                 return BW_UNIT;
2422
2423         /*
2424          * Doing this here saves a lot of checks in all
2425          * the calling paths, and returning zero seems
2426          * safe for them anyway.
2427          */
2428         if (period == 0)
2429                 return 0;
2430
2431         return div64_u64(runtime << BW_SHIFT, period);
2432 }
2433
2434 /*
2435  * wake_up_new_task - wake up a newly created task for the first time.
2436  *
2437  * This function will do some initial scheduler statistics housekeeping
2438  * that must be done for every newly created context, then puts the task
2439  * on the runqueue and wakes it.
2440  */
2441 void wake_up_new_task(struct task_struct *p)
2442 {
2443         struct rq_flags rf;
2444         struct rq *rq;
2445
2446         raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2447         p->state = TASK_RUNNING;
2448 #ifdef CONFIG_SMP
2449         /*
2450          * Fork balancing, do it here and not earlier because:
2451          *  - cpus_allowed can change in the fork path
2452          *  - any previously selected CPU might disappear through hotplug
2453          *
2454          * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2455          * as we're not fully set-up yet.
2456          */
2457         p->recent_used_cpu = task_cpu(p);
2458         __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2459 #endif
2460         rq = __task_rq_lock(p, &rf);
2461         update_rq_clock(rq);
2462         post_init_entity_util_avg(&p->se);
2463
2464         activate_task(rq, p, ENQUEUE_NOCLOCK);
2465         p->on_rq = TASK_ON_RQ_QUEUED;
2466         trace_sched_wakeup_new(p);
2467         check_preempt_curr(rq, p, WF_FORK);
2468 #ifdef CONFIG_SMP
2469         if (p->sched_class->task_woken) {
2470                 /*
2471                  * Nothing relies on rq->lock after this, so its fine to
2472                  * drop it.
2473                  */
2474                 rq_unpin_lock(rq, &rf);
2475                 p->sched_class->task_woken(rq, p);
2476                 rq_repin_lock(rq, &rf);
2477         }
2478 #endif
2479         task_rq_unlock(rq, p, &rf);
2480 }
2481
2482 #ifdef CONFIG_PREEMPT_NOTIFIERS
2483
2484 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
2485
2486 void preempt_notifier_inc(void)
2487 {
2488         static_branch_inc(&preempt_notifier_key);
2489 }
2490 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2491
2492 void preempt_notifier_dec(void)
2493 {
2494         static_branch_dec(&preempt_notifier_key);
2495 }
2496 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2497
2498 /**
2499  * preempt_notifier_register - tell me when current is being preempted & rescheduled
2500  * @notifier: notifier struct to register
2501  */
2502 void preempt_notifier_register(struct preempt_notifier *notifier)
2503 {
2504         if (!static_branch_unlikely(&preempt_notifier_key))
2505                 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2506
2507         hlist_add_head(&notifier->link, &current->preempt_notifiers);
2508 }
2509 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2510
2511 /**
2512  * preempt_notifier_unregister - no longer interested in preemption notifications
2513  * @notifier: notifier struct to unregister
2514  *
2515  * This is *not* safe to call from within a preemption notifier.
2516  */
2517 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2518 {
2519         hlist_del(&notifier->link);
2520 }
2521 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2522
2523 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2524 {
2525         struct preempt_notifier *notifier;
2526
2527         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2528                 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2529 }
2530
2531 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2532 {
2533         if (static_branch_unlikely(&preempt_notifier_key))
2534                 __fire_sched_in_preempt_notifiers(curr);
2535 }
2536
2537 static void
2538 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2539                                    struct task_struct *next)
2540 {
2541         struct preempt_notifier *notifier;
2542
2543         hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2544                 notifier->ops->sched_out(notifier, next);
2545 }
2546
2547 static __always_inline void
2548 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2549                                  struct task_struct *next)
2550 {
2551         if (static_branch_unlikely(&preempt_notifier_key))
2552                 __fire_sched_out_preempt_notifiers(curr, next);
2553 }
2554
2555 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2556
2557 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2558 {
2559 }
2560
2561 static inline void
2562 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2563                                  struct task_struct *next)
2564 {
2565 }
2566
2567 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2568
2569 static inline void prepare_task(struct task_struct *next)
2570 {
2571 #ifdef CONFIG_SMP
2572         /*
2573          * Claim the task as running, we do this before switching to it
2574          * such that any running task will have this set.
2575          */
2576         next->on_cpu = 1;
2577 #endif
2578 }
2579
2580 static inline void finish_task(struct task_struct *prev)
2581 {
2582 #ifdef CONFIG_SMP
2583         /*
2584          * After ->on_cpu is cleared, the task can be moved to a different CPU.
2585          * We must ensure this doesn't happen until the switch is completely
2586          * finished.
2587          *
2588          * In particular, the load of prev->state in finish_task_switch() must
2589          * happen before this.
2590          *
2591          * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
2592          */
2593         smp_store_release(&prev->on_cpu, 0);
2594 #endif
2595 }
2596
2597 static inline void
2598 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
2599 {
2600         /*
2601          * Since the runqueue lock will be released by the next
2602          * task (which is an invalid locking op but in the case
2603          * of the scheduler it's an obvious special-case), so we
2604          * do an early lockdep release here:
2605          */
2606         rq_unpin_lock(rq, rf);
2607         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2608 #ifdef CONFIG_DEBUG_SPINLOCK
2609         /* this is a valid case when another task releases the spinlock */
2610         rq->lock.owner = next;
2611 #endif
2612 }
2613
2614 static inline void finish_lock_switch(struct rq *rq)
2615 {
2616         /*
2617          * If we are tracking spinlock dependencies then we have to
2618          * fix up the runqueue lock - which gets 'carried over' from
2619          * prev into current:
2620          */
2621         spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
2622         raw_spin_unlock_irq(&rq->lock);
2623 }
2624
2625 /*
2626  * NOP if the arch has not defined these:
2627  */
2628
2629 #ifndef prepare_arch_switch
2630 # define prepare_arch_switch(next)      do { } while (0)
2631 #endif
2632
2633 #ifndef finish_arch_post_lock_switch
2634 # define finish_arch_post_lock_switch() do { } while (0)
2635 #endif
2636
2637 /**
2638  * prepare_task_switch - prepare to switch tasks
2639  * @rq: the runqueue preparing to switch
2640  * @prev: the current task that is being switched out
2641  * @next: the task we are going to switch to.
2642  *
2643  * This is called with the rq lock held and interrupts off. It must
2644  * be paired with a subsequent finish_task_switch after the context
2645  * switch.
2646  *
2647  * prepare_task_switch sets up locking and calls architecture specific
2648  * hooks.
2649  */
2650 static inline void
2651 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2652                     struct task_struct *next)
2653 {
2654         kcov_prepare_switch(prev);
2655         sched_info_switch(rq, prev, next);
2656         perf_event_task_sched_out(prev, next);
2657         rseq_preempt(prev);
2658         fire_sched_out_preempt_notifiers(prev, next);
2659         prepare_task(next);
2660         prepare_arch_switch(next);
2661 }
2662
2663 /**
2664  * finish_task_switch - clean up after a task-switch
2665  * @prev: the thread we just switched away from.
2666  *
2667  * finish_task_switch must be called after the context switch, paired
2668  * with a prepare_task_switch call before the context switch.
2669  * finish_task_switch will reconcile locking set up by prepare_task_switch,
2670  * and do any other architecture-specific cleanup actions.
2671  *
2672  * Note that we may have delayed dropping an mm in context_switch(). If
2673  * so, we finish that here outside of the runqueue lock. (Doing it
2674  * with the lock held can cause deadlocks; see schedule() for
2675  * details.)
2676  *
2677  * The context switch have flipped the stack from under us and restored the
2678  * local variables which were saved when this task called schedule() in the
2679  * past. prev == current is still correct but we need to recalculate this_rq
2680  * because prev may have moved to another CPU.
2681  */
2682 static struct rq *finish_task_switch(struct task_struct *prev)
2683         __releases(rq->lock)
2684 {
2685         struct rq *rq = this_rq();
2686         struct mm_struct *mm = rq->prev_mm;
2687         long prev_state;
2688
2689         /*
2690          * The previous task will have left us with a preempt_count of 2
2691          * because it left us after:
2692          *
2693          *      schedule()
2694          *        preempt_disable();                    // 1
2695          *        __schedule()
2696          *          raw_spin_lock_irq(&rq->lock)        // 2
2697          *
2698          * Also, see FORK_PREEMPT_COUNT.
2699          */
2700         if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2701                       "corrupted preempt_count: %s/%d/0x%x\n",
2702                       current->comm, current->pid, preempt_count()))
2703                 preempt_count_set(FORK_PREEMPT_COUNT);
2704
2705         rq->prev_mm = NULL;
2706
2707         /*
2708          * A task struct has one reference for the use as "current".
2709          * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2710          * schedule one last time. The schedule call will never return, and
2711          * the scheduled task must drop that reference.
2712          *
2713          * We must observe prev->state before clearing prev->on_cpu (in
2714          * finish_task), otherwise a concurrent wakeup can get prev
2715          * running on another CPU and we could rave with its RUNNING -> DEAD
2716          * transition, resulting in a double drop.
2717          */
2718         prev_state = prev->state;
2719         vtime_task_switch(prev);
2720         perf_event_task_sched_in(prev, current);
2721         finish_task(prev);
2722         finish_lock_switch(rq);
2723         finish_arch_post_lock_switch();
2724         kcov_finish_switch(current);
2725
2726         fire_sched_in_preempt_notifiers(current);
2727         /*
2728          * When switching through a kernel thread, the loop in
2729          * membarrier_{private,global}_expedited() may have observed that
2730          * kernel thread and not issued an IPI. It is therefore possible to
2731          * schedule between user->kernel->user threads without passing though
2732          * switch_mm(). Membarrier requires a barrier after storing to
2733          * rq->curr, before returning to userspace, so provide them here:
2734          *
2735          * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
2736          *   provided by mmdrop(),
2737          * - a sync_core for SYNC_CORE.
2738          */
2739         if (mm) {
2740                 membarrier_mm_sync_core_before_usermode(mm);
2741                 mmdrop(mm);
2742         }
2743         if (unlikely(prev_state == TASK_DEAD)) {
2744                 if (prev->sched_class->task_dead)
2745                         prev->sched_class->task_dead(prev);
2746
2747                 /*
2748                  * Remove function-return probe instances associated with this
2749                  * task and put them back on the free list.
2750                  */
2751                 kprobe_flush_task(prev);
2752
2753                 /* Task is done with its stack. */
2754                 put_task_stack(prev);
2755
2756                 put_task_struct(prev);
2757         }
2758
2759         tick_nohz_task_switch();
2760         return rq;
2761 }
2762
2763 #ifdef CONFIG_SMP
2764
2765 /* rq->lock is NOT held, but preemption is disabled */
2766 static void __balance_callback(struct rq *rq)
2767 {
2768         struct callback_head *head, *next;
2769         void (*func)(struct rq *rq);
2770         unsigned long flags;
2771
2772         raw_spin_lock_irqsave(&rq->lock, flags);
2773         head = rq->balance_callback;
2774         rq->balance_callback = NULL;
2775         while (head) {
2776                 func = (void (*)(struct rq *))head->func;
2777                 next = head->next;
2778                 head->next = NULL;
2779                 head = next;
2780
2781                 func(rq);
2782         }
2783         raw_spin_unlock_irqrestore(&rq->lock, flags);
2784 }
2785
2786 static inline void balance_callback(struct rq *rq)
2787 {
2788         if (unlikely(rq->balance_callback))
2789                 __balance_callback(rq);
2790 }
2791
2792 #else
2793
2794 static inline void balance_callback(struct rq *rq)
2795 {
2796 }
2797
2798 #endif
2799
2800 /**
2801  * schedule_tail - first thing a freshly forked thread must call.
2802  * @prev: the thread we just switched away from.
2803  */
2804 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2805         __releases(rq->lock)
2806 {
2807         struct rq *rq;
2808
2809         /*
2810          * New tasks start with FORK_PREEMPT_COUNT, see there and
2811          * finish_task_switch() for details.
2812          *
2813          * finish_task_switch() will drop rq->lock() and lower preempt_count
2814          * and the preempt_enable() will end up enabling preemption (on
2815          * PREEMPT_COUNT kernels).
2816          */
2817
2818         rq = finish_task_switch(prev);
2819         balance_callback(rq);
2820         preempt_enable();
2821
2822         if (current->set_child_tid)
2823                 put_user(task_pid_vnr(current), current->set_child_tid);
2824
2825         calculate_sigpending();
2826 }
2827
2828 /*
2829  * context_switch - switch to the new MM and the new thread's register state.
2830  */
2831 static __always_inline struct rq *
2832 context_switch(struct rq *rq, struct task_struct *prev,
2833                struct task_struct *next, struct rq_flags *rf)
2834 {
2835         struct mm_struct *mm, *oldmm;
2836
2837         prepare_task_switch(rq, prev, next);
2838
2839         mm = next->mm;
2840         oldmm = prev->active_mm;
2841         /*
2842          * For paravirt, this is coupled with an exit in switch_to to
2843          * combine the page table reload and the switch backend into
2844          * one hypercall.
2845          */
2846         arch_start_context_switch(prev);
2847
2848         /*
2849          * If mm is non-NULL, we pass through switch_mm(). If mm is
2850          * NULL, we will pass through mmdrop() in finish_task_switch().
2851          * Both of these contain the full memory barrier required by
2852          * membarrier after storing to rq->curr, before returning to
2853          * user-space.
2854          */
2855         if (!mm) {
2856                 next->active_mm = oldmm;
2857                 mmgrab(oldmm);
2858                 enter_lazy_tlb(oldmm, next);
2859         } else
2860                 switch_mm_irqs_off(oldmm, mm, next);
2861
2862         if (!prev->mm) {
2863                 prev->active_mm = NULL;
2864                 rq->prev_mm = oldmm;
2865         }
2866
2867         rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2868
2869         prepare_lock_switch(rq, next, rf);
2870
2871         /* Here we just switch the register state and the stack. */
2872         switch_to(prev, next, prev);
2873         barrier();
2874
2875         return finish_task_switch(prev);
2876 }
2877
2878 /*
2879  * nr_running and nr_context_switches:
2880  *
2881  * externally visible scheduler statistics: current number of runnable
2882  * threads, total number of context switches performed since bootup.
2883  */
2884 unsigned long nr_running(void)
2885 {
2886         unsigned long i, sum = 0;
2887
2888         for_each_online_cpu(i)
2889                 sum += cpu_rq(i)->nr_running;
2890
2891         return sum;
2892 }
2893
2894 /*
2895  * Check if only the current task is running on the CPU.
2896  *
2897  * Caution: this function does not check that the caller has disabled
2898  * preemption, thus the result might have a time-of-check-to-time-of-use
2899  * race.  The caller is responsible to use it correctly, for example:
2900  *
2901  * - from a non-preemptible section (of course)
2902  *
2903  * - from a thread that is bound to a single CPU
2904  *
2905  * - in a loop with very short iterations (e.g. a polling loop)
2906  */
2907 bool single_task_running(void)
2908 {
2909         return raw_rq()->nr_running == 1;
2910 }
2911 EXPORT_SYMBOL(single_task_running);
2912
2913 unsigned long long nr_context_switches(void)
2914 {
2915         int i;
2916         unsigned long long sum = 0;
2917
2918         for_each_possible_cpu(i)
2919                 sum += cpu_rq(i)->nr_switches;
2920
2921         return sum;
2922 }
2923
2924 /*
2925  * Consumers of these two interfaces, like for example the cpuidle menu
2926  * governor, are using nonsensical data. Preferring shallow idle state selection
2927  * for a CPU that has IO-wait which might not even end up running the task when
2928  * it does become runnable.
2929  */
2930
2931 unsigned long nr_iowait_cpu(int cpu)
2932 {
2933         return atomic_read(&cpu_rq(cpu)->nr_iowait);
2934 }
2935
2936 /*
2937  * IO-wait accounting, and how its mostly bollocks (on SMP).
2938  *
2939  * The idea behind IO-wait account is to account the idle time that we could
2940  * have spend running if it were not for IO. That is, if we were to improve the
2941  * storage performance, we'd have a proportional reduction in IO-wait time.
2942  *
2943  * This all works nicely on UP, where, when a task blocks on IO, we account
2944  * idle time as IO-wait, because if the storage were faster, it could've been
2945  * running and we'd not be idle.
2946  *
2947  * This has been extended to SMP, by doing the same for each CPU. This however
2948  * is broken.
2949  *
2950  * Imagine for instance the case where two tasks block on one CPU, only the one
2951  * CPU will have IO-wait accounted, while the other has regular idle. Even
2952  * though, if the storage were faster, both could've ran at the same time,
2953  * utilising both CPUs.
2954  *
2955  * This means, that when looking globally, the current IO-wait accounting on
2956  * SMP is a lower bound, by reason of under accounting.
2957  *
2958  * Worse, since the numbers are provided per CPU, they are sometimes
2959  * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2960  * associated with any one particular CPU, it can wake to another CPU than it
2961  * blocked on. This means the per CPU IO-wait number is meaningless.
2962  *
2963  * Task CPU affinities can make all that even more 'interesting'.
2964  */
2965
2966 unsigned long nr_iowait(void)
2967 {
2968         unsigned long i, sum = 0;
2969
2970         for_each_possible_cpu(i)
2971                 sum += nr_iowait_cpu(i);
2972
2973         return sum;
2974 }
2975
2976 #ifdef CONFIG_SMP
2977
2978 /*
2979  * sched_exec - execve() is a valuable balancing opportunity, because at
2980  * this point the task has the smallest effective memory and cache footprint.
2981  */
2982 void sched_exec(void)
2983 {
2984         struct task_struct *p = current;
2985         unsigned long flags;
2986         int dest_cpu;
2987
2988         raw_spin_lock_irqsave(&p->pi_lock, flags);
2989         dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2990         if (dest_cpu == smp_processor_id())
2991                 goto unlock;
2992
2993         if (likely(cpu_active(dest_cpu))) {
2994                 struct migration_arg arg = { p, dest_cpu };
2995
2996                 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2997                 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2998                 return;
2999         }
3000 unlock:
3001         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3002 }
3003
3004 #endif
3005
3006 DEFINE_PER_CPU(struct kernel_stat, kstat);
3007 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3008
3009 EXPORT_PER_CPU_SYMBOL(kstat);
3010 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3011
3012 /*
3013  * The function fair_sched_class.update_curr accesses the struct curr
3014  * and its field curr->exec_start; when called from task_sched_runtime(),
3015  * we observe a high rate of cache misses in practice.
3016  * Prefetching this data results in improved performance.
3017  */
3018 static inline void prefetch_curr_exec_start(struct task_struct *p)
3019 {
3020 #ifdef CONFIG_FAIR_GROUP_SCHED
3021         struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3022 #else
3023         struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3024 #endif
3025         prefetch(curr);
3026         prefetch(&curr->exec_start);
3027 }
3028
3029 /*
3030  * Return accounted runtime for the task.
3031  * In case the task is currently running, return the runtime plus current's
3032  * pending runtime that have not been accounted yet.
3033  */
3034 unsigned long long task_sched_runtime(struct task_struct *p)
3035 {
3036         struct rq_flags rf;
3037         struct rq *rq;
3038         u64 ns;
3039
3040 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3041         /*
3042          * 64-bit doesn't need locks to atomically read a 64-bit value.
3043          * So we have a optimization chance when the task's delta_exec is 0.
3044          * Reading ->on_cpu is racy, but this is ok.
3045          *
3046          * If we race with it leaving CPU, we'll take a lock. So we're correct.
3047          * If we race with it entering CPU, unaccounted time is 0. This is
3048          * indistinguishable from the read occurring a few cycles earlier.
3049          * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3050          * been accounted, so we're correct here as well.
3051          */
3052         if (!p->on_cpu || !task_on_rq_queued(p))
3053                 return p->se.sum_exec_runtime;
3054 #endif
3055
3056         rq = task_rq_lock(p, &rf);
3057         /*
3058          * Must be ->curr _and_ ->on_rq.  If dequeued, we would
3059          * project cycles that may never be accounted to this
3060          * thread, breaking clock_gettime().
3061          */
3062         if (task_current(rq, p) && task_on_rq_queued(p)) {
3063                 prefetch_curr_exec_start(p);
3064                 update_rq_clock(rq);
3065                 p->sched_class->update_curr(rq);
3066         }
3067         ns = p->se.sum_exec_runtime;
3068         task_rq_unlock(rq, p, &rf);
3069
3070         return ns;
3071 }
3072
3073 /*
3074  * This function gets called by the timer code, with HZ frequency.
3075  * We call it with interrupts disabled.
3076  */
3077 void scheduler_tick(void)
3078 {
3079         int cpu = smp_processor_id();
3080         struct rq *rq = cpu_rq(cpu);
3081         struct task_struct *curr = rq->curr;
3082         struct rq_flags rf;
3083
3084         sched_clock_tick();
3085
3086         rq_lock(rq, &rf);
3087
3088         update_rq_clock(rq);
3089         curr->sched_class->task_tick(rq, curr, 0);
3090         cpu_load_update_active(rq);
3091         calc_global_load_tick(rq);
3092         psi_task_tick(rq);
3093
3094         rq_unlock(rq, &rf);
3095
3096         perf_event_task_tick();
3097
3098 #ifdef CONFIG_SMP
3099         rq->idle_balance = idle_cpu(cpu);
3100         trigger_load_balance(rq);
3101 #endif
3102 }
3103
3104 #ifdef CONFIG_NO_HZ_FULL
3105
3106 struct tick_work {
3107         int                     cpu;
3108         struct delayed_work     work;
3109 };
3110
3111 static struct tick_work __percpu *tick_work_cpu;
3112
3113 static void sched_tick_remote(struct work_struct *work)
3114 {
3115         struct delayed_work *dwork = to_delayed_work(work);
3116         struct tick_work *twork = container_of(dwork, struct tick_work, work);
3117         int cpu = twork->cpu;
3118         struct rq *rq = cpu_rq(cpu);
3119         struct task_struct *curr;
3120         struct rq_flags rf;
3121         u64 delta;
3122
3123         /*
3124          * Handle the tick only if it appears the remote CPU is running in full
3125          * dynticks mode. The check is racy by nature, but missing a tick or
3126          * having one too much is no big deal because the scheduler tick updates
3127          * statistics and checks timeslices in a time-independent way, regardless
3128          * of when exactly it is running.
3129          */
3130         if (idle_cpu(cpu) || !tick_nohz_tick_stopped_cpu(cpu))
3131                 goto out_requeue;
3132
3133         rq_lock_irq(rq, &rf);
3134         curr = rq->curr;
3135         if (is_idle_task(curr))
3136                 goto out_unlock;
3137
3138         update_rq_clock(rq);
3139         delta = rq_clock_task(rq) - curr->se.exec_start;
3140
3141         /*
3142          * Make sure the next tick runs within a reasonable
3143          * amount of time.
3144          */
3145         WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
3146         curr->sched_class->task_tick(rq, curr, 0);
3147
3148 out_unlock:
3149         rq_unlock_irq(rq, &rf);
3150
3151 out_requeue:
3152         /*
3153          * Run the remote tick once per second (1Hz). This arbitrary
3154          * frequency is large enough to avoid overload but short enough
3155          * to keep scheduler internal stats reasonably up to date.
3156          */
3157         queue_delayed_work(system_unbound_wq, dwork, HZ);
3158 }
3159
3160 static void sched_tick_start(int cpu)
3161 {
3162         struct tick_work *twork;
3163
3164         if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3165                 return;
3166
3167         WARN_ON_ONCE(!tick_work_cpu);
3168
3169         twork = per_cpu_ptr(tick_work_cpu, cpu);
3170         twork->cpu = cpu;
3171         INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
3172         queue_delayed_work(system_unbound_wq, &twork->work, HZ);
3173 }
3174
3175 #ifdef CONFIG_HOTPLUG_CPU
3176 static void sched_tick_stop(int cpu)
3177 {
3178         struct tick_work *twork;
3179
3180         if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3181                 return;
3182
3183         WARN_ON_ONCE(!tick_work_cpu);
3184
3185         twork = per_cpu_ptr(tick_work_cpu, cpu);
3186         cancel_delayed_work_sync(&twork->work);
3187 }
3188 #endif /* CONFIG_HOTPLUG_CPU */
3189
3190 int __init sched_tick_offload_init(void)
3191 {
3192         tick_work_cpu = alloc_percpu(struct tick_work);
3193         BUG_ON(!tick_work_cpu);
3194
3195         return 0;
3196 }
3197
3198 #else /* !CONFIG_NO_HZ_FULL */
3199 static inline void sched_tick_start(int cpu) { }
3200 static inline void sched_tick_stop(int cpu) { }
3201 #endif
3202
3203 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3204                                 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
3205 /*
3206  * If the value passed in is equal to the current preempt count
3207  * then we just disabled preemption. Start timing the latency.
3208  */
3209 static inline void preempt_latency_start(int val)
3210 {
3211         if (preempt_count() == val) {
3212                 unsigned long ip = get_lock_parent_ip();
3213 #ifdef CONFIG_DEBUG_PREEMPT
3214                 current->preempt_disable_ip = ip;
3215 #endif
3216                 trace_preempt_off(CALLER_ADDR0, ip);
3217         }
3218 }
3219
3220 void preempt_count_add(int val)
3221 {
3222 #ifdef CONFIG_DEBUG_PREEMPT
3223         /*
3224          * Underflow?
3225          */
3226         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3227                 return;
3228 #endif
3229         __preempt_count_add(val);
3230 #ifdef CONFIG_DEBUG_PREEMPT
3231         /*
3232          * Spinlock count overflowing soon?
3233          */
3234         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3235                                 PREEMPT_MASK - 10);
3236 #endif
3237         preempt_latency_start(val);
3238 }
3239 EXPORT_SYMBOL(preempt_count_add);
3240 NOKPROBE_SYMBOL(preempt_count_add);
3241
3242 /*
3243  * If the value passed in equals to the current preempt count
3244  * then we just enabled preemption. Stop timing the latency.
3245  */
3246 static inline void preempt_latency_stop(int val)
3247 {
3248         if (preempt_count() == val)
3249                 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3250 }
3251
3252 void preempt_count_sub(int val)
3253 {
3254 #ifdef CONFIG_DEBUG_PREEMPT
3255         /*
3256          * Underflow?
3257          */
3258         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3259                 return;
3260         /*
3261          * Is the spinlock portion underflowing?
3262          */
3263         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3264                         !(preempt_count() & PREEMPT_MASK)))
3265                 return;
3266 #endif
3267
3268         preempt_latency_stop(val);
3269         __preempt_count_sub(val);
3270 }
3271 EXPORT_SYMBOL(preempt_count_sub);
3272 NOKPROBE_SYMBOL(preempt_count_sub);
3273
3274 #else
3275 static inline void preempt_latency_start(int val) { }
3276 static inline void preempt_latency_stop(int val) { }
3277 #endif
3278
3279 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3280 {
3281 #ifdef CONFIG_DEBUG_PREEMPT
3282         return p->preempt_disable_ip;
3283 #else
3284         return 0;
3285 #endif
3286 }
3287
3288 /*
3289  * Print scheduling while atomic bug:
3290  */
3291 static noinline void __schedule_bug(struct task_struct *prev)
3292 {
3293         /* Save this before calling printk(), since that will clobber it */
3294         unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3295
3296         if (oops_in_progress)
3297                 return;
3298
3299         printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3300                 prev->comm, prev->pid, preempt_count());
3301
3302         debug_show_held_locks(prev);
3303         print_modules();
3304         if (irqs_disabled())
3305                 print_irqtrace_events(prev);
3306         if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3307             && in_atomic_preempt_off()) {
3308                 pr_err("Preemption disabled at:");
3309                 print_ip_sym(preempt_disable_ip);
3310                 pr_cont("\n");
3311         }
3312         if (panic_on_warn)
3313                 panic("scheduling while atomic\n");
3314
3315         dump_stack();
3316         add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3317 }
3318
3319 /*
3320  * Various schedule()-time debugging checks and statistics:
3321  */
3322 static inline void schedule_debug(struct task_struct *prev)
3323 {
3324 #ifdef CONFIG_SCHED_STACK_END_CHECK
3325         if (task_stack_end_corrupted(prev))
3326                 panic("corrupted stack end detected inside scheduler\n");
3327 #endif
3328
3329         if (unlikely(in_atomic_preempt_off())) {
3330                 __schedule_bug(prev);
3331                 preempt_count_set(PREEMPT_DISABLED);
3332         }
3333         rcu_sleep_check();
3334
3335         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3336
3337         schedstat_inc(this_rq()->sched_count);
3338 }
3339
3340 /*
3341  * Pick up the highest-prio task:
3342  */
3343 static inline struct task_struct *
3344 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3345 {
3346         const struct sched_class *class;
3347         struct task_struct *p;
3348
3349         /*
3350          * Optimization: we know that if all tasks are in the fair class we can
3351          * call that function directly, but only if the @prev task wasn't of a
3352          * higher scheduling class, because otherwise those loose the
3353          * opportunity to pull in more work from other CPUs.
3354          */
3355         if (likely((prev->sched_class == &idle_sched_class ||
3356                     prev->sched_class == &fair_sched_class) &&
3357                    rq->nr_running == rq->cfs.h_nr_running)) {
3358
3359                 p = fair_sched_class.pick_next_task(rq, prev, rf);
3360                 if (unlikely(p == RETRY_TASK))
3361                         goto again;
3362
3363                 /* Assumes fair_sched_class->next == idle_sched_class */
3364                 if (unlikely(!p))
3365                         p = idle_sched_class.pick_next_task(rq, prev, rf);
3366
3367                 return p;
3368         }
3369
3370 again:
3371         for_each_class(class) {
3372                 p = class->pick_next_task(rq, prev, rf);
3373                 if (p) {
3374                         if (unlikely(p == RETRY_TASK))
3375                                 goto again;
3376                         return p;
3377                 }
3378         }
3379
3380         /* The idle class should always have a runnable task: */
3381         BUG();
3382 }
3383
3384 /*
3385  * __schedule() is the main scheduler function.
3386  *
3387  * The main means of driving the scheduler and thus entering this function are:
3388  *
3389  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3390  *
3391  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3392  *      paths. For example, see arch/x86/entry_64.S.
3393  *
3394  *      To drive preemption between tasks, the scheduler sets the flag in timer
3395  *      interrupt handler scheduler_tick().
3396  *
3397  *   3. Wakeups don't really cause entry into schedule(). They add a
3398  *      task to the run-queue and that's it.
3399  *
3400  *      Now, if the new task added to the run-queue preempts the current
3401  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3402  *      called on the nearest possible occasion:
3403  *
3404  *       - If the kernel is preemptible (CONFIG_PREEMPT=y):
3405  *
3406  *         - in syscall or exception context, at the next outmost
3407  *           preempt_enable(). (this might be as soon as the wake_up()'s
3408  *           spin_unlock()!)
3409  *
3410  *         - in IRQ context, return from interrupt-handler to
3411  *           preemptible context
3412  *
3413  *       - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3414  *         then at the next:
3415  *
3416  *          - cond_resched() call
3417  *          - explicit schedule() call
3418  *          - return from syscall or exception to user-space
3419  *          - return from interrupt-handler to user-space
3420  *
3421  * WARNING: must be called with preemption disabled!
3422  */
3423 static void __sched notrace __schedule(bool preempt)
3424 {
3425         struct task_struct *prev, *next;
3426         unsigned long *switch_count;
3427         struct rq_flags rf;
3428         struct rq *rq;
3429         int cpu;
3430
3431         cpu = smp_processor_id();
3432         rq = cpu_rq(cpu);
3433         prev = rq->curr;
3434
3435         schedule_debug(prev);
3436
3437         if (sched_feat(HRTICK))
3438                 hrtick_clear(rq);
3439
3440         local_irq_disable();
3441         rcu_note_context_switch(preempt);
3442
3443         /*
3444          * Make sure that signal_pending_state()->signal_pending() below
3445          * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3446          * done by the caller to avoid the race with signal_wake_up().
3447          *
3448          * The membarrier system call requires a full memory barrier
3449          * after coming from user-space, before storing to rq->curr.
3450          */
3451         rq_lock(rq, &rf);
3452         smp_mb__after_spinlock();
3453
3454         /* Promote REQ to ACT */
3455         rq->clock_update_flags <<= 1;
3456         update_rq_clock(rq);
3457
3458         switch_count = &prev->nivcsw;
3459         if (!preempt && prev->state) {
3460                 if (signal_pending_state(prev->state, prev)) {
3461                         prev->state = TASK_RUNNING;
3462                 } else {
3463                         deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
3464                         prev->on_rq = 0;
3465
3466                         if (prev->in_iowait) {
3467                                 atomic_inc(&rq->nr_iowait);
3468                                 delayacct_blkio_start();
3469                         }
3470
3471                         /*
3472                          * If a worker went to sleep, notify and ask workqueue
3473                          * whether it wants to wake up a task to maintain
3474                          * concurrency.
3475                          */
3476                         if (prev->flags & PF_WQ_WORKER) {
3477                                 struct task_struct *to_wakeup;
3478
3479                                 to_wakeup = wq_worker_sleeping(prev);
3480                                 if (to_wakeup)
3481                                         try_to_wake_up_local(to_wakeup, &rf);
3482                         }
3483                 }
3484                 switch_count = &prev->nvcsw;
3485         }
3486
3487         next = pick_next_task(rq, prev, &rf);
3488         clear_tsk_need_resched(prev);
3489         clear_preempt_need_resched();
3490
3491         if (likely(prev != next)) {
3492                 rq->nr_switches++;
3493                 rq->curr = next;
3494                 /*
3495                  * The membarrier system call requires each architecture
3496                  * to have a full memory barrier after updating
3497                  * rq->curr, before returning to user-space.
3498                  *
3499                  * Here are the schemes providing that barrier on the
3500                  * various architectures:
3501                  * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
3502                  *   switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
3503                  * - finish_lock_switch() for weakly-ordered
3504                  *   architectures where spin_unlock is a full barrier,
3505                  * - switch_to() for arm64 (weakly-ordered, spin_unlock
3506                  *   is a RELEASE barrier),
3507                  */
3508                 ++*switch_count;
3509
3510                 trace_sched_switch(preempt, prev, next);
3511
3512                 /* Also unlocks the rq: */
3513                 rq = context_switch(rq, prev, next, &rf);
3514         } else {
3515                 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3516                 rq_unlock_irq(rq, &rf);
3517         }
3518
3519         balance_callback(rq);
3520 }
3521
3522 void __noreturn do_task_dead(void)
3523 {
3524         /* Causes final put_task_struct in finish_task_switch(): */
3525         set_special_state(TASK_DEAD);
3526
3527         /* Tell freezer to ignore us: */
3528         current->flags |= PF_NOFREEZE;
3529
3530         __schedule(false);
3531         BUG();
3532
3533         /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3534         for (;;)
3535                 cpu_relax();
3536 }
3537
3538 static inline void sched_submit_work(struct task_struct *tsk)
3539 {
3540         if (!tsk->state || tsk_is_pi_blocked(tsk))
3541                 return;
3542         /*
3543          * If we are going to sleep and we have plugged IO queued,
3544          * make sure to submit it to avoid deadlocks.
3545          */
3546         if (blk_needs_flush_plug(tsk))
3547                 blk_schedule_flush_plug(tsk);
3548 }
3549
3550 asmlinkage __visible void __sched schedule(void)
3551 {
3552         struct task_struct *tsk = current;
3553
3554         sched_submit_work(tsk);
3555         do {
3556                 preempt_disable();
3557                 __schedule(false);
3558                 sched_preempt_enable_no_resched();
3559         } while (need_resched());
3560 }
3561 EXPORT_SYMBOL(schedule);
3562
3563 /*
3564  * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3565  * state (have scheduled out non-voluntarily) by making sure that all
3566  * tasks have either left the run queue or have gone into user space.
3567  * As idle tasks do not do either, they must not ever be preempted
3568  * (schedule out non-voluntarily).
3569  *
3570  * schedule_idle() is similar to schedule_preempt_disable() except that it
3571  * never enables preemption because it does not call sched_submit_work().
3572  */
3573 void __sched schedule_idle(void)
3574 {
3575         /*
3576          * As this skips calling sched_submit_work(), which the idle task does
3577          * regardless because that function is a nop when the task is in a
3578          * TASK_RUNNING state, make sure this isn't used someplace that the
3579          * current task can be in any other state. Note, idle is always in the
3580          * TASK_RUNNING state.
3581          */
3582         WARN_ON_ONCE(current->state);
3583         do {
3584                 __schedule(false);
3585         } while (need_resched());
3586 }
3587
3588 #ifdef CONFIG_CONTEXT_TRACKING
3589 asmlinkage __visible void __sched schedule_user(void)
3590 {
3591         /*
3592          * If we come here after a random call to set_need_resched(),
3593          * or we have been woken up remotely but the IPI has not yet arrived,
3594          * we haven't yet exited the RCU idle mode. Do it here manually until
3595          * we find a better solution.
3596          *
3597          * NB: There are buggy callers of this function.  Ideally we
3598          * should warn if prev_state != CONTEXT_USER, but that will trigger
3599          * too frequently to make sense yet.
3600          */
3601         enum ctx_state prev_state = exception_enter();
3602         schedule();
3603         exception_exit(prev_state);
3604 }
3605 #endif
3606
3607 /**
3608  * schedule_preempt_disabled - called with preemption disabled
3609  *
3610  * Returns with preemption disabled. Note: preempt_count must be 1
3611  */
3612 void __sched schedule_preempt_disabled(void)
3613 {
3614         sched_preempt_enable_no_resched();
3615         schedule();
3616         preempt_disable();
3617 }
3618
3619 static void __sched notrace preempt_schedule_common(void)
3620 {
3621         do {
3622                 /*
3623                  * Because the function tracer can trace preempt_count_sub()
3624                  * and it also uses preempt_enable/disable_notrace(), if
3625                  * NEED_RESCHED is set, the preempt_enable_notrace() called
3626                  * by the function tracer will call this function again and
3627                  * cause infinite recursion.
3628                  *
3629                  * Preemption must be disabled here before the function
3630                  * tracer can trace. Break up preempt_disable() into two
3631                  * calls. One to disable preemption without fear of being
3632                  * traced. The other to still record the preemption latency,
3633                  * which can also be traced by the function tracer.
3634                  */
3635                 preempt_disable_notrace();
3636                 preempt_latency_start(1);
3637                 __schedule(true);
3638                 preempt_latency_stop(1);
3639                 preempt_enable_no_resched_notrace();
3640
3641                 /*
3642                  * Check again in case we missed a preemption opportunity
3643                  * between schedule and now.
3644                  */
3645         } while (need_resched());
3646 }
3647
3648 #ifdef CONFIG_PREEMPT
3649 /*
3650  * this is the entry point to schedule() from in-kernel preemption
3651  * off of preempt_enable. Kernel preemptions off return from interrupt
3652  * occur there and call schedule directly.
3653  */
3654 asmlinkage __visible void __sched notrace preempt_schedule(void)
3655 {
3656         /*
3657          * If there is a non-zero preempt_count or interrupts are disabled,
3658          * we do not want to preempt the current task. Just return..
3659          */
3660         if (likely(!preemptible()))
3661                 return;
3662
3663         preempt_schedule_common();
3664 }
3665 NOKPROBE_SYMBOL(preempt_schedule);
3666 EXPORT_SYMBOL(preempt_schedule);
3667
3668 /**
3669  * preempt_schedule_notrace - preempt_schedule called by tracing
3670  *
3671  * The tracing infrastructure uses preempt_enable_notrace to prevent
3672  * recursion and tracing preempt enabling caused by the tracing
3673  * infrastructure itself. But as tracing can happen in areas coming
3674  * from userspace or just about to enter userspace, a preempt enable
3675  * can occur before user_exit() is called. This will cause the scheduler
3676  * to be called when the system is still in usermode.
3677  *
3678  * To prevent this, the preempt_enable_notrace will use this function
3679  * instead of preempt_schedule() to exit user context if needed before
3680  * calling the scheduler.
3681  */
3682 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3683 {
3684         enum ctx_state prev_ctx;
3685
3686         if (likely(!preemptible()))
3687                 return;
3688
3689         do {
3690                 /*
3691                  * Because the function tracer can trace preempt_count_sub()
3692                  * and it also uses preempt_enable/disable_notrace(), if
3693                  * NEED_RESCHED is set, the preempt_enable_notrace() called
3694                  * by the function tracer will call this function again and
3695                  * cause infinite recursion.
3696                  *
3697                  * Preemption must be disabled here before the function
3698                  * tracer can trace. Break up preempt_disable() into two
3699                  * calls. One to disable preemption without fear of being
3700                  * traced. The other to still record the preemption latency,
3701                  * which can also be traced by the function tracer.
3702                  */
3703                 preempt_disable_notrace();
3704                 preempt_latency_start(1);
3705                 /*
3706                  * Needs preempt disabled in case user_exit() is traced
3707                  * and the tracer calls preempt_enable_notrace() causing
3708                  * an infinite recursion.
3709                  */
3710                 prev_ctx = exception_enter();
3711                 __schedule(true);
3712                 exception_exit(prev_ctx);
3713
3714                 preempt_latency_stop(1);
3715                 preempt_enable_no_resched_notrace();
3716         } while (need_resched());
3717 }
3718 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3719
3720 #endif /* CONFIG_PREEMPT */
3721
3722 /*
3723  * this is the entry point to schedule() from kernel preemption
3724  * off of irq context.
3725  * Note, that this is called and return with irqs disabled. This will
3726  * protect us against recursive calling from irq.
3727  */
3728 asmlinkage __visible void __sched preempt_schedule_irq(void)
3729 {
3730         enum ctx_state prev_state;
3731
3732         /* Catch callers which need to be fixed */
3733         BUG_ON(preempt_count() || !irqs_disabled());
3734
3735         prev_state = exception_enter();
3736
3737         do {
3738                 preempt_disable();
3739                 local_irq_enable();
3740                 __schedule(true);
3741                 local_irq_disable();
3742                 sched_preempt_enable_no_resched();
3743         } while (need_resched());
3744
3745         exception_exit(prev_state);
3746 }
3747
3748 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
3749                           void *key)
3750 {
3751         return try_to_wake_up(curr->private, mode, wake_flags);
3752 }
3753 EXPORT_SYMBOL(default_wake_function);
3754
3755 #ifdef CONFIG_RT_MUTEXES
3756
3757 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3758 {
3759         if (pi_task)
3760                 prio = min(prio, pi_task->prio);
3761
3762         return prio;
3763 }
3764
3765 static inline int rt_effective_prio(struct task_struct *p, int prio)
3766 {
3767         struct task_struct *pi_task = rt_mutex_get_top_task(p);
3768
3769         return __rt_effective_prio(pi_task, prio);
3770 }
3771
3772 /*
3773  * rt_mutex_setprio - set the current priority of a task
3774  * @p: task to boost
3775  * @pi_task: donor task
3776  *
3777  * This function changes the 'effective' priority of a task. It does
3778  * not touch ->normal_prio like __setscheduler().
3779  *
3780  * Used by the rt_mutex code to implement priority inheritance
3781  * logic. Call site only calls if the priority of the task changed.
3782  */
3783 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
3784 {
3785         int prio, oldprio, queued, running, queue_flag =
3786                 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3787         const struct sched_class *prev_class;
3788         struct rq_flags rf;
3789         struct rq *rq;
3790
3791         /* XXX used to be waiter->prio, not waiter->task->prio */
3792         prio = __rt_effective_prio(pi_task, p->normal_prio);
3793
3794         /*
3795          * If nothing changed; bail early.
3796          */
3797         if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3798                 return;
3799
3800         rq = __task_rq_lock(p, &rf);
3801         update_rq_clock(rq);
3802         /*
3803          * Set under pi_lock && rq->lock, such that the value can be used under
3804          * either lock.
3805          *
3806          * Note that there is loads of tricky to make this pointer cache work
3807          * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3808          * ensure a task is de-boosted (pi_task is set to NULL) before the
3809          * task is allowed to run again (and can exit). This ensures the pointer
3810          * points to a blocked task -- which guaratees the task is present.
3811          */
3812         p->pi_top_task = pi_task;
3813
3814         /*
3815          * For FIFO/RR we only need to set prio, if that matches we're done.
3816          */
3817         if (prio == p->prio && !dl_prio(prio))
3818                 goto out_unlock;
3819
3820         /*
3821          * Idle task boosting is a nono in general. There is one
3822          * exception, when PREEMPT_RT and NOHZ is active:
3823          *
3824          * The idle task calls get_next_timer_interrupt() and holds
3825          * the timer wheel base->lock on the CPU and another CPU wants
3826          * to access the timer (probably to cancel it). We can safely
3827          * ignore the boosting request, as the idle CPU runs this code
3828          * with interrupts disabled and will complete the lock
3829          * protected section without being interrupted. So there is no
3830          * real need to boost.
3831          */
3832         if (unlikely(p == rq->idle)) {
3833                 WARN_ON(p != rq->curr);
3834                 WARN_ON(p->pi_blocked_on);
3835                 goto out_unlock;
3836         }
3837
3838         trace_sched_pi_setprio(p, pi_task);
3839         oldprio = p->prio;
3840
3841         if (oldprio == prio)
3842                 queue_flag &= ~DEQUEUE_MOVE;
3843
3844         prev_class = p->sched_class;
3845         queued = task_on_rq_queued(p);
3846         running = task_current(rq, p);
3847         if (queued)
3848                 dequeue_task(rq, p, queue_flag);
3849         if (running)
3850                 put_prev_task(rq, p);
3851
3852         /*
3853          * Boosting condition are:
3854          * 1. -rt task is running and holds mutex A
3855          *      --> -dl task blocks on mutex A
3856          *
3857          * 2. -dl task is running and holds mutex A
3858          *      --> -dl task blocks on mutex A and could preempt the
3859          *          running task
3860          */
3861         if (dl_prio(prio)) {
3862                 if (!dl_prio(p->normal_prio) ||
3863                     (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3864                         p->dl.dl_boosted = 1;
3865                         queue_flag |= ENQUEUE_REPLENISH;
3866                 } else
3867                         p->dl.dl_boosted = 0;
3868                 p->sched_class = &dl_sched_class;
3869         } else if (rt_prio(prio)) {
3870                 if (dl_prio(oldprio))
3871                         p->dl.dl_boosted = 0;
3872                 if (oldprio < prio)
3873                         queue_flag |= ENQUEUE_HEAD;
3874                 p->sched_class = &rt_sched_class;
3875         } else {
3876                 if (dl_prio(oldprio))
3877                         p->dl.dl_boosted = 0;
3878                 if (rt_prio(oldprio))
3879                         p->rt.timeout = 0;
3880                 p->sched_class = &fair_sched_class;
3881         }
3882
3883         p->prio = prio;
3884
3885         if (queued)
3886                 enqueue_task(rq, p, queue_flag);
3887         if (running)
3888                 set_curr_task(rq, p);
3889
3890         check_class_changed(rq, p, prev_class, oldprio);
3891 out_unlock:
3892         /* Avoid rq from going away on us: */
3893         preempt_disable();
3894         __task_rq_unlock(rq, &rf);
3895
3896         balance_callback(rq);
3897         preempt_enable();
3898 }
3899 #else
3900 static inline int rt_effective_prio(struct task_struct *p, int prio)
3901 {
3902         return prio;
3903 }
3904 #endif
3905
3906 void set_user_nice(struct task_struct *p, long nice)
3907 {
3908         bool queued, running;
3909         int old_prio, delta;
3910         struct rq_flags rf;
3911         struct rq *rq;
3912
3913         if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3914                 return;
3915         /*
3916          * We have to be careful, if called from sys_setpriority(),
3917          * the task might be in the middle of scheduling on another CPU.
3918          */
3919         rq = task_rq_lock(p, &rf);
3920         update_rq_clock(rq);
3921
3922         /*
3923          * The RT priorities are set via sched_setscheduler(), but we still
3924          * allow the 'normal' nice value to be set - but as expected
3925          * it wont have any effect on scheduling until the task is
3926          * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3927          */
3928         if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3929                 p->static_prio = NICE_TO_PRIO(nice);
3930                 goto out_unlock;
3931         }
3932         queued = task_on_rq_queued(p);
3933         running = task_current(rq, p);
3934         if (queued)
3935                 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
3936         if (running)
3937                 put_prev_task(rq, p);
3938
3939         p->static_prio = NICE_TO_PRIO(nice);
3940         set_load_weight(p, true);
3941         old_prio = p->prio;
3942         p->prio = effective_prio(p);
3943         delta = p->prio - old_prio;
3944
3945         if (queued) {
3946                 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
3947                 /*
3948                  * If the task increased its priority or is running and
3949                  * lowered its priority, then reschedule its CPU:
3950                  */
3951                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3952                         resched_curr(rq);
3953         }
3954         if (running)
3955                 set_curr_task(rq, p);
3956 out_unlock:
3957         task_rq_unlock(rq, p, &rf);
3958 }
3959 EXPORT_SYMBOL(set_user_nice);
3960
3961 /*
3962  * can_nice - check if a task can reduce its nice value
3963  * @p: task
3964  * @nice: nice value
3965  */
3966 int can_nice(const struct task_struct *p, const int nice)
3967 {
3968         /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3969         int nice_rlim = nice_to_rlimit(nice);
3970
3971         return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3972                 capable(CAP_SYS_NICE));
3973 }
3974
3975 #ifdef __ARCH_WANT_SYS_NICE
3976
3977 /*
3978  * sys_nice - change the priority of the current process.
3979  * @increment: priority increment
3980  *
3981  * sys_setpriority is a more generic, but much slower function that
3982  * does similar things.
3983  */
3984 SYSCALL_DEFINE1(nice, int, increment)
3985 {
3986         long nice, retval;
3987
3988         /*
3989          * Setpriority might change our priority at the same moment.
3990          * We don't have to worry. Conceptually one call occurs first
3991          * and we have a single winner.
3992          */
3993         increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3994         nice = task_nice(current) + increment;
3995
3996         nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3997         if (increment < 0 && !can_nice(current, nice))
3998                 return -EPERM;
3999
4000         retval = security_task_setnice(current, nice);
4001         if (retval)
4002                 return retval;
4003
4004         set_user_nice(current, nice);
4005         return 0;
4006 }
4007
4008 #endif
4009
4010 /**
4011  * task_prio - return the priority value of a given task.
4012  * @p: the task in question.
4013  *
4014  * Return: The priority value as seen by users in /proc.
4015  * RT tasks are offset by -200. Normal tasks are centered
4016  * around 0, value goes from -16 to +15.
4017  */
4018 int task_prio(const struct task_struct *p)
4019 {
4020         return p->prio - MAX_RT_PRIO;
4021 }
4022
4023 /**
4024  * idle_cpu - is a given CPU idle currently?
4025  * @cpu: the processor in question.
4026  *
4027  * Return: 1 if the CPU is currently idle. 0 otherwise.
4028  */
4029 int idle_cpu(int cpu)
4030 {
4031         struct rq *rq = cpu_rq(cpu);
4032
4033         if (rq->curr != rq->idle)
4034                 return 0;
4035
4036         if (rq->nr_running)
4037                 return 0;
4038
4039 #ifdef CONFIG_SMP
4040         if (!llist_empty(&rq->wake_list))
4041                 return 0;
4042 #endif
4043
4044         return 1;
4045 }
4046
4047 /**
4048  * available_idle_cpu - is a given CPU idle for enqueuing work.
4049  * @cpu: the CPU in question.
4050  *
4051  * Return: 1 if the CPU is currently idle. 0 otherwise.
4052  */
4053 int available_idle_cpu(int cpu)
4054 {
4055         if (!idle_cpu(cpu))
4056                 return 0;
4057
4058         if (vcpu_is_preempted(cpu))
4059                 return 0;
4060
4061         return 1;
4062 }
4063
4064 /**
4065  * idle_task - return the idle task for a given CPU.
4066  * @cpu: the processor in question.
4067  *
4068  * Return: The idle task for the CPU @cpu.
4069  */
4070 struct task_struct *idle_task(int cpu)
4071 {
4072         return cpu_rq(cpu)->idle;
4073 }
4074
4075 /**
4076  * find_process_by_pid - find a process with a matching PID value.
4077  * @pid: the pid in question.
4078  *
4079  * The task of @pid, if found. %NULL otherwise.
4080  */
4081 static struct task_struct *find_process_by_pid(pid_t pid)
4082 {
4083         return pid ? find_task_by_vpid(pid) : current;
4084 }
4085
4086 /*
4087  * sched_setparam() passes in -1 for its policy, to let the functions
4088  * it calls know not to change it.
4089  */
4090 #define SETPARAM_POLICY -1
4091
4092 static void __setscheduler_params(struct task_struct *p,
4093                 const struct sched_attr *attr)
4094 {
4095         int policy = attr->sched_policy;
4096
4097         if (policy == SETPARAM_POLICY)
4098                 policy = p->policy;
4099
4100         p->policy = policy;
4101
4102         if (dl_policy(policy))
4103                 __setparam_dl(p, attr);
4104         else if (fair_policy(policy))
4105                 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4106
4107         /*
4108          * __sched_setscheduler() ensures attr->sched_priority == 0 when
4109          * !rt_policy. Always setting this ensures that things like
4110          * getparam()/getattr() don't report silly values for !rt tasks.
4111          */
4112         p->rt_priority = attr->sched_priority;
4113         p->normal_prio = normal_prio(p);
4114         set_load_weight(p, true);
4115 }
4116
4117 /* Actually do priority change: must hold pi & rq lock. */
4118 static void __setscheduler(struct rq *rq, struct task_struct *p,
4119                            const struct sched_attr *attr, bool keep_boost)
4120 {
4121         __setscheduler_params(p, attr);
4122
4123         /*
4124          * Keep a potential priority boosting if called from
4125          * sched_setscheduler().
4126          */
4127         p->prio = normal_prio(p);
4128         if (keep_boost)
4129                 p->prio = rt_effective_prio(p, p->prio);
4130
4131         if (dl_prio(p->prio))
4132                 p->sched_class = &dl_sched_class;
4133         else if (rt_prio(p->prio))
4134                 p->sched_class = &rt_sched_class;
4135         else
4136                 p->sched_class = &fair_sched_class;
4137 }
4138
4139 /*
4140  * Check the target process has a UID that matches the current process's:
4141  */
4142 static bool check_same_owner(struct task_struct *p)
4143 {
4144         const struct cred *cred = current_cred(), *pcred;
4145         bool match;
4146
4147         rcu_read_lock();
4148         pcred = __task_cred(p);
4149         match = (uid_eq(cred->euid, pcred->euid) ||
4150                  uid_eq(cred->euid, pcred->uid));
4151         rcu_read_unlock();
4152         return match;
4153 }
4154
4155 static int __sched_setscheduler(struct task_struct *p,
4156                                 const struct sched_attr *attr,
4157                                 bool user, bool pi)
4158 {
4159         int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4160                       MAX_RT_PRIO - 1 - attr->sched_priority;
4161         int retval, oldprio, oldpolicy = -1, queued, running;
4162         int new_effective_prio, policy = attr->sched_policy;
4163         const struct sched_class *prev_class;
4164         struct rq_flags rf;
4165         int reset_on_fork;
4166         int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4167         struct rq *rq;
4168
4169         /* The pi code expects interrupts enabled */
4170         BUG_ON(pi && in_interrupt());
4171 recheck:
4172         /* Double check policy once rq lock held: */
4173         if (policy < 0) {
4174                 reset_on_fork = p->sched_reset_on_fork;
4175                 policy = oldpolicy = p->policy;
4176         } else {
4177                 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4178
4179                 if (!valid_policy(policy))
4180                         return -EINVAL;
4181         }
4182
4183         if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
4184                 return -EINVAL;
4185
4186         /*
4187          * Valid priorities for SCHED_FIFO and SCHED_RR are
4188          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4189          * SCHED_BATCH and SCHED_IDLE is 0.
4190          */
4191         if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4192             (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4193                 return -EINVAL;
4194         if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4195             (rt_policy(policy) != (attr->sched_priority != 0)))
4196                 return -EINVAL;
4197
4198         /*
4199          * Allow unprivileged RT tasks to decrease priority:
4200          */
4201         if (user && !capable(CAP_SYS_NICE)) {
4202                 if (fair_policy(policy)) {
4203                         if (attr->sched_nice < task_nice(p) &&
4204                             !can_nice(p, attr->sched_nice))
4205                                 return -EPERM;
4206                 }
4207
4208                 if (rt_policy(policy)) {
4209                         unsigned long rlim_rtprio =
4210                                         task_rlimit(p, RLIMIT_RTPRIO);
4211
4212                         /* Can't set/change the rt policy: */
4213                         if (policy != p->policy && !rlim_rtprio)
4214                                 return -EPERM;
4215
4216                         /* Can't increase priority: */
4217                         if (attr->sched_priority > p->rt_priority &&
4218                             attr->sched_priority > rlim_rtprio)
4219                                 return -EPERM;
4220                 }
4221
4222                  /*
4223                   * Can't set/change SCHED_DEADLINE policy at all for now
4224                   * (safest behavior); in the future we would like to allow
4225                   * unprivileged DL tasks to increase their relative deadline
4226                   * or reduce their runtime (both ways reducing utilization)
4227                   */
4228                 if (dl_policy(policy))
4229                         return -EPERM;
4230
4231                 /*
4232                  * Treat SCHED_IDLE as nice 20. Only allow a switch to
4233                  * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4234                  */
4235                 if (task_has_idle_policy(p) && !idle_policy(policy)) {
4236                         if (!can_nice(p, task_nice(p)))
4237                                 return -EPERM;
4238                 }
4239
4240                 /* Can't change other user's priorities: */
4241                 if (!check_same_owner(p))
4242                         return -EPERM;
4243
4244                 /* Normal users shall not reset the sched_reset_on_fork flag: */
4245                 if (p->sched_reset_on_fork && !reset_on_fork)
4246                         return -EPERM;
4247         }
4248
4249         if (user) {
4250                 if (attr->sched_flags & SCHED_FLAG_SUGOV)
4251                         return -EINVAL;
4252
4253                 retval = security_task_setscheduler(p);
4254                 if (retval)
4255                         return retval;
4256         }
4257
4258         /*
4259          * Make sure no PI-waiters arrive (or leave) while we are
4260          * changing the priority of the task:
4261          *
4262          * To be able to change p->policy safely, the appropriate
4263          * runqueue lock must be held.
4264          */
4265         rq = task_rq_lock(p, &rf);
4266         update_rq_clock(rq);
4267
4268         /*
4269          * Changing the policy of the stop threads its a very bad idea:
4270          */
4271         if (p == rq->stop) {
4272                 task_rq_unlock(rq, p, &rf);
4273                 return -EINVAL;
4274         }
4275
4276         /*
4277          * If not changing anything there's no need to proceed further,
4278          * but store a possible modification of reset_on_fork.
4279          */
4280         if (unlikely(policy == p->policy)) {
4281                 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4282                         goto change;
4283                 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4284                         goto change;
4285                 if (dl_policy(policy) && dl_param_changed(p, attr))
4286                         goto change;
4287
4288                 p->sched_reset_on_fork = reset_on_fork;
4289                 task_rq_unlock(rq, p, &rf);
4290                 return 0;
4291         }
4292 change:
4293
4294         if (user) {
4295 #ifdef CONFIG_RT_GROUP_SCHED
4296                 /*
4297                  * Do not allow realtime tasks into groups that have no runtime
4298                  * assigned.
4299                  */
4300                 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4301                                 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4302                                 !task_group_is_autogroup(task_group(p))) {
4303                         task_rq_unlock(rq, p, &rf);
4304                         return -EPERM;
4305                 }
4306 #endif
4307 #ifdef CONFIG_SMP
4308                 if (dl_bandwidth_enabled() && dl_policy(policy) &&
4309                                 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
4310                         cpumask_t *span = rq->rd->span;
4311
4312                         /*
4313                          * Don't allow tasks with an affinity mask smaller than
4314                          * the entire root_domain to become SCHED_DEADLINE. We
4315                          * will also fail if there's no bandwidth available.
4316                          */
4317                         if (!cpumask_subset(span, &p->cpus_allowed) ||
4318                             rq->rd->dl_bw.bw == 0) {
4319                                 task_rq_unlock(rq, p, &rf);
4320                                 return -EPERM;
4321                         }
4322                 }
4323 #endif
4324         }
4325
4326         /* Re-check policy now with rq lock held: */
4327         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4328                 policy = oldpolicy = -1;
4329                 task_rq_unlock(rq, p, &rf);
4330                 goto recheck;
4331         }
4332
4333         /*
4334          * If setscheduling to SCHED_DEADLINE (or changing the parameters
4335          * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4336          * is available.
4337          */
4338         if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4339                 task_rq_unlock(rq, p, &rf);
4340                 return -EBUSY;
4341         }
4342
4343         p->sched_reset_on_fork = reset_on_fork;
4344         oldprio = p->prio;
4345
4346         if (pi) {
4347                 /*
4348                  * Take priority boosted tasks into account. If the new
4349                  * effective priority is unchanged, we just store the new
4350                  * normal parameters and do not touch the scheduler class and
4351                  * the runqueue. This will be done when the task deboost
4352                  * itself.
4353                  */
4354                 new_effective_prio = rt_effective_prio(p, newprio);
4355                 if (new_effective_prio == oldprio)
4356                         queue_flags &= ~DEQUEUE_MOVE;
4357         }
4358
4359         queued = task_on_rq_queued(p);
4360         running = task_current(rq, p);
4361         if (queued)
4362                 dequeue_task(rq, p, queue_flags);
4363         if (running)
4364                 put_prev_task(rq, p);
4365
4366         prev_class = p->sched_class;
4367         __setscheduler(rq, p, attr, pi);
4368
4369         if (queued) {
4370                 /*
4371                  * We enqueue to tail when the priority of a task is
4372                  * increased (user space view).
4373                  */
4374                 if (oldprio < p->prio)
4375                         queue_flags |= ENQUEUE_HEAD;
4376
4377                 enqueue_task(rq, p, queue_flags);
4378         }
4379         if (running)
4380                 set_curr_task(rq, p);
4381
4382         check_class_changed(rq, p, prev_class, oldprio);
4383
4384         /* Avoid rq from going away on us: */
4385         preempt_disable();
4386         task_rq_unlock(rq, p, &rf);
4387
4388         if (pi)
4389                 rt_mutex_adjust_pi(p);
4390
4391         /* Run balance callbacks after we've adjusted the PI chain: */
4392         balance_callback(rq);
4393         preempt_enable();
4394
4395         return 0;
4396 }
4397
4398 static int _sched_setscheduler(struct task_struct *p, int policy,
4399                                const struct sched_param *param, bool check)
4400 {
4401         struct sched_attr attr = {
4402                 .sched_policy   = policy,
4403                 .sched_priority = param->sched_priority,
4404                 .sched_nice     = PRIO_TO_NICE(p->static_prio),
4405         };
4406
4407         /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4408         if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4409                 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4410                 policy &= ~SCHED_RESET_ON_FORK;
4411                 attr.sched_policy = policy;
4412         }
4413
4414         return __sched_setscheduler(p, &attr, check, true);
4415 }
4416 /**
4417  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4418  * @p: the task in question.
4419  * @policy: new policy.
4420  * @param: structure containing the new RT priority.
4421  *
4422  * Return: 0 on success. An error code otherwise.
4423  *
4424  * NOTE that the task may be already dead.
4425  */
4426 int sched_setscheduler(struct task_struct *p, int policy,
4427                        const struct sched_param *param)
4428 {
4429         return _sched_setscheduler(p, policy, param, true);
4430 }
4431 EXPORT_SYMBOL_GPL(sched_setscheduler);
4432
4433 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4434 {
4435         return __sched_setscheduler(p, attr, true, true);
4436 }
4437 EXPORT_SYMBOL_GPL(sched_setattr);
4438
4439 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
4440 {
4441         return __sched_setscheduler(p, attr, false, true);
4442 }
4443
4444 /**
4445  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4446  * @p: the task in question.
4447  * @policy: new policy.
4448  * @param: structure containing the new RT priority.
4449  *
4450  * Just like sched_setscheduler, only don't bother checking if the
4451  * current context has permission.  For example, this is needed in
4452  * stop_machine(): we create temporary high priority worker threads,
4453  * but our caller might not have that capability.
4454  *
4455  * Return: 0 on success. An error code otherwise.
4456  */
4457 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4458                                const struct sched_param *param)
4459 {
4460         return _sched_setscheduler(p, policy, param, false);
4461 }
4462 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4463
4464 static int
4465 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4466 {
4467         struct sched_param lparam;
4468         struct task_struct *p;
4469         int retval;
4470
4471         if (!param || pid < 0)
4472                 return -EINVAL;
4473         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4474                 return -EFAULT;
4475
4476         rcu_read_lock();
4477         retval = -ESRCH;
4478         p = find_process_by_pid(pid);
4479         if (p != NULL)
4480                 retval = sched_setscheduler(p, policy, &lparam);
4481         rcu_read_unlock();
4482
4483         return retval;
4484 }
4485
4486 /*
4487  * Mimics kernel/events/core.c perf_copy_attr().
4488  */
4489 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4490 {
4491         u32 size;
4492         int ret;
4493
4494         if (!access_ok(uattr, SCHED_ATTR_SIZE_VER0))
4495                 return -EFAULT;
4496
4497         /* Zero the full structure, so that a short copy will be nice: */
4498         memset(attr, 0, sizeof(*attr));
4499
4500         ret = get_user(size, &uattr->size);
4501         if (ret)
4502                 return ret;
4503
4504         /* Bail out on silly large: */
4505         if (size > PAGE_SIZE)
4506                 goto err_size;
4507
4508         /* ABI compatibility quirk: */
4509         if (!size)
4510                 size = SCHED_ATTR_SIZE_VER0;
4511
4512         if (size < SCHED_ATTR_SIZE_VER0)
4513                 goto err_size;
4514
4515         /*
4516          * If we're handed a bigger struct than we know of,
4517          * ensure all the unknown bits are 0 - i.e. new
4518          * user-space does not rely on any kernel feature
4519          * extensions we dont know about yet.
4520          */
4521         if (size > sizeof(*attr)) {
4522                 unsigned char __user *addr;
4523                 unsigned char __user *end;
4524                 unsigned char val;
4525
4526                 addr = (void __user *)uattr + sizeof(*attr);
4527                 end  = (void __user *)uattr + size;
4528
4529                 for (; addr < end; addr++) {
4530                         ret = get_user(val, addr);
4531                         if (ret)
4532                                 return ret;
4533                         if (val)
4534                                 goto err_size;
4535                 }
4536                 size = sizeof(*attr);
4537         }
4538
4539         ret = copy_from_user(attr, uattr, size);
4540         if (ret)
4541                 return -EFAULT;
4542
4543         /*
4544          * XXX: Do we want to be lenient like existing syscalls; or do we want
4545          * to be strict and return an error on out-of-bounds values?
4546          */
4547         attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4548
4549         return 0;
4550
4551 err_size:
4552         put_user(sizeof(*attr), &uattr->size);
4553         return -E2BIG;
4554 }
4555
4556 /**
4557  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4558  * @pid: the pid in question.
4559  * @policy: new policy.
4560  * @param: structure containing the new RT priority.
4561  *
4562  * Return: 0 on success. An error code otherwise.
4563  */
4564 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4565 {
4566         if (policy < 0)
4567                 return -EINVAL;
4568
4569         return do_sched_setscheduler(pid, policy, param);
4570 }
4571
4572 /**
4573  * sys_sched_setparam - set/change the RT priority of a thread
4574  * @pid: the pid in question.
4575  * @param: structure containing the new RT priority.
4576  *
4577  * Return: 0 on success. An error code otherwise.
4578  */
4579 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4580 {
4581         return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4582 }
4583
4584 /**
4585  * sys_sched_setattr - same as above, but with extended sched_attr
4586  * @pid: the pid in question.
4587  * @uattr: structure containing the extended parameters.
4588  * @flags: for future extension.
4589  */
4590 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4591                                unsigned int, flags)
4592 {
4593         struct sched_attr attr;
4594         struct task_struct *p;
4595         int retval;
4596
4597         if (!uattr || pid < 0 || flags)
4598                 return -EINVAL;
4599
4600         retval = sched_copy_attr(uattr, &attr);
4601         if (retval)
4602                 return retval;
4603
4604         if ((int)attr.sched_policy < 0)
4605                 return -EINVAL;
4606
4607         rcu_read_lock();
4608         retval = -ESRCH;
4609         p = find_process_by_pid(pid);
4610         if (p != NULL)
4611                 retval = sched_setattr(p, &attr);
4612         rcu_read_unlock();
4613
4614         return retval;
4615 }
4616
4617 /**
4618  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4619  * @pid: the pid in question.
4620  *
4621  * Return: On success, the policy of the thread. Otherwise, a negative error
4622  * code.
4623  */
4624 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4625 {
4626         struct task_struct *p;
4627         int retval;
4628
4629         if (pid < 0)
4630                 return -EINVAL;
4631
4632         retval = -ESRCH;
4633         rcu_read_lock();
4634         p = find_process_by_pid(pid);
4635         if (p) {
4636                 retval = security_task_getscheduler(p);
4637                 if (!retval)
4638                         retval = p->policy
4639                                 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4640         }
4641         rcu_read_unlock();
4642         return retval;
4643 }
4644
4645 /**
4646  * sys_sched_getparam - get the RT priority of a thread
4647  * @pid: the pid in question.
4648  * @param: structure containing the RT priority.
4649  *
4650  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4651  * code.
4652  */
4653 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4654 {
4655         struct sched_param lp = { .sched_priority = 0 };
4656         struct task_struct *p;
4657         int retval;
4658
4659         if (!param || pid < 0)
4660                 return -EINVAL;
4661
4662         rcu_read_lock();
4663         p = find_process_by_pid(pid);
4664         retval = -ESRCH;
4665         if (!p)
4666                 goto out_unlock;
4667
4668         retval = security_task_getscheduler(p);
4669         if (retval)
4670                 goto out_unlock;
4671
4672         if (task_has_rt_policy(p))
4673                 lp.sched_priority = p->rt_priority;
4674         rcu_read_unlock();
4675
4676         /*
4677          * This one might sleep, we cannot do it with a spinlock held ...
4678          */
4679         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4680
4681         return retval;
4682
4683 out_unlock:
4684         rcu_read_unlock();
4685         return retval;
4686 }
4687
4688 static int sched_read_attr(struct sched_attr __user *uattr,
4689                            struct sched_attr *attr,
4690                            unsigned int usize)
4691 {
4692         int ret;
4693
4694         if (!access_ok(uattr, usize))
4695                 return -EFAULT;
4696
4697         /*
4698          * If we're handed a smaller struct than we know of,
4699          * ensure all the unknown bits are 0 - i.e. old
4700          * user-space does not get uncomplete information.
4701          */
4702         if (usize < sizeof(*attr)) {
4703                 unsigned char *addr;
4704                 unsigned char *end;
4705
4706                 addr = (void *)attr + usize;
4707                 end  = (void *)attr + sizeof(*attr);
4708
4709                 for (; addr < end; addr++) {
4710                         if (*addr)
4711                                 return -EFBIG;
4712                 }
4713
4714                 attr->size = usize;
4715         }
4716
4717         ret = copy_to_user(uattr, attr, attr->size);
4718         if (ret)
4719                 return -EFAULT;
4720
4721         return 0;
4722 }
4723
4724 /**
4725  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4726  * @pid: the pid in question.
4727  * @uattr: structure containing the extended parameters.
4728  * @size: sizeof(attr) for fwd/bwd comp.
4729  * @flags: for future extension.
4730  */
4731 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4732                 unsigned int, size, unsigned int, flags)
4733 {
4734         struct sched_attr attr = {
4735                 .size = sizeof(struct sched_attr),
4736         };
4737         struct task_struct *p;
4738         int retval;
4739
4740         if (!uattr || pid < 0 || size > PAGE_SIZE ||
4741             size < SCHED_ATTR_SIZE_VER0 || flags)
4742                 return -EINVAL;
4743
4744         rcu_read_lock();
4745         p = find_process_by_pid(pid);
4746         retval = -ESRCH;
4747         if (!p)
4748                 goto out_unlock;
4749
4750         retval = security_task_getscheduler(p);
4751         if (retval)
4752                 goto out_unlock;
4753
4754         attr.sched_policy = p->policy;
4755         if (p->sched_reset_on_fork)
4756                 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4757         if (task_has_dl_policy(p))
4758                 __getparam_dl(p, &attr);
4759         else if (task_has_rt_policy(p))
4760                 attr.sched_priority = p->rt_priority;
4761         else
4762                 attr.sched_nice = task_nice(p);
4763
4764         rcu_read_unlock();
4765
4766         retval = sched_read_attr(uattr, &attr, size);
4767         return retval;
4768
4769 out_unlock:
4770         rcu_read_unlock();
4771         return retval;
4772 }
4773
4774 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4775 {
4776         cpumask_var_t cpus_allowed, new_mask;
4777         struct task_struct *p;
4778         int retval;
4779
4780         rcu_read_lock();
4781
4782         p = find_process_by_pid(pid);
4783         if (!p) {
4784                 rcu_read_unlock();
4785                 return -ESRCH;
4786         }
4787
4788         /* Prevent p going away */
4789         get_task_struct(p);
4790         rcu_read_unlock();
4791
4792         if (p->flags & PF_NO_SETAFFINITY) {
4793                 retval = -EINVAL;
4794                 goto out_put_task;
4795         }
4796         if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4797                 retval = -ENOMEM;
4798                 goto out_put_task;
4799         }
4800         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4801                 retval = -ENOMEM;
4802                 goto out_free_cpus_allowed;
4803         }
4804         retval = -EPERM;
4805         if (!check_same_owner(p)) {
4806                 rcu_read_lock();
4807                 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4808                         rcu_read_unlock();
4809                         goto out_free_new_mask;
4810                 }
4811                 rcu_read_unlock();
4812         }
4813
4814         retval = security_task_setscheduler(p);
4815         if (retval)
4816                 goto out_free_new_mask;
4817
4818
4819         cpuset_cpus_allowed(p, cpus_allowed);
4820         cpumask_and(new_mask, in_mask, cpus_allowed);
4821
4822         /*
4823          * Since bandwidth control happens on root_domain basis,
4824          * if admission test is enabled, we only admit -deadline
4825          * tasks allowed to run on all the CPUs in the task's
4826          * root_domain.
4827          */
4828 #ifdef CONFIG_SMP
4829         if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4830                 rcu_read_lock();
4831                 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4832                         retval = -EBUSY;
4833                         rcu_read_unlock();
4834                         goto out_free_new_mask;
4835                 }
4836                 rcu_read_unlock();
4837         }
4838 #endif
4839 again:
4840         retval = __set_cpus_allowed_ptr(p, new_mask, true);
4841
4842         if (!retval) {
4843                 cpuset_cpus_allowed(p, cpus_allowed);
4844                 if (!cpumask_subset(new_mask, cpus_allowed)) {
4845                         /*
4846                          * We must have raced with a concurrent cpuset
4847                          * update. Just reset the cpus_allowed to the
4848                          * cpuset's cpus_allowed
4849                          */
4850                         cpumask_copy(new_mask, cpus_allowed);
4851                         goto again;
4852                 }
4853         }
4854 out_free_new_mask:
4855         free_cpumask_var(new_mask);
4856 out_free_cpus_allowed:
4857         free_cpumask_var(cpus_allowed);
4858 out_put_task:
4859         put_task_struct(p);
4860         return retval;
4861 }
4862
4863 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4864                              struct cpumask *new_mask)
4865 {
4866         if (len < cpumask_size())
4867                 cpumask_clear(new_mask);
4868         else if (len > cpumask_size())
4869                 len = cpumask_size();
4870
4871         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4872 }
4873
4874 /**
4875  * sys_sched_setaffinity - set the CPU affinity of a process
4876  * @pid: pid of the process
4877  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4878  * @user_mask_ptr: user-space pointer to the new CPU mask
4879  *
4880  * Return: 0 on success. An error code otherwise.
4881  */
4882 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4883                 unsigned long __user *, user_mask_ptr)
4884 {
4885         cpumask_var_t new_mask;
4886         int retval;
4887
4888         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4889                 return -ENOMEM;
4890
4891         retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4892         if (retval == 0)
4893                 retval = sched_setaffinity(pid, new_mask);
4894         free_cpumask_var(new_mask);
4895         return retval;
4896 }
4897
4898 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4899 {
4900         struct task_struct *p;
4901         unsigned long flags;
4902         int retval;
4903
4904         rcu_read_lock();
4905
4906         retval = -ESRCH;
4907         p = find_process_by_pid(pid);
4908         if (!p)
4909                 goto out_unlock;
4910
4911         retval = security_task_getscheduler(p);
4912         if (retval)
4913                 goto out_unlock;
4914
4915         raw_spin_lock_irqsave(&p->pi_lock, flags);
4916         cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4917         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4918
4919 out_unlock:
4920         rcu_read_unlock();
4921
4922         return retval;
4923 }
4924
4925 /**
4926  * sys_sched_getaffinity - get the CPU affinity of a process
4927  * @pid: pid of the process
4928  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4929  * @user_mask_ptr: user-space pointer to hold the current CPU mask
4930  *
4931  * Return: size of CPU mask copied to user_mask_ptr on success. An
4932  * error code otherwise.
4933  */
4934 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4935                 unsigned long __user *, user_mask_ptr)
4936 {
4937         int ret;
4938         cpumask_var_t mask;
4939
4940         if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4941                 return -EINVAL;
4942         if (len & (sizeof(unsigned long)-1))
4943                 return -EINVAL;
4944
4945         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4946                 return -ENOMEM;
4947
4948         ret = sched_getaffinity(pid, mask);
4949         if (ret == 0) {
4950                 unsigned int retlen = min(len, cpumask_size());
4951
4952                 if (copy_to_user(user_mask_ptr, mask, retlen))
4953                         ret = -EFAULT;
4954                 else
4955                         ret = retlen;
4956         }
4957         free_cpumask_var(mask);
4958
4959         return ret;
4960 }
4961
4962 /**
4963  * sys_sched_yield - yield the current processor to other threads.
4964  *
4965  * This function yields the current CPU to other tasks. If there are no
4966  * other threads running on this CPU then this function will return.
4967  *
4968  * Return: 0.
4969  */
4970 static void do_sched_yield(void)
4971 {
4972         struct rq_flags rf;
4973         struct rq *rq;
4974
4975         rq = this_rq_lock_irq(&rf);
4976
4977         schedstat_inc(rq->yld_count);
4978         current->sched_class->yield_task(rq);
4979
4980         /*
4981          * Since we are going to call schedule() anyway, there's
4982          * no need to preempt or enable interrupts:
4983          */
4984         preempt_disable();
4985         rq_unlock(rq, &rf);
4986         sched_preempt_enable_no_resched();
4987
4988         schedule();
4989 }
4990
4991 SYSCALL_DEFINE0(sched_yield)
4992 {
4993         do_sched_yield();
4994         return 0;
4995 }
4996
4997 #ifndef CONFIG_PREEMPT
4998 int __sched _cond_resched(void)
4999 {
5000         if (should_resched(0)) {
5001                 preempt_schedule_common();
5002                 return 1;
5003         }
5004         rcu_all_qs();
5005         return 0;
5006 }
5007 EXPORT_SYMBOL(_cond_resched);
5008 #endif
5009
5010 /*
5011  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5012  * call schedule, and on return reacquire the lock.
5013  *
5014  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5015  * operations here to prevent schedule() from being called twice (once via
5016  * spin_unlock(), once by hand).
5017  */
5018 int __cond_resched_lock(spinlock_t *lock)
5019 {
5020         int resched = should_resched(PREEMPT_LOCK_OFFSET);
5021         int ret = 0;
5022
5023         lockdep_assert_held(lock);
5024
5025         if (spin_needbreak(lock) || resched) {
5026                 spin_unlock(lock);
5027                 if (resched)
5028                         preempt_schedule_common();
5029                 else
5030                         cpu_relax();
5031                 ret = 1;
5032                 spin_lock(lock);
5033         }
5034         return ret;
5035 }
5036 EXPORT_SYMBOL(__cond_resched_lock);
5037
5038 /**
5039  * yield - yield the current processor to other threads.
5040  *
5041  * Do not ever use this function, there's a 99% chance you're doing it wrong.
5042  *
5043  * The scheduler is at all times free to pick the calling task as the most
5044  * eligible task to run, if removing the yield() call from your code breaks
5045  * it, its already broken.
5046  *
5047  * Typical broken usage is:
5048  *
5049  * while (!event)
5050  *      yield();
5051  *
5052  * where one assumes that yield() will let 'the other' process run that will
5053  * make event true. If the current task is a SCHED_FIFO task that will never
5054  * happen. Never use yield() as a progress guarantee!!
5055  *
5056  * If you want to use yield() to wait for something, use wait_event().
5057  * If you want to use yield() to be 'nice' for others, use cond_resched().
5058  * If you still want to use yield(), do not!
5059  */
5060 void __sched yield(void)
5061 {
5062         set_current_state(TASK_RUNNING);
5063         do_sched_yield();
5064 }
5065 EXPORT_SYMBOL(yield);
5066
5067 /**
5068  * yield_to - yield the current processor to another thread in
5069  * your thread group, or accelerate that thread toward the
5070  * processor it's on.
5071  * @p: target task
5072  * @preempt: whether task preemption is allowed or not
5073  *
5074  * It's the caller's job to ensure that the target task struct
5075  * can't go away on us before we can do any checks.
5076  *
5077  * Return:
5078  *      true (>0) if we indeed boosted the target task.
5079  *      false (0) if we failed to boost the target.
5080  *      -ESRCH if there's no task to yield to.
5081  */
5082 int __sched yield_to(struct task_struct *p, bool preempt)
5083 {
5084         struct task_struct *curr = current;
5085         struct rq *rq, *p_rq;
5086         unsigned long flags;
5087         int yielded = 0;
5088
5089         local_irq_save(flags);
5090         rq = this_rq();
5091
5092 again:
5093         p_rq = task_rq(p);
5094         /*
5095          * If we're the only runnable task on the rq and target rq also
5096          * has only one task, there's absolutely no point in yielding.
5097          */
5098         if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5099                 yielded = -ESRCH;
5100                 goto out_irq;
5101         }
5102
5103         double_rq_lock(rq, p_rq);
5104         if (task_rq(p) != p_rq) {
5105                 double_rq_unlock(rq, p_rq);
5106                 goto again;
5107         }
5108
5109         if (!curr->sched_class->yield_to_task)
5110                 goto out_unlock;
5111
5112         if (curr->sched_class != p->sched_class)
5113                 goto out_unlock;
5114
5115         if (task_running(p_rq, p) || p->state)
5116                 goto out_unlock;
5117
5118         yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5119         if (yielded) {
5120                 schedstat_inc(rq->yld_count);
5121                 /*
5122                  * Make p's CPU reschedule; pick_next_entity takes care of
5123                  * fairness.
5124                  */
5125                 if (preempt && rq != p_rq)
5126                         resched_curr(p_rq);
5127         }
5128
5129 out_unlock:
5130         double_rq_unlock(rq, p_rq);
5131 out_irq:
5132         local_irq_restore(flags);
5133
5134         if (yielded > 0)
5135                 schedule();
5136
5137         return yielded;
5138 }
5139 EXPORT_SYMBOL_GPL(yield_to);
5140
5141 int io_schedule_prepare(void)
5142 {
5143         int old_iowait = current->in_iowait;
5144
5145         current->in_iowait = 1;
5146         blk_schedule_flush_plug(current);
5147
5148         return old_iowait;
5149 }
5150
5151 void io_schedule_finish(int token)
5152 {
5153         current->in_iowait = token;
5154 }
5155
5156 /*
5157  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5158  * that process accounting knows that this is a task in IO wait state.
5159  */
5160 long __sched io_schedule_timeout(long timeout)
5161 {
5162         int token;
5163         long ret;
5164
5165         token = io_schedule_prepare();
5166         ret = schedule_timeout(timeout);
5167         io_schedule_finish(token);
5168
5169         return ret;
5170 }
5171 EXPORT_SYMBOL(io_schedule_timeout);
5172
5173 void io_schedule(void)
5174 {
5175         int token;
5176
5177         token = io_schedule_prepare();
5178         schedule();
5179         io_schedule_finish(token);
5180 }
5181 EXPORT_SYMBOL(io_schedule);
5182
5183 /**
5184  * sys_sched_get_priority_max - return maximum RT priority.
5185  * @policy: scheduling class.
5186  *
5187  * Return: On success, this syscall returns the maximum
5188  * rt_priority that can be used by a given scheduling class.
5189  * On failure, a negative error code is returned.
5190  */
5191 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5192 {
5193         int ret = -EINVAL;
5194
5195         switch (policy) {
5196         case SCHED_FIFO:
5197         case SCHED_RR:
5198                 ret = MAX_USER_RT_PRIO-1;
5199                 break;
5200         case SCHED_DEADLINE:
5201         case SCHED_NORMAL:
5202         case SCHED_BATCH:
5203         case SCHED_IDLE:
5204                 ret = 0;
5205                 break;
5206         }
5207         return ret;
5208 }
5209
5210 /**
5211  * sys_sched_get_priority_min - return minimum RT priority.
5212  * @policy: scheduling class.
5213  *
5214  * Return: On success, this syscall returns the minimum
5215  * rt_priority that can be used by a given scheduling class.
5216  * On failure, a negative error code is returned.
5217  */
5218 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5219 {
5220         int ret = -EINVAL;
5221
5222         switch (policy) {
5223         case SCHED_FIFO:
5224         case SCHED_RR:
5225                 ret = 1;
5226                 break;
5227         case SCHED_DEADLINE:
5228         case SCHED_NORMAL:
5229         case SCHED_BATCH:
5230         case SCHED_IDLE:
5231                 ret = 0;
5232         }
5233         return ret;
5234 }
5235
5236 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
5237 {
5238         struct task_struct *p;
5239         unsigned int time_slice;
5240         struct rq_flags rf;
5241         struct rq *rq;
5242         int retval;
5243
5244         if (pid < 0)
5245                 return -EINVAL;
5246
5247         retval = -ESRCH;
5248         rcu_read_lock();
5249         p = find_process_by_pid(pid);
5250         if (!p)
5251                 goto out_unlock;
5252
5253         retval = security_task_getscheduler(p);
5254         if (retval)
5255                 goto out_unlock;
5256
5257         rq = task_rq_lock(p, &rf);
5258         time_slice = 0;
5259         if (p->sched_class->get_rr_interval)
5260                 time_slice = p->sched_class->get_rr_interval(rq, p);
5261         task_rq_unlock(rq, p, &rf);
5262
5263         rcu_read_unlock();
5264         jiffies_to_timespec64(time_slice, t);
5265         return 0;
5266
5267 out_unlock:
5268         rcu_read_unlock();
5269         return retval;
5270 }
5271
5272 /**
5273  * sys_sched_rr_get_interval - return the default timeslice of a process.
5274  * @pid: pid of the process.
5275  * @interval: userspace pointer to the timeslice value.
5276  *
5277  * this syscall writes the default timeslice value of a given process
5278  * into the user-space timespec buffer. A value of '0' means infinity.
5279  *
5280  * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5281  * an error code.
5282  */
5283 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5284                 struct __kernel_timespec __user *, interval)
5285 {
5286         struct timespec64 t;
5287         int retval = sched_rr_get_interval(pid, &t);
5288
5289         if (retval == 0)
5290                 retval = put_timespec64(&t, interval);
5291
5292         return retval;
5293 }
5294
5295 #ifdef CONFIG_COMPAT_32BIT_TIME
5296 COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5297                        compat_pid_t, pid,
5298                        struct old_timespec32 __user *, interval)
5299 {
5300         struct timespec64 t;
5301         int retval = sched_rr_get_interval(pid, &t);
5302
5303         if (retval == 0)
5304                 retval = put_old_timespec32(&t, interval);
5305         return retval;
5306 }
5307 #endif
5308
5309 void sched_show_task(struct task_struct *p)
5310 {
5311         unsigned long free = 0;
5312         int ppid;
5313
5314         if (!try_get_task_stack(p))
5315                 return;
5316
5317         printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5318
5319         if (p->state == TASK_RUNNING)
5320                 printk(KERN_CONT "  running task    ");
5321 #ifdef CONFIG_DEBUG_STACK_USAGE
5322         free = stack_not_used(p);
5323 #endif
5324         ppid = 0;
5325         rcu_read_lock();
5326         if (pid_alive(p))
5327                 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5328         rcu_read_unlock();
5329         printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5330                 task_pid_nr(p), ppid,
5331                 (unsigned long)task_thread_info(p)->flags);
5332
5333         print_worker_info(KERN_INFO, p);
5334         show_stack(p, NULL);
5335         put_task_stack(p);
5336 }
5337 EXPORT_SYMBOL_GPL(sched_show_task);
5338
5339 static inline bool
5340 state_filter_match(unsigned long state_filter, struct task_struct *p)
5341 {
5342         /* no filter, everything matches */
5343         if (!state_filter)
5344                 return true;
5345
5346         /* filter, but doesn't match */
5347         if (!(p->state & state_filter))
5348                 return false;
5349
5350         /*
5351          * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5352          * TASK_KILLABLE).
5353          */
5354         if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5355                 return false;
5356
5357         return true;
5358 }
5359
5360
5361 void show_state_filter(unsigned long state_filter)
5362 {
5363         struct task_struct *g, *p;
5364
5365 #if BITS_PER_LONG == 32
5366         printk(KERN_INFO
5367                 "  task                PC stack   pid father\n");
5368 #else
5369         printk(KERN_INFO
5370                 "  task                        PC stack   pid father\n");
5371 #endif
5372         rcu_read_lock();
5373         for_each_process_thread(g, p) {
5374                 /*
5375                  * reset the NMI-timeout, listing all files on a slow
5376                  * console might take a lot of time:
5377                  * Also, reset softlockup watchdogs on all CPUs, because
5378                  * another CPU might be blocked waiting for us to process
5379                  * an IPI.
5380                  */
5381                 touch_nmi_watchdog();
5382                 touch_all_softlockup_watchdogs();
5383                 if (state_filter_match(state_filter, p))
5384                         sched_show_task(p);
5385         }
5386
5387 #ifdef CONFIG_SCHED_DEBUG
5388         if (!state_filter)
5389                 sysrq_sched_debug_show();
5390 #endif
5391         rcu_read_unlock();
5392         /*
5393          * Only show locks if all tasks are dumped:
5394          */
5395         if (!state_filter)
5396                 debug_show_all_locks();
5397 }
5398
5399 /**
5400  * init_idle - set up an idle thread for a given CPU
5401  * @idle: task in question
5402  * @cpu: CPU the idle task belongs to
5403  *
5404  * NOTE: this function does not set the idle thread's NEED_RESCHED
5405  * flag, to make booting more robust.
5406  */
5407 void init_idle(struct task_struct *idle, int cpu)
5408 {
5409         struct rq *rq = cpu_rq(cpu);
5410         unsigned long flags;
5411
5412         raw_spin_lock_irqsave(&idle->pi_lock, flags);
5413         raw_spin_lock(&rq->lock);
5414
5415         __sched_fork(0, idle);
5416         idle->state = TASK_RUNNING;
5417         idle->se.exec_start = sched_clock();
5418         idle->flags |= PF_IDLE;
5419
5420         kasan_unpoison_task_stack(idle);
5421
5422 #ifdef CONFIG_SMP
5423         /*
5424          * Its possible that init_idle() gets called multiple times on a task,
5425          * in that case do_set_cpus_allowed() will not do the right thing.
5426          *
5427          * And since this is boot we can forgo the serialization.
5428          */
5429         set_cpus_allowed_common(idle, cpumask_of(cpu));
5430 #endif
5431         /*
5432          * We're having a chicken and egg problem, even though we are
5433          * holding rq->lock, the CPU isn't yet set to this CPU so the
5434          * lockdep check in task_group() will fail.
5435          *
5436          * Similar case to sched_fork(). / Alternatively we could
5437          * use task_rq_lock() here and obtain the other rq->lock.
5438          *
5439          * Silence PROVE_RCU
5440          */
5441         rcu_read_lock();
5442         __set_task_cpu(idle, cpu);
5443         rcu_read_unlock();
5444
5445         rq->curr = rq->idle = idle;
5446         idle->on_rq = TASK_ON_RQ_QUEUED;
5447 #ifdef CONFIG_SMP
5448         idle->on_cpu = 1;
5449 #endif
5450         raw_spin_unlock(&rq->lock);
5451         raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5452
5453         /* Set the preempt count _outside_ the spinlocks! */
5454         init_idle_preempt_count(idle, cpu);
5455
5456         /*
5457          * The idle tasks have their own, simple scheduling class:
5458          */
5459         idle->sched_class = &idle_sched_class;
5460         ftrace_graph_init_idle_task(idle, cpu);
5461         vtime_init_idle(idle, cpu);
5462 #ifdef CONFIG_SMP
5463         sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5464 #endif
5465 }
5466
5467 #ifdef CONFIG_SMP
5468
5469 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5470                               const struct cpumask *trial)
5471 {
5472         int ret = 1;
5473
5474         if (!cpumask_weight(cur))
5475                 return ret;
5476
5477         ret = dl_cpuset_cpumask_can_shrink(cur, trial);
5478
5479         return ret;
5480 }
5481
5482 int task_can_attach(struct task_struct *p,
5483                     const struct cpumask *cs_cpus_allowed)
5484 {
5485         int ret = 0;
5486
5487         /*
5488          * Kthreads which disallow setaffinity shouldn't be moved
5489          * to a new cpuset; we don't want to change their CPU
5490          * affinity and isolating such threads by their set of
5491          * allowed nodes is unnecessary.  Thus, cpusets are not
5492          * applicable for such threads.  This prevents checking for
5493          * success of set_cpus_allowed_ptr() on all attached tasks
5494          * before cpus_allowed may be changed.
5495          */
5496         if (p->flags & PF_NO_SETAFFINITY) {
5497                 ret = -EINVAL;
5498                 goto out;
5499         }
5500
5501         if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5502                                               cs_cpus_allowed))
5503                 ret = dl_task_can_attach(p, cs_cpus_allowed);
5504
5505 out:
5506         return ret;
5507 }
5508
5509 bool sched_smp_initialized __read_mostly;
5510
5511 #ifdef CONFIG_NUMA_BALANCING
5512 /* Migrate current task p to target_cpu */
5513 int migrate_task_to(struct task_struct *p, int target_cpu)
5514 {
5515         struct migration_arg arg = { p, target_cpu };
5516         int curr_cpu = task_cpu(p);
5517
5518         if (curr_cpu == target_cpu)
5519                 return 0;
5520
5521         if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5522                 return -EINVAL;
5523
5524         /* TODO: This is not properly updating schedstats */
5525
5526         trace_sched_move_numa(p, curr_cpu, target_cpu);
5527         return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5528 }
5529
5530 /*
5531  * Requeue a task on a given node and accurately track the number of NUMA
5532  * tasks on the runqueues
5533  */
5534 void sched_setnuma(struct task_struct *p, int nid)
5535 {
5536         bool queued, running;
5537         struct rq_flags rf;
5538         struct rq *rq;
5539
5540         rq = task_rq_lock(p, &rf);
5541         queued = task_on_rq_queued(p);
5542         running = task_current(rq, p);
5543
5544         if (queued)
5545                 dequeue_task(rq, p, DEQUEUE_SAVE);
5546         if (running)
5547                 put_prev_task(rq, p);
5548
5549         p->numa_preferred_nid = nid;
5550
5551         if (queued)
5552                 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5553         if (running)
5554                 set_curr_task(rq, p);
5555         task_rq_unlock(rq, p, &rf);
5556 }
5557 #endif /* CONFIG_NUMA_BALANCING */
5558
5559 #ifdef CONFIG_HOTPLUG_CPU
5560 /*
5561  * Ensure that the idle task is using init_mm right before its CPU goes
5562  * offline.
5563  */
5564 void idle_task_exit(void)
5565 {
5566         struct mm_struct *mm = current->active_mm;
5567
5568         BUG_ON(cpu_online(smp_processor_id()));
5569
5570         if (mm != &init_mm) {
5571                 switch_mm(mm, &init_mm, current);
5572                 current->active_mm = &init_mm;
5573                 finish_arch_post_lock_switch();
5574         }
5575         mmdrop(mm);
5576 }
5577
5578 /*
5579  * Since this CPU is going 'away' for a while, fold any nr_active delta
5580  * we might have. Assumes we're called after migrate_tasks() so that the
5581  * nr_active count is stable. We need to take the teardown thread which
5582  * is calling this into account, so we hand in adjust = 1 to the load
5583  * calculation.
5584  *
5585  * Also see the comment "Global load-average calculations".
5586  */
5587 static void calc_load_migrate(struct rq *rq)
5588 {
5589         long delta = calc_load_fold_active(rq, 1);
5590         if (delta)
5591                 atomic_long_add(delta, &calc_load_tasks);
5592 }
5593
5594 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5595 {
5596 }
5597
5598 static const struct sched_class fake_sched_class = {
5599         .put_prev_task = put_prev_task_fake,
5600 };
5601
5602 static struct task_struct fake_task = {
5603         /*
5604          * Avoid pull_{rt,dl}_task()
5605          */
5606         .prio = MAX_PRIO + 1,
5607         .sched_class = &fake_sched_class,
5608 };
5609
5610 /*
5611  * Migrate all tasks from the rq, sleeping tasks will be migrated by
5612  * try_to_wake_up()->select_task_rq().
5613  *
5614  * Called with rq->lock held even though we'er in stop_machine() and
5615  * there's no concurrency possible, we hold the required locks anyway
5616  * because of lock validation efforts.
5617  */
5618 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
5619 {
5620         struct rq *rq = dead_rq;
5621         struct task_struct *next, *stop = rq->stop;
5622         struct rq_flags orf = *rf;
5623         int dest_cpu;
5624
5625         /*
5626          * Fudge the rq selection such that the below task selection loop
5627          * doesn't get stuck on the currently eligible stop task.
5628          *
5629          * We're currently inside stop_machine() and the rq is either stuck
5630          * in the stop_machine_cpu_stop() loop, or we're executing this code,
5631          * either way we should never end up calling schedule() until we're
5632          * done here.
5633          */
5634         rq->stop = NULL;
5635
5636         /*
5637          * put_prev_task() and pick_next_task() sched
5638          * class method both need to have an up-to-date
5639          * value of rq->clock[_task]
5640          */
5641         update_rq_clock(rq);
5642
5643         for (;;) {
5644                 /*
5645                  * There's this thread running, bail when that's the only
5646                  * remaining thread:
5647                  */
5648                 if (rq->nr_running == 1)
5649                         break;
5650
5651                 /*
5652                  * pick_next_task() assumes pinned rq->lock:
5653                  */
5654                 next = pick_next_task(rq, &fake_task, rf);
5655                 BUG_ON(!next);
5656                 put_prev_task(rq, next);
5657
5658                 /*
5659                  * Rules for changing task_struct::cpus_allowed are holding
5660                  * both pi_lock and rq->lock, such that holding either
5661                  * stabilizes the mask.
5662                  *
5663                  * Drop rq->lock is not quite as disastrous as it usually is
5664                  * because !cpu_active at this point, which means load-balance
5665                  * will not interfere. Also, stop-machine.
5666                  */
5667                 rq_unlock(rq, rf);
5668                 raw_spin_lock(&next->pi_lock);
5669                 rq_relock(rq, rf);
5670
5671                 /*
5672                  * Since we're inside stop-machine, _nothing_ should have
5673                  * changed the task, WARN if weird stuff happened, because in
5674                  * that case the above rq->lock drop is a fail too.
5675                  */
5676                 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5677                         raw_spin_unlock(&next->pi_lock);
5678                         continue;
5679                 }
5680
5681                 /* Find suitable destination for @next, with force if needed. */
5682                 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5683                 rq = __migrate_task(rq, rf, next, dest_cpu);
5684                 if (rq != dead_rq) {
5685                         rq_unlock(rq, rf);
5686                         rq = dead_rq;
5687                         *rf = orf;
5688                         rq_relock(rq, rf);
5689                 }
5690                 raw_spin_unlock(&next->pi_lock);
5691         }
5692
5693         rq->stop = stop;
5694 }
5695 #endif /* CONFIG_HOTPLUG_CPU */
5696
5697 void set_rq_online(struct rq *rq)
5698 {
5699         if (!rq->online) {
5700                 const struct sched_class *class;
5701
5702                 cpumask_set_cpu(rq->cpu, rq->rd->online);
5703                 rq->online = 1;
5704
5705                 for_each_class(class) {
5706                         if (class->rq_online)
5707                                 class->rq_online(rq);
5708                 }
5709         }
5710 }
5711
5712 void set_rq_offline(struct rq *rq)
5713 {
5714         if (rq->online) {
5715                 const struct sched_class *class;
5716
5717                 for_each_class(class) {
5718                         if (class->rq_offline)
5719                                 class->rq_offline(rq);
5720                 }
5721
5722                 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5723                 rq->online = 0;
5724         }
5725 }
5726
5727 /*
5728  * used to mark begin/end of suspend/resume:
5729  */
5730 static int num_cpus_frozen;
5731
5732 /*
5733  * Update cpusets according to cpu_active mask.  If cpusets are
5734  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5735  * around partition_sched_domains().
5736  *
5737  * If we come here as part of a suspend/resume, don't touch cpusets because we
5738  * want to restore it back to its original state upon resume anyway.
5739  */
5740 static void cpuset_cpu_active(void)
5741 {
5742         if (cpuhp_tasks_frozen) {
5743                 /*
5744                  * num_cpus_frozen tracks how many CPUs are involved in suspend
5745                  * resume sequence. As long as this is not the last online
5746                  * operation in the resume sequence, just build a single sched
5747                  * domain, ignoring cpusets.
5748                  */
5749                 partition_sched_domains(1, NULL, NULL);
5750                 if (--num_cpus_frozen)
5751                         return;
5752                 /*
5753                  * This is the last CPU online operation. So fall through and
5754                  * restore the original sched domains by considering the
5755                  * cpuset configurations.
5756                  */
5757                 cpuset_force_rebuild();
5758         }
5759         cpuset_update_active_cpus();
5760 }
5761
5762 static int cpuset_cpu_inactive(unsigned int cpu)
5763 {
5764         if (!cpuhp_tasks_frozen) {
5765                 if (dl_cpu_busy(cpu))
5766                         return -EBUSY;
5767                 cpuset_update_active_cpus();
5768         } else {
5769                 num_cpus_frozen++;
5770                 partition_sched_domains(1, NULL, NULL);
5771         }
5772         return 0;
5773 }
5774
5775 int sched_cpu_activate(unsigned int cpu)
5776 {
5777         struct rq *rq = cpu_rq(cpu);
5778         struct rq_flags rf;
5779
5780 #ifdef CONFIG_SCHED_SMT
5781         /*
5782          * When going up, increment the number of cores with SMT present.
5783          */
5784         if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
5785                 static_branch_inc_cpuslocked(&sched_smt_present);
5786 #endif
5787         set_cpu_active(cpu, true);
5788
5789         if (sched_smp_initialized) {
5790                 sched_domains_numa_masks_set(cpu);
5791                 cpuset_cpu_active();
5792         }
5793
5794         /*
5795          * Put the rq online, if not already. This happens:
5796          *
5797          * 1) In the early boot process, because we build the real domains
5798          *    after all CPUs have been brought up.
5799          *
5800          * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5801          *    domains.
5802          */
5803         rq_lock_irqsave(rq, &rf);
5804         if (rq->rd) {
5805                 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5806                 set_rq_online(rq);
5807         }
5808         rq_unlock_irqrestore(rq, &rf);
5809
5810         update_max_interval();
5811
5812         return 0;
5813 }
5814
5815 int sched_cpu_deactivate(unsigned int cpu)
5816 {
5817         int ret;
5818
5819         set_cpu_active(cpu, false);
5820         /*
5821          * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5822          * users of this state to go away such that all new such users will
5823          * observe it.
5824          *
5825          * Do sync before park smpboot threads to take care the rcu boost case.
5826          */
5827         synchronize_rcu();
5828
5829 #ifdef CONFIG_SCHED_SMT
5830         /*
5831          * When going down, decrement the number of cores with SMT present.
5832          */
5833         if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
5834                 static_branch_dec_cpuslocked(&sched_smt_present);
5835 #endif
5836
5837         if (!sched_smp_initialized)
5838                 return 0;
5839
5840         ret = cpuset_cpu_inactive(cpu);
5841         if (ret) {
5842                 set_cpu_active(cpu, true);
5843                 return ret;
5844         }
5845         sched_domains_numa_masks_clear(cpu);
5846         return 0;
5847 }
5848
5849 static void sched_rq_cpu_starting(unsigned int cpu)
5850 {
5851         struct rq *rq = cpu_rq(cpu);
5852
5853         rq->calc_load_update = calc_load_update;
5854         update_max_interval();
5855 }
5856
5857 int sched_cpu_starting(unsigned int cpu)
5858 {
5859         sched_rq_cpu_starting(cpu);
5860         sched_tick_start(cpu);
5861         return 0;
5862 }
5863
5864 #ifdef CONFIG_HOTPLUG_CPU
5865 int sched_cpu_dying(unsigned int cpu)
5866 {
5867         struct rq *rq = cpu_rq(cpu);
5868         struct rq_flags rf;
5869
5870         /* Handle pending wakeups and then migrate everything off */
5871         sched_ttwu_pending();
5872         sched_tick_stop(cpu);
5873
5874         rq_lock_irqsave(rq, &rf);
5875         if (rq->rd) {
5876                 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5877                 set_rq_offline(rq);
5878         }
5879         migrate_tasks(rq, &rf);
5880         BUG_ON(rq->nr_running != 1);
5881         rq_unlock_irqrestore(rq, &rf);
5882
5883         calc_load_migrate(rq);
5884         update_max_interval();
5885         nohz_balance_exit_idle(rq);
5886         hrtick_clear(rq);
5887         return 0;
5888 }
5889 #endif
5890
5891 void __init sched_init_smp(void)
5892 {
5893         sched_init_numa();
5894
5895         /*
5896          * There's no userspace yet to cause hotplug operations; hence all the
5897          * CPU masks are stable and all blatant races in the below code cannot
5898          * happen.
5899          */
5900         mutex_lock(&sched_domains_mutex);
5901         sched_init_domains(cpu_active_mask);
5902         mutex_unlock(&sched_domains_mutex);
5903
5904         /* Move init over to a non-isolated CPU */
5905         if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5906                 BUG();
5907         sched_init_granularity();
5908
5909         init_sched_rt_class();
5910         init_sched_dl_class();
5911
5912         sched_smp_initialized = true;
5913 }
5914
5915 static int __init migration_init(void)
5916 {
5917         sched_rq_cpu_starting(smp_processor_id());
5918         return 0;
5919 }
5920 early_initcall(migration_init);
5921
5922 #else
5923 void __init sched_init_smp(void)
5924 {
5925         sched_init_granularity();
5926 }
5927 #endif /* CONFIG_SMP */
5928
5929 int in_sched_functions(unsigned long addr)
5930 {
5931         return in_lock_functions(addr) ||
5932                 (addr >= (unsigned long)__sched_text_start
5933                 && addr < (unsigned long)__sched_text_end);
5934 }
5935
5936 #ifdef CONFIG_CGROUP_SCHED
5937 /*
5938  * Default task group.
5939  * Every task in system belongs to this group at bootup.
5940  */
5941 struct task_group root_task_group;
5942 LIST_HEAD(task_groups);
5943
5944 /* Cacheline aligned slab cache for task_group */
5945 static struct kmem_cache *task_group_cache __read_mostly;
5946 #endif
5947
5948 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5949 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5950
5951 void __init sched_init(void)
5952 {
5953         int i, j;
5954         unsigned long alloc_size = 0, ptr;
5955
5956         wait_bit_init();
5957
5958 #ifdef CONFIG_FAIR_GROUP_SCHED
5959         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5960 #endif
5961 #ifdef CONFIG_RT_GROUP_SCHED
5962         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5963 #endif
5964         if (alloc_size) {
5965                 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5966
5967 #ifdef CONFIG_FAIR_GROUP_SCHED
5968                 root_task_group.se = (struct sched_entity **)ptr;
5969                 ptr += nr_cpu_ids * sizeof(void **);
5970
5971                 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5972                 ptr += nr_cpu_ids * sizeof(void **);
5973
5974 #endif /* CONFIG_FAIR_GROUP_SCHED */
5975 #ifdef CONFIG_RT_GROUP_SCHED
5976                 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
5977                 ptr += nr_cpu_ids * sizeof(void **);
5978
5979                 root_task_group.rt_rq = (struct rt_rq **)ptr;
5980                 ptr += nr_cpu_ids * sizeof(void **);
5981
5982 #endif /* CONFIG_RT_GROUP_SCHED */
5983         }
5984 #ifdef CONFIG_CPUMASK_OFFSTACK
5985         for_each_possible_cpu(i) {
5986                 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5987                         cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5988                 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5989                         cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5990         }
5991 #endif /* CONFIG_CPUMASK_OFFSTACK */
5992
5993         init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5994         init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
5995
5996 #ifdef CONFIG_SMP
5997         init_defrootdomain();
5998 #endif
5999
6000 #ifdef CONFIG_RT_GROUP_SCHED
6001         init_rt_bandwidth(&root_task_group.rt_bandwidth,
6002                         global_rt_period(), global_rt_runtime());
6003 #endif /* CONFIG_RT_GROUP_SCHED */
6004
6005 #ifdef CONFIG_CGROUP_SCHED
6006         task_group_cache = KMEM_CACHE(task_group, 0);
6007
6008         list_add(&root_task_group.list, &task_groups);
6009         INIT_LIST_HEAD(&root_task_group.children);
6010         INIT_LIST_HEAD(&root_task_group.siblings);
6011         autogroup_init(&init_task);
6012 #endif /* CONFIG_CGROUP_SCHED */
6013
6014         for_each_possible_cpu(i) {
6015                 struct rq *rq;
6016
6017                 rq = cpu_rq(i);
6018                 raw_spin_lock_init(&rq->lock);
6019                 rq->nr_running = 0;
6020                 rq->calc_load_active = 0;
6021                 rq->calc_load_update = jiffies + LOAD_FREQ;
6022                 init_cfs_rq(&rq->cfs);
6023                 init_rt_rq(&rq->rt);
6024                 init_dl_rq(&rq->dl);
6025 #ifdef CONFIG_FAIR_GROUP_SCHED
6026                 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6027                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6028                 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
6029                 /*
6030                  * How much CPU bandwidth does root_task_group get?
6031                  *
6032                  * In case of task-groups formed thr' the cgroup filesystem, it
6033                  * gets 100% of the CPU resources in the system. This overall
6034                  * system CPU resource is divided among the tasks of
6035                  * root_task_group and its child task-groups in a fair manner,
6036                  * based on each entity's (task or task-group's) weight
6037                  * (se->load.weight).
6038                  *
6039                  * In other words, if root_task_group has 10 tasks of weight
6040                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
6041                  * then A0's share of the CPU resource is:
6042                  *
6043                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
6044                  *
6045                  * We achieve this by letting root_task_group's tasks sit
6046                  * directly in rq->cfs (i.e root_task_group->se[] = NULL).
6047                  */
6048                 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6049                 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
6050 #endif /* CONFIG_FAIR_GROUP_SCHED */
6051
6052                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6053 #ifdef CONFIG_RT_GROUP_SCHED
6054                 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6055 #endif
6056
6057                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6058                         rq->cpu_load[j] = 0;
6059
6060 #ifdef CONFIG_SMP
6061                 rq->sd = NULL;
6062                 rq->rd = NULL;
6063                 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6064                 rq->balance_callback = NULL;
6065                 rq->active_balance = 0;
6066                 rq->next_balance = jiffies;
6067                 rq->push_cpu = 0;
6068                 rq->cpu = i;
6069                 rq->online = 0;
6070                 rq->idle_stamp = 0;
6071                 rq->avg_idle = 2*sysctl_sched_migration_cost;
6072                 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6073
6074                 INIT_LIST_HEAD(&rq->cfs_tasks);
6075
6076                 rq_attach_root(rq, &def_root_domain);
6077 #ifdef CONFIG_NO_HZ_COMMON
6078                 rq->last_load_update_tick = jiffies;
6079                 rq->last_blocked_load_update_tick = jiffies;
6080                 atomic_set(&rq->nohz_flags, 0);
6081 #endif
6082 #endif /* CONFIG_SMP */
6083                 hrtick_rq_init(rq);
6084                 atomic_set(&rq->nr_iowait, 0);
6085         }
6086
6087         set_load_weight(&init_task, false);
6088
6089         /*
6090          * The boot idle thread does lazy MMU switching as well:
6091          */
6092         mmgrab(&init_mm);
6093         enter_lazy_tlb(&init_mm, current);
6094
6095         /*
6096          * Make us the idle thread. Technically, schedule() should not be
6097          * called from this thread, however somewhere below it might be,
6098          * but because we are the idle thread, we just pick up running again
6099          * when this runqueue becomes "idle".
6100          */
6101         init_idle(current, smp_processor_id());
6102
6103         calc_load_update = jiffies + LOAD_FREQ;
6104
6105 #ifdef CONFIG_SMP
6106         idle_thread_set_boot_cpu();
6107 #endif
6108         init_sched_fair_class();
6109
6110         init_schedstats();
6111
6112         psi_init();
6113
6114         scheduler_running = 1;
6115 }
6116
6117 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6118 static inline int preempt_count_equals(int preempt_offset)
6119 {
6120         int nested = preempt_count() + rcu_preempt_depth();
6121
6122         return (nested == preempt_offset);
6123 }
6124
6125 void __might_sleep(const char *file, int line, int preempt_offset)
6126 {
6127         /*
6128          * Blocking primitives will set (and therefore destroy) current->state,
6129          * since we will exit with TASK_RUNNING make sure we enter with it,
6130          * otherwise we will destroy state.
6131          */
6132         WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6133                         "do not call blocking ops when !TASK_RUNNING; "
6134                         "state=%lx set at [<%p>] %pS\n",
6135                         current->state,
6136                         (void *)current->task_state_change,
6137                         (void *)current->task_state_change);
6138
6139         ___might_sleep(file, line, preempt_offset);
6140 }
6141 EXPORT_SYMBOL(__might_sleep);
6142
6143 void ___might_sleep(const char *file, int line, int preempt_offset)
6144 {
6145         /* Ratelimiting timestamp: */
6146         static unsigned long prev_jiffy;
6147
6148         unsigned long preempt_disable_ip;
6149
6150         /* WARN_ON_ONCE() by default, no rate limit required: */
6151         rcu_sleep_check();
6152
6153         if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6154              !is_idle_task(current)) ||
6155             system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6156             oops_in_progress)
6157                 return;
6158
6159         if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6160                 return;
6161         prev_jiffy = jiffies;
6162
6163         /* Save this before calling printk(), since that will clobber it: */
6164         preempt_disable_ip = get_preempt_disable_ip(current);
6165
6166         printk(KERN_ERR
6167                 "BUG: sleeping function called from invalid context at %s:%d\n",
6168                         file, line);
6169         printk(KERN_ERR
6170                 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6171                         in_atomic(), irqs_disabled(),
6172                         current->pid, current->comm);
6173
6174         if (task_stack_end_corrupted(current))
6175                 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6176
6177         debug_show_held_locks(current);
6178         if (irqs_disabled())
6179                 print_irqtrace_events(current);
6180         if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6181             && !preempt_count_equals(preempt_offset)) {
6182                 pr_err("Preemption disabled at:");
6183                 print_ip_sym(preempt_disable_ip);
6184                 pr_cont("\n");
6185         }
6186         dump_stack();
6187         add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6188 }
6189 EXPORT_SYMBOL(___might_sleep);
6190 #endif
6191
6192 #ifdef CONFIG_MAGIC_SYSRQ
6193 void normalize_rt_tasks(void)
6194 {
6195         struct task_struct *g, *p;
6196         struct sched_attr attr = {
6197                 .sched_policy = SCHED_NORMAL,
6198         };
6199
6200         read_lock(&tasklist_lock);
6201         for_each_process_thread(g, p) {
6202                 /*
6203                  * Only normalize user tasks:
6204                  */
6205                 if (p->flags & PF_KTHREAD)
6206                         continue;
6207
6208                 p->se.exec_start = 0;
6209                 schedstat_set(p->se.statistics.wait_start,  0);
6210                 schedstat_set(p->se.statistics.sleep_start, 0);
6211                 schedstat_set(p->se.statistics.block_start, 0);
6212
6213                 if (!dl_task(p) && !rt_task(p)) {
6214                         /*
6215                          * Renice negative nice level userspace
6216                          * tasks back to 0:
6217                          */
6218                         if (task_nice(p) < 0)
6219                                 set_user_nice(p, 0);
6220                         continue;
6221                 }
6222
6223                 __sched_setscheduler(p, &attr, false, false);
6224         }
6225         read_unlock(&tasklist_lock);
6226 }
6227
6228 #endif /* CONFIG_MAGIC_SYSRQ */
6229
6230 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6231 /*
6232  * These functions are only useful for the IA64 MCA handling, or kdb.
6233  *
6234  * They can only be called when the whole system has been
6235  * stopped - every CPU needs to be quiescent, and no scheduling
6236  * activity can take place. Using them for anything else would
6237  * be a serious bug, and as a result, they aren't even visible
6238  * under any other configuration.
6239  */
6240
6241 /**
6242  * curr_task - return the current task for a given CPU.
6243  * @cpu: the processor in question.
6244  *
6245  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6246  *
6247  * Return: The current task for @cpu.
6248  */
6249 struct task_struct *curr_task(int cpu)
6250 {
6251         return cpu_curr(cpu);
6252 }
6253
6254 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6255
6256 #ifdef CONFIG_IA64
6257 /**
6258  * set_curr_task - set the current task for a given CPU.
6259  * @cpu: the processor in question.
6260  * @p: the task pointer to set.
6261  *
6262  * Description: This function must only be used when non-maskable interrupts
6263  * are serviced on a separate stack. It allows the architecture to switch the
6264  * notion of the current task on a CPU in a non-blocking manner. This function
6265  * must be called with all CPU's synchronized, and interrupts disabled, the
6266  * and caller must save the original value of the current task (see
6267  * curr_task() above) and restore that value before reenabling interrupts and
6268  * re-starting the system.
6269  *
6270  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6271  */
6272 void ia64_set_curr_task(int cpu, struct task_struct *p)
6273 {
6274         cpu_curr(cpu) = p;
6275 }
6276
6277 #endif
6278
6279 #ifdef CONFIG_CGROUP_SCHED
6280 /* task_group_lock serializes the addition/removal of task groups */
6281 static DEFINE_SPINLOCK(task_group_lock);
6282
6283 static void sched_free_group(struct task_group *tg)
6284 {
6285         free_fair_sched_group(tg);
6286         free_rt_sched_group(tg);
6287         autogroup_free(tg);
6288         kmem_cache_free(task_group_cache, tg);
6289 }
6290
6291 /* allocate runqueue etc for a new task group */
6292 struct task_group *sched_create_group(struct task_group *parent)
6293 {
6294         struct task_group *tg;
6295
6296         tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6297         if (!tg)
6298                 return ERR_PTR(-ENOMEM);
6299
6300         if (!alloc_fair_sched_group(tg, parent))
6301                 goto err;
6302
6303         if (!alloc_rt_sched_group(tg, parent))
6304                 goto err;
6305
6306         return tg;
6307
6308 err:
6309         sched_free_group(tg);
6310         return ERR_PTR(-ENOMEM);
6311 }
6312
6313 void sched_online_group(struct task_group *tg, struct task_group *parent)
6314 {
6315         unsigned long flags;
6316
6317         spin_lock_irqsave(&task_group_lock, flags);
6318         list_add_rcu(&tg->list, &task_groups);
6319
6320         /* Root should already exist: */
6321         WARN_ON(!parent);
6322
6323         tg->parent = parent;
6324         INIT_LIST_HEAD(&tg->children);
6325         list_add_rcu(&tg->siblings, &parent->children);
6326         spin_unlock_irqrestore(&task_group_lock, flags);
6327
6328         online_fair_sched_group(tg);
6329 }
6330
6331 /* rcu callback to free various structures associated with a task group */
6332 static void sched_free_group_rcu(struct rcu_head *rhp)
6333 {
6334         /* Now it should be safe to free those cfs_rqs: */
6335         sched_free_group(container_of(rhp, struct task_group, rcu));
6336 }
6337
6338 void sched_destroy_group(struct task_group *tg)
6339 {
6340         /* Wait for possible concurrent references to cfs_rqs complete: */
6341         call_rcu(&tg->rcu, sched_free_group_rcu);
6342 }
6343
6344 void sched_offline_group(struct task_group *tg)
6345 {
6346         unsigned long flags;
6347
6348         /* End participation in shares distribution: */
6349         unregister_fair_sched_group(tg);
6350
6351         spin_lock_irqsave(&task_group_lock, flags);
6352         list_del_rcu(&tg->list);
6353         list_del_rcu(&tg->siblings);
6354         spin_unlock_irqrestore(&task_group_lock, flags);
6355 }
6356
6357 static void sched_change_group(struct task_struct *tsk, int type)
6358 {
6359         struct task_group *tg;
6360
6361         /*
6362          * All callers are synchronized by task_rq_lock(); we do not use RCU
6363          * which is pointless here. Thus, we pass "true" to task_css_check()
6364          * to prevent lockdep warnings.
6365          */
6366         tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6367                           struct task_group, css);
6368         tg = autogroup_task_group(tsk, tg);
6369         tsk->sched_task_group = tg;
6370
6371 #ifdef CONFIG_FAIR_GROUP_SCHED
6372         if (tsk->sched_class->task_change_group)
6373                 tsk->sched_class->task_change_group(tsk, type);
6374         else
6375 #endif
6376                 set_task_rq(tsk, task_cpu(tsk));
6377 }
6378
6379 /*
6380  * Change task's runqueue when it moves between groups.
6381  *
6382  * The caller of this function should have put the task in its new group by
6383  * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6384  * its new group.
6385  */
6386 void sched_move_task(struct task_struct *tsk)
6387 {
6388         int queued, running, queue_flags =
6389                 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6390         struct rq_flags rf;
6391         struct rq *rq;
6392
6393         rq = task_rq_lock(tsk, &rf);
6394         update_rq_clock(rq);
6395
6396         running = task_current(rq, tsk);
6397         queued = task_on_rq_queued(tsk);
6398
6399         if (queued)
6400                 dequeue_task(rq, tsk, queue_flags);
6401         if (running)
6402                 put_prev_task(rq, tsk);
6403
6404         sched_change_group(tsk, TASK_MOVE_GROUP);
6405
6406         if (queued)
6407                 enqueue_task(rq, tsk, queue_flags);
6408         if (running)
6409                 set_curr_task(rq, tsk);
6410
6411         task_rq_unlock(rq, tsk, &rf);
6412 }
6413
6414 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6415 {
6416         return css ? container_of(css, struct task_group, css) : NULL;
6417 }
6418
6419 static struct cgroup_subsys_state *
6420 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6421 {
6422         struct task_group *parent = css_tg(parent_css);
6423         struct task_group *tg;
6424
6425         if (!parent) {
6426                 /* This is early initialization for the top cgroup */
6427                 return &root_task_group.css;
6428         }
6429
6430         tg = sched_create_group(parent);
6431         if (IS_ERR(tg))
6432                 return ERR_PTR(-ENOMEM);
6433
6434         return &tg->css;
6435 }
6436
6437 /* Expose task group only after completing cgroup initialization */
6438 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6439 {
6440         struct task_group *tg = css_tg(css);
6441         struct task_group *parent = css_tg(css->parent);
6442
6443         if (parent)
6444                 sched_online_group(tg, parent);
6445         return 0;
6446 }
6447
6448 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6449 {
6450         struct task_group *tg = css_tg(css);
6451
6452         sched_offline_group(tg);
6453 }
6454
6455 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6456 {
6457         struct task_group *tg = css_tg(css);
6458
6459         /*
6460          * Relies on the RCU grace period between css_released() and this.
6461          */
6462         sched_free_group(tg);
6463 }
6464
6465 /*
6466  * This is called before wake_up_new_task(), therefore we really only
6467  * have to set its group bits, all the other stuff does not apply.
6468  */
6469 static void cpu_cgroup_fork(struct task_struct *task)
6470 {
6471         struct rq_flags rf;
6472         struct rq *rq;
6473
6474         rq = task_rq_lock(task, &rf);
6475
6476         update_rq_clock(rq);
6477         sched_change_group(task, TASK_SET_GROUP);
6478
6479         task_rq_unlock(rq, task, &rf);
6480 }
6481
6482 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6483 {
6484         struct task_struct *task;
6485         struct cgroup_subsys_state *css;
6486         int ret = 0;
6487
6488         cgroup_taskset_for_each(task, css, tset) {
6489 #ifdef CONFIG_RT_GROUP_SCHED
6490                 if (!sched_rt_can_attach(css_tg(css), task))
6491                         return -EINVAL;
6492 #else
6493                 /* We don't support RT-tasks being in separate groups */
6494                 if (task->sched_class != &fair_sched_class)
6495                         return -EINVAL;
6496 #endif
6497                 /*
6498                  * Serialize against wake_up_new_task() such that if its
6499                  * running, we're sure to observe its full state.
6500                  */
6501                 raw_spin_lock_irq(&task->pi_lock);
6502                 /*
6503                  * Avoid calling sched_move_task() before wake_up_new_task()
6504                  * has happened. This would lead to problems with PELT, due to
6505                  * move wanting to detach+attach while we're not attached yet.
6506                  */
6507                 if (task->state == TASK_NEW)
6508                         ret = -EINVAL;
6509                 raw_spin_unlock_irq(&task->pi_lock);
6510
6511                 if (ret)
6512                         break;
6513         }
6514         return ret;
6515 }
6516
6517 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6518 {
6519         struct task_struct *task;
6520         struct cgroup_subsys_state *css;
6521
6522         cgroup_taskset_for_each(task, css, tset)
6523                 sched_move_task(task);
6524 }
6525
6526 #ifdef CONFIG_FAIR_GROUP_SCHED
6527 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6528                                 struct cftype *cftype, u64 shareval)
6529 {
6530         return sched_group_set_shares(css_tg(css), scale_load(shareval));
6531 }
6532
6533 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6534                                struct cftype *cft)
6535 {
6536         struct task_group *tg = css_tg(css);
6537
6538         return (u64) scale_load_down(tg->shares);
6539 }
6540
6541 #ifdef CONFIG_CFS_BANDWIDTH
6542 static DEFINE_MUTEX(cfs_constraints_mutex);
6543
6544 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6545 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6546
6547 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6548
6549 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6550 {
6551         int i, ret = 0, runtime_enabled, runtime_was_enabled;
6552         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6553
6554         if (tg == &root_task_group)
6555                 return -EINVAL;
6556
6557         /*
6558          * Ensure we have at some amount of bandwidth every period.  This is
6559          * to prevent reaching a state of large arrears when throttled via
6560          * entity_tick() resulting in prolonged exit starvation.
6561          */
6562         if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6563                 return -EINVAL;
6564
6565         /*
6566          * Likewise, bound things on the otherside by preventing insane quota
6567          * periods.  This also allows us to normalize in computing quota
6568          * feasibility.
6569          */
6570         if (period > max_cfs_quota_period)
6571                 return -EINVAL;
6572
6573         /*
6574          * Prevent race between setting of cfs_rq->runtime_enabled and
6575          * unthrottle_offline_cfs_rqs().
6576          */
6577         get_online_cpus();
6578         mutex_lock(&cfs_constraints_mutex);
6579         ret = __cfs_schedulable(tg, period, quota);
6580         if (ret)
6581                 goto out_unlock;
6582
6583         runtime_enabled = quota != RUNTIME_INF;
6584         runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6585         /*
6586          * If we need to toggle cfs_bandwidth_used, off->on must occur
6587          * before making related changes, and on->off must occur afterwards
6588          */
6589         if (runtime_enabled && !runtime_was_enabled)
6590                 cfs_bandwidth_usage_inc();
6591         raw_spin_lock_irq(&cfs_b->lock);
6592         cfs_b->period = ns_to_ktime(period);
6593         cfs_b->quota = quota;
6594
6595         __refill_cfs_bandwidth_runtime(cfs_b);
6596
6597         /* Restart the period timer (if active) to handle new period expiry: */
6598         if (runtime_enabled)
6599                 start_cfs_bandwidth(cfs_b);
6600
6601         raw_spin_unlock_irq(&cfs_b->lock);
6602
6603         for_each_online_cpu(i) {
6604                 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
6605                 struct rq *rq = cfs_rq->rq;
6606                 struct rq_flags rf;
6607
6608                 rq_lock_irq(rq, &rf);
6609                 cfs_rq->runtime_enabled = runtime_enabled;
6610                 cfs_rq->runtime_remaining = 0;
6611
6612                 if (cfs_rq->throttled)
6613                         unthrottle_cfs_rq(cfs_rq);
6614                 rq_unlock_irq(rq, &rf);
6615         }
6616         if (runtime_was_enabled && !runtime_enabled)
6617                 cfs_bandwidth_usage_dec();
6618 out_unlock:
6619         mutex_unlock(&cfs_constraints_mutex);
6620         put_online_cpus();
6621
6622         return ret;
6623 }
6624
6625 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6626 {
6627         u64 quota, period;
6628
6629         period = ktime_to_ns(tg->cfs_bandwidth.period);
6630         if (cfs_quota_us < 0)
6631                 quota = RUNTIME_INF;
6632         else
6633                 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6634
6635         return tg_set_cfs_bandwidth(tg, period, quota);
6636 }
6637
6638 long tg_get_cfs_quota(struct task_group *tg)
6639 {
6640         u64 quota_us;
6641
6642         if (tg->cfs_bandwidth.quota == RUNTIME_INF)
6643                 return -1;
6644
6645         quota_us = tg->cfs_bandwidth.quota;
6646         do_div(quota_us, NSEC_PER_USEC);
6647
6648         return quota_us;
6649 }
6650
6651 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6652 {
6653         u64 quota, period;
6654
6655         period = (u64)cfs_period_us * NSEC_PER_USEC;
6656         quota = tg->cfs_bandwidth.quota;
6657
6658         return tg_set_cfs_bandwidth(tg, period, quota);
6659 }
6660
6661 long tg_get_cfs_period(struct task_group *tg)
6662 {
6663         u64 cfs_period_us;
6664
6665         cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
6666         do_div(cfs_period_us, NSEC_PER_USEC);
6667
6668         return cfs_period_us;
6669 }
6670
6671 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6672                                   struct cftype *cft)
6673 {
6674         return tg_get_cfs_quota(css_tg(css));
6675 }
6676
6677 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6678                                    struct cftype *cftype, s64 cfs_quota_us)
6679 {
6680         return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
6681 }
6682
6683 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6684                                    struct cftype *cft)
6685 {
6686         return tg_get_cfs_period(css_tg(css));
6687 }
6688
6689 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6690                                     struct cftype *cftype, u64 cfs_period_us)
6691 {
6692         return tg_set_cfs_period(css_tg(css), cfs_period_us);
6693 }
6694
6695 struct cfs_schedulable_data {
6696         struct task_group *tg;
6697         u64 period, quota;
6698 };
6699
6700 /*
6701  * normalize group quota/period to be quota/max_period
6702  * note: units are usecs
6703  */
6704 static u64 normalize_cfs_quota(struct task_group *tg,
6705                                struct cfs_schedulable_data *d)
6706 {
6707         u64 quota, period;
6708
6709         if (tg == d->tg) {
6710                 period = d->period;
6711                 quota = d->quota;
6712         } else {
6713                 period = tg_get_cfs_period(tg);
6714                 quota = tg_get_cfs_quota(tg);
6715         }
6716
6717         /* note: these should typically be equivalent */
6718         if (quota == RUNTIME_INF || quota == -1)
6719                 return RUNTIME_INF;
6720
6721         return to_ratio(period, quota);
6722 }
6723
6724 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6725 {
6726         struct cfs_schedulable_data *d = data;
6727         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6728         s64 quota = 0, parent_quota = -1;
6729
6730         if (!tg->parent) {
6731                 quota = RUNTIME_INF;
6732         } else {
6733                 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
6734
6735                 quota = normalize_cfs_quota(tg, d);
6736                 parent_quota = parent_b->hierarchical_quota;
6737
6738                 /*
6739                  * Ensure max(child_quota) <= parent_quota.  On cgroup2,
6740                  * always take the min.  On cgroup1, only inherit when no
6741                  * limit is set:
6742                  */
6743                 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6744                         quota = min(quota, parent_quota);
6745                 } else {
6746                         if (quota == RUNTIME_INF)
6747                                 quota = parent_quota;
6748                         else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6749                                 return -EINVAL;
6750                 }
6751         }
6752         cfs_b->hierarchical_quota = quota;
6753
6754         return 0;
6755 }
6756
6757 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6758 {
6759         int ret;
6760         struct cfs_schedulable_data data = {
6761                 .tg = tg,
6762                 .period = period,
6763                 .quota = quota,
6764         };
6765
6766         if (quota != RUNTIME_INF) {
6767                 do_div(data.period, NSEC_PER_USEC);
6768                 do_div(data.quota, NSEC_PER_USEC);
6769         }
6770
6771         rcu_read_lock();
6772         ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6773         rcu_read_unlock();
6774
6775         return ret;
6776 }
6777
6778 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
6779 {
6780         struct task_group *tg = css_tg(seq_css(sf));
6781         struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6782
6783         seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6784         seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6785         seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
6786
6787         if (schedstat_enabled() && tg != &root_task_group) {
6788                 u64 ws = 0;
6789                 int i;
6790
6791                 for_each_possible_cpu(i)
6792                         ws += schedstat_val(tg->se[i]->statistics.wait_sum);
6793
6794                 seq_printf(sf, "wait_sum %llu\n", ws);
6795         }
6796
6797         return 0;
6798 }
6799 #endif /* CONFIG_CFS_BANDWIDTH */
6800 #endif /* CONFIG_FAIR_GROUP_SCHED */
6801
6802 #ifdef CONFIG_RT_GROUP_SCHED
6803 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6804                                 struct cftype *cft, s64 val)
6805 {
6806         return sched_group_set_rt_runtime(css_tg(css), val);
6807 }
6808
6809 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6810                                struct cftype *cft)
6811 {
6812         return sched_group_rt_runtime(css_tg(css));
6813 }
6814
6815 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6816                                     struct cftype *cftype, u64 rt_period_us)
6817 {
6818         return sched_group_set_rt_period(css_tg(css), rt_period_us);
6819 }
6820
6821 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6822                                    struct cftype *cft)
6823 {
6824         return sched_group_rt_period(css_tg(css));
6825 }
6826 #endif /* CONFIG_RT_GROUP_SCHED */
6827
6828 static struct cftype cpu_legacy_files[] = {
6829 #ifdef CONFIG_FAIR_GROUP_SCHED
6830         {
6831                 .name = "shares",
6832                 .read_u64 = cpu_shares_read_u64,
6833                 .write_u64 = cpu_shares_write_u64,
6834         },
6835 #endif
6836 #ifdef CONFIG_CFS_BANDWIDTH
6837         {
6838                 .name = "cfs_quota_us",
6839                 .read_s64 = cpu_cfs_quota_read_s64,
6840                 .write_s64 = cpu_cfs_quota_write_s64,
6841         },
6842         {
6843                 .name = "cfs_period_us",
6844                 .read_u64 = cpu_cfs_period_read_u64,
6845                 .write_u64 = cpu_cfs_period_write_u64,
6846         },
6847         {
6848                 .name = "stat",
6849                 .seq_show = cpu_cfs_stat_show,
6850         },
6851 #endif
6852 #ifdef CONFIG_RT_GROUP_SCHED
6853         {
6854                 .name = "rt_runtime_us",
6855                 .read_s64 = cpu_rt_runtime_read,
6856                 .write_s64 = cpu_rt_runtime_write,
6857         },
6858         {
6859                 .name = "rt_period_us",
6860                 .read_u64 = cpu_rt_period_read_uint,
6861                 .write_u64 = cpu_rt_period_write_uint,
6862         },
6863 #endif
6864         { }     /* Terminate */
6865 };
6866
6867 static int cpu_extra_stat_show(struct seq_file *sf,
6868                                struct cgroup_subsys_state *css)
6869 {
6870 #ifdef CONFIG_CFS_BANDWIDTH
6871         {
6872                 struct task_group *tg = css_tg(css);
6873                 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6874                 u64 throttled_usec;
6875
6876                 throttled_usec = cfs_b->throttled_time;
6877                 do_div(throttled_usec, NSEC_PER_USEC);
6878
6879                 seq_printf(sf, "nr_periods %d\n"
6880                            "nr_throttled %d\n"
6881                            "throttled_usec %llu\n",
6882                            cfs_b->nr_periods, cfs_b->nr_throttled,
6883                            throttled_usec);
6884         }
6885 #endif
6886         return 0;
6887 }
6888
6889 #ifdef CONFIG_FAIR_GROUP_SCHED
6890 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6891                                struct cftype *cft)
6892 {
6893         struct task_group *tg = css_tg(css);
6894         u64 weight = scale_load_down(tg->shares);
6895
6896         return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6897 }
6898
6899 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6900                                 struct cftype *cft, u64 weight)
6901 {
6902         /*
6903          * cgroup weight knobs should use the common MIN, DFL and MAX
6904          * values which are 1, 100 and 10000 respectively.  While it loses
6905          * a bit of range on both ends, it maps pretty well onto the shares
6906          * value used by scheduler and the round-trip conversions preserve
6907          * the original value over the entire range.
6908          */
6909         if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6910                 return -ERANGE;
6911
6912         weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6913
6914         return sched_group_set_shares(css_tg(css), scale_load(weight));
6915 }
6916
6917 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6918                                     struct cftype *cft)
6919 {
6920         unsigned long weight = scale_load_down(css_tg(css)->shares);
6921         int last_delta = INT_MAX;
6922         int prio, delta;
6923
6924         /* find the closest nice value to the current weight */
6925         for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6926                 delta = abs(sched_prio_to_weight[prio] - weight);
6927                 if (delta >= last_delta)
6928                         break;
6929                 last_delta = delta;
6930         }
6931
6932         return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6933 }
6934
6935 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6936                                      struct cftype *cft, s64 nice)
6937 {
6938         unsigned long weight;
6939         int idx;
6940
6941         if (nice < MIN_NICE || nice > MAX_NICE)
6942                 return -ERANGE;
6943
6944         idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6945         idx = array_index_nospec(idx, 40);
6946         weight = sched_prio_to_weight[idx];
6947
6948         return sched_group_set_shares(css_tg(css), scale_load(weight));
6949 }
6950 #endif
6951
6952 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6953                                                   long period, long quota)
6954 {
6955         if (quota < 0)
6956                 seq_puts(sf, "max");
6957         else
6958                 seq_printf(sf, "%ld", quota);
6959
6960         seq_printf(sf, " %ld\n", period);
6961 }
6962
6963 /* caller should put the current value in *@periodp before calling */
6964 static int __maybe_unused cpu_period_quota_parse(char *buf,
6965                                                  u64 *periodp, u64 *quotap)
6966 {
6967         char tok[21];   /* U64_MAX */
6968
6969         if (!sscanf(buf, "%s %llu", tok, periodp))
6970                 return -EINVAL;
6971
6972         *periodp *= NSEC_PER_USEC;
6973
6974         if (sscanf(tok, "%llu", quotap))
6975                 *quotap *= NSEC_PER_USEC;
6976         else if (!strcmp(tok, "max"))
6977                 *quotap = RUNTIME_INF;
6978         else
6979                 return -EINVAL;
6980
6981         return 0;
6982 }
6983
6984 #ifdef CONFIG_CFS_BANDWIDTH
6985 static int cpu_max_show(struct seq_file *sf, void *v)
6986 {
6987         struct task_group *tg = css_tg(seq_css(sf));
6988
6989         cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6990         return 0;
6991 }
6992
6993 static ssize_t cpu_max_write(struct kernfs_open_file *of,
6994                              char *buf, size_t nbytes, loff_t off)
6995 {
6996         struct task_group *tg = css_tg(of_css(of));
6997         u64 period = tg_get_cfs_period(tg);
6998         u64 quota;
6999         int ret;
7000
7001         ret = cpu_period_quota_parse(buf, &period, &quota);
7002         if (!ret)
7003                 ret = tg_set_cfs_bandwidth(tg, period, quota);
7004         return ret ?: nbytes;
7005 }
7006 #endif
7007
7008 static struct cftype cpu_files[] = {
7009 #ifdef CONFIG_FAIR_GROUP_SCHED
7010         {
7011                 .name = "weight",
7012                 .flags = CFTYPE_NOT_ON_ROOT,
7013                 .read_u64 = cpu_weight_read_u64,
7014                 .write_u64 = cpu_weight_write_u64,
7015         },
7016         {
7017                 .name = "weight.nice",
7018                 .flags = CFTYPE_NOT_ON_ROOT,
7019                 .read_s64 = cpu_weight_nice_read_s64,
7020                 .write_s64 = cpu_weight_nice_write_s64,
7021         },
7022 #endif
7023 #ifdef CONFIG_CFS_BANDWIDTH
7024         {
7025                 .name = "max",
7026                 .flags = CFTYPE_NOT_ON_ROOT,
7027                 .seq_show = cpu_max_show,
7028                 .write = cpu_max_write,
7029         },
7030 #endif
7031         { }     /* terminate */
7032 };
7033
7034 struct cgroup_subsys cpu_cgrp_subsys = {
7035         .css_alloc      = cpu_cgroup_css_alloc,
7036         .css_online     = cpu_cgroup_css_online,
7037         .css_released   = cpu_cgroup_css_released,
7038         .css_free       = cpu_cgroup_css_free,
7039         .css_extra_stat_show = cpu_extra_stat_show,
7040         .fork           = cpu_cgroup_fork,
7041         .can_attach     = cpu_cgroup_can_attach,
7042         .attach         = cpu_cgroup_attach,
7043         .legacy_cftypes = cpu_legacy_files,
7044         .dfl_cftypes    = cpu_files,
7045         .early_init     = true,
7046         .threaded       = true,
7047 };
7048
7049 #endif  /* CONFIG_CGROUP_SCHED */
7050
7051 void dump_cpu_task(int cpu)
7052 {
7053         pr_info("Task dump for CPU %d:\n", cpu);
7054         sched_show_task(cpu_curr(cpu));
7055 }
7056
7057 /*
7058  * Nice levels are multiplicative, with a gentle 10% change for every
7059  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
7060  * nice 1, it will get ~10% less CPU time than another CPU-bound task
7061  * that remained on nice 0.
7062  *
7063  * The "10% effect" is relative and cumulative: from _any_ nice level,
7064  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7065  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7066  * If a task goes up by ~10% and another task goes down by ~10% then
7067  * the relative distance between them is ~25%.)
7068  */
7069 const int sched_prio_to_weight[40] = {
7070  /* -20 */     88761,     71755,     56483,     46273,     36291,
7071  /* -15 */     29154,     23254,     18705,     14949,     11916,
7072  /* -10 */      9548,      7620,      6100,      4904,      3906,
7073  /*  -5 */      3121,      2501,      1991,      1586,      1277,
7074  /*   0 */      1024,       820,       655,       526,       423,
7075  /*   5 */       335,       272,       215,       172,       137,
7076  /*  10 */       110,        87,        70,        56,        45,
7077  /*  15 */        36,        29,        23,        18,        15,
7078 };
7079
7080 /*
7081  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7082  *
7083  * In cases where the weight does not change often, we can use the
7084  * precalculated inverse to speed up arithmetics by turning divisions
7085  * into multiplications:
7086  */
7087 const u32 sched_prio_to_wmult[40] = {
7088  /* -20 */     48388,     59856,     76040,     92818,    118348,
7089  /* -15 */    147320,    184698,    229616,    287308,    360437,
7090  /* -10 */    449829,    563644,    704093,    875809,   1099582,
7091  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
7092  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
7093  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
7094  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
7095  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
7096 };
7097
7098 #undef CREATE_TRACE_POINTS