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