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