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