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