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