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