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