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