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