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