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