Merge tag 'usb-serial-6.6-rc7' of https://git.kernel.org/pub/scm/linux/kernel/git...
[platform/kernel/linux-rpi.git] / kernel / sched / fair.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4  *
5  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6  *
7  *  Interactivity improvements by Mike Galbraith
8  *  (C) 2007 Mike Galbraith <efault@gmx.de>
9  *
10  *  Various enhancements by Dmitry Adamushko.
11  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12  *
13  *  Group scheduling enhancements by Srivatsa Vaddagiri
14  *  Copyright IBM Corporation, 2007
15  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16  *
17  *  Scaled math optimizations by Thomas Gleixner
18  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19  *
20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22  */
23 #include <linux/energy_model.h>
24 #include <linux/mmap_lock.h>
25 #include <linux/hugetlb_inline.h>
26 #include <linux/jiffies.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/spinlock_api.h>
30 #include <linux/cpumask_api.h>
31 #include <linux/lockdep_api.h>
32 #include <linux/softirq.h>
33 #include <linux/refcount_api.h>
34 #include <linux/topology.h>
35 #include <linux/sched/clock.h>
36 #include <linux/sched/cond_resched.h>
37 #include <linux/sched/cputime.h>
38 #include <linux/sched/isolation.h>
39 #include <linux/sched/nohz.h>
40
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
51
52 #include <asm/switch_to.h>
53
54 #include <linux/sched/cond_resched.h>
55
56 #include "sched.h"
57 #include "stats.h"
58 #include "autogroup.h"
59
60 /*
61  * The initial- and re-scaling of tunables is configurable
62  *
63  * Options are:
64  *
65  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
66  *   SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
67  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
68  *
69  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
70  */
71 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
72
73 /*
74  * Minimal preemption granularity for CPU-bound tasks:
75  *
76  * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
77  */
78 unsigned int sysctl_sched_base_slice                    = 750000ULL;
79 static unsigned int normalized_sysctl_sched_base_slice  = 750000ULL;
80
81 /*
82  * After fork, child runs first. If set to 0 (default) then
83  * parent will (try to) run first.
84  */
85 unsigned int sysctl_sched_child_runs_first __read_mostly;
86
87 const_debug unsigned int sysctl_sched_migration_cost    = 500000UL;
88
89 int sched_thermal_decay_shift;
90 static int __init setup_sched_thermal_decay_shift(char *str)
91 {
92         int _shift = 0;
93
94         if (kstrtoint(str, 0, &_shift))
95                 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
96
97         sched_thermal_decay_shift = clamp(_shift, 0, 10);
98         return 1;
99 }
100 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
101
102 #ifdef CONFIG_SMP
103 /*
104  * For asym packing, by default the lower numbered CPU has higher priority.
105  */
106 int __weak arch_asym_cpu_priority(int cpu)
107 {
108         return -cpu;
109 }
110
111 /*
112  * The margin used when comparing utilization with CPU capacity.
113  *
114  * (default: ~20%)
115  */
116 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
117
118 /*
119  * The margin used when comparing CPU capacities.
120  * is 'cap1' noticeably greater than 'cap2'
121  *
122  * (default: ~5%)
123  */
124 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
125 #endif
126
127 #ifdef CONFIG_CFS_BANDWIDTH
128 /*
129  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
130  * each time a cfs_rq requests quota.
131  *
132  * Note: in the case that the slice exceeds the runtime remaining (either due
133  * to consumption or the quota being specified to be smaller than the slice)
134  * we will always only issue the remaining available time.
135  *
136  * (default: 5 msec, units: microseconds)
137  */
138 static unsigned int sysctl_sched_cfs_bandwidth_slice            = 5000UL;
139 #endif
140
141 #ifdef CONFIG_NUMA_BALANCING
142 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
143 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
144 #endif
145
146 #ifdef CONFIG_SYSCTL
147 static struct ctl_table sched_fair_sysctls[] = {
148         {
149                 .procname       = "sched_child_runs_first",
150                 .data           = &sysctl_sched_child_runs_first,
151                 .maxlen         = sizeof(unsigned int),
152                 .mode           = 0644,
153                 .proc_handler   = proc_dointvec,
154         },
155 #ifdef CONFIG_CFS_BANDWIDTH
156         {
157                 .procname       = "sched_cfs_bandwidth_slice_us",
158                 .data           = &sysctl_sched_cfs_bandwidth_slice,
159                 .maxlen         = sizeof(unsigned int),
160                 .mode           = 0644,
161                 .proc_handler   = proc_dointvec_minmax,
162                 .extra1         = SYSCTL_ONE,
163         },
164 #endif
165 #ifdef CONFIG_NUMA_BALANCING
166         {
167                 .procname       = "numa_balancing_promote_rate_limit_MBps",
168                 .data           = &sysctl_numa_balancing_promote_rate_limit,
169                 .maxlen         = sizeof(unsigned int),
170                 .mode           = 0644,
171                 .proc_handler   = proc_dointvec_minmax,
172                 .extra1         = SYSCTL_ZERO,
173         },
174 #endif /* CONFIG_NUMA_BALANCING */
175         {}
176 };
177
178 static int __init sched_fair_sysctl_init(void)
179 {
180         register_sysctl_init("kernel", sched_fair_sysctls);
181         return 0;
182 }
183 late_initcall(sched_fair_sysctl_init);
184 #endif
185
186 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
187 {
188         lw->weight += inc;
189         lw->inv_weight = 0;
190 }
191
192 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
193 {
194         lw->weight -= dec;
195         lw->inv_weight = 0;
196 }
197
198 static inline void update_load_set(struct load_weight *lw, unsigned long w)
199 {
200         lw->weight = w;
201         lw->inv_weight = 0;
202 }
203
204 /*
205  * Increase the granularity value when there are more CPUs,
206  * because with more CPUs the 'effective latency' as visible
207  * to users decreases. But the relationship is not linear,
208  * so pick a second-best guess by going with the log2 of the
209  * number of CPUs.
210  *
211  * This idea comes from the SD scheduler of Con Kolivas:
212  */
213 static unsigned int get_update_sysctl_factor(void)
214 {
215         unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
216         unsigned int factor;
217
218         switch (sysctl_sched_tunable_scaling) {
219         case SCHED_TUNABLESCALING_NONE:
220                 factor = 1;
221                 break;
222         case SCHED_TUNABLESCALING_LINEAR:
223                 factor = cpus;
224                 break;
225         case SCHED_TUNABLESCALING_LOG:
226         default:
227                 factor = 1 + ilog2(cpus);
228                 break;
229         }
230
231         return factor;
232 }
233
234 static void update_sysctl(void)
235 {
236         unsigned int factor = get_update_sysctl_factor();
237
238 #define SET_SYSCTL(name) \
239         (sysctl_##name = (factor) * normalized_sysctl_##name)
240         SET_SYSCTL(sched_base_slice);
241 #undef SET_SYSCTL
242 }
243
244 void __init sched_init_granularity(void)
245 {
246         update_sysctl();
247 }
248
249 #define WMULT_CONST     (~0U)
250 #define WMULT_SHIFT     32
251
252 static void __update_inv_weight(struct load_weight *lw)
253 {
254         unsigned long w;
255
256         if (likely(lw->inv_weight))
257                 return;
258
259         w = scale_load_down(lw->weight);
260
261         if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
262                 lw->inv_weight = 1;
263         else if (unlikely(!w))
264                 lw->inv_weight = WMULT_CONST;
265         else
266                 lw->inv_weight = WMULT_CONST / w;
267 }
268
269 /*
270  * delta_exec * weight / lw.weight
271  *   OR
272  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
273  *
274  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
275  * we're guaranteed shift stays positive because inv_weight is guaranteed to
276  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
277  *
278  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
279  * weight/lw.weight <= 1, and therefore our shift will also be positive.
280  */
281 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
282 {
283         u64 fact = scale_load_down(weight);
284         u32 fact_hi = (u32)(fact >> 32);
285         int shift = WMULT_SHIFT;
286         int fs;
287
288         __update_inv_weight(lw);
289
290         if (unlikely(fact_hi)) {
291                 fs = fls(fact_hi);
292                 shift -= fs;
293                 fact >>= fs;
294         }
295
296         fact = mul_u32_u32(fact, lw->inv_weight);
297
298         fact_hi = (u32)(fact >> 32);
299         if (fact_hi) {
300                 fs = fls(fact_hi);
301                 shift -= fs;
302                 fact >>= fs;
303         }
304
305         return mul_u64_u32_shr(delta_exec, fact, shift);
306 }
307
308 /*
309  * delta /= w
310  */
311 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
312 {
313         if (unlikely(se->load.weight != NICE_0_LOAD))
314                 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
315
316         return delta;
317 }
318
319 const struct sched_class fair_sched_class;
320
321 /**************************************************************
322  * CFS operations on generic schedulable entities:
323  */
324
325 #ifdef CONFIG_FAIR_GROUP_SCHED
326
327 /* Walk up scheduling entities hierarchy */
328 #define for_each_sched_entity(se) \
329                 for (; se; se = se->parent)
330
331 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
332 {
333         struct rq *rq = rq_of(cfs_rq);
334         int cpu = cpu_of(rq);
335
336         if (cfs_rq->on_list)
337                 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
338
339         cfs_rq->on_list = 1;
340
341         /*
342          * Ensure we either appear before our parent (if already
343          * enqueued) or force our parent to appear after us when it is
344          * enqueued. The fact that we always enqueue bottom-up
345          * reduces this to two cases and a special case for the root
346          * cfs_rq. Furthermore, it also means that we will always reset
347          * tmp_alone_branch either when the branch is connected
348          * to a tree or when we reach the top of the tree
349          */
350         if (cfs_rq->tg->parent &&
351             cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
352                 /*
353                  * If parent is already on the list, we add the child
354                  * just before. Thanks to circular linked property of
355                  * the list, this means to put the child at the tail
356                  * of the list that starts by parent.
357                  */
358                 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
359                         &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
360                 /*
361                  * The branch is now connected to its tree so we can
362                  * reset tmp_alone_branch to the beginning of the
363                  * list.
364                  */
365                 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
366                 return true;
367         }
368
369         if (!cfs_rq->tg->parent) {
370                 /*
371                  * cfs rq without parent should be put
372                  * at the tail of the list.
373                  */
374                 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
375                         &rq->leaf_cfs_rq_list);
376                 /*
377                  * We have reach the top of a tree so we can reset
378                  * tmp_alone_branch to the beginning of the list.
379                  */
380                 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
381                 return true;
382         }
383
384         /*
385          * The parent has not already been added so we want to
386          * make sure that it will be put after us.
387          * tmp_alone_branch points to the begin of the branch
388          * where we will add parent.
389          */
390         list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
391         /*
392          * update tmp_alone_branch to points to the new begin
393          * of the branch
394          */
395         rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
396         return false;
397 }
398
399 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
400 {
401         if (cfs_rq->on_list) {
402                 struct rq *rq = rq_of(cfs_rq);
403
404                 /*
405                  * With cfs_rq being unthrottled/throttled during an enqueue,
406                  * it can happen the tmp_alone_branch points the a leaf that
407                  * we finally want to del. In this case, tmp_alone_branch moves
408                  * to the prev element but it will point to rq->leaf_cfs_rq_list
409                  * at the end of the enqueue.
410                  */
411                 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
412                         rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
413
414                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
415                 cfs_rq->on_list = 0;
416         }
417 }
418
419 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
420 {
421         SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
422 }
423
424 /* Iterate thr' all leaf cfs_rq's on a runqueue */
425 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)                      \
426         list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,    \
427                                  leaf_cfs_rq_list)
428
429 /* Do the two (enqueued) entities belong to the same group ? */
430 static inline struct cfs_rq *
431 is_same_group(struct sched_entity *se, struct sched_entity *pse)
432 {
433         if (se->cfs_rq == pse->cfs_rq)
434                 return se->cfs_rq;
435
436         return NULL;
437 }
438
439 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
440 {
441         return se->parent;
442 }
443
444 static void
445 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
446 {
447         int se_depth, pse_depth;
448
449         /*
450          * preemption test can be made between sibling entities who are in the
451          * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
452          * both tasks until we find their ancestors who are siblings of common
453          * parent.
454          */
455
456         /* First walk up until both entities are at same depth */
457         se_depth = (*se)->depth;
458         pse_depth = (*pse)->depth;
459
460         while (se_depth > pse_depth) {
461                 se_depth--;
462                 *se = parent_entity(*se);
463         }
464
465         while (pse_depth > se_depth) {
466                 pse_depth--;
467                 *pse = parent_entity(*pse);
468         }
469
470         while (!is_same_group(*se, *pse)) {
471                 *se = parent_entity(*se);
472                 *pse = parent_entity(*pse);
473         }
474 }
475
476 static int tg_is_idle(struct task_group *tg)
477 {
478         return tg->idle > 0;
479 }
480
481 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
482 {
483         return cfs_rq->idle > 0;
484 }
485
486 static int se_is_idle(struct sched_entity *se)
487 {
488         if (entity_is_task(se))
489                 return task_has_idle_policy(task_of(se));
490         return cfs_rq_is_idle(group_cfs_rq(se));
491 }
492
493 #else   /* !CONFIG_FAIR_GROUP_SCHED */
494
495 #define for_each_sched_entity(se) \
496                 for (; se; se = NULL)
497
498 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
499 {
500         return true;
501 }
502
503 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
504 {
505 }
506
507 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
508 {
509 }
510
511 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)      \
512                 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
513
514 static inline struct sched_entity *parent_entity(struct sched_entity *se)
515 {
516         return NULL;
517 }
518
519 static inline void
520 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
521 {
522 }
523
524 static inline int tg_is_idle(struct task_group *tg)
525 {
526         return 0;
527 }
528
529 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
530 {
531         return 0;
532 }
533
534 static int se_is_idle(struct sched_entity *se)
535 {
536         return 0;
537 }
538
539 #endif  /* CONFIG_FAIR_GROUP_SCHED */
540
541 static __always_inline
542 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
543
544 /**************************************************************
545  * Scheduling class tree data structure manipulation methods:
546  */
547
548 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
549 {
550         s64 delta = (s64)(vruntime - max_vruntime);
551         if (delta > 0)
552                 max_vruntime = vruntime;
553
554         return max_vruntime;
555 }
556
557 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
558 {
559         s64 delta = (s64)(vruntime - min_vruntime);
560         if (delta < 0)
561                 min_vruntime = vruntime;
562
563         return min_vruntime;
564 }
565
566 static inline bool entity_before(const struct sched_entity *a,
567                                  const struct sched_entity *b)
568 {
569         return (s64)(a->vruntime - b->vruntime) < 0;
570 }
571
572 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
573 {
574         return (s64)(se->vruntime - cfs_rq->min_vruntime);
575 }
576
577 #define __node_2_se(node) \
578         rb_entry((node), struct sched_entity, run_node)
579
580 /*
581  * Compute virtual time from the per-task service numbers:
582  *
583  * Fair schedulers conserve lag:
584  *
585  *   \Sum lag_i = 0
586  *
587  * Where lag_i is given by:
588  *
589  *   lag_i = S - s_i = w_i * (V - v_i)
590  *
591  * Where S is the ideal service time and V is it's virtual time counterpart.
592  * Therefore:
593  *
594  *   \Sum lag_i = 0
595  *   \Sum w_i * (V - v_i) = 0
596  *   \Sum w_i * V - w_i * v_i = 0
597  *
598  * From which we can solve an expression for V in v_i (which we have in
599  * se->vruntime):
600  *
601  *       \Sum v_i * w_i   \Sum v_i * w_i
602  *   V = -------------- = --------------
603  *          \Sum w_i            W
604  *
605  * Specifically, this is the weighted average of all entity virtual runtimes.
606  *
607  * [[ NOTE: this is only equal to the ideal scheduler under the condition
608  *          that join/leave operations happen at lag_i = 0, otherwise the
609  *          virtual time has non-continguous motion equivalent to:
610  *
611  *            V +-= lag_i / W
612  *
613  *          Also see the comment in place_entity() that deals with this. ]]
614  *
615  * However, since v_i is u64, and the multiplcation could easily overflow
616  * transform it into a relative form that uses smaller quantities:
617  *
618  * Substitute: v_i == (v_i - v0) + v0
619  *
620  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
621  * V = ---------------------------- = --------------------- + v0
622  *                  W                            W
623  *
624  * Which we track using:
625  *
626  *                    v0 := cfs_rq->min_vruntime
627  * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
628  *              \Sum w_i := cfs_rq->avg_load
629  *
630  * Since min_vruntime is a monotonic increasing variable that closely tracks
631  * the per-task service, these deltas: (v_i - v), will be in the order of the
632  * maximal (virtual) lag induced in the system due to quantisation.
633  *
634  * Also, we use scale_load_down() to reduce the size.
635  *
636  * As measured, the max (key * weight) value was ~44 bits for a kernel build.
637  */
638 static void
639 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
640 {
641         unsigned long weight = scale_load_down(se->load.weight);
642         s64 key = entity_key(cfs_rq, se);
643
644         cfs_rq->avg_vruntime += key * weight;
645         cfs_rq->avg_load += weight;
646 }
647
648 static void
649 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
650 {
651         unsigned long weight = scale_load_down(se->load.weight);
652         s64 key = entity_key(cfs_rq, se);
653
654         cfs_rq->avg_vruntime -= key * weight;
655         cfs_rq->avg_load -= weight;
656 }
657
658 static inline
659 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
660 {
661         /*
662          * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
663          */
664         cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
665 }
666
667 /*
668  * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
669  * For this to be so, the result of this function must have a left bias.
670  */
671 u64 avg_vruntime(struct cfs_rq *cfs_rq)
672 {
673         struct sched_entity *curr = cfs_rq->curr;
674         s64 avg = cfs_rq->avg_vruntime;
675         long load = cfs_rq->avg_load;
676
677         if (curr && curr->on_rq) {
678                 unsigned long weight = scale_load_down(curr->load.weight);
679
680                 avg += entity_key(cfs_rq, curr) * weight;
681                 load += weight;
682         }
683
684         if (load) {
685                 /* sign flips effective floor / ceil */
686                 if (avg < 0)
687                         avg -= (load - 1);
688                 avg = div_s64(avg, load);
689         }
690
691         return cfs_rq->min_vruntime + avg;
692 }
693
694 /*
695  * lag_i = S - s_i = w_i * (V - v_i)
696  *
697  * However, since V is approximated by the weighted average of all entities it
698  * is possible -- by addition/removal/reweight to the tree -- to move V around
699  * and end up with a larger lag than we started with.
700  *
701  * Limit this to either double the slice length with a minimum of TICK_NSEC
702  * since that is the timing granularity.
703  *
704  * EEVDF gives the following limit for a steady state system:
705  *
706  *   -r_max < lag < max(r_max, q)
707  *
708  * XXX could add max_slice to the augmented data to track this.
709  */
710 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
711 {
712         s64 lag, limit;
713
714         SCHED_WARN_ON(!se->on_rq);
715         lag = avg_vruntime(cfs_rq) - se->vruntime;
716
717         limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
718         se->vlag = clamp(lag, -limit, limit);
719 }
720
721 /*
722  * Entity is eligible once it received less service than it ought to have,
723  * eg. lag >= 0.
724  *
725  * lag_i = S - s_i = w_i*(V - v_i)
726  *
727  * lag_i >= 0 -> V >= v_i
728  *
729  *     \Sum (v_i - v)*w_i
730  * V = ------------------ + v
731  *          \Sum w_i
732  *
733  * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
734  *
735  * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
736  *       to the loss in precision caused by the division.
737  */
738 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
739 {
740         struct sched_entity *curr = cfs_rq->curr;
741         s64 avg = cfs_rq->avg_vruntime;
742         long load = cfs_rq->avg_load;
743
744         if (curr && curr->on_rq) {
745                 unsigned long weight = scale_load_down(curr->load.weight);
746
747                 avg += entity_key(cfs_rq, curr) * weight;
748                 load += weight;
749         }
750
751         return avg >= entity_key(cfs_rq, se) * load;
752 }
753
754 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
755 {
756         u64 min_vruntime = cfs_rq->min_vruntime;
757         /*
758          * open coded max_vruntime() to allow updating avg_vruntime
759          */
760         s64 delta = (s64)(vruntime - min_vruntime);
761         if (delta > 0) {
762                 avg_vruntime_update(cfs_rq, delta);
763                 min_vruntime = vruntime;
764         }
765         return min_vruntime;
766 }
767
768 static void update_min_vruntime(struct cfs_rq *cfs_rq)
769 {
770         struct sched_entity *se = __pick_first_entity(cfs_rq);
771         struct sched_entity *curr = cfs_rq->curr;
772
773         u64 vruntime = cfs_rq->min_vruntime;
774
775         if (curr) {
776                 if (curr->on_rq)
777                         vruntime = curr->vruntime;
778                 else
779                         curr = NULL;
780         }
781
782         if (se) {
783                 if (!curr)
784                         vruntime = se->vruntime;
785                 else
786                         vruntime = min_vruntime(vruntime, se->vruntime);
787         }
788
789         /* ensure we never gain time by being placed backwards. */
790         u64_u32_store(cfs_rq->min_vruntime,
791                       __update_min_vruntime(cfs_rq, vruntime));
792 }
793
794 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
795 {
796         return entity_before(__node_2_se(a), __node_2_se(b));
797 }
798
799 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
800
801 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
802 {
803         if (node) {
804                 struct sched_entity *rse = __node_2_se(node);
805                 if (deadline_gt(min_deadline, se, rse))
806                         se->min_deadline = rse->min_deadline;
807         }
808 }
809
810 /*
811  * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
812  */
813 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
814 {
815         u64 old_min_deadline = se->min_deadline;
816         struct rb_node *node = &se->run_node;
817
818         se->min_deadline = se->deadline;
819         __update_min_deadline(se, node->rb_right);
820         __update_min_deadline(se, node->rb_left);
821
822         return se->min_deadline == old_min_deadline;
823 }
824
825 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
826                      run_node, min_deadline, min_deadline_update);
827
828 /*
829  * Enqueue an entity into the rb-tree:
830  */
831 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
832 {
833         avg_vruntime_add(cfs_rq, se);
834         se->min_deadline = se->deadline;
835         rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
836                                 __entity_less, &min_deadline_cb);
837 }
838
839 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
840 {
841         rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
842                                   &min_deadline_cb);
843         avg_vruntime_sub(cfs_rq, se);
844 }
845
846 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
847 {
848         struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
849
850         if (!left)
851                 return NULL;
852
853         return __node_2_se(left);
854 }
855
856 /*
857  * Earliest Eligible Virtual Deadline First
858  *
859  * In order to provide latency guarantees for different request sizes
860  * EEVDF selects the best runnable task from two criteria:
861  *
862  *  1) the task must be eligible (must be owed service)
863  *
864  *  2) from those tasks that meet 1), we select the one
865  *     with the earliest virtual deadline.
866  *
867  * We can do this in O(log n) time due to an augmented RB-tree. The
868  * tree keeps the entries sorted on service, but also functions as a
869  * heap based on the deadline by keeping:
870  *
871  *  se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
872  *
873  * Which allows an EDF like search on (sub)trees.
874  */
875 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq)
876 {
877         struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
878         struct sched_entity *curr = cfs_rq->curr;
879         struct sched_entity *best = NULL;
880         struct sched_entity *best_left = NULL;
881
882         if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
883                 curr = NULL;
884         best = curr;
885
886         /*
887          * Once selected, run a task until it either becomes non-eligible or
888          * until it gets a new slice. See the HACK in set_next_entity().
889          */
890         if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
891                 return curr;
892
893         while (node) {
894                 struct sched_entity *se = __node_2_se(node);
895
896                 /*
897                  * If this entity is not eligible, try the left subtree.
898                  */
899                 if (!entity_eligible(cfs_rq, se)) {
900                         node = node->rb_left;
901                         continue;
902                 }
903
904                 /*
905                  * Now we heap search eligible trees for the best (min_)deadline
906                  */
907                 if (!best || deadline_gt(deadline, best, se))
908                         best = se;
909
910                 /*
911                  * Every se in a left branch is eligible, keep track of the
912                  * branch with the best min_deadline
913                  */
914                 if (node->rb_left) {
915                         struct sched_entity *left = __node_2_se(node->rb_left);
916
917                         if (!best_left || deadline_gt(min_deadline, best_left, left))
918                                 best_left = left;
919
920                         /*
921                          * min_deadline is in the left branch. rb_left and all
922                          * descendants are eligible, so immediately switch to the second
923                          * loop.
924                          */
925                         if (left->min_deadline == se->min_deadline)
926                                 break;
927                 }
928
929                 /* min_deadline is at this node, no need to look right */
930                 if (se->deadline == se->min_deadline)
931                         break;
932
933                 /* else min_deadline is in the right branch. */
934                 node = node->rb_right;
935         }
936
937         /*
938          * We ran into an eligible node which is itself the best.
939          * (Or nr_running == 0 and both are NULL)
940          */
941         if (!best_left || (s64)(best_left->min_deadline - best->deadline) > 0)
942                 return best;
943
944         /*
945          * Now best_left and all of its children are eligible, and we are just
946          * looking for deadline == min_deadline
947          */
948         node = &best_left->run_node;
949         while (node) {
950                 struct sched_entity *se = __node_2_se(node);
951
952                 /* min_deadline is the current node */
953                 if (se->deadline == se->min_deadline)
954                         return se;
955
956                 /* min_deadline is in the left branch */
957                 if (node->rb_left &&
958                     __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
959                         node = node->rb_left;
960                         continue;
961                 }
962
963                 /* else min_deadline is in the right branch */
964                 node = node->rb_right;
965         }
966         return NULL;
967 }
968
969 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
970 {
971         struct sched_entity *se = __pick_eevdf(cfs_rq);
972
973         if (!se) {
974                 struct sched_entity *left = __pick_first_entity(cfs_rq);
975                 if (left) {
976                         pr_err("EEVDF scheduling fail, picking leftmost\n");
977                         return left;
978                 }
979         }
980
981         return se;
982 }
983
984 #ifdef CONFIG_SCHED_DEBUG
985 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
986 {
987         struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
988
989         if (!last)
990                 return NULL;
991
992         return __node_2_se(last);
993 }
994
995 /**************************************************************
996  * Scheduling class statistics methods:
997  */
998 #ifdef CONFIG_SMP
999 int sched_update_scaling(void)
1000 {
1001         unsigned int factor = get_update_sysctl_factor();
1002
1003 #define WRT_SYSCTL(name) \
1004         (normalized_sysctl_##name = sysctl_##name / (factor))
1005         WRT_SYSCTL(sched_base_slice);
1006 #undef WRT_SYSCTL
1007
1008         return 0;
1009 }
1010 #endif
1011 #endif
1012
1013 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1014
1015 /*
1016  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1017  * this is probably good enough.
1018  */
1019 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1020 {
1021         if ((s64)(se->vruntime - se->deadline) < 0)
1022                 return;
1023
1024         /*
1025          * For EEVDF the virtual time slope is determined by w_i (iow.
1026          * nice) while the request time r_i is determined by
1027          * sysctl_sched_base_slice.
1028          */
1029         se->slice = sysctl_sched_base_slice;
1030
1031         /*
1032          * EEVDF: vd_i = ve_i + r_i / w_i
1033          */
1034         se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1035
1036         /*
1037          * The task has consumed its request, reschedule.
1038          */
1039         if (cfs_rq->nr_running > 1) {
1040                 resched_curr(rq_of(cfs_rq));
1041                 clear_buddies(cfs_rq, se);
1042         }
1043 }
1044
1045 #include "pelt.h"
1046 #ifdef CONFIG_SMP
1047
1048 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1049 static unsigned long task_h_load(struct task_struct *p);
1050 static unsigned long capacity_of(int cpu);
1051
1052 /* Give new sched_entity start runnable values to heavy its load in infant time */
1053 void init_entity_runnable_average(struct sched_entity *se)
1054 {
1055         struct sched_avg *sa = &se->avg;
1056
1057         memset(sa, 0, sizeof(*sa));
1058
1059         /*
1060          * Tasks are initialized with full load to be seen as heavy tasks until
1061          * they get a chance to stabilize to their real load level.
1062          * Group entities are initialized with zero load to reflect the fact that
1063          * nothing has been attached to the task group yet.
1064          */
1065         if (entity_is_task(se))
1066                 sa->load_avg = scale_load_down(se->load.weight);
1067
1068         /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1069 }
1070
1071 /*
1072  * With new tasks being created, their initial util_avgs are extrapolated
1073  * based on the cfs_rq's current util_avg:
1074  *
1075  *   util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1076  *
1077  * However, in many cases, the above util_avg does not give a desired
1078  * value. Moreover, the sum of the util_avgs may be divergent, such
1079  * as when the series is a harmonic series.
1080  *
1081  * To solve this problem, we also cap the util_avg of successive tasks to
1082  * only 1/2 of the left utilization budget:
1083  *
1084  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1085  *
1086  * where n denotes the nth task and cpu_scale the CPU capacity.
1087  *
1088  * For example, for a CPU with 1024 of capacity, a simplest series from
1089  * the beginning would be like:
1090  *
1091  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1092  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1093  *
1094  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1095  * if util_avg > util_avg_cap.
1096  */
1097 void post_init_entity_util_avg(struct task_struct *p)
1098 {
1099         struct sched_entity *se = &p->se;
1100         struct cfs_rq *cfs_rq = cfs_rq_of(se);
1101         struct sched_avg *sa = &se->avg;
1102         long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1103         long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1104
1105         if (p->sched_class != &fair_sched_class) {
1106                 /*
1107                  * For !fair tasks do:
1108                  *
1109                 update_cfs_rq_load_avg(now, cfs_rq);
1110                 attach_entity_load_avg(cfs_rq, se);
1111                 switched_from_fair(rq, p);
1112                  *
1113                  * such that the next switched_to_fair() has the
1114                  * expected state.
1115                  */
1116                 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1117                 return;
1118         }
1119
1120         if (cap > 0) {
1121                 if (cfs_rq->avg.util_avg != 0) {
1122                         sa->util_avg  = cfs_rq->avg.util_avg * se->load.weight;
1123                         sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1124
1125                         if (sa->util_avg > cap)
1126                                 sa->util_avg = cap;
1127                 } else {
1128                         sa->util_avg = cap;
1129                 }
1130         }
1131
1132         sa->runnable_avg = sa->util_avg;
1133 }
1134
1135 #else /* !CONFIG_SMP */
1136 void init_entity_runnable_average(struct sched_entity *se)
1137 {
1138 }
1139 void post_init_entity_util_avg(struct task_struct *p)
1140 {
1141 }
1142 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1143 {
1144 }
1145 #endif /* CONFIG_SMP */
1146
1147 /*
1148  * Update the current task's runtime statistics.
1149  */
1150 static void update_curr(struct cfs_rq *cfs_rq)
1151 {
1152         struct sched_entity *curr = cfs_rq->curr;
1153         u64 now = rq_clock_task(rq_of(cfs_rq));
1154         u64 delta_exec;
1155
1156         if (unlikely(!curr))
1157                 return;
1158
1159         delta_exec = now - curr->exec_start;
1160         if (unlikely((s64)delta_exec <= 0))
1161                 return;
1162
1163         curr->exec_start = now;
1164
1165         if (schedstat_enabled()) {
1166                 struct sched_statistics *stats;
1167
1168                 stats = __schedstats_from_se(curr);
1169                 __schedstat_set(stats->exec_max,
1170                                 max(delta_exec, stats->exec_max));
1171         }
1172
1173         curr->sum_exec_runtime += delta_exec;
1174         schedstat_add(cfs_rq->exec_clock, delta_exec);
1175
1176         curr->vruntime += calc_delta_fair(delta_exec, curr);
1177         update_deadline(cfs_rq, curr);
1178         update_min_vruntime(cfs_rq);
1179
1180         if (entity_is_task(curr)) {
1181                 struct task_struct *curtask = task_of(curr);
1182
1183                 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1184                 cgroup_account_cputime(curtask, delta_exec);
1185                 account_group_exec_runtime(curtask, delta_exec);
1186         }
1187
1188         account_cfs_rq_runtime(cfs_rq, delta_exec);
1189 }
1190
1191 static void update_curr_fair(struct rq *rq)
1192 {
1193         update_curr(cfs_rq_of(&rq->curr->se));
1194 }
1195
1196 static inline void
1197 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1198 {
1199         struct sched_statistics *stats;
1200         struct task_struct *p = NULL;
1201
1202         if (!schedstat_enabled())
1203                 return;
1204
1205         stats = __schedstats_from_se(se);
1206
1207         if (entity_is_task(se))
1208                 p = task_of(se);
1209
1210         __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1211 }
1212
1213 static inline void
1214 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1215 {
1216         struct sched_statistics *stats;
1217         struct task_struct *p = NULL;
1218
1219         if (!schedstat_enabled())
1220                 return;
1221
1222         stats = __schedstats_from_se(se);
1223
1224         /*
1225          * When the sched_schedstat changes from 0 to 1, some sched se
1226          * maybe already in the runqueue, the se->statistics.wait_start
1227          * will be 0.So it will let the delta wrong. We need to avoid this
1228          * scenario.
1229          */
1230         if (unlikely(!schedstat_val(stats->wait_start)))
1231                 return;
1232
1233         if (entity_is_task(se))
1234                 p = task_of(se);
1235
1236         __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1237 }
1238
1239 static inline void
1240 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1241 {
1242         struct sched_statistics *stats;
1243         struct task_struct *tsk = NULL;
1244
1245         if (!schedstat_enabled())
1246                 return;
1247
1248         stats = __schedstats_from_se(se);
1249
1250         if (entity_is_task(se))
1251                 tsk = task_of(se);
1252
1253         __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1254 }
1255
1256 /*
1257  * Task is being enqueued - update stats:
1258  */
1259 static inline void
1260 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1261 {
1262         if (!schedstat_enabled())
1263                 return;
1264
1265         /*
1266          * Are we enqueueing a waiting task? (for current tasks
1267          * a dequeue/enqueue event is a NOP)
1268          */
1269         if (se != cfs_rq->curr)
1270                 update_stats_wait_start_fair(cfs_rq, se);
1271
1272         if (flags & ENQUEUE_WAKEUP)
1273                 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1274 }
1275
1276 static inline void
1277 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1278 {
1279
1280         if (!schedstat_enabled())
1281                 return;
1282
1283         /*
1284          * Mark the end of the wait period if dequeueing a
1285          * waiting task:
1286          */
1287         if (se != cfs_rq->curr)
1288                 update_stats_wait_end_fair(cfs_rq, se);
1289
1290         if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1291                 struct task_struct *tsk = task_of(se);
1292                 unsigned int state;
1293
1294                 /* XXX racy against TTWU */
1295                 state = READ_ONCE(tsk->__state);
1296                 if (state & TASK_INTERRUPTIBLE)
1297                         __schedstat_set(tsk->stats.sleep_start,
1298                                       rq_clock(rq_of(cfs_rq)));
1299                 if (state & TASK_UNINTERRUPTIBLE)
1300                         __schedstat_set(tsk->stats.block_start,
1301                                       rq_clock(rq_of(cfs_rq)));
1302         }
1303 }
1304
1305 /*
1306  * We are picking a new current task - update its stats:
1307  */
1308 static inline void
1309 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1310 {
1311         /*
1312          * We are starting a new run period:
1313          */
1314         se->exec_start = rq_clock_task(rq_of(cfs_rq));
1315 }
1316
1317 /**************************************************
1318  * Scheduling class queueing methods:
1319  */
1320
1321 static inline bool is_core_idle(int cpu)
1322 {
1323 #ifdef CONFIG_SCHED_SMT
1324         int sibling;
1325
1326         for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1327                 if (cpu == sibling)
1328                         continue;
1329
1330                 if (!idle_cpu(sibling))
1331                         return false;
1332         }
1333 #endif
1334
1335         return true;
1336 }
1337
1338 #ifdef CONFIG_NUMA
1339 #define NUMA_IMBALANCE_MIN 2
1340
1341 static inline long
1342 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1343 {
1344         /*
1345          * Allow a NUMA imbalance if busy CPUs is less than the maximum
1346          * threshold. Above this threshold, individual tasks may be contending
1347          * for both memory bandwidth and any shared HT resources.  This is an
1348          * approximation as the number of running tasks may not be related to
1349          * the number of busy CPUs due to sched_setaffinity.
1350          */
1351         if (dst_running > imb_numa_nr)
1352                 return imbalance;
1353
1354         /*
1355          * Allow a small imbalance based on a simple pair of communicating
1356          * tasks that remain local when the destination is lightly loaded.
1357          */
1358         if (imbalance <= NUMA_IMBALANCE_MIN)
1359                 return 0;
1360
1361         return imbalance;
1362 }
1363 #endif /* CONFIG_NUMA */
1364
1365 #ifdef CONFIG_NUMA_BALANCING
1366 /*
1367  * Approximate time to scan a full NUMA task in ms. The task scan period is
1368  * calculated based on the tasks virtual memory size and
1369  * numa_balancing_scan_size.
1370  */
1371 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1372 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1373
1374 /* Portion of address space to scan in MB */
1375 unsigned int sysctl_numa_balancing_scan_size = 256;
1376
1377 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1378 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1379
1380 /* The page with hint page fault latency < threshold in ms is considered hot */
1381 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1382
1383 struct numa_group {
1384         refcount_t refcount;
1385
1386         spinlock_t lock; /* nr_tasks, tasks */
1387         int nr_tasks;
1388         pid_t gid;
1389         int active_nodes;
1390
1391         struct rcu_head rcu;
1392         unsigned long total_faults;
1393         unsigned long max_faults_cpu;
1394         /*
1395          * faults[] array is split into two regions: faults_mem and faults_cpu.
1396          *
1397          * Faults_cpu is used to decide whether memory should move
1398          * towards the CPU. As a consequence, these stats are weighted
1399          * more by CPU use than by memory faults.
1400          */
1401         unsigned long faults[];
1402 };
1403
1404 /*
1405  * For functions that can be called in multiple contexts that permit reading
1406  * ->numa_group (see struct task_struct for locking rules).
1407  */
1408 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1409 {
1410         return rcu_dereference_check(p->numa_group, p == current ||
1411                 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1412 }
1413
1414 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1415 {
1416         return rcu_dereference_protected(p->numa_group, p == current);
1417 }
1418
1419 static inline unsigned long group_faults_priv(struct numa_group *ng);
1420 static inline unsigned long group_faults_shared(struct numa_group *ng);
1421
1422 static unsigned int task_nr_scan_windows(struct task_struct *p)
1423 {
1424         unsigned long rss = 0;
1425         unsigned long nr_scan_pages;
1426
1427         /*
1428          * Calculations based on RSS as non-present and empty pages are skipped
1429          * by the PTE scanner and NUMA hinting faults should be trapped based
1430          * on resident pages
1431          */
1432         nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1433         rss = get_mm_rss(p->mm);
1434         if (!rss)
1435                 rss = nr_scan_pages;
1436
1437         rss = round_up(rss, nr_scan_pages);
1438         return rss / nr_scan_pages;
1439 }
1440
1441 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1442 #define MAX_SCAN_WINDOW 2560
1443
1444 static unsigned int task_scan_min(struct task_struct *p)
1445 {
1446         unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1447         unsigned int scan, floor;
1448         unsigned int windows = 1;
1449
1450         if (scan_size < MAX_SCAN_WINDOW)
1451                 windows = MAX_SCAN_WINDOW / scan_size;
1452         floor = 1000 / windows;
1453
1454         scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1455         return max_t(unsigned int, floor, scan);
1456 }
1457
1458 static unsigned int task_scan_start(struct task_struct *p)
1459 {
1460         unsigned long smin = task_scan_min(p);
1461         unsigned long period = smin;
1462         struct numa_group *ng;
1463
1464         /* Scale the maximum scan period with the amount of shared memory. */
1465         rcu_read_lock();
1466         ng = rcu_dereference(p->numa_group);
1467         if (ng) {
1468                 unsigned long shared = group_faults_shared(ng);
1469                 unsigned long private = group_faults_priv(ng);
1470
1471                 period *= refcount_read(&ng->refcount);
1472                 period *= shared + 1;
1473                 period /= private + shared + 1;
1474         }
1475         rcu_read_unlock();
1476
1477         return max(smin, period);
1478 }
1479
1480 static unsigned int task_scan_max(struct task_struct *p)
1481 {
1482         unsigned long smin = task_scan_min(p);
1483         unsigned long smax;
1484         struct numa_group *ng;
1485
1486         /* Watch for min being lower than max due to floor calculations */
1487         smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1488
1489         /* Scale the maximum scan period with the amount of shared memory. */
1490         ng = deref_curr_numa_group(p);
1491         if (ng) {
1492                 unsigned long shared = group_faults_shared(ng);
1493                 unsigned long private = group_faults_priv(ng);
1494                 unsigned long period = smax;
1495
1496                 period *= refcount_read(&ng->refcount);
1497                 period *= shared + 1;
1498                 period /= private + shared + 1;
1499
1500                 smax = max(smax, period);
1501         }
1502
1503         return max(smin, smax);
1504 }
1505
1506 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1507 {
1508         rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1509         rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1510 }
1511
1512 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1513 {
1514         rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1515         rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1516 }
1517
1518 /* Shared or private faults. */
1519 #define NR_NUMA_HINT_FAULT_TYPES 2
1520
1521 /* Memory and CPU locality */
1522 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1523
1524 /* Averaged statistics, and temporary buffers. */
1525 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1526
1527 pid_t task_numa_group_id(struct task_struct *p)
1528 {
1529         struct numa_group *ng;
1530         pid_t gid = 0;
1531
1532         rcu_read_lock();
1533         ng = rcu_dereference(p->numa_group);
1534         if (ng)
1535                 gid = ng->gid;
1536         rcu_read_unlock();
1537
1538         return gid;
1539 }
1540
1541 /*
1542  * The averaged statistics, shared & private, memory & CPU,
1543  * occupy the first half of the array. The second half of the
1544  * array is for current counters, which are averaged into the
1545  * first set by task_numa_placement.
1546  */
1547 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1548 {
1549         return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1550 }
1551
1552 static inline unsigned long task_faults(struct task_struct *p, int nid)
1553 {
1554         if (!p->numa_faults)
1555                 return 0;
1556
1557         return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1558                 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1559 }
1560
1561 static inline unsigned long group_faults(struct task_struct *p, int nid)
1562 {
1563         struct numa_group *ng = deref_task_numa_group(p);
1564
1565         if (!ng)
1566                 return 0;
1567
1568         return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1569                 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1570 }
1571
1572 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1573 {
1574         return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1575                 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1576 }
1577
1578 static inline unsigned long group_faults_priv(struct numa_group *ng)
1579 {
1580         unsigned long faults = 0;
1581         int node;
1582
1583         for_each_online_node(node) {
1584                 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1585         }
1586
1587         return faults;
1588 }
1589
1590 static inline unsigned long group_faults_shared(struct numa_group *ng)
1591 {
1592         unsigned long faults = 0;
1593         int node;
1594
1595         for_each_online_node(node) {
1596                 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1597         }
1598
1599         return faults;
1600 }
1601
1602 /*
1603  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1604  * considered part of a numa group's pseudo-interleaving set. Migrations
1605  * between these nodes are slowed down, to allow things to settle down.
1606  */
1607 #define ACTIVE_NODE_FRACTION 3
1608
1609 static bool numa_is_active_node(int nid, struct numa_group *ng)
1610 {
1611         return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1612 }
1613
1614 /* Handle placement on systems where not all nodes are directly connected. */
1615 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1616                                         int lim_dist, bool task)
1617 {
1618         unsigned long score = 0;
1619         int node, max_dist;
1620
1621         /*
1622          * All nodes are directly connected, and the same distance
1623          * from each other. No need for fancy placement algorithms.
1624          */
1625         if (sched_numa_topology_type == NUMA_DIRECT)
1626                 return 0;
1627
1628         /* sched_max_numa_distance may be changed in parallel. */
1629         max_dist = READ_ONCE(sched_max_numa_distance);
1630         /*
1631          * This code is called for each node, introducing N^2 complexity,
1632          * which should be ok given the number of nodes rarely exceeds 8.
1633          */
1634         for_each_online_node(node) {
1635                 unsigned long faults;
1636                 int dist = node_distance(nid, node);
1637
1638                 /*
1639                  * The furthest away nodes in the system are not interesting
1640                  * for placement; nid was already counted.
1641                  */
1642                 if (dist >= max_dist || node == nid)
1643                         continue;
1644
1645                 /*
1646                  * On systems with a backplane NUMA topology, compare groups
1647                  * of nodes, and move tasks towards the group with the most
1648                  * memory accesses. When comparing two nodes at distance
1649                  * "hoplimit", only nodes closer by than "hoplimit" are part
1650                  * of each group. Skip other nodes.
1651                  */
1652                 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1653                         continue;
1654
1655                 /* Add up the faults from nearby nodes. */
1656                 if (task)
1657                         faults = task_faults(p, node);
1658                 else
1659                         faults = group_faults(p, node);
1660
1661                 /*
1662                  * On systems with a glueless mesh NUMA topology, there are
1663                  * no fixed "groups of nodes". Instead, nodes that are not
1664                  * directly connected bounce traffic through intermediate
1665                  * nodes; a numa_group can occupy any set of nodes.
1666                  * The further away a node is, the less the faults count.
1667                  * This seems to result in good task placement.
1668                  */
1669                 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1670                         faults *= (max_dist - dist);
1671                         faults /= (max_dist - LOCAL_DISTANCE);
1672                 }
1673
1674                 score += faults;
1675         }
1676
1677         return score;
1678 }
1679
1680 /*
1681  * These return the fraction of accesses done by a particular task, or
1682  * task group, on a particular numa node.  The group weight is given a
1683  * larger multiplier, in order to group tasks together that are almost
1684  * evenly spread out between numa nodes.
1685  */
1686 static inline unsigned long task_weight(struct task_struct *p, int nid,
1687                                         int dist)
1688 {
1689         unsigned long faults, total_faults;
1690
1691         if (!p->numa_faults)
1692                 return 0;
1693
1694         total_faults = p->total_numa_faults;
1695
1696         if (!total_faults)
1697                 return 0;
1698
1699         faults = task_faults(p, nid);
1700         faults += score_nearby_nodes(p, nid, dist, true);
1701
1702         return 1000 * faults / total_faults;
1703 }
1704
1705 static inline unsigned long group_weight(struct task_struct *p, int nid,
1706                                          int dist)
1707 {
1708         struct numa_group *ng = deref_task_numa_group(p);
1709         unsigned long faults, total_faults;
1710
1711         if (!ng)
1712                 return 0;
1713
1714         total_faults = ng->total_faults;
1715
1716         if (!total_faults)
1717                 return 0;
1718
1719         faults = group_faults(p, nid);
1720         faults += score_nearby_nodes(p, nid, dist, false);
1721
1722         return 1000 * faults / total_faults;
1723 }
1724
1725 /*
1726  * If memory tiering mode is enabled, cpupid of slow memory page is
1727  * used to record scan time instead of CPU and PID.  When tiering mode
1728  * is disabled at run time, the scan time (in cpupid) will be
1729  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
1730  * access out of array bound.
1731  */
1732 static inline bool cpupid_valid(int cpupid)
1733 {
1734         return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1735 }
1736
1737 /*
1738  * For memory tiering mode, if there are enough free pages (more than
1739  * enough watermark defined here) in fast memory node, to take full
1740  * advantage of fast memory capacity, all recently accessed slow
1741  * memory pages will be migrated to fast memory node without
1742  * considering hot threshold.
1743  */
1744 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1745 {
1746         int z;
1747         unsigned long enough_wmark;
1748
1749         enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1750                            pgdat->node_present_pages >> 4);
1751         for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1752                 struct zone *zone = pgdat->node_zones + z;
1753
1754                 if (!populated_zone(zone))
1755                         continue;
1756
1757                 if (zone_watermark_ok(zone, 0,
1758                                       wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1759                                       ZONE_MOVABLE, 0))
1760                         return true;
1761         }
1762         return false;
1763 }
1764
1765 /*
1766  * For memory tiering mode, when page tables are scanned, the scan
1767  * time will be recorded in struct page in addition to make page
1768  * PROT_NONE for slow memory page.  So when the page is accessed, in
1769  * hint page fault handler, the hint page fault latency is calculated
1770  * via,
1771  *
1772  *      hint page fault latency = hint page fault time - scan time
1773  *
1774  * The smaller the hint page fault latency, the higher the possibility
1775  * for the page to be hot.
1776  */
1777 static int numa_hint_fault_latency(struct page *page)
1778 {
1779         int last_time, time;
1780
1781         time = jiffies_to_msecs(jiffies);
1782         last_time = xchg_page_access_time(page, time);
1783
1784         return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1785 }
1786
1787 /*
1788  * For memory tiering mode, too high promotion/demotion throughput may
1789  * hurt application latency.  So we provide a mechanism to rate limit
1790  * the number of pages that are tried to be promoted.
1791  */
1792 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1793                                       unsigned long rate_limit, int nr)
1794 {
1795         unsigned long nr_cand;
1796         unsigned int now, start;
1797
1798         now = jiffies_to_msecs(jiffies);
1799         mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1800         nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1801         start = pgdat->nbp_rl_start;
1802         if (now - start > MSEC_PER_SEC &&
1803             cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1804                 pgdat->nbp_rl_nr_cand = nr_cand;
1805         if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1806                 return true;
1807         return false;
1808 }
1809
1810 #define NUMA_MIGRATION_ADJUST_STEPS     16
1811
1812 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1813                                             unsigned long rate_limit,
1814                                             unsigned int ref_th)
1815 {
1816         unsigned int now, start, th_period, unit_th, th;
1817         unsigned long nr_cand, ref_cand, diff_cand;
1818
1819         now = jiffies_to_msecs(jiffies);
1820         th_period = sysctl_numa_balancing_scan_period_max;
1821         start = pgdat->nbp_th_start;
1822         if (now - start > th_period &&
1823             cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1824                 ref_cand = rate_limit *
1825                         sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1826                 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1827                 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1828                 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1829                 th = pgdat->nbp_threshold ? : ref_th;
1830                 if (diff_cand > ref_cand * 11 / 10)
1831                         th = max(th - unit_th, unit_th);
1832                 else if (diff_cand < ref_cand * 9 / 10)
1833                         th = min(th + unit_th, ref_th * 2);
1834                 pgdat->nbp_th_nr_cand = nr_cand;
1835                 pgdat->nbp_threshold = th;
1836         }
1837 }
1838
1839 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1840                                 int src_nid, int dst_cpu)
1841 {
1842         struct numa_group *ng = deref_curr_numa_group(p);
1843         int dst_nid = cpu_to_node(dst_cpu);
1844         int last_cpupid, this_cpupid;
1845
1846         /*
1847          * The pages in slow memory node should be migrated according
1848          * to hot/cold instead of private/shared.
1849          */
1850         if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1851             !node_is_toptier(src_nid)) {
1852                 struct pglist_data *pgdat;
1853                 unsigned long rate_limit;
1854                 unsigned int latency, th, def_th;
1855
1856                 pgdat = NODE_DATA(dst_nid);
1857                 if (pgdat_free_space_enough(pgdat)) {
1858                         /* workload changed, reset hot threshold */
1859                         pgdat->nbp_threshold = 0;
1860                         return true;
1861                 }
1862
1863                 def_th = sysctl_numa_balancing_hot_threshold;
1864                 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1865                         (20 - PAGE_SHIFT);
1866                 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1867
1868                 th = pgdat->nbp_threshold ? : def_th;
1869                 latency = numa_hint_fault_latency(page);
1870                 if (latency >= th)
1871                         return false;
1872
1873                 return !numa_promotion_rate_limit(pgdat, rate_limit,
1874                                                   thp_nr_pages(page));
1875         }
1876
1877         this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1878         last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1879
1880         if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1881             !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1882                 return false;
1883
1884         /*
1885          * Allow first faults or private faults to migrate immediately early in
1886          * the lifetime of a task. The magic number 4 is based on waiting for
1887          * two full passes of the "multi-stage node selection" test that is
1888          * executed below.
1889          */
1890         if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1891             (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1892                 return true;
1893
1894         /*
1895          * Multi-stage node selection is used in conjunction with a periodic
1896          * migration fault to build a temporal task<->page relation. By using
1897          * a two-stage filter we remove short/unlikely relations.
1898          *
1899          * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1900          * a task's usage of a particular page (n_p) per total usage of this
1901          * page (n_t) (in a given time-span) to a probability.
1902          *
1903          * Our periodic faults will sample this probability and getting the
1904          * same result twice in a row, given these samples are fully
1905          * independent, is then given by P(n)^2, provided our sample period
1906          * is sufficiently short compared to the usage pattern.
1907          *
1908          * This quadric squishes small probabilities, making it less likely we
1909          * act on an unlikely task<->page relation.
1910          */
1911         if (!cpupid_pid_unset(last_cpupid) &&
1912                                 cpupid_to_nid(last_cpupid) != dst_nid)
1913                 return false;
1914
1915         /* Always allow migrate on private faults */
1916         if (cpupid_match_pid(p, last_cpupid))
1917                 return true;
1918
1919         /* A shared fault, but p->numa_group has not been set up yet. */
1920         if (!ng)
1921                 return true;
1922
1923         /*
1924          * Destination node is much more heavily used than the source
1925          * node? Allow migration.
1926          */
1927         if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1928                                         ACTIVE_NODE_FRACTION)
1929                 return true;
1930
1931         /*
1932          * Distribute memory according to CPU & memory use on each node,
1933          * with 3/4 hysteresis to avoid unnecessary memory migrations:
1934          *
1935          * faults_cpu(dst)   3   faults_cpu(src)
1936          * --------------- * - > ---------------
1937          * faults_mem(dst)   4   faults_mem(src)
1938          */
1939         return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1940                group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1941 }
1942
1943 /*
1944  * 'numa_type' describes the node at the moment of load balancing.
1945  */
1946 enum numa_type {
1947         /* The node has spare capacity that can be used to run more tasks.  */
1948         node_has_spare = 0,
1949         /*
1950          * The node is fully used and the tasks don't compete for more CPU
1951          * cycles. Nevertheless, some tasks might wait before running.
1952          */
1953         node_fully_busy,
1954         /*
1955          * The node is overloaded and can't provide expected CPU cycles to all
1956          * tasks.
1957          */
1958         node_overloaded
1959 };
1960
1961 /* Cached statistics for all CPUs within a node */
1962 struct numa_stats {
1963         unsigned long load;
1964         unsigned long runnable;
1965         unsigned long util;
1966         /* Total compute capacity of CPUs on a node */
1967         unsigned long compute_capacity;
1968         unsigned int nr_running;
1969         unsigned int weight;
1970         enum numa_type node_type;
1971         int idle_cpu;
1972 };
1973
1974 struct task_numa_env {
1975         struct task_struct *p;
1976
1977         int src_cpu, src_nid;
1978         int dst_cpu, dst_nid;
1979         int imb_numa_nr;
1980
1981         struct numa_stats src_stats, dst_stats;
1982
1983         int imbalance_pct;
1984         int dist;
1985
1986         struct task_struct *best_task;
1987         long best_imp;
1988         int best_cpu;
1989 };
1990
1991 static unsigned long cpu_load(struct rq *rq);
1992 static unsigned long cpu_runnable(struct rq *rq);
1993
1994 static inline enum
1995 numa_type numa_classify(unsigned int imbalance_pct,
1996                          struct numa_stats *ns)
1997 {
1998         if ((ns->nr_running > ns->weight) &&
1999             (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2000              ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2001                 return node_overloaded;
2002
2003         if ((ns->nr_running < ns->weight) ||
2004             (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2005              ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2006                 return node_has_spare;
2007
2008         return node_fully_busy;
2009 }
2010
2011 #ifdef CONFIG_SCHED_SMT
2012 /* Forward declarations of select_idle_sibling helpers */
2013 static inline bool test_idle_cores(int cpu);
2014 static inline int numa_idle_core(int idle_core, int cpu)
2015 {
2016         if (!static_branch_likely(&sched_smt_present) ||
2017             idle_core >= 0 || !test_idle_cores(cpu))
2018                 return idle_core;
2019
2020         /*
2021          * Prefer cores instead of packing HT siblings
2022          * and triggering future load balancing.
2023          */
2024         if (is_core_idle(cpu))
2025                 idle_core = cpu;
2026
2027         return idle_core;
2028 }
2029 #else
2030 static inline int numa_idle_core(int idle_core, int cpu)
2031 {
2032         return idle_core;
2033 }
2034 #endif
2035
2036 /*
2037  * Gather all necessary information to make NUMA balancing placement
2038  * decisions that are compatible with standard load balancer. This
2039  * borrows code and logic from update_sg_lb_stats but sharing a
2040  * common implementation is impractical.
2041  */
2042 static void update_numa_stats(struct task_numa_env *env,
2043                               struct numa_stats *ns, int nid,
2044                               bool find_idle)
2045 {
2046         int cpu, idle_core = -1;
2047
2048         memset(ns, 0, sizeof(*ns));
2049         ns->idle_cpu = -1;
2050
2051         rcu_read_lock();
2052         for_each_cpu(cpu, cpumask_of_node(nid)) {
2053                 struct rq *rq = cpu_rq(cpu);
2054
2055                 ns->load += cpu_load(rq);
2056                 ns->runnable += cpu_runnable(rq);
2057                 ns->util += cpu_util_cfs(cpu);
2058                 ns->nr_running += rq->cfs.h_nr_running;
2059                 ns->compute_capacity += capacity_of(cpu);
2060
2061                 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2062                         if (READ_ONCE(rq->numa_migrate_on) ||
2063                             !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2064                                 continue;
2065
2066                         if (ns->idle_cpu == -1)
2067                                 ns->idle_cpu = cpu;
2068
2069                         idle_core = numa_idle_core(idle_core, cpu);
2070                 }
2071         }
2072         rcu_read_unlock();
2073
2074         ns->weight = cpumask_weight(cpumask_of_node(nid));
2075
2076         ns->node_type = numa_classify(env->imbalance_pct, ns);
2077
2078         if (idle_core >= 0)
2079                 ns->idle_cpu = idle_core;
2080 }
2081
2082 static void task_numa_assign(struct task_numa_env *env,
2083                              struct task_struct *p, long imp)
2084 {
2085         struct rq *rq = cpu_rq(env->dst_cpu);
2086
2087         /* Check if run-queue part of active NUMA balance. */
2088         if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2089                 int cpu;
2090                 int start = env->dst_cpu;
2091
2092                 /* Find alternative idle CPU. */
2093                 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2094                         if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2095                             !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2096                                 continue;
2097                         }
2098
2099                         env->dst_cpu = cpu;
2100                         rq = cpu_rq(env->dst_cpu);
2101                         if (!xchg(&rq->numa_migrate_on, 1))
2102                                 goto assign;
2103                 }
2104
2105                 /* Failed to find an alternative idle CPU */
2106                 return;
2107         }
2108
2109 assign:
2110         /*
2111          * Clear previous best_cpu/rq numa-migrate flag, since task now
2112          * found a better CPU to move/swap.
2113          */
2114         if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2115                 rq = cpu_rq(env->best_cpu);
2116                 WRITE_ONCE(rq->numa_migrate_on, 0);
2117         }
2118
2119         if (env->best_task)
2120                 put_task_struct(env->best_task);
2121         if (p)
2122                 get_task_struct(p);
2123
2124         env->best_task = p;
2125         env->best_imp = imp;
2126         env->best_cpu = env->dst_cpu;
2127 }
2128
2129 static bool load_too_imbalanced(long src_load, long dst_load,
2130                                 struct task_numa_env *env)
2131 {
2132         long imb, old_imb;
2133         long orig_src_load, orig_dst_load;
2134         long src_capacity, dst_capacity;
2135
2136         /*
2137          * The load is corrected for the CPU capacity available on each node.
2138          *
2139          * src_load        dst_load
2140          * ------------ vs ---------
2141          * src_capacity    dst_capacity
2142          */
2143         src_capacity = env->src_stats.compute_capacity;
2144         dst_capacity = env->dst_stats.compute_capacity;
2145
2146         imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2147
2148         orig_src_load = env->src_stats.load;
2149         orig_dst_load = env->dst_stats.load;
2150
2151         old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2152
2153         /* Would this change make things worse? */
2154         return (imb > old_imb);
2155 }
2156
2157 /*
2158  * Maximum NUMA importance can be 1998 (2*999);
2159  * SMALLIMP @ 30 would be close to 1998/64.
2160  * Used to deter task migration.
2161  */
2162 #define SMALLIMP        30
2163
2164 /*
2165  * This checks if the overall compute and NUMA accesses of the system would
2166  * be improved if the source tasks was migrated to the target dst_cpu taking
2167  * into account that it might be best if task running on the dst_cpu should
2168  * be exchanged with the source task
2169  */
2170 static bool task_numa_compare(struct task_numa_env *env,
2171                               long taskimp, long groupimp, bool maymove)
2172 {
2173         struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2174         struct rq *dst_rq = cpu_rq(env->dst_cpu);
2175         long imp = p_ng ? groupimp : taskimp;
2176         struct task_struct *cur;
2177         long src_load, dst_load;
2178         int dist = env->dist;
2179         long moveimp = imp;
2180         long load;
2181         bool stopsearch = false;
2182
2183         if (READ_ONCE(dst_rq->numa_migrate_on))
2184                 return false;
2185
2186         rcu_read_lock();
2187         cur = rcu_dereference(dst_rq->curr);
2188         if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2189                 cur = NULL;
2190
2191         /*
2192          * Because we have preemption enabled we can get migrated around and
2193          * end try selecting ourselves (current == env->p) as a swap candidate.
2194          */
2195         if (cur == env->p) {
2196                 stopsearch = true;
2197                 goto unlock;
2198         }
2199
2200         if (!cur) {
2201                 if (maymove && moveimp >= env->best_imp)
2202                         goto assign;
2203                 else
2204                         goto unlock;
2205         }
2206
2207         /* Skip this swap candidate if cannot move to the source cpu. */
2208         if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2209                 goto unlock;
2210
2211         /*
2212          * Skip this swap candidate if it is not moving to its preferred
2213          * node and the best task is.
2214          */
2215         if (env->best_task &&
2216             env->best_task->numa_preferred_nid == env->src_nid &&
2217             cur->numa_preferred_nid != env->src_nid) {
2218                 goto unlock;
2219         }
2220
2221         /*
2222          * "imp" is the fault differential for the source task between the
2223          * source and destination node. Calculate the total differential for
2224          * the source task and potential destination task. The more negative
2225          * the value is, the more remote accesses that would be expected to
2226          * be incurred if the tasks were swapped.
2227          *
2228          * If dst and source tasks are in the same NUMA group, or not
2229          * in any group then look only at task weights.
2230          */
2231         cur_ng = rcu_dereference(cur->numa_group);
2232         if (cur_ng == p_ng) {
2233                 /*
2234                  * Do not swap within a group or between tasks that have
2235                  * no group if there is spare capacity. Swapping does
2236                  * not address the load imbalance and helps one task at
2237                  * the cost of punishing another.
2238                  */
2239                 if (env->dst_stats.node_type == node_has_spare)
2240                         goto unlock;
2241
2242                 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2243                       task_weight(cur, env->dst_nid, dist);
2244                 /*
2245                  * Add some hysteresis to prevent swapping the
2246                  * tasks within a group over tiny differences.
2247                  */
2248                 if (cur_ng)
2249                         imp -= imp / 16;
2250         } else {
2251                 /*
2252                  * Compare the group weights. If a task is all by itself
2253                  * (not part of a group), use the task weight instead.
2254                  */
2255                 if (cur_ng && p_ng)
2256                         imp += group_weight(cur, env->src_nid, dist) -
2257                                group_weight(cur, env->dst_nid, dist);
2258                 else
2259                         imp += task_weight(cur, env->src_nid, dist) -
2260                                task_weight(cur, env->dst_nid, dist);
2261         }
2262
2263         /* Discourage picking a task already on its preferred node */
2264         if (cur->numa_preferred_nid == env->dst_nid)
2265                 imp -= imp / 16;
2266
2267         /*
2268          * Encourage picking a task that moves to its preferred node.
2269          * This potentially makes imp larger than it's maximum of
2270          * 1998 (see SMALLIMP and task_weight for why) but in this
2271          * case, it does not matter.
2272          */
2273         if (cur->numa_preferred_nid == env->src_nid)
2274                 imp += imp / 8;
2275
2276         if (maymove && moveimp > imp && moveimp > env->best_imp) {
2277                 imp = moveimp;
2278                 cur = NULL;
2279                 goto assign;
2280         }
2281
2282         /*
2283          * Prefer swapping with a task moving to its preferred node over a
2284          * task that is not.
2285          */
2286         if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2287             env->best_task->numa_preferred_nid != env->src_nid) {
2288                 goto assign;
2289         }
2290
2291         /*
2292          * If the NUMA importance is less than SMALLIMP,
2293          * task migration might only result in ping pong
2294          * of tasks and also hurt performance due to cache
2295          * misses.
2296          */
2297         if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2298                 goto unlock;
2299
2300         /*
2301          * In the overloaded case, try and keep the load balanced.
2302          */
2303         load = task_h_load(env->p) - task_h_load(cur);
2304         if (!load)
2305                 goto assign;
2306
2307         dst_load = env->dst_stats.load + load;
2308         src_load = env->src_stats.load - load;
2309
2310         if (load_too_imbalanced(src_load, dst_load, env))
2311                 goto unlock;
2312
2313 assign:
2314         /* Evaluate an idle CPU for a task numa move. */
2315         if (!cur) {
2316                 int cpu = env->dst_stats.idle_cpu;
2317
2318                 /* Nothing cached so current CPU went idle since the search. */
2319                 if (cpu < 0)
2320                         cpu = env->dst_cpu;
2321
2322                 /*
2323                  * If the CPU is no longer truly idle and the previous best CPU
2324                  * is, keep using it.
2325                  */
2326                 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2327                     idle_cpu(env->best_cpu)) {
2328                         cpu = env->best_cpu;
2329                 }
2330
2331                 env->dst_cpu = cpu;
2332         }
2333
2334         task_numa_assign(env, cur, imp);
2335
2336         /*
2337          * If a move to idle is allowed because there is capacity or load
2338          * balance improves then stop the search. While a better swap
2339          * candidate may exist, a search is not free.
2340          */
2341         if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2342                 stopsearch = true;
2343
2344         /*
2345          * If a swap candidate must be identified and the current best task
2346          * moves its preferred node then stop the search.
2347          */
2348         if (!maymove && env->best_task &&
2349             env->best_task->numa_preferred_nid == env->src_nid) {
2350                 stopsearch = true;
2351         }
2352 unlock:
2353         rcu_read_unlock();
2354
2355         return stopsearch;
2356 }
2357
2358 static void task_numa_find_cpu(struct task_numa_env *env,
2359                                 long taskimp, long groupimp)
2360 {
2361         bool maymove = false;
2362         int cpu;
2363
2364         /*
2365          * If dst node has spare capacity, then check if there is an
2366          * imbalance that would be overruled by the load balancer.
2367          */
2368         if (env->dst_stats.node_type == node_has_spare) {
2369                 unsigned int imbalance;
2370                 int src_running, dst_running;
2371
2372                 /*
2373                  * Would movement cause an imbalance? Note that if src has
2374                  * more running tasks that the imbalance is ignored as the
2375                  * move improves the imbalance from the perspective of the
2376                  * CPU load balancer.
2377                  * */
2378                 src_running = env->src_stats.nr_running - 1;
2379                 dst_running = env->dst_stats.nr_running + 1;
2380                 imbalance = max(0, dst_running - src_running);
2381                 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2382                                                   env->imb_numa_nr);
2383
2384                 /* Use idle CPU if there is no imbalance */
2385                 if (!imbalance) {
2386                         maymove = true;
2387                         if (env->dst_stats.idle_cpu >= 0) {
2388                                 env->dst_cpu = env->dst_stats.idle_cpu;
2389                                 task_numa_assign(env, NULL, 0);
2390                                 return;
2391                         }
2392                 }
2393         } else {
2394                 long src_load, dst_load, load;
2395                 /*
2396                  * If the improvement from just moving env->p direction is better
2397                  * than swapping tasks around, check if a move is possible.
2398                  */
2399                 load = task_h_load(env->p);
2400                 dst_load = env->dst_stats.load + load;
2401                 src_load = env->src_stats.load - load;
2402                 maymove = !load_too_imbalanced(src_load, dst_load, env);
2403         }
2404
2405         for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2406                 /* Skip this CPU if the source task cannot migrate */
2407                 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2408                         continue;
2409
2410                 env->dst_cpu = cpu;
2411                 if (task_numa_compare(env, taskimp, groupimp, maymove))
2412                         break;
2413         }
2414 }
2415
2416 static int task_numa_migrate(struct task_struct *p)
2417 {
2418         struct task_numa_env env = {
2419                 .p = p,
2420
2421                 .src_cpu = task_cpu(p),
2422                 .src_nid = task_node(p),
2423
2424                 .imbalance_pct = 112,
2425
2426                 .best_task = NULL,
2427                 .best_imp = 0,
2428                 .best_cpu = -1,
2429         };
2430         unsigned long taskweight, groupweight;
2431         struct sched_domain *sd;
2432         long taskimp, groupimp;
2433         struct numa_group *ng;
2434         struct rq *best_rq;
2435         int nid, ret, dist;
2436
2437         /*
2438          * Pick the lowest SD_NUMA domain, as that would have the smallest
2439          * imbalance and would be the first to start moving tasks about.
2440          *
2441          * And we want to avoid any moving of tasks about, as that would create
2442          * random movement of tasks -- counter the numa conditions we're trying
2443          * to satisfy here.
2444          */
2445         rcu_read_lock();
2446         sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2447         if (sd) {
2448                 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2449                 env.imb_numa_nr = sd->imb_numa_nr;
2450         }
2451         rcu_read_unlock();
2452
2453         /*
2454          * Cpusets can break the scheduler domain tree into smaller
2455          * balance domains, some of which do not cross NUMA boundaries.
2456          * Tasks that are "trapped" in such domains cannot be migrated
2457          * elsewhere, so there is no point in (re)trying.
2458          */
2459         if (unlikely(!sd)) {
2460                 sched_setnuma(p, task_node(p));
2461                 return -EINVAL;
2462         }
2463
2464         env.dst_nid = p->numa_preferred_nid;
2465         dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2466         taskweight = task_weight(p, env.src_nid, dist);
2467         groupweight = group_weight(p, env.src_nid, dist);
2468         update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2469         taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2470         groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2471         update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2472
2473         /* Try to find a spot on the preferred nid. */
2474         task_numa_find_cpu(&env, taskimp, groupimp);
2475
2476         /*
2477          * Look at other nodes in these cases:
2478          * - there is no space available on the preferred_nid
2479          * - the task is part of a numa_group that is interleaved across
2480          *   multiple NUMA nodes; in order to better consolidate the group,
2481          *   we need to check other locations.
2482          */
2483         ng = deref_curr_numa_group(p);
2484         if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2485                 for_each_node_state(nid, N_CPU) {
2486                         if (nid == env.src_nid || nid == p->numa_preferred_nid)
2487                                 continue;
2488
2489                         dist = node_distance(env.src_nid, env.dst_nid);
2490                         if (sched_numa_topology_type == NUMA_BACKPLANE &&
2491                                                 dist != env.dist) {
2492                                 taskweight = task_weight(p, env.src_nid, dist);
2493                                 groupweight = group_weight(p, env.src_nid, dist);
2494                         }
2495
2496                         /* Only consider nodes where both task and groups benefit */
2497                         taskimp = task_weight(p, nid, dist) - taskweight;
2498                         groupimp = group_weight(p, nid, dist) - groupweight;
2499                         if (taskimp < 0 && groupimp < 0)
2500                                 continue;
2501
2502                         env.dist = dist;
2503                         env.dst_nid = nid;
2504                         update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2505                         task_numa_find_cpu(&env, taskimp, groupimp);
2506                 }
2507         }
2508
2509         /*
2510          * If the task is part of a workload that spans multiple NUMA nodes,
2511          * and is migrating into one of the workload's active nodes, remember
2512          * this node as the task's preferred numa node, so the workload can
2513          * settle down.
2514          * A task that migrated to a second choice node will be better off
2515          * trying for a better one later. Do not set the preferred node here.
2516          */
2517         if (ng) {
2518                 if (env.best_cpu == -1)
2519                         nid = env.src_nid;
2520                 else
2521                         nid = cpu_to_node(env.best_cpu);
2522
2523                 if (nid != p->numa_preferred_nid)
2524                         sched_setnuma(p, nid);
2525         }
2526
2527         /* No better CPU than the current one was found. */
2528         if (env.best_cpu == -1) {
2529                 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2530                 return -EAGAIN;
2531         }
2532
2533         best_rq = cpu_rq(env.best_cpu);
2534         if (env.best_task == NULL) {
2535                 ret = migrate_task_to(p, env.best_cpu);
2536                 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2537                 if (ret != 0)
2538                         trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2539                 return ret;
2540         }
2541
2542         ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2543         WRITE_ONCE(best_rq->numa_migrate_on, 0);
2544
2545         if (ret != 0)
2546                 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2547         put_task_struct(env.best_task);
2548         return ret;
2549 }
2550
2551 /* Attempt to migrate a task to a CPU on the preferred node. */
2552 static void numa_migrate_preferred(struct task_struct *p)
2553 {
2554         unsigned long interval = HZ;
2555
2556         /* This task has no NUMA fault statistics yet */
2557         if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2558                 return;
2559
2560         /* Periodically retry migrating the task to the preferred node */
2561         interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2562         p->numa_migrate_retry = jiffies + interval;
2563
2564         /* Success if task is already running on preferred CPU */
2565         if (task_node(p) == p->numa_preferred_nid)
2566                 return;
2567
2568         /* Otherwise, try migrate to a CPU on the preferred node */
2569         task_numa_migrate(p);
2570 }
2571
2572 /*
2573  * Find out how many nodes the workload is actively running on. Do this by
2574  * tracking the nodes from which NUMA hinting faults are triggered. This can
2575  * be different from the set of nodes where the workload's memory is currently
2576  * located.
2577  */
2578 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2579 {
2580         unsigned long faults, max_faults = 0;
2581         int nid, active_nodes = 0;
2582
2583         for_each_node_state(nid, N_CPU) {
2584                 faults = group_faults_cpu(numa_group, nid);
2585                 if (faults > max_faults)
2586                         max_faults = faults;
2587         }
2588
2589         for_each_node_state(nid, N_CPU) {
2590                 faults = group_faults_cpu(numa_group, nid);
2591                 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2592                         active_nodes++;
2593         }
2594
2595         numa_group->max_faults_cpu = max_faults;
2596         numa_group->active_nodes = active_nodes;
2597 }
2598
2599 /*
2600  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2601  * increments. The more local the fault statistics are, the higher the scan
2602  * period will be for the next scan window. If local/(local+remote) ratio is
2603  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2604  * the scan period will decrease. Aim for 70% local accesses.
2605  */
2606 #define NUMA_PERIOD_SLOTS 10
2607 #define NUMA_PERIOD_THRESHOLD 7
2608
2609 /*
2610  * Increase the scan period (slow down scanning) if the majority of
2611  * our memory is already on our local node, or if the majority of
2612  * the page accesses are shared with other processes.
2613  * Otherwise, decrease the scan period.
2614  */
2615 static void update_task_scan_period(struct task_struct *p,
2616                         unsigned long shared, unsigned long private)
2617 {
2618         unsigned int period_slot;
2619         int lr_ratio, ps_ratio;
2620         int diff;
2621
2622         unsigned long remote = p->numa_faults_locality[0];
2623         unsigned long local = p->numa_faults_locality[1];
2624
2625         /*
2626          * If there were no record hinting faults then either the task is
2627          * completely idle or all activity is in areas that are not of interest
2628          * to automatic numa balancing. Related to that, if there were failed
2629          * migration then it implies we are migrating too quickly or the local
2630          * node is overloaded. In either case, scan slower
2631          */
2632         if (local + shared == 0 || p->numa_faults_locality[2]) {
2633                 p->numa_scan_period = min(p->numa_scan_period_max,
2634                         p->numa_scan_period << 1);
2635
2636                 p->mm->numa_next_scan = jiffies +
2637                         msecs_to_jiffies(p->numa_scan_period);
2638
2639                 return;
2640         }
2641
2642         /*
2643          * Prepare to scale scan period relative to the current period.
2644          *       == NUMA_PERIOD_THRESHOLD scan period stays the same
2645          *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2646          *       >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2647          */
2648         period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2649         lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2650         ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2651
2652         if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2653                 /*
2654                  * Most memory accesses are local. There is no need to
2655                  * do fast NUMA scanning, since memory is already local.
2656                  */
2657                 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2658                 if (!slot)
2659                         slot = 1;
2660                 diff = slot * period_slot;
2661         } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2662                 /*
2663                  * Most memory accesses are shared with other tasks.
2664                  * There is no point in continuing fast NUMA scanning,
2665                  * since other tasks may just move the memory elsewhere.
2666                  */
2667                 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2668                 if (!slot)
2669                         slot = 1;
2670                 diff = slot * period_slot;
2671         } else {
2672                 /*
2673                  * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2674                  * yet they are not on the local NUMA node. Speed up
2675                  * NUMA scanning to get the memory moved over.
2676                  */
2677                 int ratio = max(lr_ratio, ps_ratio);
2678                 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2679         }
2680
2681         p->numa_scan_period = clamp(p->numa_scan_period + diff,
2682                         task_scan_min(p), task_scan_max(p));
2683         memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2684 }
2685
2686 /*
2687  * Get the fraction of time the task has been running since the last
2688  * NUMA placement cycle. The scheduler keeps similar statistics, but
2689  * decays those on a 32ms period, which is orders of magnitude off
2690  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2691  * stats only if the task is so new there are no NUMA statistics yet.
2692  */
2693 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2694 {
2695         u64 runtime, delta, now;
2696         /* Use the start of this time slice to avoid calculations. */
2697         now = p->se.exec_start;
2698         runtime = p->se.sum_exec_runtime;
2699
2700         if (p->last_task_numa_placement) {
2701                 delta = runtime - p->last_sum_exec_runtime;
2702                 *period = now - p->last_task_numa_placement;
2703
2704                 /* Avoid time going backwards, prevent potential divide error: */
2705                 if (unlikely((s64)*period < 0))
2706                         *period = 0;
2707         } else {
2708                 delta = p->se.avg.load_sum;
2709                 *period = LOAD_AVG_MAX;
2710         }
2711
2712         p->last_sum_exec_runtime = runtime;
2713         p->last_task_numa_placement = now;
2714
2715         return delta;
2716 }
2717
2718 /*
2719  * Determine the preferred nid for a task in a numa_group. This needs to
2720  * be done in a way that produces consistent results with group_weight,
2721  * otherwise workloads might not converge.
2722  */
2723 static int preferred_group_nid(struct task_struct *p, int nid)
2724 {
2725         nodemask_t nodes;
2726         int dist;
2727
2728         /* Direct connections between all NUMA nodes. */
2729         if (sched_numa_topology_type == NUMA_DIRECT)
2730                 return nid;
2731
2732         /*
2733          * On a system with glueless mesh NUMA topology, group_weight
2734          * scores nodes according to the number of NUMA hinting faults on
2735          * both the node itself, and on nearby nodes.
2736          */
2737         if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2738                 unsigned long score, max_score = 0;
2739                 int node, max_node = nid;
2740
2741                 dist = sched_max_numa_distance;
2742
2743                 for_each_node_state(node, N_CPU) {
2744                         score = group_weight(p, node, dist);
2745                         if (score > max_score) {
2746                                 max_score = score;
2747                                 max_node = node;
2748                         }
2749                 }
2750                 return max_node;
2751         }
2752
2753         /*
2754          * Finding the preferred nid in a system with NUMA backplane
2755          * interconnect topology is more involved. The goal is to locate
2756          * tasks from numa_groups near each other in the system, and
2757          * untangle workloads from different sides of the system. This requires
2758          * searching down the hierarchy of node groups, recursively searching
2759          * inside the highest scoring group of nodes. The nodemask tricks
2760          * keep the complexity of the search down.
2761          */
2762         nodes = node_states[N_CPU];
2763         for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2764                 unsigned long max_faults = 0;
2765                 nodemask_t max_group = NODE_MASK_NONE;
2766                 int a, b;
2767
2768                 /* Are there nodes at this distance from each other? */
2769                 if (!find_numa_distance(dist))
2770                         continue;
2771
2772                 for_each_node_mask(a, nodes) {
2773                         unsigned long faults = 0;
2774                         nodemask_t this_group;
2775                         nodes_clear(this_group);
2776
2777                         /* Sum group's NUMA faults; includes a==b case. */
2778                         for_each_node_mask(b, nodes) {
2779                                 if (node_distance(a, b) < dist) {
2780                                         faults += group_faults(p, b);
2781                                         node_set(b, this_group);
2782                                         node_clear(b, nodes);
2783                                 }
2784                         }
2785
2786                         /* Remember the top group. */
2787                         if (faults > max_faults) {
2788                                 max_faults = faults;
2789                                 max_group = this_group;
2790                                 /*
2791                                  * subtle: at the smallest distance there is
2792                                  * just one node left in each "group", the
2793                                  * winner is the preferred nid.
2794                                  */
2795                                 nid = a;
2796                         }
2797                 }
2798                 /* Next round, evaluate the nodes within max_group. */
2799                 if (!max_faults)
2800                         break;
2801                 nodes = max_group;
2802         }
2803         return nid;
2804 }
2805
2806 static void task_numa_placement(struct task_struct *p)
2807 {
2808         int seq, nid, max_nid = NUMA_NO_NODE;
2809         unsigned long max_faults = 0;
2810         unsigned long fault_types[2] = { 0, 0 };
2811         unsigned long total_faults;
2812         u64 runtime, period;
2813         spinlock_t *group_lock = NULL;
2814         struct numa_group *ng;
2815
2816         /*
2817          * The p->mm->numa_scan_seq field gets updated without
2818          * exclusive access. Use READ_ONCE() here to ensure
2819          * that the field is read in a single access:
2820          */
2821         seq = READ_ONCE(p->mm->numa_scan_seq);
2822         if (p->numa_scan_seq == seq)
2823                 return;
2824         p->numa_scan_seq = seq;
2825         p->numa_scan_period_max = task_scan_max(p);
2826
2827         total_faults = p->numa_faults_locality[0] +
2828                        p->numa_faults_locality[1];
2829         runtime = numa_get_avg_runtime(p, &period);
2830
2831         /* If the task is part of a group prevent parallel updates to group stats */
2832         ng = deref_curr_numa_group(p);
2833         if (ng) {
2834                 group_lock = &ng->lock;
2835                 spin_lock_irq(group_lock);
2836         }
2837
2838         /* Find the node with the highest number of faults */
2839         for_each_online_node(nid) {
2840                 /* Keep track of the offsets in numa_faults array */
2841                 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2842                 unsigned long faults = 0, group_faults = 0;
2843                 int priv;
2844
2845                 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2846                         long diff, f_diff, f_weight;
2847
2848                         mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2849                         membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2850                         cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2851                         cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2852
2853                         /* Decay existing window, copy faults since last scan */
2854                         diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2855                         fault_types[priv] += p->numa_faults[membuf_idx];
2856                         p->numa_faults[membuf_idx] = 0;
2857
2858                         /*
2859                          * Normalize the faults_from, so all tasks in a group
2860                          * count according to CPU use, instead of by the raw
2861                          * number of faults. Tasks with little runtime have
2862                          * little over-all impact on throughput, and thus their
2863                          * faults are less important.
2864                          */
2865                         f_weight = div64_u64(runtime << 16, period + 1);
2866                         f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2867                                    (total_faults + 1);
2868                         f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2869                         p->numa_faults[cpubuf_idx] = 0;
2870
2871                         p->numa_faults[mem_idx] += diff;
2872                         p->numa_faults[cpu_idx] += f_diff;
2873                         faults += p->numa_faults[mem_idx];
2874                         p->total_numa_faults += diff;
2875                         if (ng) {
2876                                 /*
2877                                  * safe because we can only change our own group
2878                                  *
2879                                  * mem_idx represents the offset for a given
2880                                  * nid and priv in a specific region because it
2881                                  * is at the beginning of the numa_faults array.
2882                                  */
2883                                 ng->faults[mem_idx] += diff;
2884                                 ng->faults[cpu_idx] += f_diff;
2885                                 ng->total_faults += diff;
2886                                 group_faults += ng->faults[mem_idx];
2887                         }
2888                 }
2889
2890                 if (!ng) {
2891                         if (faults > max_faults) {
2892                                 max_faults = faults;
2893                                 max_nid = nid;
2894                         }
2895                 } else if (group_faults > max_faults) {
2896                         max_faults = group_faults;
2897                         max_nid = nid;
2898                 }
2899         }
2900
2901         /* Cannot migrate task to CPU-less node */
2902         if (max_nid != NUMA_NO_NODE && !node_state(max_nid, N_CPU)) {
2903                 int near_nid = max_nid;
2904                 int distance, near_distance = INT_MAX;
2905
2906                 for_each_node_state(nid, N_CPU) {
2907                         distance = node_distance(max_nid, nid);
2908                         if (distance < near_distance) {
2909                                 near_nid = nid;
2910                                 near_distance = distance;
2911                         }
2912                 }
2913                 max_nid = near_nid;
2914         }
2915
2916         if (ng) {
2917                 numa_group_count_active_nodes(ng);
2918                 spin_unlock_irq(group_lock);
2919                 max_nid = preferred_group_nid(p, max_nid);
2920         }
2921
2922         if (max_faults) {
2923                 /* Set the new preferred node */
2924                 if (max_nid != p->numa_preferred_nid)
2925                         sched_setnuma(p, max_nid);
2926         }
2927
2928         update_task_scan_period(p, fault_types[0], fault_types[1]);
2929 }
2930
2931 static inline int get_numa_group(struct numa_group *grp)
2932 {
2933         return refcount_inc_not_zero(&grp->refcount);
2934 }
2935
2936 static inline void put_numa_group(struct numa_group *grp)
2937 {
2938         if (refcount_dec_and_test(&grp->refcount))
2939                 kfree_rcu(grp, rcu);
2940 }
2941
2942 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2943                         int *priv)
2944 {
2945         struct numa_group *grp, *my_grp;
2946         struct task_struct *tsk;
2947         bool join = false;
2948         int cpu = cpupid_to_cpu(cpupid);
2949         int i;
2950
2951         if (unlikely(!deref_curr_numa_group(p))) {
2952                 unsigned int size = sizeof(struct numa_group) +
2953                                     NR_NUMA_HINT_FAULT_STATS *
2954                                     nr_node_ids * sizeof(unsigned long);
2955
2956                 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2957                 if (!grp)
2958                         return;
2959
2960                 refcount_set(&grp->refcount, 1);
2961                 grp->active_nodes = 1;
2962                 grp->max_faults_cpu = 0;
2963                 spin_lock_init(&grp->lock);
2964                 grp->gid = p->pid;
2965
2966                 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2967                         grp->faults[i] = p->numa_faults[i];
2968
2969                 grp->total_faults = p->total_numa_faults;
2970
2971                 grp->nr_tasks++;
2972                 rcu_assign_pointer(p->numa_group, grp);
2973         }
2974
2975         rcu_read_lock();
2976         tsk = READ_ONCE(cpu_rq(cpu)->curr);
2977
2978         if (!cpupid_match_pid(tsk, cpupid))
2979                 goto no_join;
2980
2981         grp = rcu_dereference(tsk->numa_group);
2982         if (!grp)
2983                 goto no_join;
2984
2985         my_grp = deref_curr_numa_group(p);
2986         if (grp == my_grp)
2987                 goto no_join;
2988
2989         /*
2990          * Only join the other group if its bigger; if we're the bigger group,
2991          * the other task will join us.
2992          */
2993         if (my_grp->nr_tasks > grp->nr_tasks)
2994                 goto no_join;
2995
2996         /*
2997          * Tie-break on the grp address.
2998          */
2999         if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3000                 goto no_join;
3001
3002         /* Always join threads in the same process. */
3003         if (tsk->mm == current->mm)
3004                 join = true;
3005
3006         /* Simple filter to avoid false positives due to PID collisions */
3007         if (flags & TNF_SHARED)
3008                 join = true;
3009
3010         /* Update priv based on whether false sharing was detected */
3011         *priv = !join;
3012
3013         if (join && !get_numa_group(grp))
3014                 goto no_join;
3015
3016         rcu_read_unlock();
3017
3018         if (!join)
3019                 return;
3020
3021         WARN_ON_ONCE(irqs_disabled());
3022         double_lock_irq(&my_grp->lock, &grp->lock);
3023
3024         for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3025                 my_grp->faults[i] -= p->numa_faults[i];
3026                 grp->faults[i] += p->numa_faults[i];
3027         }
3028         my_grp->total_faults -= p->total_numa_faults;
3029         grp->total_faults += p->total_numa_faults;
3030
3031         my_grp->nr_tasks--;
3032         grp->nr_tasks++;
3033
3034         spin_unlock(&my_grp->lock);
3035         spin_unlock_irq(&grp->lock);
3036
3037         rcu_assign_pointer(p->numa_group, grp);
3038
3039         put_numa_group(my_grp);
3040         return;
3041
3042 no_join:
3043         rcu_read_unlock();
3044         return;
3045 }
3046
3047 /*
3048  * Get rid of NUMA statistics associated with a task (either current or dead).
3049  * If @final is set, the task is dead and has reached refcount zero, so we can
3050  * safely free all relevant data structures. Otherwise, there might be
3051  * concurrent reads from places like load balancing and procfs, and we should
3052  * reset the data back to default state without freeing ->numa_faults.
3053  */
3054 void task_numa_free(struct task_struct *p, bool final)
3055 {
3056         /* safe: p either is current or is being freed by current */
3057         struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3058         unsigned long *numa_faults = p->numa_faults;
3059         unsigned long flags;
3060         int i;
3061
3062         if (!numa_faults)
3063                 return;
3064
3065         if (grp) {
3066                 spin_lock_irqsave(&grp->lock, flags);
3067                 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3068                         grp->faults[i] -= p->numa_faults[i];
3069                 grp->total_faults -= p->total_numa_faults;
3070
3071                 grp->nr_tasks--;
3072                 spin_unlock_irqrestore(&grp->lock, flags);
3073                 RCU_INIT_POINTER(p->numa_group, NULL);
3074                 put_numa_group(grp);
3075         }
3076
3077         if (final) {
3078                 p->numa_faults = NULL;
3079                 kfree(numa_faults);
3080         } else {
3081                 p->total_numa_faults = 0;
3082                 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3083                         numa_faults[i] = 0;
3084         }
3085 }
3086
3087 /*
3088  * Got a PROT_NONE fault for a page on @node.
3089  */
3090 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3091 {
3092         struct task_struct *p = current;
3093         bool migrated = flags & TNF_MIGRATED;
3094         int cpu_node = task_node(current);
3095         int local = !!(flags & TNF_FAULT_LOCAL);
3096         struct numa_group *ng;
3097         int priv;
3098
3099         if (!static_branch_likely(&sched_numa_balancing))
3100                 return;
3101
3102         /* for example, ksmd faulting in a user's mm */
3103         if (!p->mm)
3104                 return;
3105
3106         /*
3107          * NUMA faults statistics are unnecessary for the slow memory
3108          * node for memory tiering mode.
3109          */
3110         if (!node_is_toptier(mem_node) &&
3111             (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3112              !cpupid_valid(last_cpupid)))
3113                 return;
3114
3115         /* Allocate buffer to track faults on a per-node basis */
3116         if (unlikely(!p->numa_faults)) {
3117                 int size = sizeof(*p->numa_faults) *
3118                            NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3119
3120                 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3121                 if (!p->numa_faults)
3122                         return;
3123
3124                 p->total_numa_faults = 0;
3125                 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3126         }
3127
3128         /*
3129          * First accesses are treated as private, otherwise consider accesses
3130          * to be private if the accessing pid has not changed
3131          */
3132         if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3133                 priv = 1;
3134         } else {
3135                 priv = cpupid_match_pid(p, last_cpupid);
3136                 if (!priv && !(flags & TNF_NO_GROUP))
3137                         task_numa_group(p, last_cpupid, flags, &priv);
3138         }
3139
3140         /*
3141          * If a workload spans multiple NUMA nodes, a shared fault that
3142          * occurs wholly within the set of nodes that the workload is
3143          * actively using should be counted as local. This allows the
3144          * scan rate to slow down when a workload has settled down.
3145          */
3146         ng = deref_curr_numa_group(p);
3147         if (!priv && !local && ng && ng->active_nodes > 1 &&
3148                                 numa_is_active_node(cpu_node, ng) &&
3149                                 numa_is_active_node(mem_node, ng))
3150                 local = 1;
3151
3152         /*
3153          * Retry to migrate task to preferred node periodically, in case it
3154          * previously failed, or the scheduler moved us.
3155          */
3156         if (time_after(jiffies, p->numa_migrate_retry)) {
3157                 task_numa_placement(p);
3158                 numa_migrate_preferred(p);
3159         }
3160
3161         if (migrated)
3162                 p->numa_pages_migrated += pages;
3163         if (flags & TNF_MIGRATE_FAIL)
3164                 p->numa_faults_locality[2] += pages;
3165
3166         p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3167         p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3168         p->numa_faults_locality[local] += pages;
3169 }
3170
3171 static void reset_ptenuma_scan(struct task_struct *p)
3172 {
3173         /*
3174          * We only did a read acquisition of the mmap sem, so
3175          * p->mm->numa_scan_seq is written to without exclusive access
3176          * and the update is not guaranteed to be atomic. That's not
3177          * much of an issue though, since this is just used for
3178          * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3179          * expensive, to avoid any form of compiler optimizations:
3180          */
3181         WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3182         p->mm->numa_scan_offset = 0;
3183 }
3184
3185 static bool vma_is_accessed(struct vm_area_struct *vma)
3186 {
3187         unsigned long pids;
3188         /*
3189          * Allow unconditional access first two times, so that all the (pages)
3190          * of VMAs get prot_none fault introduced irrespective of accesses.
3191          * This is also done to avoid any side effect of task scanning
3192          * amplifying the unfairness of disjoint set of VMAs' access.
3193          */
3194         if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3195                 return true;
3196
3197         pids = vma->numab_state->access_pids[0] | vma->numab_state->access_pids[1];
3198         return test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids);
3199 }
3200
3201 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3202
3203 /*
3204  * The expensive part of numa migration is done from task_work context.
3205  * Triggered from task_tick_numa().
3206  */
3207 static void task_numa_work(struct callback_head *work)
3208 {
3209         unsigned long migrate, next_scan, now = jiffies;
3210         struct task_struct *p = current;
3211         struct mm_struct *mm = p->mm;
3212         u64 runtime = p->se.sum_exec_runtime;
3213         struct vm_area_struct *vma;
3214         unsigned long start, end;
3215         unsigned long nr_pte_updates = 0;
3216         long pages, virtpages;
3217         struct vma_iterator vmi;
3218
3219         SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3220
3221         work->next = work;
3222         /*
3223          * Who cares about NUMA placement when they're dying.
3224          *
3225          * NOTE: make sure not to dereference p->mm before this check,
3226          * exit_task_work() happens _after_ exit_mm() so we could be called
3227          * without p->mm even though we still had it when we enqueued this
3228          * work.
3229          */
3230         if (p->flags & PF_EXITING)
3231                 return;
3232
3233         if (!mm->numa_next_scan) {
3234                 mm->numa_next_scan = now +
3235                         msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3236         }
3237
3238         /*
3239          * Enforce maximal scan/migration frequency..
3240          */
3241         migrate = mm->numa_next_scan;
3242         if (time_before(now, migrate))
3243                 return;
3244
3245         if (p->numa_scan_period == 0) {
3246                 p->numa_scan_period_max = task_scan_max(p);
3247                 p->numa_scan_period = task_scan_start(p);
3248         }
3249
3250         next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3251         if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3252                 return;
3253
3254         /*
3255          * Delay this task enough that another task of this mm will likely win
3256          * the next time around.
3257          */
3258         p->node_stamp += 2 * TICK_NSEC;
3259
3260         start = mm->numa_scan_offset;
3261         pages = sysctl_numa_balancing_scan_size;
3262         pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3263         virtpages = pages * 8;     /* Scan up to this much virtual space */
3264         if (!pages)
3265                 return;
3266
3267
3268         if (!mmap_read_trylock(mm))
3269                 return;
3270         vma_iter_init(&vmi, mm, start);
3271         vma = vma_next(&vmi);
3272         if (!vma) {
3273                 reset_ptenuma_scan(p);
3274                 start = 0;
3275                 vma_iter_set(&vmi, start);
3276                 vma = vma_next(&vmi);
3277         }
3278
3279         do {
3280                 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3281                         is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3282                         continue;
3283                 }
3284
3285                 /*
3286                  * Shared library pages mapped by multiple processes are not
3287                  * migrated as it is expected they are cache replicated. Avoid
3288                  * hinting faults in read-only file-backed mappings or the vdso
3289                  * as migrating the pages will be of marginal benefit.
3290                  */
3291                 if (!vma->vm_mm ||
3292                     (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
3293                         continue;
3294
3295                 /*
3296                  * Skip inaccessible VMAs to avoid any confusion between
3297                  * PROT_NONE and NUMA hinting ptes
3298                  */
3299                 if (!vma_is_accessible(vma))
3300                         continue;
3301
3302                 /* Initialise new per-VMA NUMAB state. */
3303                 if (!vma->numab_state) {
3304                         vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3305                                 GFP_KERNEL);
3306                         if (!vma->numab_state)
3307                                 continue;
3308
3309                         vma->numab_state->next_scan = now +
3310                                 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3311
3312                         /* Reset happens after 4 times scan delay of scan start */
3313                         vma->numab_state->next_pid_reset =  vma->numab_state->next_scan +
3314                                 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3315                 }
3316
3317                 /*
3318                  * Scanning the VMA's of short lived tasks add more overhead. So
3319                  * delay the scan for new VMAs.
3320                  */
3321                 if (mm->numa_scan_seq && time_before(jiffies,
3322                                                 vma->numab_state->next_scan))
3323                         continue;
3324
3325                 /* Do not scan the VMA if task has not accessed */
3326                 if (!vma_is_accessed(vma))
3327                         continue;
3328
3329                 /*
3330                  * RESET access PIDs regularly for old VMAs. Resetting after checking
3331                  * vma for recent access to avoid clearing PID info before access..
3332                  */
3333                 if (mm->numa_scan_seq &&
3334                                 time_after(jiffies, vma->numab_state->next_pid_reset)) {
3335                         vma->numab_state->next_pid_reset = vma->numab_state->next_pid_reset +
3336                                 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3337                         vma->numab_state->access_pids[0] = READ_ONCE(vma->numab_state->access_pids[1]);
3338                         vma->numab_state->access_pids[1] = 0;
3339                 }
3340
3341                 do {
3342                         start = max(start, vma->vm_start);
3343                         end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3344                         end = min(end, vma->vm_end);
3345                         nr_pte_updates = change_prot_numa(vma, start, end);
3346
3347                         /*
3348                          * Try to scan sysctl_numa_balancing_size worth of
3349                          * hpages that have at least one present PTE that
3350                          * is not already pte-numa. If the VMA contains
3351                          * areas that are unused or already full of prot_numa
3352                          * PTEs, scan up to virtpages, to skip through those
3353                          * areas faster.
3354                          */
3355                         if (nr_pte_updates)
3356                                 pages -= (end - start) >> PAGE_SHIFT;
3357                         virtpages -= (end - start) >> PAGE_SHIFT;
3358
3359                         start = end;
3360                         if (pages <= 0 || virtpages <= 0)
3361                                 goto out;
3362
3363                         cond_resched();
3364                 } while (end != vma->vm_end);
3365         } for_each_vma(vmi, vma);
3366
3367 out:
3368         /*
3369          * It is possible to reach the end of the VMA list but the last few
3370          * VMAs are not guaranteed to the vma_migratable. If they are not, we
3371          * would find the !migratable VMA on the next scan but not reset the
3372          * scanner to the start so check it now.
3373          */
3374         if (vma)
3375                 mm->numa_scan_offset = start;
3376         else
3377                 reset_ptenuma_scan(p);
3378         mmap_read_unlock(mm);
3379
3380         /*
3381          * Make sure tasks use at least 32x as much time to run other code
3382          * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3383          * Usually update_task_scan_period slows down scanning enough; on an
3384          * overloaded system we need to limit overhead on a per task basis.
3385          */
3386         if (unlikely(p->se.sum_exec_runtime != runtime)) {
3387                 u64 diff = p->se.sum_exec_runtime - runtime;
3388                 p->node_stamp += 32 * diff;
3389         }
3390 }
3391
3392 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3393 {
3394         int mm_users = 0;
3395         struct mm_struct *mm = p->mm;
3396
3397         if (mm) {
3398                 mm_users = atomic_read(&mm->mm_users);
3399                 if (mm_users == 1) {
3400                         mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3401                         mm->numa_scan_seq = 0;
3402                 }
3403         }
3404         p->node_stamp                   = 0;
3405         p->numa_scan_seq                = mm ? mm->numa_scan_seq : 0;
3406         p->numa_scan_period             = sysctl_numa_balancing_scan_delay;
3407         p->numa_migrate_retry           = 0;
3408         /* Protect against double add, see task_tick_numa and task_numa_work */
3409         p->numa_work.next               = &p->numa_work;
3410         p->numa_faults                  = NULL;
3411         p->numa_pages_migrated          = 0;
3412         p->total_numa_faults            = 0;
3413         RCU_INIT_POINTER(p->numa_group, NULL);
3414         p->last_task_numa_placement     = 0;
3415         p->last_sum_exec_runtime        = 0;
3416
3417         init_task_work(&p->numa_work, task_numa_work);
3418
3419         /* New address space, reset the preferred nid */
3420         if (!(clone_flags & CLONE_VM)) {
3421                 p->numa_preferred_nid = NUMA_NO_NODE;
3422                 return;
3423         }
3424
3425         /*
3426          * New thread, keep existing numa_preferred_nid which should be copied
3427          * already by arch_dup_task_struct but stagger when scans start.
3428          */
3429         if (mm) {
3430                 unsigned int delay;
3431
3432                 delay = min_t(unsigned int, task_scan_max(current),
3433                         current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3434                 delay += 2 * TICK_NSEC;
3435                 p->node_stamp = delay;
3436         }
3437 }
3438
3439 /*
3440  * Drive the periodic memory faults..
3441  */
3442 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3443 {
3444         struct callback_head *work = &curr->numa_work;
3445         u64 period, now;
3446
3447         /*
3448          * We don't care about NUMA placement if we don't have memory.
3449          */
3450         if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3451                 return;
3452
3453         /*
3454          * Using runtime rather than walltime has the dual advantage that
3455          * we (mostly) drive the selection from busy threads and that the
3456          * task needs to have done some actual work before we bother with
3457          * NUMA placement.
3458          */
3459         now = curr->se.sum_exec_runtime;
3460         period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3461
3462         if (now > curr->node_stamp + period) {
3463                 if (!curr->node_stamp)
3464                         curr->numa_scan_period = task_scan_start(curr);
3465                 curr->node_stamp += period;
3466
3467                 if (!time_before(jiffies, curr->mm->numa_next_scan))
3468                         task_work_add(curr, work, TWA_RESUME);
3469         }
3470 }
3471
3472 static void update_scan_period(struct task_struct *p, int new_cpu)
3473 {
3474         int src_nid = cpu_to_node(task_cpu(p));
3475         int dst_nid = cpu_to_node(new_cpu);
3476
3477         if (!static_branch_likely(&sched_numa_balancing))
3478                 return;
3479
3480         if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3481                 return;
3482
3483         if (src_nid == dst_nid)
3484                 return;
3485
3486         /*
3487          * Allow resets if faults have been trapped before one scan
3488          * has completed. This is most likely due to a new task that
3489          * is pulled cross-node due to wakeups or load balancing.
3490          */
3491         if (p->numa_scan_seq) {
3492                 /*
3493                  * Avoid scan adjustments if moving to the preferred
3494                  * node or if the task was not previously running on
3495                  * the preferred node.
3496                  */
3497                 if (dst_nid == p->numa_preferred_nid ||
3498                     (p->numa_preferred_nid != NUMA_NO_NODE &&
3499                         src_nid != p->numa_preferred_nid))
3500                         return;
3501         }
3502
3503         p->numa_scan_period = task_scan_start(p);
3504 }
3505
3506 #else
3507 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3508 {
3509 }
3510
3511 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3512 {
3513 }
3514
3515 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3516 {
3517 }
3518
3519 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3520 {
3521 }
3522
3523 #endif /* CONFIG_NUMA_BALANCING */
3524
3525 static void
3526 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3527 {
3528         update_load_add(&cfs_rq->load, se->load.weight);
3529 #ifdef CONFIG_SMP
3530         if (entity_is_task(se)) {
3531                 struct rq *rq = rq_of(cfs_rq);
3532
3533                 account_numa_enqueue(rq, task_of(se));
3534                 list_add(&se->group_node, &rq->cfs_tasks);
3535         }
3536 #endif
3537         cfs_rq->nr_running++;
3538         if (se_is_idle(se))
3539                 cfs_rq->idle_nr_running++;
3540 }
3541
3542 static void
3543 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3544 {
3545         update_load_sub(&cfs_rq->load, se->load.weight);
3546 #ifdef CONFIG_SMP
3547         if (entity_is_task(se)) {
3548                 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3549                 list_del_init(&se->group_node);
3550         }
3551 #endif
3552         cfs_rq->nr_running--;
3553         if (se_is_idle(se))
3554                 cfs_rq->idle_nr_running--;
3555 }
3556
3557 /*
3558  * Signed add and clamp on underflow.
3559  *
3560  * Explicitly do a load-store to ensure the intermediate value never hits
3561  * memory. This allows lockless observations without ever seeing the negative
3562  * values.
3563  */
3564 #define add_positive(_ptr, _val) do {                           \
3565         typeof(_ptr) ptr = (_ptr);                              \
3566         typeof(_val) val = (_val);                              \
3567         typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3568                                                                 \
3569         res = var + val;                                        \
3570                                                                 \
3571         if (val < 0 && res > var)                               \
3572                 res = 0;                                        \
3573                                                                 \
3574         WRITE_ONCE(*ptr, res);                                  \
3575 } while (0)
3576
3577 /*
3578  * Unsigned subtract and clamp on underflow.
3579  *
3580  * Explicitly do a load-store to ensure the intermediate value never hits
3581  * memory. This allows lockless observations without ever seeing the negative
3582  * values.
3583  */
3584 #define sub_positive(_ptr, _val) do {                           \
3585         typeof(_ptr) ptr = (_ptr);                              \
3586         typeof(*ptr) val = (_val);                              \
3587         typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3588         res = var - val;                                        \
3589         if (res > var)                                          \
3590                 res = 0;                                        \
3591         WRITE_ONCE(*ptr, res);                                  \
3592 } while (0)
3593
3594 /*
3595  * Remove and clamp on negative, from a local variable.
3596  *
3597  * A variant of sub_positive(), which does not use explicit load-store
3598  * and is thus optimized for local variable updates.
3599  */
3600 #define lsub_positive(_ptr, _val) do {                          \
3601         typeof(_ptr) ptr = (_ptr);                              \
3602         *ptr -= min_t(typeof(*ptr), *ptr, _val);                \
3603 } while (0)
3604
3605 #ifdef CONFIG_SMP
3606 static inline void
3607 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3608 {
3609         cfs_rq->avg.load_avg += se->avg.load_avg;
3610         cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3611 }
3612
3613 static inline void
3614 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3615 {
3616         sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3617         sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3618         /* See update_cfs_rq_load_avg() */
3619         cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3620                                           cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3621 }
3622 #else
3623 static inline void
3624 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3625 static inline void
3626 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3627 #endif
3628
3629 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3630                             unsigned long weight)
3631 {
3632         unsigned long old_weight = se->load.weight;
3633
3634         if (se->on_rq) {
3635                 /* commit outstanding execution time */
3636                 if (cfs_rq->curr == se)
3637                         update_curr(cfs_rq);
3638                 else
3639                         avg_vruntime_sub(cfs_rq, se);
3640                 update_load_sub(&cfs_rq->load, se->load.weight);
3641         }
3642         dequeue_load_avg(cfs_rq, se);
3643
3644         update_load_set(&se->load, weight);
3645
3646         if (!se->on_rq) {
3647                 /*
3648                  * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3649                  * we need to scale se->vlag when w_i changes.
3650                  */
3651                 se->vlag = div_s64(se->vlag * old_weight, weight);
3652         } else {
3653                 s64 deadline = se->deadline - se->vruntime;
3654                 /*
3655                  * When the weight changes, the virtual time slope changes and
3656                  * we should adjust the relative virtual deadline accordingly.
3657                  */
3658                 deadline = div_s64(deadline * old_weight, weight);
3659                 se->deadline = se->vruntime + deadline;
3660                 min_deadline_cb_propagate(&se->run_node, NULL);
3661         }
3662
3663 #ifdef CONFIG_SMP
3664         do {
3665                 u32 divider = get_pelt_divider(&se->avg);
3666
3667                 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3668         } while (0);
3669 #endif
3670
3671         enqueue_load_avg(cfs_rq, se);
3672         if (se->on_rq) {
3673                 update_load_add(&cfs_rq->load, se->load.weight);
3674                 if (cfs_rq->curr != se)
3675                         avg_vruntime_add(cfs_rq, se);
3676         }
3677 }
3678
3679 void reweight_task(struct task_struct *p, int prio)
3680 {
3681         struct sched_entity *se = &p->se;
3682         struct cfs_rq *cfs_rq = cfs_rq_of(se);
3683         struct load_weight *load = &se->load;
3684         unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3685
3686         reweight_entity(cfs_rq, se, weight);
3687         load->inv_weight = sched_prio_to_wmult[prio];
3688 }
3689
3690 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3691
3692 #ifdef CONFIG_FAIR_GROUP_SCHED
3693 #ifdef CONFIG_SMP
3694 /*
3695  * All this does is approximate the hierarchical proportion which includes that
3696  * global sum we all love to hate.
3697  *
3698  * That is, the weight of a group entity, is the proportional share of the
3699  * group weight based on the group runqueue weights. That is:
3700  *
3701  *                     tg->weight * grq->load.weight
3702  *   ge->load.weight = -----------------------------               (1)
3703  *                       \Sum grq->load.weight
3704  *
3705  * Now, because computing that sum is prohibitively expensive to compute (been
3706  * there, done that) we approximate it with this average stuff. The average
3707  * moves slower and therefore the approximation is cheaper and more stable.
3708  *
3709  * So instead of the above, we substitute:
3710  *
3711  *   grq->load.weight -> grq->avg.load_avg                         (2)
3712  *
3713  * which yields the following:
3714  *
3715  *                     tg->weight * grq->avg.load_avg
3716  *   ge->load.weight = ------------------------------              (3)
3717  *                             tg->load_avg
3718  *
3719  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3720  *
3721  * That is shares_avg, and it is right (given the approximation (2)).
3722  *
3723  * The problem with it is that because the average is slow -- it was designed
3724  * to be exactly that of course -- this leads to transients in boundary
3725  * conditions. In specific, the case where the group was idle and we start the
3726  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3727  * yielding bad latency etc..
3728  *
3729  * Now, in that special case (1) reduces to:
3730  *
3731  *                     tg->weight * grq->load.weight
3732  *   ge->load.weight = ----------------------------- = tg->weight   (4)
3733  *                         grp->load.weight
3734  *
3735  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3736  *
3737  * So what we do is modify our approximation (3) to approach (4) in the (near)
3738  * UP case, like:
3739  *
3740  *   ge->load.weight =
3741  *
3742  *              tg->weight * grq->load.weight
3743  *     ---------------------------------------------------         (5)
3744  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
3745  *
3746  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3747  * we need to use grq->avg.load_avg as its lower bound, which then gives:
3748  *
3749  *
3750  *                     tg->weight * grq->load.weight
3751  *   ge->load.weight = -----------------------------               (6)
3752  *                             tg_load_avg'
3753  *
3754  * Where:
3755  *
3756  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3757  *                  max(grq->load.weight, grq->avg.load_avg)
3758  *
3759  * And that is shares_weight and is icky. In the (near) UP case it approaches
3760  * (4) while in the normal case it approaches (3). It consistently
3761  * overestimates the ge->load.weight and therefore:
3762  *
3763  *   \Sum ge->load.weight >= tg->weight
3764  *
3765  * hence icky!
3766  */
3767 static long calc_group_shares(struct cfs_rq *cfs_rq)
3768 {
3769         long tg_weight, tg_shares, load, shares;
3770         struct task_group *tg = cfs_rq->tg;
3771
3772         tg_shares = READ_ONCE(tg->shares);
3773
3774         load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3775
3776         tg_weight = atomic_long_read(&tg->load_avg);
3777
3778         /* Ensure tg_weight >= load */
3779         tg_weight -= cfs_rq->tg_load_avg_contrib;
3780         tg_weight += load;
3781
3782         shares = (tg_shares * load);
3783         if (tg_weight)
3784                 shares /= tg_weight;
3785
3786         /*
3787          * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3788          * of a group with small tg->shares value. It is a floor value which is
3789          * assigned as a minimum load.weight to the sched_entity representing
3790          * the group on a CPU.
3791          *
3792          * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3793          * on an 8-core system with 8 tasks each runnable on one CPU shares has
3794          * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3795          * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3796          * instead of 0.
3797          */
3798         return clamp_t(long, shares, MIN_SHARES, tg_shares);
3799 }
3800 #endif /* CONFIG_SMP */
3801
3802 /*
3803  * Recomputes the group entity based on the current state of its group
3804  * runqueue.
3805  */
3806 static void update_cfs_group(struct sched_entity *se)
3807 {
3808         struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3809         long shares;
3810
3811         if (!gcfs_rq)
3812                 return;
3813
3814         if (throttled_hierarchy(gcfs_rq))
3815                 return;
3816
3817 #ifndef CONFIG_SMP
3818         shares = READ_ONCE(gcfs_rq->tg->shares);
3819
3820         if (likely(se->load.weight == shares))
3821                 return;
3822 #else
3823         shares   = calc_group_shares(gcfs_rq);
3824 #endif
3825
3826         reweight_entity(cfs_rq_of(se), se, shares);
3827 }
3828
3829 #else /* CONFIG_FAIR_GROUP_SCHED */
3830 static inline void update_cfs_group(struct sched_entity *se)
3831 {
3832 }
3833 #endif /* CONFIG_FAIR_GROUP_SCHED */
3834
3835 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3836 {
3837         struct rq *rq = rq_of(cfs_rq);
3838
3839         if (&rq->cfs == cfs_rq) {
3840                 /*
3841                  * There are a few boundary cases this might miss but it should
3842                  * get called often enough that that should (hopefully) not be
3843                  * a real problem.
3844                  *
3845                  * It will not get called when we go idle, because the idle
3846                  * thread is a different class (!fair), nor will the utilization
3847                  * number include things like RT tasks.
3848                  *
3849                  * As is, the util number is not freq-invariant (we'd have to
3850                  * implement arch_scale_freq_capacity() for that).
3851                  *
3852                  * See cpu_util_cfs().
3853                  */
3854                 cpufreq_update_util(rq, flags);
3855         }
3856 }
3857
3858 #ifdef CONFIG_SMP
3859 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3860 {
3861         if (sa->load_sum)
3862                 return false;
3863
3864         if (sa->util_sum)
3865                 return false;
3866
3867         if (sa->runnable_sum)
3868                 return false;
3869
3870         /*
3871          * _avg must be null when _sum are null because _avg = _sum / divider
3872          * Make sure that rounding and/or propagation of PELT values never
3873          * break this.
3874          */
3875         SCHED_WARN_ON(sa->load_avg ||
3876                       sa->util_avg ||
3877                       sa->runnable_avg);
3878
3879         return true;
3880 }
3881
3882 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3883 {
3884         return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3885                                  cfs_rq->last_update_time_copy);
3886 }
3887 #ifdef CONFIG_FAIR_GROUP_SCHED
3888 /*
3889  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
3890  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
3891  * bottom-up, we only have to test whether the cfs_rq before us on the list
3892  * is our child.
3893  * If cfs_rq is not on the list, test whether a child needs its to be added to
3894  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
3895  */
3896 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
3897 {
3898         struct cfs_rq *prev_cfs_rq;
3899         struct list_head *prev;
3900
3901         if (cfs_rq->on_list) {
3902                 prev = cfs_rq->leaf_cfs_rq_list.prev;
3903         } else {
3904                 struct rq *rq = rq_of(cfs_rq);
3905
3906                 prev = rq->tmp_alone_branch;
3907         }
3908
3909         prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
3910
3911         return (prev_cfs_rq->tg->parent == cfs_rq->tg);
3912 }
3913
3914 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
3915 {
3916         if (cfs_rq->load.weight)
3917                 return false;
3918
3919         if (!load_avg_is_decayed(&cfs_rq->avg))
3920                 return false;
3921
3922         if (child_cfs_rq_on_list(cfs_rq))
3923                 return false;
3924
3925         return true;
3926 }
3927
3928 /**
3929  * update_tg_load_avg - update the tg's load avg
3930  * @cfs_rq: the cfs_rq whose avg changed
3931  *
3932  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3933  * However, because tg->load_avg is a global value there are performance
3934  * considerations.
3935  *
3936  * In order to avoid having to look at the other cfs_rq's, we use a
3937  * differential update where we store the last value we propagated. This in
3938  * turn allows skipping updates if the differential is 'small'.
3939  *
3940  * Updating tg's load_avg is necessary before update_cfs_share().
3941  */
3942 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
3943 {
3944         long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3945
3946         /*
3947          * No need to update load_avg for root_task_group as it is not used.
3948          */
3949         if (cfs_rq->tg == &root_task_group)
3950                 return;
3951
3952         if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3953                 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3954                 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3955         }
3956 }
3957
3958 /*
3959  * Called within set_task_rq() right before setting a task's CPU. The
3960  * caller only guarantees p->pi_lock is held; no other assumptions,
3961  * including the state of rq->lock, should be made.
3962  */
3963 void set_task_rq_fair(struct sched_entity *se,
3964                       struct cfs_rq *prev, struct cfs_rq *next)
3965 {
3966         u64 p_last_update_time;
3967         u64 n_last_update_time;
3968
3969         if (!sched_feat(ATTACH_AGE_LOAD))
3970                 return;
3971
3972         /*
3973          * We are supposed to update the task to "current" time, then its up to
3974          * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3975          * getting what current time is, so simply throw away the out-of-date
3976          * time. This will result in the wakee task is less decayed, but giving
3977          * the wakee more load sounds not bad.
3978          */
3979         if (!(se->avg.last_update_time && prev))
3980                 return;
3981
3982         p_last_update_time = cfs_rq_last_update_time(prev);
3983         n_last_update_time = cfs_rq_last_update_time(next);
3984
3985         __update_load_avg_blocked_se(p_last_update_time, se);
3986         se->avg.last_update_time = n_last_update_time;
3987 }
3988
3989 /*
3990  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3991  * propagate its contribution. The key to this propagation is the invariant
3992  * that for each group:
3993  *
3994  *   ge->avg == grq->avg                                                (1)
3995  *
3996  * _IFF_ we look at the pure running and runnable sums. Because they
3997  * represent the very same entity, just at different points in the hierarchy.
3998  *
3999  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4000  * and simply copies the running/runnable sum over (but still wrong, because
4001  * the group entity and group rq do not have their PELT windows aligned).
4002  *
4003  * However, update_tg_cfs_load() is more complex. So we have:
4004  *
4005  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg          (2)
4006  *
4007  * And since, like util, the runnable part should be directly transferable,
4008  * the following would _appear_ to be the straight forward approach:
4009  *
4010  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg       (3)
4011  *
4012  * And per (1) we have:
4013  *
4014  *   ge->avg.runnable_avg == grq->avg.runnable_avg
4015  *
4016  * Which gives:
4017  *
4018  *                      ge->load.weight * grq->avg.load_avg
4019  *   ge->avg.load_avg = -----------------------------------             (4)
4020  *                               grq->load.weight
4021  *
4022  * Except that is wrong!
4023  *
4024  * Because while for entities historical weight is not important and we
4025  * really only care about our future and therefore can consider a pure
4026  * runnable sum, runqueues can NOT do this.
4027  *
4028  * We specifically want runqueues to have a load_avg that includes
4029  * historical weights. Those represent the blocked load, the load we expect
4030  * to (shortly) return to us. This only works by keeping the weights as
4031  * integral part of the sum. We therefore cannot decompose as per (3).
4032  *
4033  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4034  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4035  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4036  * runnable section of these tasks overlap (or not). If they were to perfectly
4037  * align the rq as a whole would be runnable 2/3 of the time. If however we
4038  * always have at least 1 runnable task, the rq as a whole is always runnable.
4039  *
4040  * So we'll have to approximate.. :/
4041  *
4042  * Given the constraint:
4043  *
4044  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4045  *
4046  * We can construct a rule that adds runnable to a rq by assuming minimal
4047  * overlap.
4048  *
4049  * On removal, we'll assume each task is equally runnable; which yields:
4050  *
4051  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4052  *
4053  * XXX: only do this for the part of runnable > running ?
4054  *
4055  */
4056 static inline void
4057 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4058 {
4059         long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4060         u32 new_sum, divider;
4061
4062         /* Nothing to update */
4063         if (!delta_avg)
4064                 return;
4065
4066         /*
4067          * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4068          * See ___update_load_avg() for details.
4069          */
4070         divider = get_pelt_divider(&cfs_rq->avg);
4071
4072
4073         /* Set new sched_entity's utilization */
4074         se->avg.util_avg = gcfs_rq->avg.util_avg;
4075         new_sum = se->avg.util_avg * divider;
4076         delta_sum = (long)new_sum - (long)se->avg.util_sum;
4077         se->avg.util_sum = new_sum;
4078
4079         /* Update parent cfs_rq utilization */
4080         add_positive(&cfs_rq->avg.util_avg, delta_avg);
4081         add_positive(&cfs_rq->avg.util_sum, delta_sum);
4082
4083         /* See update_cfs_rq_load_avg() */
4084         cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4085                                           cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4086 }
4087
4088 static inline void
4089 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4090 {
4091         long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4092         u32 new_sum, divider;
4093
4094         /* Nothing to update */
4095         if (!delta_avg)
4096                 return;
4097
4098         /*
4099          * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4100          * See ___update_load_avg() for details.
4101          */
4102         divider = get_pelt_divider(&cfs_rq->avg);
4103
4104         /* Set new sched_entity's runnable */
4105         se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4106         new_sum = se->avg.runnable_avg * divider;
4107         delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4108         se->avg.runnable_sum = new_sum;
4109
4110         /* Update parent cfs_rq runnable */
4111         add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4112         add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4113         /* See update_cfs_rq_load_avg() */
4114         cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4115                                               cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4116 }
4117
4118 static inline void
4119 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4120 {
4121         long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4122         unsigned long load_avg;
4123         u64 load_sum = 0;
4124         s64 delta_sum;
4125         u32 divider;
4126
4127         if (!runnable_sum)
4128                 return;
4129
4130         gcfs_rq->prop_runnable_sum = 0;
4131
4132         /*
4133          * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4134          * See ___update_load_avg() for details.
4135          */
4136         divider = get_pelt_divider(&cfs_rq->avg);
4137
4138         if (runnable_sum >= 0) {
4139                 /*
4140                  * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4141                  * the CPU is saturated running == runnable.
4142                  */
4143                 runnable_sum += se->avg.load_sum;
4144                 runnable_sum = min_t(long, runnable_sum, divider);
4145         } else {
4146                 /*
4147                  * Estimate the new unweighted runnable_sum of the gcfs_rq by
4148                  * assuming all tasks are equally runnable.
4149                  */
4150                 if (scale_load_down(gcfs_rq->load.weight)) {
4151                         load_sum = div_u64(gcfs_rq->avg.load_sum,
4152                                 scale_load_down(gcfs_rq->load.weight));
4153                 }
4154
4155                 /* But make sure to not inflate se's runnable */
4156                 runnable_sum = min(se->avg.load_sum, load_sum);
4157         }
4158
4159         /*
4160          * runnable_sum can't be lower than running_sum
4161          * Rescale running sum to be in the same range as runnable sum
4162          * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
4163          * runnable_sum is in [0 : LOAD_AVG_MAX]
4164          */
4165         running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4166         runnable_sum = max(runnable_sum, running_sum);
4167
4168         load_sum = se_weight(se) * runnable_sum;
4169         load_avg = div_u64(load_sum, divider);
4170
4171         delta_avg = load_avg - se->avg.load_avg;
4172         if (!delta_avg)
4173                 return;
4174
4175         delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4176
4177         se->avg.load_sum = runnable_sum;
4178         se->avg.load_avg = load_avg;
4179         add_positive(&cfs_rq->avg.load_avg, delta_avg);
4180         add_positive(&cfs_rq->avg.load_sum, delta_sum);
4181         /* See update_cfs_rq_load_avg() */
4182         cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4183                                           cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4184 }
4185
4186 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4187 {
4188         cfs_rq->propagate = 1;
4189         cfs_rq->prop_runnable_sum += runnable_sum;
4190 }
4191
4192 /* Update task and its cfs_rq load average */
4193 static inline int propagate_entity_load_avg(struct sched_entity *se)
4194 {
4195         struct cfs_rq *cfs_rq, *gcfs_rq;
4196
4197         if (entity_is_task(se))
4198                 return 0;
4199
4200         gcfs_rq = group_cfs_rq(se);
4201         if (!gcfs_rq->propagate)
4202                 return 0;
4203
4204         gcfs_rq->propagate = 0;
4205
4206         cfs_rq = cfs_rq_of(se);
4207
4208         add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4209
4210         update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4211         update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4212         update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4213
4214         trace_pelt_cfs_tp(cfs_rq);
4215         trace_pelt_se_tp(se);
4216
4217         return 1;
4218 }
4219
4220 /*
4221  * Check if we need to update the load and the utilization of a blocked
4222  * group_entity:
4223  */
4224 static inline bool skip_blocked_update(struct sched_entity *se)
4225 {
4226         struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4227
4228         /*
4229          * If sched_entity still have not zero load or utilization, we have to
4230          * decay it:
4231          */
4232         if (se->avg.load_avg || se->avg.util_avg)
4233                 return false;
4234
4235         /*
4236          * If there is a pending propagation, we have to update the load and
4237          * the utilization of the sched_entity:
4238          */
4239         if (gcfs_rq->propagate)
4240                 return false;
4241
4242         /*
4243          * Otherwise, the load and the utilization of the sched_entity is
4244          * already zero and there is no pending propagation, so it will be a
4245          * waste of time to try to decay it:
4246          */
4247         return true;
4248 }
4249
4250 #else /* CONFIG_FAIR_GROUP_SCHED */
4251
4252 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4253
4254 static inline int propagate_entity_load_avg(struct sched_entity *se)
4255 {
4256         return 0;
4257 }
4258
4259 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4260
4261 #endif /* CONFIG_FAIR_GROUP_SCHED */
4262
4263 #ifdef CONFIG_NO_HZ_COMMON
4264 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4265 {
4266         u64 throttled = 0, now, lut;
4267         struct cfs_rq *cfs_rq;
4268         struct rq *rq;
4269         bool is_idle;
4270
4271         if (load_avg_is_decayed(&se->avg))
4272                 return;
4273
4274         cfs_rq = cfs_rq_of(se);
4275         rq = rq_of(cfs_rq);
4276
4277         rcu_read_lock();
4278         is_idle = is_idle_task(rcu_dereference(rq->curr));
4279         rcu_read_unlock();
4280
4281         /*
4282          * The lag estimation comes with a cost we don't want to pay all the
4283          * time. Hence, limiting to the case where the source CPU is idle and
4284          * we know we are at the greatest risk to have an outdated clock.
4285          */
4286         if (!is_idle)
4287                 return;
4288
4289         /*
4290          * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4291          *
4292          *   last_update_time (the cfs_rq's last_update_time)
4293          *      = cfs_rq_clock_pelt()@cfs_rq_idle
4294          *      = rq_clock_pelt()@cfs_rq_idle
4295          *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
4296          *
4297          *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
4298          *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4299          *
4300          *   rq_idle_lag (delta between now and rq's update)
4301          *      = sched_clock_cpu() - rq_clock()@rq_idle
4302          *
4303          * We can then write:
4304          *
4305          *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4306          *          sched_clock_cpu() - rq_clock()@rq_idle
4307          * Where:
4308          *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4309          *      rq_clock()@rq_idle      is rq->clock_idle
4310          *      cfs->throttled_clock_pelt_time@cfs_rq_idle
4311          *                              is cfs_rq->throttled_pelt_idle
4312          */
4313
4314 #ifdef CONFIG_CFS_BANDWIDTH
4315         throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4316         /* The clock has been stopped for throttling */
4317         if (throttled == U64_MAX)
4318                 return;
4319 #endif
4320         now = u64_u32_load(rq->clock_pelt_idle);
4321         /*
4322          * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4323          * is observed the old clock_pelt_idle value and the new clock_idle,
4324          * which lead to an underestimation. The opposite would lead to an
4325          * overestimation.
4326          */
4327         smp_rmb();
4328         lut = cfs_rq_last_update_time(cfs_rq);
4329
4330         now -= throttled;
4331         if (now < lut)
4332                 /*
4333                  * cfs_rq->avg.last_update_time is more recent than our
4334                  * estimation, let's use it.
4335                  */
4336                 now = lut;
4337         else
4338                 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4339
4340         __update_load_avg_blocked_se(now, se);
4341 }
4342 #else
4343 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4344 #endif
4345
4346 /**
4347  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4348  * @now: current time, as per cfs_rq_clock_pelt()
4349  * @cfs_rq: cfs_rq to update
4350  *
4351  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4352  * avg. The immediate corollary is that all (fair) tasks must be attached.
4353  *
4354  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4355  *
4356  * Return: true if the load decayed or we removed load.
4357  *
4358  * Since both these conditions indicate a changed cfs_rq->avg.load we should
4359  * call update_tg_load_avg() when this function returns true.
4360  */
4361 static inline int
4362 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4363 {
4364         unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4365         struct sched_avg *sa = &cfs_rq->avg;
4366         int decayed = 0;
4367
4368         if (cfs_rq->removed.nr) {
4369                 unsigned long r;
4370                 u32 divider = get_pelt_divider(&cfs_rq->avg);
4371
4372                 raw_spin_lock(&cfs_rq->removed.lock);
4373                 swap(cfs_rq->removed.util_avg, removed_util);
4374                 swap(cfs_rq->removed.load_avg, removed_load);
4375                 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4376                 cfs_rq->removed.nr = 0;
4377                 raw_spin_unlock(&cfs_rq->removed.lock);
4378
4379                 r = removed_load;
4380                 sub_positive(&sa->load_avg, r);
4381                 sub_positive(&sa->load_sum, r * divider);
4382                 /* See sa->util_sum below */
4383                 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4384
4385                 r = removed_util;
4386                 sub_positive(&sa->util_avg, r);
4387                 sub_positive(&sa->util_sum, r * divider);
4388                 /*
4389                  * Because of rounding, se->util_sum might ends up being +1 more than
4390                  * cfs->util_sum. Although this is not a problem by itself, detaching
4391                  * a lot of tasks with the rounding problem between 2 updates of
4392                  * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4393                  * cfs_util_avg is not.
4394                  * Check that util_sum is still above its lower bound for the new
4395                  * util_avg. Given that period_contrib might have moved since the last
4396                  * sync, we are only sure that util_sum must be above or equal to
4397                  *    util_avg * minimum possible divider
4398                  */
4399                 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4400
4401                 r = removed_runnable;
4402                 sub_positive(&sa->runnable_avg, r);
4403                 sub_positive(&sa->runnable_sum, r * divider);
4404                 /* See sa->util_sum above */
4405                 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4406                                               sa->runnable_avg * PELT_MIN_DIVIDER);
4407
4408                 /*
4409                  * removed_runnable is the unweighted version of removed_load so we
4410                  * can use it to estimate removed_load_sum.
4411                  */
4412                 add_tg_cfs_propagate(cfs_rq,
4413                         -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4414
4415                 decayed = 1;
4416         }
4417
4418         decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4419         u64_u32_store_copy(sa->last_update_time,
4420                            cfs_rq->last_update_time_copy,
4421                            sa->last_update_time);
4422         return decayed;
4423 }
4424
4425 /**
4426  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4427  * @cfs_rq: cfs_rq to attach to
4428  * @se: sched_entity to attach
4429  *
4430  * Must call update_cfs_rq_load_avg() before this, since we rely on
4431  * cfs_rq->avg.last_update_time being current.
4432  */
4433 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4434 {
4435         /*
4436          * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4437          * See ___update_load_avg() for details.
4438          */
4439         u32 divider = get_pelt_divider(&cfs_rq->avg);
4440
4441         /*
4442          * When we attach the @se to the @cfs_rq, we must align the decay
4443          * window because without that, really weird and wonderful things can
4444          * happen.
4445          *
4446          * XXX illustrate
4447          */
4448         se->avg.last_update_time = cfs_rq->avg.last_update_time;
4449         se->avg.period_contrib = cfs_rq->avg.period_contrib;
4450
4451         /*
4452          * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4453          * period_contrib. This isn't strictly correct, but since we're
4454          * entirely outside of the PELT hierarchy, nobody cares if we truncate
4455          * _sum a little.
4456          */
4457         se->avg.util_sum = se->avg.util_avg * divider;
4458
4459         se->avg.runnable_sum = se->avg.runnable_avg * divider;
4460
4461         se->avg.load_sum = se->avg.load_avg * divider;
4462         if (se_weight(se) < se->avg.load_sum)
4463                 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4464         else
4465                 se->avg.load_sum = 1;
4466
4467         enqueue_load_avg(cfs_rq, se);
4468         cfs_rq->avg.util_avg += se->avg.util_avg;
4469         cfs_rq->avg.util_sum += se->avg.util_sum;
4470         cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4471         cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4472
4473         add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4474
4475         cfs_rq_util_change(cfs_rq, 0);
4476
4477         trace_pelt_cfs_tp(cfs_rq);
4478 }
4479
4480 /**
4481  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4482  * @cfs_rq: cfs_rq to detach from
4483  * @se: sched_entity to detach
4484  *
4485  * Must call update_cfs_rq_load_avg() before this, since we rely on
4486  * cfs_rq->avg.last_update_time being current.
4487  */
4488 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4489 {
4490         dequeue_load_avg(cfs_rq, se);
4491         sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4492         sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4493         /* See update_cfs_rq_load_avg() */
4494         cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4495                                           cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4496
4497         sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4498         sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4499         /* See update_cfs_rq_load_avg() */
4500         cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4501                                               cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4502
4503         add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4504
4505         cfs_rq_util_change(cfs_rq, 0);
4506
4507         trace_pelt_cfs_tp(cfs_rq);
4508 }
4509
4510 /*
4511  * Optional action to be done while updating the load average
4512  */
4513 #define UPDATE_TG       0x1
4514 #define SKIP_AGE_LOAD   0x2
4515 #define DO_ATTACH       0x4
4516 #define DO_DETACH       0x8
4517
4518 /* Update task and its cfs_rq load average */
4519 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4520 {
4521         u64 now = cfs_rq_clock_pelt(cfs_rq);
4522         int decayed;
4523
4524         /*
4525          * Track task load average for carrying it to new CPU after migrated, and
4526          * track group sched_entity load average for task_h_load calc in migration
4527          */
4528         if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4529                 __update_load_avg_se(now, cfs_rq, se);
4530
4531         decayed  = update_cfs_rq_load_avg(now, cfs_rq);
4532         decayed |= propagate_entity_load_avg(se);
4533
4534         if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4535
4536                 /*
4537                  * DO_ATTACH means we're here from enqueue_entity().
4538                  * !last_update_time means we've passed through
4539                  * migrate_task_rq_fair() indicating we migrated.
4540                  *
4541                  * IOW we're enqueueing a task on a new CPU.
4542                  */
4543                 attach_entity_load_avg(cfs_rq, se);
4544                 update_tg_load_avg(cfs_rq);
4545
4546         } else if (flags & DO_DETACH) {
4547                 /*
4548                  * DO_DETACH means we're here from dequeue_entity()
4549                  * and we are migrating task out of the CPU.
4550                  */
4551                 detach_entity_load_avg(cfs_rq, se);
4552                 update_tg_load_avg(cfs_rq);
4553         } else if (decayed) {
4554                 cfs_rq_util_change(cfs_rq, 0);
4555
4556                 if (flags & UPDATE_TG)
4557                         update_tg_load_avg(cfs_rq);
4558         }
4559 }
4560
4561 /*
4562  * Synchronize entity load avg of dequeued entity without locking
4563  * the previous rq.
4564  */
4565 static void sync_entity_load_avg(struct sched_entity *se)
4566 {
4567         struct cfs_rq *cfs_rq = cfs_rq_of(se);
4568         u64 last_update_time;
4569
4570         last_update_time = cfs_rq_last_update_time(cfs_rq);
4571         __update_load_avg_blocked_se(last_update_time, se);
4572 }
4573
4574 /*
4575  * Task first catches up with cfs_rq, and then subtract
4576  * itself from the cfs_rq (task must be off the queue now).
4577  */
4578 static void remove_entity_load_avg(struct sched_entity *se)
4579 {
4580         struct cfs_rq *cfs_rq = cfs_rq_of(se);
4581         unsigned long flags;
4582
4583         /*
4584          * tasks cannot exit without having gone through wake_up_new_task() ->
4585          * enqueue_task_fair() which will have added things to the cfs_rq,
4586          * so we can remove unconditionally.
4587          */
4588
4589         sync_entity_load_avg(se);
4590
4591         raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4592         ++cfs_rq->removed.nr;
4593         cfs_rq->removed.util_avg        += se->avg.util_avg;
4594         cfs_rq->removed.load_avg        += se->avg.load_avg;
4595         cfs_rq->removed.runnable_avg    += se->avg.runnable_avg;
4596         raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4597 }
4598
4599 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4600 {
4601         return cfs_rq->avg.runnable_avg;
4602 }
4603
4604 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4605 {
4606         return cfs_rq->avg.load_avg;
4607 }
4608
4609 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4610
4611 static inline unsigned long task_util(struct task_struct *p)
4612 {
4613         return READ_ONCE(p->se.avg.util_avg);
4614 }
4615
4616 static inline unsigned long _task_util_est(struct task_struct *p)
4617 {
4618         struct util_est ue = READ_ONCE(p->se.avg.util_est);
4619
4620         return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4621 }
4622
4623 static inline unsigned long task_util_est(struct task_struct *p)
4624 {
4625         return max(task_util(p), _task_util_est(p));
4626 }
4627
4628 #ifdef CONFIG_UCLAMP_TASK
4629 static inline unsigned long uclamp_task_util(struct task_struct *p,
4630                                              unsigned long uclamp_min,
4631                                              unsigned long uclamp_max)
4632 {
4633         return clamp(task_util_est(p), uclamp_min, uclamp_max);
4634 }
4635 #else
4636 static inline unsigned long uclamp_task_util(struct task_struct *p,
4637                                              unsigned long uclamp_min,
4638                                              unsigned long uclamp_max)
4639 {
4640         return task_util_est(p);
4641 }
4642 #endif
4643
4644 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4645                                     struct task_struct *p)
4646 {
4647         unsigned int enqueued;
4648
4649         if (!sched_feat(UTIL_EST))
4650                 return;
4651
4652         /* Update root cfs_rq's estimated utilization */
4653         enqueued  = cfs_rq->avg.util_est.enqueued;
4654         enqueued += _task_util_est(p);
4655         WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4656
4657         trace_sched_util_est_cfs_tp(cfs_rq);
4658 }
4659
4660 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4661                                     struct task_struct *p)
4662 {
4663         unsigned int enqueued;
4664
4665         if (!sched_feat(UTIL_EST))
4666                 return;
4667
4668         /* Update root cfs_rq's estimated utilization */
4669         enqueued  = cfs_rq->avg.util_est.enqueued;
4670         enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4671         WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4672
4673         trace_sched_util_est_cfs_tp(cfs_rq);
4674 }
4675
4676 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4677
4678 /*
4679  * Check if a (signed) value is within a specified (unsigned) margin,
4680  * based on the observation that:
4681  *
4682  *     abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4683  *
4684  * NOTE: this only works when value + margin < INT_MAX.
4685  */
4686 static inline bool within_margin(int value, int margin)
4687 {
4688         return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4689 }
4690
4691 static inline void util_est_update(struct cfs_rq *cfs_rq,
4692                                    struct task_struct *p,
4693                                    bool task_sleep)
4694 {
4695         long last_ewma_diff, last_enqueued_diff;
4696         struct util_est ue;
4697
4698         if (!sched_feat(UTIL_EST))
4699                 return;
4700
4701         /*
4702          * Skip update of task's estimated utilization when the task has not
4703          * yet completed an activation, e.g. being migrated.
4704          */
4705         if (!task_sleep)
4706                 return;
4707
4708         /*
4709          * If the PELT values haven't changed since enqueue time,
4710          * skip the util_est update.
4711          */
4712         ue = p->se.avg.util_est;
4713         if (ue.enqueued & UTIL_AVG_UNCHANGED)
4714                 return;
4715
4716         last_enqueued_diff = ue.enqueued;
4717
4718         /*
4719          * Reset EWMA on utilization increases, the moving average is used only
4720          * to smooth utilization decreases.
4721          */
4722         ue.enqueued = task_util(p);
4723         if (sched_feat(UTIL_EST_FASTUP)) {
4724                 if (ue.ewma < ue.enqueued) {
4725                         ue.ewma = ue.enqueued;
4726                         goto done;
4727                 }
4728         }
4729
4730         /*
4731          * Skip update of task's estimated utilization when its members are
4732          * already ~1% close to its last activation value.
4733          */
4734         last_ewma_diff = ue.enqueued - ue.ewma;
4735         last_enqueued_diff -= ue.enqueued;
4736         if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4737                 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4738                         goto done;
4739
4740                 return;
4741         }
4742
4743         /*
4744          * To avoid overestimation of actual task utilization, skip updates if
4745          * we cannot grant there is idle time in this CPU.
4746          */
4747         if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4748                 return;
4749
4750         /*
4751          * Update Task's estimated utilization
4752          *
4753          * When *p completes an activation we can consolidate another sample
4754          * of the task size. This is done by storing the current PELT value
4755          * as ue.enqueued and by using this value to update the Exponential
4756          * Weighted Moving Average (EWMA):
4757          *
4758          *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
4759          *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
4760          *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
4761          *          = w * (      last_ewma_diff            ) +     ewma(t-1)
4762          *          = w * (last_ewma_diff  +  ewma(t-1) / w)
4763          *
4764          * Where 'w' is the weight of new samples, which is configured to be
4765          * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4766          */
4767         ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4768         ue.ewma  += last_ewma_diff;
4769         ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4770 done:
4771         ue.enqueued |= UTIL_AVG_UNCHANGED;
4772         WRITE_ONCE(p->se.avg.util_est, ue);
4773
4774         trace_sched_util_est_se_tp(&p->se);
4775 }
4776
4777 static inline int util_fits_cpu(unsigned long util,
4778                                 unsigned long uclamp_min,
4779                                 unsigned long uclamp_max,
4780                                 int cpu)
4781 {
4782         unsigned long capacity_orig, capacity_orig_thermal;
4783         unsigned long capacity = capacity_of(cpu);
4784         bool fits, uclamp_max_fits;
4785
4786         /*
4787          * Check if the real util fits without any uclamp boost/cap applied.
4788          */
4789         fits = fits_capacity(util, capacity);
4790
4791         if (!uclamp_is_used())
4792                 return fits;
4793
4794         /*
4795          * We must use capacity_orig_of() for comparing against uclamp_min and
4796          * uclamp_max. We only care about capacity pressure (by using
4797          * capacity_of()) for comparing against the real util.
4798          *
4799          * If a task is boosted to 1024 for example, we don't want a tiny
4800          * pressure to skew the check whether it fits a CPU or not.
4801          *
4802          * Similarly if a task is capped to capacity_orig_of(little_cpu), it
4803          * should fit a little cpu even if there's some pressure.
4804          *
4805          * Only exception is for thermal pressure since it has a direct impact
4806          * on available OPP of the system.
4807          *
4808          * We honour it for uclamp_min only as a drop in performance level
4809          * could result in not getting the requested minimum performance level.
4810          *
4811          * For uclamp_max, we can tolerate a drop in performance level as the
4812          * goal is to cap the task. So it's okay if it's getting less.
4813          */
4814         capacity_orig = capacity_orig_of(cpu);
4815         capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4816
4817         /*
4818          * We want to force a task to fit a cpu as implied by uclamp_max.
4819          * But we do have some corner cases to cater for..
4820          *
4821          *
4822          *                                 C=z
4823          *   |                             ___
4824          *   |                  C=y       |   |
4825          *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
4826          *   |      C=x        |   |      |   |
4827          *   |      ___        |   |      |   |
4828          *   |     |   |       |   |      |   |    (util somewhere in this region)
4829          *   |     |   |       |   |      |   |
4830          *   |     |   |       |   |      |   |
4831          *   +----------------------------------------
4832          *         cpu0        cpu1       cpu2
4833          *
4834          *   In the above example if a task is capped to a specific performance
4835          *   point, y, then when:
4836          *
4837          *   * util = 80% of x then it does not fit on cpu0 and should migrate
4838          *     to cpu1
4839          *   * util = 80% of y then it is forced to fit on cpu1 to honour
4840          *     uclamp_max request.
4841          *
4842          *   which is what we're enforcing here. A task always fits if
4843          *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4844          *   the normal upmigration rules should withhold still.
4845          *
4846          *   Only exception is when we are on max capacity, then we need to be
4847          *   careful not to block overutilized state. This is so because:
4848          *
4849          *     1. There's no concept of capping at max_capacity! We can't go
4850          *        beyond this performance level anyway.
4851          *     2. The system is being saturated when we're operating near
4852          *        max capacity, it doesn't make sense to block overutilized.
4853          */
4854         uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4855         uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4856         fits = fits || uclamp_max_fits;
4857
4858         /*
4859          *
4860          *                                 C=z
4861          *   |                             ___       (region a, capped, util >= uclamp_max)
4862          *   |                  C=y       |   |
4863          *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4864          *   |      C=x        |   |      |   |
4865          *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
4866          *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4867          *   |     |   |       |   |      |   |
4868          *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
4869          *   +----------------------------------------
4870          *         cpu0        cpu1       cpu2
4871          *
4872          * a) If util > uclamp_max, then we're capped, we don't care about
4873          *    actual fitness value here. We only care if uclamp_max fits
4874          *    capacity without taking margin/pressure into account.
4875          *    See comment above.
4876          *
4877          * b) If uclamp_min <= util <= uclamp_max, then the normal
4878          *    fits_capacity() rules apply. Except we need to ensure that we
4879          *    enforce we remain within uclamp_max, see comment above.
4880          *
4881          * c) If util < uclamp_min, then we are boosted. Same as (b) but we
4882          *    need to take into account the boosted value fits the CPU without
4883          *    taking margin/pressure into account.
4884          *
4885          * Cases (a) and (b) are handled in the 'fits' variable already. We
4886          * just need to consider an extra check for case (c) after ensuring we
4887          * handle the case uclamp_min > uclamp_max.
4888          */
4889         uclamp_min = min(uclamp_min, uclamp_max);
4890         if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
4891                 return -1;
4892
4893         return fits;
4894 }
4895
4896 static inline int task_fits_cpu(struct task_struct *p, int cpu)
4897 {
4898         unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
4899         unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
4900         unsigned long util = task_util_est(p);
4901         /*
4902          * Return true only if the cpu fully fits the task requirements, which
4903          * include the utilization but also the performance hints.
4904          */
4905         return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
4906 }
4907
4908 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4909 {
4910         if (!sched_asym_cpucap_active())
4911                 return;
4912
4913         if (!p || p->nr_cpus_allowed == 1) {
4914                 rq->misfit_task_load = 0;
4915                 return;
4916         }
4917
4918         if (task_fits_cpu(p, cpu_of(rq))) {
4919                 rq->misfit_task_load = 0;
4920                 return;
4921         }
4922
4923         /*
4924          * Make sure that misfit_task_load will not be null even if
4925          * task_h_load() returns 0.
4926          */
4927         rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4928 }
4929
4930 #else /* CONFIG_SMP */
4931
4932 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4933 {
4934         return true;
4935 }
4936
4937 #define UPDATE_TG       0x0
4938 #define SKIP_AGE_LOAD   0x0
4939 #define DO_ATTACH       0x0
4940 #define DO_DETACH       0x0
4941
4942 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4943 {
4944         cfs_rq_util_change(cfs_rq, 0);
4945 }
4946
4947 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4948
4949 static inline void
4950 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4951 static inline void
4952 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4953
4954 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4955 {
4956         return 0;
4957 }
4958
4959 static inline void
4960 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4961
4962 static inline void
4963 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4964
4965 static inline void
4966 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4967                 bool task_sleep) {}
4968 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4969
4970 #endif /* CONFIG_SMP */
4971
4972 static void
4973 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4974 {
4975         u64 vslice, vruntime = avg_vruntime(cfs_rq);
4976         s64 lag = 0;
4977
4978         se->slice = sysctl_sched_base_slice;
4979         vslice = calc_delta_fair(se->slice, se);
4980
4981         /*
4982          * Due to how V is constructed as the weighted average of entities,
4983          * adding tasks with positive lag, or removing tasks with negative lag
4984          * will move 'time' backwards, this can screw around with the lag of
4985          * other tasks.
4986          *
4987          * EEVDF: placement strategy #1 / #2
4988          */
4989         if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
4990                 struct sched_entity *curr = cfs_rq->curr;
4991                 unsigned long load;
4992
4993                 lag = se->vlag;
4994
4995                 /*
4996                  * If we want to place a task and preserve lag, we have to
4997                  * consider the effect of the new entity on the weighted
4998                  * average and compensate for this, otherwise lag can quickly
4999                  * evaporate.
5000                  *
5001                  * Lag is defined as:
5002                  *
5003                  *   lag_i = S - s_i = w_i * (V - v_i)
5004                  *
5005                  * To avoid the 'w_i' term all over the place, we only track
5006                  * the virtual lag:
5007                  *
5008                  *   vl_i = V - v_i <=> v_i = V - vl_i
5009                  *
5010                  * And we take V to be the weighted average of all v:
5011                  *
5012                  *   V = (\Sum w_j*v_j) / W
5013                  *
5014                  * Where W is: \Sum w_j
5015                  *
5016                  * Then, the weighted average after adding an entity with lag
5017                  * vl_i is given by:
5018                  *
5019                  *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5020                  *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
5021                  *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5022                  *      = (V*(W + w_i) - w_i*l) / (W + w_i)
5023                  *      = V - w_i*vl_i / (W + w_i)
5024                  *
5025                  * And the actual lag after adding an entity with vl_i is:
5026                  *
5027                  *   vl'_i = V' - v_i
5028                  *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5029                  *         = vl_i - w_i*vl_i / (W + w_i)
5030                  *
5031                  * Which is strictly less than vl_i. So in order to preserve lag
5032                  * we should inflate the lag before placement such that the
5033                  * effective lag after placement comes out right.
5034                  *
5035                  * As such, invert the above relation for vl'_i to get the vl_i
5036                  * we need to use such that the lag after placement is the lag
5037                  * we computed before dequeue.
5038                  *
5039                  *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
5040                  *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5041                  *
5042                  *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5043                  *                   = W*vl_i
5044                  *
5045                  *   vl_i = (W + w_i)*vl'_i / W
5046                  */
5047                 load = cfs_rq->avg_load;
5048                 if (curr && curr->on_rq)
5049                         load += scale_load_down(curr->load.weight);
5050
5051                 lag *= load + scale_load_down(se->load.weight);
5052                 if (WARN_ON_ONCE(!load))
5053                         load = 1;
5054                 lag = div_s64(lag, load);
5055         }
5056
5057         se->vruntime = vruntime - lag;
5058
5059         /*
5060          * When joining the competition; the exisiting tasks will be,
5061          * on average, halfway through their slice, as such start tasks
5062          * off with half a slice to ease into the competition.
5063          */
5064         if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5065                 vslice /= 2;
5066
5067         /*
5068          * EEVDF: vd_i = ve_i + r_i/w_i
5069          */
5070         se->deadline = se->vruntime + vslice;
5071 }
5072
5073 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5074 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5075
5076 static inline bool cfs_bandwidth_used(void);
5077
5078 static void
5079 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5080 {
5081         bool curr = cfs_rq->curr == se;
5082
5083         /*
5084          * If we're the current task, we must renormalise before calling
5085          * update_curr().
5086          */
5087         if (curr)
5088                 place_entity(cfs_rq, se, flags);
5089
5090         update_curr(cfs_rq);
5091
5092         /*
5093          * When enqueuing a sched_entity, we must:
5094          *   - Update loads to have both entity and cfs_rq synced with now.
5095          *   - For group_entity, update its runnable_weight to reflect the new
5096          *     h_nr_running of its group cfs_rq.
5097          *   - For group_entity, update its weight to reflect the new share of
5098          *     its group cfs_rq
5099          *   - Add its new weight to cfs_rq->load.weight
5100          */
5101         update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5102         se_update_runnable(se);
5103         /*
5104          * XXX update_load_avg() above will have attached us to the pelt sum;
5105          * but update_cfs_group() here will re-adjust the weight and have to
5106          * undo/redo all that. Seems wasteful.
5107          */
5108         update_cfs_group(se);
5109
5110         /*
5111          * XXX now that the entity has been re-weighted, and it's lag adjusted,
5112          * we can place the entity.
5113          */
5114         if (!curr)
5115                 place_entity(cfs_rq, se, flags);
5116
5117         account_entity_enqueue(cfs_rq, se);
5118
5119         /* Entity has migrated, no longer consider this task hot */
5120         if (flags & ENQUEUE_MIGRATED)
5121                 se->exec_start = 0;
5122
5123         check_schedstat_required();
5124         update_stats_enqueue_fair(cfs_rq, se, flags);
5125         if (!curr)
5126                 __enqueue_entity(cfs_rq, se);
5127         se->on_rq = 1;
5128
5129         if (cfs_rq->nr_running == 1) {
5130                 check_enqueue_throttle(cfs_rq);
5131                 if (!throttled_hierarchy(cfs_rq)) {
5132                         list_add_leaf_cfs_rq(cfs_rq);
5133                 } else {
5134 #ifdef CONFIG_CFS_BANDWIDTH
5135                         struct rq *rq = rq_of(cfs_rq);
5136
5137                         if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5138                                 cfs_rq->throttled_clock = rq_clock(rq);
5139                         if (!cfs_rq->throttled_clock_self)
5140                                 cfs_rq->throttled_clock_self = rq_clock(rq);
5141 #endif
5142                 }
5143         }
5144 }
5145
5146 static void __clear_buddies_next(struct sched_entity *se)
5147 {
5148         for_each_sched_entity(se) {
5149                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5150                 if (cfs_rq->next != se)
5151                         break;
5152
5153                 cfs_rq->next = NULL;
5154         }
5155 }
5156
5157 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5158 {
5159         if (cfs_rq->next == se)
5160                 __clear_buddies_next(se);
5161 }
5162
5163 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5164
5165 static void
5166 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5167 {
5168         int action = UPDATE_TG;
5169
5170         if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5171                 action |= DO_DETACH;
5172
5173         /*
5174          * Update run-time statistics of the 'current'.
5175          */
5176         update_curr(cfs_rq);
5177
5178         /*
5179          * When dequeuing a sched_entity, we must:
5180          *   - Update loads to have both entity and cfs_rq synced with now.
5181          *   - For group_entity, update its runnable_weight to reflect the new
5182          *     h_nr_running of its group cfs_rq.
5183          *   - Subtract its previous weight from cfs_rq->load.weight.
5184          *   - For group entity, update its weight to reflect the new share
5185          *     of its group cfs_rq.
5186          */
5187         update_load_avg(cfs_rq, se, action);
5188         se_update_runnable(se);
5189
5190         update_stats_dequeue_fair(cfs_rq, se, flags);
5191
5192         clear_buddies(cfs_rq, se);
5193
5194         update_entity_lag(cfs_rq, se);
5195         if (se != cfs_rq->curr)
5196                 __dequeue_entity(cfs_rq, se);
5197         se->on_rq = 0;
5198         account_entity_dequeue(cfs_rq, se);
5199
5200         /* return excess runtime on last dequeue */
5201         return_cfs_rq_runtime(cfs_rq);
5202
5203         update_cfs_group(se);
5204
5205         /*
5206          * Now advance min_vruntime if @se was the entity holding it back,
5207          * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5208          * put back on, and if we advance min_vruntime, we'll be placed back
5209          * further than we started -- ie. we'll be penalized.
5210          */
5211         if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5212                 update_min_vruntime(cfs_rq);
5213
5214         if (cfs_rq->nr_running == 0)
5215                 update_idle_cfs_rq_clock_pelt(cfs_rq);
5216 }
5217
5218 static void
5219 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5220 {
5221         clear_buddies(cfs_rq, se);
5222
5223         /* 'current' is not kept within the tree. */
5224         if (se->on_rq) {
5225                 /*
5226                  * Any task has to be enqueued before it get to execute on
5227                  * a CPU. So account for the time it spent waiting on the
5228                  * runqueue.
5229                  */
5230                 update_stats_wait_end_fair(cfs_rq, se);
5231                 __dequeue_entity(cfs_rq, se);
5232                 update_load_avg(cfs_rq, se, UPDATE_TG);
5233                 /*
5234                  * HACK, stash a copy of deadline at the point of pick in vlag,
5235                  * which isn't used until dequeue.
5236                  */
5237                 se->vlag = se->deadline;
5238         }
5239
5240         update_stats_curr_start(cfs_rq, se);
5241         cfs_rq->curr = se;
5242
5243         /*
5244          * Track our maximum slice length, if the CPU's load is at
5245          * least twice that of our own weight (i.e. dont track it
5246          * when there are only lesser-weight tasks around):
5247          */
5248         if (schedstat_enabled() &&
5249             rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5250                 struct sched_statistics *stats;
5251
5252                 stats = __schedstats_from_se(se);
5253                 __schedstat_set(stats->slice_max,
5254                                 max((u64)stats->slice_max,
5255                                     se->sum_exec_runtime - se->prev_sum_exec_runtime));
5256         }
5257
5258         se->prev_sum_exec_runtime = se->sum_exec_runtime;
5259 }
5260
5261 /*
5262  * Pick the next process, keeping these things in mind, in this order:
5263  * 1) keep things fair between processes/task groups
5264  * 2) pick the "next" process, since someone really wants that to run
5265  * 3) pick the "last" process, for cache locality
5266  * 4) do not run the "skip" process, if something else is available
5267  */
5268 static struct sched_entity *
5269 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5270 {
5271         /*
5272          * Enabling NEXT_BUDDY will affect latency but not fairness.
5273          */
5274         if (sched_feat(NEXT_BUDDY) &&
5275             cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5276                 return cfs_rq->next;
5277
5278         return pick_eevdf(cfs_rq);
5279 }
5280
5281 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5282
5283 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5284 {
5285         /*
5286          * If still on the runqueue then deactivate_task()
5287          * was not called and update_curr() has to be done:
5288          */
5289         if (prev->on_rq)
5290                 update_curr(cfs_rq);
5291
5292         /* throttle cfs_rqs exceeding runtime */
5293         check_cfs_rq_runtime(cfs_rq);
5294
5295         if (prev->on_rq) {
5296                 update_stats_wait_start_fair(cfs_rq, prev);
5297                 /* Put 'current' back into the tree. */
5298                 __enqueue_entity(cfs_rq, prev);
5299                 /* in !on_rq case, update occurred at dequeue */
5300                 update_load_avg(cfs_rq, prev, 0);
5301         }
5302         cfs_rq->curr = NULL;
5303 }
5304
5305 static void
5306 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5307 {
5308         /*
5309          * Update run-time statistics of the 'current'.
5310          */
5311         update_curr(cfs_rq);
5312
5313         /*
5314          * Ensure that runnable average is periodically updated.
5315          */
5316         update_load_avg(cfs_rq, curr, UPDATE_TG);
5317         update_cfs_group(curr);
5318
5319 #ifdef CONFIG_SCHED_HRTICK
5320         /*
5321          * queued ticks are scheduled to match the slice, so don't bother
5322          * validating it and just reschedule.
5323          */
5324         if (queued) {
5325                 resched_curr(rq_of(cfs_rq));
5326                 return;
5327         }
5328         /*
5329          * don't let the period tick interfere with the hrtick preemption
5330          */
5331         if (!sched_feat(DOUBLE_TICK) &&
5332                         hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5333                 return;
5334 #endif
5335 }
5336
5337
5338 /**************************************************
5339  * CFS bandwidth control machinery
5340  */
5341
5342 #ifdef CONFIG_CFS_BANDWIDTH
5343
5344 #ifdef CONFIG_JUMP_LABEL
5345 static struct static_key __cfs_bandwidth_used;
5346
5347 static inline bool cfs_bandwidth_used(void)
5348 {
5349         return static_key_false(&__cfs_bandwidth_used);
5350 }
5351
5352 void cfs_bandwidth_usage_inc(void)
5353 {
5354         static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5355 }
5356
5357 void cfs_bandwidth_usage_dec(void)
5358 {
5359         static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5360 }
5361 #else /* CONFIG_JUMP_LABEL */
5362 static bool cfs_bandwidth_used(void)
5363 {
5364         return true;
5365 }
5366
5367 void cfs_bandwidth_usage_inc(void) {}
5368 void cfs_bandwidth_usage_dec(void) {}
5369 #endif /* CONFIG_JUMP_LABEL */
5370
5371 /*
5372  * default period for cfs group bandwidth.
5373  * default: 0.1s, units: nanoseconds
5374  */
5375 static inline u64 default_cfs_period(void)
5376 {
5377         return 100000000ULL;
5378 }
5379
5380 static inline u64 sched_cfs_bandwidth_slice(void)
5381 {
5382         return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5383 }
5384
5385 /*
5386  * Replenish runtime according to assigned quota. We use sched_clock_cpu
5387  * directly instead of rq->clock to avoid adding additional synchronization
5388  * around rq->lock.
5389  *
5390  * requires cfs_b->lock
5391  */
5392 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5393 {
5394         s64 runtime;
5395
5396         if (unlikely(cfs_b->quota == RUNTIME_INF))
5397                 return;
5398
5399         cfs_b->runtime += cfs_b->quota;
5400         runtime = cfs_b->runtime_snap - cfs_b->runtime;
5401         if (runtime > 0) {
5402                 cfs_b->burst_time += runtime;
5403                 cfs_b->nr_burst++;
5404         }
5405
5406         cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5407         cfs_b->runtime_snap = cfs_b->runtime;
5408 }
5409
5410 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5411 {
5412         return &tg->cfs_bandwidth;
5413 }
5414
5415 /* returns 0 on failure to allocate runtime */
5416 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5417                                    struct cfs_rq *cfs_rq, u64 target_runtime)
5418 {
5419         u64 min_amount, amount = 0;
5420
5421         lockdep_assert_held(&cfs_b->lock);
5422
5423         /* note: this is a positive sum as runtime_remaining <= 0 */
5424         min_amount = target_runtime - cfs_rq->runtime_remaining;
5425
5426         if (cfs_b->quota == RUNTIME_INF)
5427                 amount = min_amount;
5428         else {
5429                 start_cfs_bandwidth(cfs_b);
5430
5431                 if (cfs_b->runtime > 0) {
5432                         amount = min(cfs_b->runtime, min_amount);
5433                         cfs_b->runtime -= amount;
5434                         cfs_b->idle = 0;
5435                 }
5436         }
5437
5438         cfs_rq->runtime_remaining += amount;
5439
5440         return cfs_rq->runtime_remaining > 0;
5441 }
5442
5443 /* returns 0 on failure to allocate runtime */
5444 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5445 {
5446         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5447         int ret;
5448
5449         raw_spin_lock(&cfs_b->lock);
5450         ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5451         raw_spin_unlock(&cfs_b->lock);
5452
5453         return ret;
5454 }
5455
5456 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5457 {
5458         /* dock delta_exec before expiring quota (as it could span periods) */
5459         cfs_rq->runtime_remaining -= delta_exec;
5460
5461         if (likely(cfs_rq->runtime_remaining > 0))
5462                 return;
5463
5464         if (cfs_rq->throttled)
5465                 return;
5466         /*
5467          * if we're unable to extend our runtime we resched so that the active
5468          * hierarchy can be throttled
5469          */
5470         if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5471                 resched_curr(rq_of(cfs_rq));
5472 }
5473
5474 static __always_inline
5475 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5476 {
5477         if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5478                 return;
5479
5480         __account_cfs_rq_runtime(cfs_rq, delta_exec);
5481 }
5482
5483 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5484 {
5485         return cfs_bandwidth_used() && cfs_rq->throttled;
5486 }
5487
5488 /* check whether cfs_rq, or any parent, is throttled */
5489 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5490 {
5491         return cfs_bandwidth_used() && cfs_rq->throttle_count;
5492 }
5493
5494 /*
5495  * Ensure that neither of the group entities corresponding to src_cpu or
5496  * dest_cpu are members of a throttled hierarchy when performing group
5497  * load-balance operations.
5498  */
5499 static inline int throttled_lb_pair(struct task_group *tg,
5500                                     int src_cpu, int dest_cpu)
5501 {
5502         struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5503
5504         src_cfs_rq = tg->cfs_rq[src_cpu];
5505         dest_cfs_rq = tg->cfs_rq[dest_cpu];
5506
5507         return throttled_hierarchy(src_cfs_rq) ||
5508                throttled_hierarchy(dest_cfs_rq);
5509 }
5510
5511 static int tg_unthrottle_up(struct task_group *tg, void *data)
5512 {
5513         struct rq *rq = data;
5514         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5515
5516         cfs_rq->throttle_count--;
5517         if (!cfs_rq->throttle_count) {
5518                 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5519                                              cfs_rq->throttled_clock_pelt;
5520
5521                 /* Add cfs_rq with load or one or more already running entities to the list */
5522                 if (!cfs_rq_is_decayed(cfs_rq))
5523                         list_add_leaf_cfs_rq(cfs_rq);
5524
5525                 if (cfs_rq->throttled_clock_self) {
5526                         u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5527
5528                         cfs_rq->throttled_clock_self = 0;
5529
5530                         if (SCHED_WARN_ON((s64)delta < 0))
5531                                 delta = 0;
5532
5533                         cfs_rq->throttled_clock_self_time += delta;
5534                 }
5535         }
5536
5537         return 0;
5538 }
5539
5540 static int tg_throttle_down(struct task_group *tg, void *data)
5541 {
5542         struct rq *rq = data;
5543         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5544
5545         /* group is entering throttled state, stop time */
5546         if (!cfs_rq->throttle_count) {
5547                 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5548                 list_del_leaf_cfs_rq(cfs_rq);
5549
5550                 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5551                 if (cfs_rq->nr_running)
5552                         cfs_rq->throttled_clock_self = rq_clock(rq);
5553         }
5554         cfs_rq->throttle_count++;
5555
5556         return 0;
5557 }
5558
5559 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5560 {
5561         struct rq *rq = rq_of(cfs_rq);
5562         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5563         struct sched_entity *se;
5564         long task_delta, idle_task_delta, dequeue = 1;
5565
5566         raw_spin_lock(&cfs_b->lock);
5567         /* This will start the period timer if necessary */
5568         if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5569                 /*
5570                  * We have raced with bandwidth becoming available, and if we
5571                  * actually throttled the timer might not unthrottle us for an
5572                  * entire period. We additionally needed to make sure that any
5573                  * subsequent check_cfs_rq_runtime calls agree not to throttle
5574                  * us, as we may commit to do cfs put_prev+pick_next, so we ask
5575                  * for 1ns of runtime rather than just check cfs_b.
5576                  */
5577                 dequeue = 0;
5578         } else {
5579                 list_add_tail_rcu(&cfs_rq->throttled_list,
5580                                   &cfs_b->throttled_cfs_rq);
5581         }
5582         raw_spin_unlock(&cfs_b->lock);
5583
5584         if (!dequeue)
5585                 return false;  /* Throttle no longer required. */
5586
5587         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5588
5589         /* freeze hierarchy runnable averages while throttled */
5590         rcu_read_lock();
5591         walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5592         rcu_read_unlock();
5593
5594         task_delta = cfs_rq->h_nr_running;
5595         idle_task_delta = cfs_rq->idle_h_nr_running;
5596         for_each_sched_entity(se) {
5597                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5598                 /* throttled entity or throttle-on-deactivate */
5599                 if (!se->on_rq)
5600                         goto done;
5601
5602                 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5603
5604                 if (cfs_rq_is_idle(group_cfs_rq(se)))
5605                         idle_task_delta = cfs_rq->h_nr_running;
5606
5607                 qcfs_rq->h_nr_running -= task_delta;
5608                 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5609
5610                 if (qcfs_rq->load.weight) {
5611                         /* Avoid re-evaluating load for this entity: */
5612                         se = parent_entity(se);
5613                         break;
5614                 }
5615         }
5616
5617         for_each_sched_entity(se) {
5618                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5619                 /* throttled entity or throttle-on-deactivate */
5620                 if (!se->on_rq)
5621                         goto done;
5622
5623                 update_load_avg(qcfs_rq, se, 0);
5624                 se_update_runnable(se);
5625
5626                 if (cfs_rq_is_idle(group_cfs_rq(se)))
5627                         idle_task_delta = cfs_rq->h_nr_running;
5628
5629                 qcfs_rq->h_nr_running -= task_delta;
5630                 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5631         }
5632
5633         /* At this point se is NULL and we are at root level*/
5634         sub_nr_running(rq, task_delta);
5635
5636 done:
5637         /*
5638          * Note: distribution will already see us throttled via the
5639          * throttled-list.  rq->lock protects completion.
5640          */
5641         cfs_rq->throttled = 1;
5642         SCHED_WARN_ON(cfs_rq->throttled_clock);
5643         if (cfs_rq->nr_running)
5644                 cfs_rq->throttled_clock = rq_clock(rq);
5645         return true;
5646 }
5647
5648 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5649 {
5650         struct rq *rq = rq_of(cfs_rq);
5651         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5652         struct sched_entity *se;
5653         long task_delta, idle_task_delta;
5654
5655         se = cfs_rq->tg->se[cpu_of(rq)];
5656
5657         cfs_rq->throttled = 0;
5658
5659         update_rq_clock(rq);
5660
5661         raw_spin_lock(&cfs_b->lock);
5662         if (cfs_rq->throttled_clock) {
5663                 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5664                 cfs_rq->throttled_clock = 0;
5665         }
5666         list_del_rcu(&cfs_rq->throttled_list);
5667         raw_spin_unlock(&cfs_b->lock);
5668
5669         /* update hierarchical throttle state */
5670         walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5671
5672         if (!cfs_rq->load.weight) {
5673                 if (!cfs_rq->on_list)
5674                         return;
5675                 /*
5676                  * Nothing to run but something to decay (on_list)?
5677                  * Complete the branch.
5678                  */
5679                 for_each_sched_entity(se) {
5680                         if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5681                                 break;
5682                 }
5683                 goto unthrottle_throttle;
5684         }
5685
5686         task_delta = cfs_rq->h_nr_running;
5687         idle_task_delta = cfs_rq->idle_h_nr_running;
5688         for_each_sched_entity(se) {
5689                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5690
5691                 if (se->on_rq)
5692                         break;
5693                 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5694
5695                 if (cfs_rq_is_idle(group_cfs_rq(se)))
5696                         idle_task_delta = cfs_rq->h_nr_running;
5697
5698                 qcfs_rq->h_nr_running += task_delta;
5699                 qcfs_rq->idle_h_nr_running += idle_task_delta;
5700
5701                 /* end evaluation on encountering a throttled cfs_rq */
5702                 if (cfs_rq_throttled(qcfs_rq))
5703                         goto unthrottle_throttle;
5704         }
5705
5706         for_each_sched_entity(se) {
5707                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5708
5709                 update_load_avg(qcfs_rq, se, UPDATE_TG);
5710                 se_update_runnable(se);
5711
5712                 if (cfs_rq_is_idle(group_cfs_rq(se)))
5713                         idle_task_delta = cfs_rq->h_nr_running;
5714
5715                 qcfs_rq->h_nr_running += task_delta;
5716                 qcfs_rq->idle_h_nr_running += idle_task_delta;
5717
5718                 /* end evaluation on encountering a throttled cfs_rq */
5719                 if (cfs_rq_throttled(qcfs_rq))
5720                         goto unthrottle_throttle;
5721         }
5722
5723         /* At this point se is NULL and we are at root level*/
5724         add_nr_running(rq, task_delta);
5725
5726 unthrottle_throttle:
5727         assert_list_leaf_cfs_rq(rq);
5728
5729         /* Determine whether we need to wake up potentially idle CPU: */
5730         if (rq->curr == rq->idle && rq->cfs.nr_running)
5731                 resched_curr(rq);
5732 }
5733
5734 #ifdef CONFIG_SMP
5735 static void __cfsb_csd_unthrottle(void *arg)
5736 {
5737         struct cfs_rq *cursor, *tmp;
5738         struct rq *rq = arg;
5739         struct rq_flags rf;
5740
5741         rq_lock(rq, &rf);
5742
5743         /*
5744          * Iterating over the list can trigger several call to
5745          * update_rq_clock() in unthrottle_cfs_rq().
5746          * Do it once and skip the potential next ones.
5747          */
5748         update_rq_clock(rq);
5749         rq_clock_start_loop_update(rq);
5750
5751         /*
5752          * Since we hold rq lock we're safe from concurrent manipulation of
5753          * the CSD list. However, this RCU critical section annotates the
5754          * fact that we pair with sched_free_group_rcu(), so that we cannot
5755          * race with group being freed in the window between removing it
5756          * from the list and advancing to the next entry in the list.
5757          */
5758         rcu_read_lock();
5759
5760         list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5761                                  throttled_csd_list) {
5762                 list_del_init(&cursor->throttled_csd_list);
5763
5764                 if (cfs_rq_throttled(cursor))
5765                         unthrottle_cfs_rq(cursor);
5766         }
5767
5768         rcu_read_unlock();
5769
5770         rq_clock_stop_loop_update(rq);
5771         rq_unlock(rq, &rf);
5772 }
5773
5774 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5775 {
5776         struct rq *rq = rq_of(cfs_rq);
5777         bool first;
5778
5779         if (rq == this_rq()) {
5780                 unthrottle_cfs_rq(cfs_rq);
5781                 return;
5782         }
5783
5784         /* Already enqueued */
5785         if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5786                 return;
5787
5788         first = list_empty(&rq->cfsb_csd_list);
5789         list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5790         if (first)
5791                 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5792 }
5793 #else
5794 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5795 {
5796         unthrottle_cfs_rq(cfs_rq);
5797 }
5798 #endif
5799
5800 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5801 {
5802         lockdep_assert_rq_held(rq_of(cfs_rq));
5803
5804         if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5805             cfs_rq->runtime_remaining <= 0))
5806                 return;
5807
5808         __unthrottle_cfs_rq_async(cfs_rq);
5809 }
5810
5811 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5812 {
5813         struct cfs_rq *local_unthrottle = NULL;
5814         int this_cpu = smp_processor_id();
5815         u64 runtime, remaining = 1;
5816         bool throttled = false;
5817         struct cfs_rq *cfs_rq;
5818         struct rq_flags rf;
5819         struct rq *rq;
5820
5821         rcu_read_lock();
5822         list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5823                                 throttled_list) {
5824                 rq = rq_of(cfs_rq);
5825
5826                 if (!remaining) {
5827                         throttled = true;
5828                         break;
5829                 }
5830
5831                 rq_lock_irqsave(rq, &rf);
5832                 if (!cfs_rq_throttled(cfs_rq))
5833                         goto next;
5834
5835 #ifdef CONFIG_SMP
5836                 /* Already queued for async unthrottle */
5837                 if (!list_empty(&cfs_rq->throttled_csd_list))
5838                         goto next;
5839 #endif
5840
5841                 /* By the above checks, this should never be true */
5842                 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5843
5844                 raw_spin_lock(&cfs_b->lock);
5845                 runtime = -cfs_rq->runtime_remaining + 1;
5846                 if (runtime > cfs_b->runtime)
5847                         runtime = cfs_b->runtime;
5848                 cfs_b->runtime -= runtime;
5849                 remaining = cfs_b->runtime;
5850                 raw_spin_unlock(&cfs_b->lock);
5851
5852                 cfs_rq->runtime_remaining += runtime;
5853
5854                 /* we check whether we're throttled above */
5855                 if (cfs_rq->runtime_remaining > 0) {
5856                         if (cpu_of(rq) != this_cpu ||
5857                             SCHED_WARN_ON(local_unthrottle))
5858                                 unthrottle_cfs_rq_async(cfs_rq);
5859                         else
5860                                 local_unthrottle = cfs_rq;
5861                 } else {
5862                         throttled = true;
5863                 }
5864
5865 next:
5866                 rq_unlock_irqrestore(rq, &rf);
5867         }
5868         rcu_read_unlock();
5869
5870         if (local_unthrottle) {
5871                 rq = cpu_rq(this_cpu);
5872                 rq_lock_irqsave(rq, &rf);
5873                 if (cfs_rq_throttled(local_unthrottle))
5874                         unthrottle_cfs_rq(local_unthrottle);
5875                 rq_unlock_irqrestore(rq, &rf);
5876         }
5877
5878         return throttled;
5879 }
5880
5881 /*
5882  * Responsible for refilling a task_group's bandwidth and unthrottling its
5883  * cfs_rqs as appropriate. If there has been no activity within the last
5884  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5885  * used to track this state.
5886  */
5887 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5888 {
5889         int throttled;
5890
5891         /* no need to continue the timer with no bandwidth constraint */
5892         if (cfs_b->quota == RUNTIME_INF)
5893                 goto out_deactivate;
5894
5895         throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5896         cfs_b->nr_periods += overrun;
5897
5898         /* Refill extra burst quota even if cfs_b->idle */
5899         __refill_cfs_bandwidth_runtime(cfs_b);
5900
5901         /*
5902          * idle depends on !throttled (for the case of a large deficit), and if
5903          * we're going inactive then everything else can be deferred
5904          */
5905         if (cfs_b->idle && !throttled)
5906                 goto out_deactivate;
5907
5908         if (!throttled) {
5909                 /* mark as potentially idle for the upcoming period */
5910                 cfs_b->idle = 1;
5911                 return 0;
5912         }
5913
5914         /* account preceding periods in which throttling occurred */
5915         cfs_b->nr_throttled += overrun;
5916
5917         /*
5918          * This check is repeated as we release cfs_b->lock while we unthrottle.
5919          */
5920         while (throttled && cfs_b->runtime > 0) {
5921                 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5922                 /* we can't nest cfs_b->lock while distributing bandwidth */
5923                 throttled = distribute_cfs_runtime(cfs_b);
5924                 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5925         }
5926
5927         /*
5928          * While we are ensured activity in the period following an
5929          * unthrottle, this also covers the case in which the new bandwidth is
5930          * insufficient to cover the existing bandwidth deficit.  (Forcing the
5931          * timer to remain active while there are any throttled entities.)
5932          */
5933         cfs_b->idle = 0;
5934
5935         return 0;
5936
5937 out_deactivate:
5938         return 1;
5939 }
5940
5941 /* a cfs_rq won't donate quota below this amount */
5942 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5943 /* minimum remaining period time to redistribute slack quota */
5944 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5945 /* how long we wait to gather additional slack before distributing */
5946 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5947
5948 /*
5949  * Are we near the end of the current quota period?
5950  *
5951  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5952  * hrtimer base being cleared by hrtimer_start. In the case of
5953  * migrate_hrtimers, base is never cleared, so we are fine.
5954  */
5955 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5956 {
5957         struct hrtimer *refresh_timer = &cfs_b->period_timer;
5958         s64 remaining;
5959
5960         /* if the call-back is running a quota refresh is already occurring */
5961         if (hrtimer_callback_running(refresh_timer))
5962                 return 1;
5963
5964         /* is a quota refresh about to occur? */
5965         remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5966         if (remaining < (s64)min_expire)
5967                 return 1;
5968
5969         return 0;
5970 }
5971
5972 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5973 {
5974         u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5975
5976         /* if there's a quota refresh soon don't bother with slack */
5977         if (runtime_refresh_within(cfs_b, min_left))
5978                 return;
5979
5980         /* don't push forwards an existing deferred unthrottle */
5981         if (cfs_b->slack_started)
5982                 return;
5983         cfs_b->slack_started = true;
5984
5985         hrtimer_start(&cfs_b->slack_timer,
5986                         ns_to_ktime(cfs_bandwidth_slack_period),
5987                         HRTIMER_MODE_REL);
5988 }
5989
5990 /* we know any runtime found here is valid as update_curr() precedes return */
5991 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5992 {
5993         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5994         s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5995
5996         if (slack_runtime <= 0)
5997                 return;
5998
5999         raw_spin_lock(&cfs_b->lock);
6000         if (cfs_b->quota != RUNTIME_INF) {
6001                 cfs_b->runtime += slack_runtime;
6002
6003                 /* we are under rq->lock, defer unthrottling using a timer */
6004                 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6005                     !list_empty(&cfs_b->throttled_cfs_rq))
6006                         start_cfs_slack_bandwidth(cfs_b);
6007         }
6008         raw_spin_unlock(&cfs_b->lock);
6009
6010         /* even if it's not valid for return we don't want to try again */
6011         cfs_rq->runtime_remaining -= slack_runtime;
6012 }
6013
6014 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6015 {
6016         if (!cfs_bandwidth_used())
6017                 return;
6018
6019         if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6020                 return;
6021
6022         __return_cfs_rq_runtime(cfs_rq);
6023 }
6024
6025 /*
6026  * This is done with a timer (instead of inline with bandwidth return) since
6027  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6028  */
6029 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6030 {
6031         u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6032         unsigned long flags;
6033
6034         /* confirm we're still not at a refresh boundary */
6035         raw_spin_lock_irqsave(&cfs_b->lock, flags);
6036         cfs_b->slack_started = false;
6037
6038         if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6039                 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6040                 return;
6041         }
6042
6043         if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6044                 runtime = cfs_b->runtime;
6045
6046         raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6047
6048         if (!runtime)
6049                 return;
6050
6051         distribute_cfs_runtime(cfs_b);
6052 }
6053
6054 /*
6055  * When a group wakes up we want to make sure that its quota is not already
6056  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6057  * runtime as update_curr() throttling can not trigger until it's on-rq.
6058  */
6059 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6060 {
6061         if (!cfs_bandwidth_used())
6062                 return;
6063
6064         /* an active group must be handled by the update_curr()->put() path */
6065         if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6066                 return;
6067
6068         /* ensure the group is not already throttled */
6069         if (cfs_rq_throttled(cfs_rq))
6070                 return;
6071
6072         /* update runtime allocation */
6073         account_cfs_rq_runtime(cfs_rq, 0);
6074         if (cfs_rq->runtime_remaining <= 0)
6075                 throttle_cfs_rq(cfs_rq);
6076 }
6077
6078 static void sync_throttle(struct task_group *tg, int cpu)
6079 {
6080         struct cfs_rq *pcfs_rq, *cfs_rq;
6081
6082         if (!cfs_bandwidth_used())
6083                 return;
6084
6085         if (!tg->parent)
6086                 return;
6087
6088         cfs_rq = tg->cfs_rq[cpu];
6089         pcfs_rq = tg->parent->cfs_rq[cpu];
6090
6091         cfs_rq->throttle_count = pcfs_rq->throttle_count;
6092         cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6093 }
6094
6095 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6096 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6097 {
6098         if (!cfs_bandwidth_used())
6099                 return false;
6100
6101         if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6102                 return false;
6103
6104         /*
6105          * it's possible for a throttled entity to be forced into a running
6106          * state (e.g. set_curr_task), in this case we're finished.
6107          */
6108         if (cfs_rq_throttled(cfs_rq))
6109                 return true;
6110
6111         return throttle_cfs_rq(cfs_rq);
6112 }
6113
6114 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6115 {
6116         struct cfs_bandwidth *cfs_b =
6117                 container_of(timer, struct cfs_bandwidth, slack_timer);
6118
6119         do_sched_cfs_slack_timer(cfs_b);
6120
6121         return HRTIMER_NORESTART;
6122 }
6123
6124 extern const u64 max_cfs_quota_period;
6125
6126 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6127 {
6128         struct cfs_bandwidth *cfs_b =
6129                 container_of(timer, struct cfs_bandwidth, period_timer);
6130         unsigned long flags;
6131         int overrun;
6132         int idle = 0;
6133         int count = 0;
6134
6135         raw_spin_lock_irqsave(&cfs_b->lock, flags);
6136         for (;;) {
6137                 overrun = hrtimer_forward_now(timer, cfs_b->period);
6138                 if (!overrun)
6139                         break;
6140
6141                 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6142
6143                 if (++count > 3) {
6144                         u64 new, old = ktime_to_ns(cfs_b->period);
6145
6146                         /*
6147                          * Grow period by a factor of 2 to avoid losing precision.
6148                          * Precision loss in the quota/period ratio can cause __cfs_schedulable
6149                          * to fail.
6150                          */
6151                         new = old * 2;
6152                         if (new < max_cfs_quota_period) {
6153                                 cfs_b->period = ns_to_ktime(new);
6154                                 cfs_b->quota *= 2;
6155                                 cfs_b->burst *= 2;
6156
6157                                 pr_warn_ratelimited(
6158         "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6159                                         smp_processor_id(),
6160                                         div_u64(new, NSEC_PER_USEC),
6161                                         div_u64(cfs_b->quota, NSEC_PER_USEC));
6162                         } else {
6163                                 pr_warn_ratelimited(
6164         "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6165                                         smp_processor_id(),
6166                                         div_u64(old, NSEC_PER_USEC),
6167                                         div_u64(cfs_b->quota, NSEC_PER_USEC));
6168                         }
6169
6170                         /* reset count so we don't come right back in here */
6171                         count = 0;
6172                 }
6173         }
6174         if (idle)
6175                 cfs_b->period_active = 0;
6176         raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6177
6178         return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6179 }
6180
6181 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6182 {
6183         raw_spin_lock_init(&cfs_b->lock);
6184         cfs_b->runtime = 0;
6185         cfs_b->quota = RUNTIME_INF;
6186         cfs_b->period = ns_to_ktime(default_cfs_period());
6187         cfs_b->burst = 0;
6188         cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6189
6190         INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6191         hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6192         cfs_b->period_timer.function = sched_cfs_period_timer;
6193
6194         /* Add a random offset so that timers interleave */
6195         hrtimer_set_expires(&cfs_b->period_timer,
6196                             get_random_u32_below(cfs_b->period));
6197         hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6198         cfs_b->slack_timer.function = sched_cfs_slack_timer;
6199         cfs_b->slack_started = false;
6200 }
6201
6202 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6203 {
6204         cfs_rq->runtime_enabled = 0;
6205         INIT_LIST_HEAD(&cfs_rq->throttled_list);
6206 #ifdef CONFIG_SMP
6207         INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6208 #endif
6209 }
6210
6211 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6212 {
6213         lockdep_assert_held(&cfs_b->lock);
6214
6215         if (cfs_b->period_active)
6216                 return;
6217
6218         cfs_b->period_active = 1;
6219         hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6220         hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6221 }
6222
6223 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6224 {
6225         int __maybe_unused i;
6226
6227         /* init_cfs_bandwidth() was not called */
6228         if (!cfs_b->throttled_cfs_rq.next)
6229                 return;
6230
6231         hrtimer_cancel(&cfs_b->period_timer);
6232         hrtimer_cancel(&cfs_b->slack_timer);
6233
6234         /*
6235          * It is possible that we still have some cfs_rq's pending on a CSD
6236          * list, though this race is very rare. In order for this to occur, we
6237          * must have raced with the last task leaving the group while there
6238          * exist throttled cfs_rq(s), and the period_timer must have queued the
6239          * CSD item but the remote cpu has not yet processed it. To handle this,
6240          * we can simply flush all pending CSD work inline here. We're
6241          * guaranteed at this point that no additional cfs_rq of this group can
6242          * join a CSD list.
6243          */
6244 #ifdef CONFIG_SMP
6245         for_each_possible_cpu(i) {
6246                 struct rq *rq = cpu_rq(i);
6247                 unsigned long flags;
6248
6249                 if (list_empty(&rq->cfsb_csd_list))
6250                         continue;
6251
6252                 local_irq_save(flags);
6253                 __cfsb_csd_unthrottle(rq);
6254                 local_irq_restore(flags);
6255         }
6256 #endif
6257 }
6258
6259 /*
6260  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6261  *
6262  * The race is harmless, since modifying bandwidth settings of unhooked group
6263  * bits doesn't do much.
6264  */
6265
6266 /* cpu online callback */
6267 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6268 {
6269         struct task_group *tg;
6270
6271         lockdep_assert_rq_held(rq);
6272
6273         rcu_read_lock();
6274         list_for_each_entry_rcu(tg, &task_groups, list) {
6275                 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6276                 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6277
6278                 raw_spin_lock(&cfs_b->lock);
6279                 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6280                 raw_spin_unlock(&cfs_b->lock);
6281         }
6282         rcu_read_unlock();
6283 }
6284
6285 /* cpu offline callback */
6286 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6287 {
6288         struct task_group *tg;
6289
6290         lockdep_assert_rq_held(rq);
6291
6292         /*
6293          * The rq clock has already been updated in the
6294          * set_rq_offline(), so we should skip updating
6295          * the rq clock again in unthrottle_cfs_rq().
6296          */
6297         rq_clock_start_loop_update(rq);
6298
6299         rcu_read_lock();
6300         list_for_each_entry_rcu(tg, &task_groups, list) {
6301                 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6302
6303                 if (!cfs_rq->runtime_enabled)
6304                         continue;
6305
6306                 /*
6307                  * clock_task is not advancing so we just need to make sure
6308                  * there's some valid quota amount
6309                  */
6310                 cfs_rq->runtime_remaining = 1;
6311                 /*
6312                  * Offline rq is schedulable till CPU is completely disabled
6313                  * in take_cpu_down(), so we prevent new cfs throttling here.
6314                  */
6315                 cfs_rq->runtime_enabled = 0;
6316
6317                 if (cfs_rq_throttled(cfs_rq))
6318                         unthrottle_cfs_rq(cfs_rq);
6319         }
6320         rcu_read_unlock();
6321
6322         rq_clock_stop_loop_update(rq);
6323 }
6324
6325 bool cfs_task_bw_constrained(struct task_struct *p)
6326 {
6327         struct cfs_rq *cfs_rq = task_cfs_rq(p);
6328
6329         if (!cfs_bandwidth_used())
6330                 return false;
6331
6332         if (cfs_rq->runtime_enabled ||
6333             tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6334                 return true;
6335
6336         return false;
6337 }
6338
6339 #ifdef CONFIG_NO_HZ_FULL
6340 /* called from pick_next_task_fair() */
6341 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6342 {
6343         int cpu = cpu_of(rq);
6344
6345         if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6346                 return;
6347
6348         if (!tick_nohz_full_cpu(cpu))
6349                 return;
6350
6351         if (rq->nr_running != 1)
6352                 return;
6353
6354         /*
6355          *  We know there is only one task runnable and we've just picked it. The
6356          *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6357          *  be otherwise able to stop the tick. Just need to check if we are using
6358          *  bandwidth control.
6359          */
6360         if (cfs_task_bw_constrained(p))
6361                 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6362 }
6363 #endif
6364
6365 #else /* CONFIG_CFS_BANDWIDTH */
6366
6367 static inline bool cfs_bandwidth_used(void)
6368 {
6369         return false;
6370 }
6371
6372 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6373 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6374 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6375 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6376 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6377
6378 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6379 {
6380         return 0;
6381 }
6382
6383 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6384 {
6385         return 0;
6386 }
6387
6388 static inline int throttled_lb_pair(struct task_group *tg,
6389                                     int src_cpu, int dest_cpu)
6390 {
6391         return 0;
6392 }
6393
6394 #ifdef CONFIG_FAIR_GROUP_SCHED
6395 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6396 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6397 #endif
6398
6399 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6400 {
6401         return NULL;
6402 }
6403 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6404 static inline void update_runtime_enabled(struct rq *rq) {}
6405 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6406 #ifdef CONFIG_CGROUP_SCHED
6407 bool cfs_task_bw_constrained(struct task_struct *p)
6408 {
6409         return false;
6410 }
6411 #endif
6412 #endif /* CONFIG_CFS_BANDWIDTH */
6413
6414 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6415 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6416 #endif
6417
6418 /**************************************************
6419  * CFS operations on tasks:
6420  */
6421
6422 #ifdef CONFIG_SCHED_HRTICK
6423 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6424 {
6425         struct sched_entity *se = &p->se;
6426
6427         SCHED_WARN_ON(task_rq(p) != rq);
6428
6429         if (rq->cfs.h_nr_running > 1) {
6430                 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6431                 u64 slice = se->slice;
6432                 s64 delta = slice - ran;
6433
6434                 if (delta < 0) {
6435                         if (task_current(rq, p))
6436                                 resched_curr(rq);
6437                         return;
6438                 }
6439                 hrtick_start(rq, delta);
6440         }
6441 }
6442
6443 /*
6444  * called from enqueue/dequeue and updates the hrtick when the
6445  * current task is from our class and nr_running is low enough
6446  * to matter.
6447  */
6448 static void hrtick_update(struct rq *rq)
6449 {
6450         struct task_struct *curr = rq->curr;
6451
6452         if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6453                 return;
6454
6455         hrtick_start_fair(rq, curr);
6456 }
6457 #else /* !CONFIG_SCHED_HRTICK */
6458 static inline void
6459 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6460 {
6461 }
6462
6463 static inline void hrtick_update(struct rq *rq)
6464 {
6465 }
6466 #endif
6467
6468 #ifdef CONFIG_SMP
6469 static inline bool cpu_overutilized(int cpu)
6470 {
6471         unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6472         unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6473
6474         /* Return true only if the utilization doesn't fit CPU's capacity */
6475         return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6476 }
6477
6478 static inline void update_overutilized_status(struct rq *rq)
6479 {
6480         if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6481                 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6482                 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6483         }
6484 }
6485 #else
6486 static inline void update_overutilized_status(struct rq *rq) { }
6487 #endif
6488
6489 /* Runqueue only has SCHED_IDLE tasks enqueued */
6490 static int sched_idle_rq(struct rq *rq)
6491 {
6492         return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6493                         rq->nr_running);
6494 }
6495
6496 #ifdef CONFIG_SMP
6497 static int sched_idle_cpu(int cpu)
6498 {
6499         return sched_idle_rq(cpu_rq(cpu));
6500 }
6501 #endif
6502
6503 /*
6504  * The enqueue_task method is called before nr_running is
6505  * increased. Here we update the fair scheduling stats and
6506  * then put the task into the rbtree:
6507  */
6508 static void
6509 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6510 {
6511         struct cfs_rq *cfs_rq;
6512         struct sched_entity *se = &p->se;
6513         int idle_h_nr_running = task_has_idle_policy(p);
6514         int task_new = !(flags & ENQUEUE_WAKEUP);
6515
6516         /*
6517          * The code below (indirectly) updates schedutil which looks at
6518          * the cfs_rq utilization to select a frequency.
6519          * Let's add the task's estimated utilization to the cfs_rq's
6520          * estimated utilization, before we update schedutil.
6521          */
6522         util_est_enqueue(&rq->cfs, p);
6523
6524         /*
6525          * If in_iowait is set, the code below may not trigger any cpufreq
6526          * utilization updates, so do it here explicitly with the IOWAIT flag
6527          * passed.
6528          */
6529         if (p->in_iowait)
6530                 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6531
6532         for_each_sched_entity(se) {
6533                 if (se->on_rq)
6534                         break;
6535                 cfs_rq = cfs_rq_of(se);
6536                 enqueue_entity(cfs_rq, se, flags);
6537
6538                 cfs_rq->h_nr_running++;
6539                 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6540
6541                 if (cfs_rq_is_idle(cfs_rq))
6542                         idle_h_nr_running = 1;
6543
6544                 /* end evaluation on encountering a throttled cfs_rq */
6545                 if (cfs_rq_throttled(cfs_rq))
6546                         goto enqueue_throttle;
6547
6548                 flags = ENQUEUE_WAKEUP;
6549         }
6550
6551         for_each_sched_entity(se) {
6552                 cfs_rq = cfs_rq_of(se);
6553
6554                 update_load_avg(cfs_rq, se, UPDATE_TG);
6555                 se_update_runnable(se);
6556                 update_cfs_group(se);
6557
6558                 cfs_rq->h_nr_running++;
6559                 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6560
6561                 if (cfs_rq_is_idle(cfs_rq))
6562                         idle_h_nr_running = 1;
6563
6564                 /* end evaluation on encountering a throttled cfs_rq */
6565                 if (cfs_rq_throttled(cfs_rq))
6566                         goto enqueue_throttle;
6567         }
6568
6569         /* At this point se is NULL and we are at root level*/
6570         add_nr_running(rq, 1);
6571
6572         /*
6573          * Since new tasks are assigned an initial util_avg equal to
6574          * half of the spare capacity of their CPU, tiny tasks have the
6575          * ability to cross the overutilized threshold, which will
6576          * result in the load balancer ruining all the task placement
6577          * done by EAS. As a way to mitigate that effect, do not account
6578          * for the first enqueue operation of new tasks during the
6579          * overutilized flag detection.
6580          *
6581          * A better way of solving this problem would be to wait for
6582          * the PELT signals of tasks to converge before taking them
6583          * into account, but that is not straightforward to implement,
6584          * and the following generally works well enough in practice.
6585          */
6586         if (!task_new)
6587                 update_overutilized_status(rq);
6588
6589 enqueue_throttle:
6590         assert_list_leaf_cfs_rq(rq);
6591
6592         hrtick_update(rq);
6593 }
6594
6595 static void set_next_buddy(struct sched_entity *se);
6596
6597 /*
6598  * The dequeue_task method is called before nr_running is
6599  * decreased. We remove the task from the rbtree and
6600  * update the fair scheduling stats:
6601  */
6602 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6603 {
6604         struct cfs_rq *cfs_rq;
6605         struct sched_entity *se = &p->se;
6606         int task_sleep = flags & DEQUEUE_SLEEP;
6607         int idle_h_nr_running = task_has_idle_policy(p);
6608         bool was_sched_idle = sched_idle_rq(rq);
6609
6610         util_est_dequeue(&rq->cfs, p);
6611
6612         for_each_sched_entity(se) {
6613                 cfs_rq = cfs_rq_of(se);
6614                 dequeue_entity(cfs_rq, se, flags);
6615
6616                 cfs_rq->h_nr_running--;
6617                 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6618
6619                 if (cfs_rq_is_idle(cfs_rq))
6620                         idle_h_nr_running = 1;
6621
6622                 /* end evaluation on encountering a throttled cfs_rq */
6623                 if (cfs_rq_throttled(cfs_rq))
6624                         goto dequeue_throttle;
6625
6626                 /* Don't dequeue parent if it has other entities besides us */
6627                 if (cfs_rq->load.weight) {
6628                         /* Avoid re-evaluating load for this entity: */
6629                         se = parent_entity(se);
6630                         /*
6631                          * Bias pick_next to pick a task from this cfs_rq, as
6632                          * p is sleeping when it is within its sched_slice.
6633                          */
6634                         if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6635                                 set_next_buddy(se);
6636                         break;
6637                 }
6638                 flags |= DEQUEUE_SLEEP;
6639         }
6640
6641         for_each_sched_entity(se) {
6642                 cfs_rq = cfs_rq_of(se);
6643
6644                 update_load_avg(cfs_rq, se, UPDATE_TG);
6645                 se_update_runnable(se);
6646                 update_cfs_group(se);
6647
6648                 cfs_rq->h_nr_running--;
6649                 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6650
6651                 if (cfs_rq_is_idle(cfs_rq))
6652                         idle_h_nr_running = 1;
6653
6654                 /* end evaluation on encountering a throttled cfs_rq */
6655                 if (cfs_rq_throttled(cfs_rq))
6656                         goto dequeue_throttle;
6657
6658         }
6659
6660         /* At this point se is NULL and we are at root level*/
6661         sub_nr_running(rq, 1);
6662
6663         /* balance early to pull high priority tasks */
6664         if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6665                 rq->next_balance = jiffies;
6666
6667 dequeue_throttle:
6668         util_est_update(&rq->cfs, p, task_sleep);
6669         hrtick_update(rq);
6670 }
6671
6672 #ifdef CONFIG_SMP
6673
6674 /* Working cpumask for: load_balance, load_balance_newidle. */
6675 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6676 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6677 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6678
6679 #ifdef CONFIG_NO_HZ_COMMON
6680
6681 static struct {
6682         cpumask_var_t idle_cpus_mask;
6683         atomic_t nr_cpus;
6684         int has_blocked;                /* Idle CPUS has blocked load */
6685         int needs_update;               /* Newly idle CPUs need their next_balance collated */
6686         unsigned long next_balance;     /* in jiffy units */
6687         unsigned long next_blocked;     /* Next update of blocked load in jiffies */
6688 } nohz ____cacheline_aligned;
6689
6690 #endif /* CONFIG_NO_HZ_COMMON */
6691
6692 static unsigned long cpu_load(struct rq *rq)
6693 {
6694         return cfs_rq_load_avg(&rq->cfs);
6695 }
6696
6697 /*
6698  * cpu_load_without - compute CPU load without any contributions from *p
6699  * @cpu: the CPU which load is requested
6700  * @p: the task which load should be discounted
6701  *
6702  * The load of a CPU is defined by the load of tasks currently enqueued on that
6703  * CPU as well as tasks which are currently sleeping after an execution on that
6704  * CPU.
6705  *
6706  * This method returns the load of the specified CPU by discounting the load of
6707  * the specified task, whenever the task is currently contributing to the CPU
6708  * load.
6709  */
6710 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6711 {
6712         struct cfs_rq *cfs_rq;
6713         unsigned int load;
6714
6715         /* Task has no contribution or is new */
6716         if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6717                 return cpu_load(rq);
6718
6719         cfs_rq = &rq->cfs;
6720         load = READ_ONCE(cfs_rq->avg.load_avg);
6721
6722         /* Discount task's util from CPU's util */
6723         lsub_positive(&load, task_h_load(p));
6724
6725         return load;
6726 }
6727
6728 static unsigned long cpu_runnable(struct rq *rq)
6729 {
6730         return cfs_rq_runnable_avg(&rq->cfs);
6731 }
6732
6733 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6734 {
6735         struct cfs_rq *cfs_rq;
6736         unsigned int runnable;
6737
6738         /* Task has no contribution or is new */
6739         if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6740                 return cpu_runnable(rq);
6741
6742         cfs_rq = &rq->cfs;
6743         runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6744
6745         /* Discount task's runnable from CPU's runnable */
6746         lsub_positive(&runnable, p->se.avg.runnable_avg);
6747
6748         return runnable;
6749 }
6750
6751 static unsigned long capacity_of(int cpu)
6752 {
6753         return cpu_rq(cpu)->cpu_capacity;
6754 }
6755
6756 static void record_wakee(struct task_struct *p)
6757 {
6758         /*
6759          * Only decay a single time; tasks that have less then 1 wakeup per
6760          * jiffy will not have built up many flips.
6761          */
6762         if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6763                 current->wakee_flips >>= 1;
6764                 current->wakee_flip_decay_ts = jiffies;
6765         }
6766
6767         if (current->last_wakee != p) {
6768                 current->last_wakee = p;
6769                 current->wakee_flips++;
6770         }
6771 }
6772
6773 /*
6774  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6775  *
6776  * A waker of many should wake a different task than the one last awakened
6777  * at a frequency roughly N times higher than one of its wakees.
6778  *
6779  * In order to determine whether we should let the load spread vs consolidating
6780  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6781  * partner, and a factor of lls_size higher frequency in the other.
6782  *
6783  * With both conditions met, we can be relatively sure that the relationship is
6784  * non-monogamous, with partner count exceeding socket size.
6785  *
6786  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6787  * whatever is irrelevant, spread criteria is apparent partner count exceeds
6788  * socket size.
6789  */
6790 static int wake_wide(struct task_struct *p)
6791 {
6792         unsigned int master = current->wakee_flips;
6793         unsigned int slave = p->wakee_flips;
6794         int factor = __this_cpu_read(sd_llc_size);
6795
6796         if (master < slave)
6797                 swap(master, slave);
6798         if (slave < factor || master < slave * factor)
6799                 return 0;
6800         return 1;
6801 }
6802
6803 /*
6804  * The purpose of wake_affine() is to quickly determine on which CPU we can run
6805  * soonest. For the purpose of speed we only consider the waking and previous
6806  * CPU.
6807  *
6808  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6809  *                      cache-affine and is (or will be) idle.
6810  *
6811  * wake_affine_weight() - considers the weight to reflect the average
6812  *                        scheduling latency of the CPUs. This seems to work
6813  *                        for the overloaded case.
6814  */
6815 static int
6816 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6817 {
6818         /*
6819          * If this_cpu is idle, it implies the wakeup is from interrupt
6820          * context. Only allow the move if cache is shared. Otherwise an
6821          * interrupt intensive workload could force all tasks onto one
6822          * node depending on the IO topology or IRQ affinity settings.
6823          *
6824          * If the prev_cpu is idle and cache affine then avoid a migration.
6825          * There is no guarantee that the cache hot data from an interrupt
6826          * is more important than cache hot data on the prev_cpu and from
6827          * a cpufreq perspective, it's better to have higher utilisation
6828          * on one CPU.
6829          */
6830         if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6831                 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6832
6833         if (sync && cpu_rq(this_cpu)->nr_running == 1)
6834                 return this_cpu;
6835
6836         if (available_idle_cpu(prev_cpu))
6837                 return prev_cpu;
6838
6839         return nr_cpumask_bits;
6840 }
6841
6842 static int
6843 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6844                    int this_cpu, int prev_cpu, int sync)
6845 {
6846         s64 this_eff_load, prev_eff_load;
6847         unsigned long task_load;
6848
6849         this_eff_load = cpu_load(cpu_rq(this_cpu));
6850
6851         if (sync) {
6852                 unsigned long current_load = task_h_load(current);
6853
6854                 if (current_load > this_eff_load)
6855                         return this_cpu;
6856
6857                 this_eff_load -= current_load;
6858         }
6859
6860         task_load = task_h_load(p);
6861
6862         this_eff_load += task_load;
6863         if (sched_feat(WA_BIAS))
6864                 this_eff_load *= 100;
6865         this_eff_load *= capacity_of(prev_cpu);
6866
6867         prev_eff_load = cpu_load(cpu_rq(prev_cpu));
6868         prev_eff_load -= task_load;
6869         if (sched_feat(WA_BIAS))
6870                 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
6871         prev_eff_load *= capacity_of(this_cpu);
6872
6873         /*
6874          * If sync, adjust the weight of prev_eff_load such that if
6875          * prev_eff == this_eff that select_idle_sibling() will consider
6876          * stacking the wakee on top of the waker if no other CPU is
6877          * idle.
6878          */
6879         if (sync)
6880                 prev_eff_load += 1;
6881
6882         return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6883 }
6884
6885 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6886                        int this_cpu, int prev_cpu, int sync)
6887 {
6888         int target = nr_cpumask_bits;
6889
6890         if (sched_feat(WA_IDLE))
6891                 target = wake_affine_idle(this_cpu, prev_cpu, sync);
6892
6893         if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6894                 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6895
6896         schedstat_inc(p->stats.nr_wakeups_affine_attempts);
6897         if (target != this_cpu)
6898                 return prev_cpu;
6899
6900         schedstat_inc(sd->ttwu_move_affine);
6901         schedstat_inc(p->stats.nr_wakeups_affine);
6902         return target;
6903 }
6904
6905 static struct sched_group *
6906 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6907
6908 /*
6909  * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6910  */
6911 static int
6912 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6913 {
6914         unsigned long load, min_load = ULONG_MAX;
6915         unsigned int min_exit_latency = UINT_MAX;
6916         u64 latest_idle_timestamp = 0;
6917         int least_loaded_cpu = this_cpu;
6918         int shallowest_idle_cpu = -1;
6919         int i;
6920
6921         /* Check if we have any choice: */
6922         if (group->group_weight == 1)
6923                 return cpumask_first(sched_group_span(group));
6924
6925         /* Traverse only the allowed CPUs */
6926         for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6927                 struct rq *rq = cpu_rq(i);
6928
6929                 if (!sched_core_cookie_match(rq, p))
6930                         continue;
6931
6932                 if (sched_idle_cpu(i))
6933                         return i;
6934
6935                 if (available_idle_cpu(i)) {
6936                         struct cpuidle_state *idle = idle_get_state(rq);
6937                         if (idle && idle->exit_latency < min_exit_latency) {
6938                                 /*
6939                                  * We give priority to a CPU whose idle state
6940                                  * has the smallest exit latency irrespective
6941                                  * of any idle timestamp.
6942                                  */
6943                                 min_exit_latency = idle->exit_latency;
6944                                 latest_idle_timestamp = rq->idle_stamp;
6945                                 shallowest_idle_cpu = i;
6946                         } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6947                                    rq->idle_stamp > latest_idle_timestamp) {
6948                                 /*
6949                                  * If equal or no active idle state, then
6950                                  * the most recently idled CPU might have
6951                                  * a warmer cache.
6952                                  */
6953                                 latest_idle_timestamp = rq->idle_stamp;
6954                                 shallowest_idle_cpu = i;
6955                         }
6956                 } else if (shallowest_idle_cpu == -1) {
6957                         load = cpu_load(cpu_rq(i));
6958                         if (load < min_load) {
6959                                 min_load = load;
6960                                 least_loaded_cpu = i;
6961                         }
6962                 }
6963         }
6964
6965         return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6966 }
6967
6968 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6969                                   int cpu, int prev_cpu, int sd_flag)
6970 {
6971         int new_cpu = cpu;
6972
6973         if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6974                 return prev_cpu;
6975
6976         /*
6977          * We need task's util for cpu_util_without, sync it up to
6978          * prev_cpu's last_update_time.
6979          */
6980         if (!(sd_flag & SD_BALANCE_FORK))
6981                 sync_entity_load_avg(&p->se);
6982
6983         while (sd) {
6984                 struct sched_group *group;
6985                 struct sched_domain *tmp;
6986                 int weight;
6987
6988                 if (!(sd->flags & sd_flag)) {
6989                         sd = sd->child;
6990                         continue;
6991                 }
6992
6993                 group = find_idlest_group(sd, p, cpu);
6994                 if (!group) {
6995                         sd = sd->child;
6996                         continue;
6997                 }
6998
6999                 new_cpu = find_idlest_group_cpu(group, p, cpu);
7000                 if (new_cpu == cpu) {
7001                         /* Now try balancing at a lower domain level of 'cpu': */
7002                         sd = sd->child;
7003                         continue;
7004                 }
7005
7006                 /* Now try balancing at a lower domain level of 'new_cpu': */
7007                 cpu = new_cpu;
7008                 weight = sd->span_weight;
7009                 sd = NULL;
7010                 for_each_domain(cpu, tmp) {
7011                         if (weight <= tmp->span_weight)
7012                                 break;
7013                         if (tmp->flags & sd_flag)
7014                                 sd = tmp;
7015                 }
7016         }
7017
7018         return new_cpu;
7019 }
7020
7021 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7022 {
7023         if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7024             sched_cpu_cookie_match(cpu_rq(cpu), p))
7025                 return cpu;
7026
7027         return -1;
7028 }
7029
7030 #ifdef CONFIG_SCHED_SMT
7031 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7032 EXPORT_SYMBOL_GPL(sched_smt_present);
7033
7034 static inline void set_idle_cores(int cpu, int val)
7035 {
7036         struct sched_domain_shared *sds;
7037
7038         sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7039         if (sds)
7040                 WRITE_ONCE(sds->has_idle_cores, val);
7041 }
7042
7043 static inline bool test_idle_cores(int cpu)
7044 {
7045         struct sched_domain_shared *sds;
7046
7047         sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7048         if (sds)
7049                 return READ_ONCE(sds->has_idle_cores);
7050
7051         return false;
7052 }
7053
7054 /*
7055  * Scans the local SMT mask to see if the entire core is idle, and records this
7056  * information in sd_llc_shared->has_idle_cores.
7057  *
7058  * Since SMT siblings share all cache levels, inspecting this limited remote
7059  * state should be fairly cheap.
7060  */
7061 void __update_idle_core(struct rq *rq)
7062 {
7063         int core = cpu_of(rq);
7064         int cpu;
7065
7066         rcu_read_lock();
7067         if (test_idle_cores(core))
7068                 goto unlock;
7069
7070         for_each_cpu(cpu, cpu_smt_mask(core)) {
7071                 if (cpu == core)
7072                         continue;
7073
7074                 if (!available_idle_cpu(cpu))
7075                         goto unlock;
7076         }
7077
7078         set_idle_cores(core, 1);
7079 unlock:
7080         rcu_read_unlock();
7081 }
7082
7083 /*
7084  * Scan the entire LLC domain for idle cores; this dynamically switches off if
7085  * there are no idle cores left in the system; tracked through
7086  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7087  */
7088 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7089 {
7090         bool idle = true;
7091         int cpu;
7092
7093         for_each_cpu(cpu, cpu_smt_mask(core)) {
7094                 if (!available_idle_cpu(cpu)) {
7095                         idle = false;
7096                         if (*idle_cpu == -1) {
7097                                 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
7098                                         *idle_cpu = cpu;
7099                                         break;
7100                                 }
7101                                 continue;
7102                         }
7103                         break;
7104                 }
7105                 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
7106                         *idle_cpu = cpu;
7107         }
7108
7109         if (idle)
7110                 return core;
7111
7112         cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7113         return -1;
7114 }
7115
7116 /*
7117  * Scan the local SMT mask for idle CPUs.
7118  */
7119 static int select_idle_smt(struct task_struct *p, int target)
7120 {
7121         int cpu;
7122
7123         for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7124                 if (cpu == target)
7125                         continue;
7126                 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7127                         return cpu;
7128         }
7129
7130         return -1;
7131 }
7132
7133 #else /* CONFIG_SCHED_SMT */
7134
7135 static inline void set_idle_cores(int cpu, int val)
7136 {
7137 }
7138
7139 static inline bool test_idle_cores(int cpu)
7140 {
7141         return false;
7142 }
7143
7144 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7145 {
7146         return __select_idle_cpu(core, p);
7147 }
7148
7149 static inline int select_idle_smt(struct task_struct *p, int target)
7150 {
7151         return -1;
7152 }
7153
7154 #endif /* CONFIG_SCHED_SMT */
7155
7156 /*
7157  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7158  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7159  * average idle time for this rq (as found in rq->avg_idle).
7160  */
7161 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7162 {
7163         struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7164         int i, cpu, idle_cpu = -1, nr = INT_MAX;
7165         struct sched_domain_shared *sd_share;
7166         struct rq *this_rq = this_rq();
7167         int this = smp_processor_id();
7168         struct sched_domain *this_sd = NULL;
7169         u64 time = 0;
7170
7171         cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7172
7173         if (sched_feat(SIS_PROP) && !has_idle_core) {
7174                 u64 avg_cost, avg_idle, span_avg;
7175                 unsigned long now = jiffies;
7176
7177                 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7178                 if (!this_sd)
7179                         return -1;
7180
7181                 /*
7182                  * If we're busy, the assumption that the last idle period
7183                  * predicts the future is flawed; age away the remaining
7184                  * predicted idle time.
7185                  */
7186                 if (unlikely(this_rq->wake_stamp < now)) {
7187                         while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7188                                 this_rq->wake_stamp++;
7189                                 this_rq->wake_avg_idle >>= 1;
7190                         }
7191                 }
7192
7193                 avg_idle = this_rq->wake_avg_idle;
7194                 avg_cost = this_sd->avg_scan_cost + 1;
7195
7196                 span_avg = sd->span_weight * avg_idle;
7197                 if (span_avg > 4*avg_cost)
7198                         nr = div_u64(span_avg, avg_cost);
7199                 else
7200                         nr = 4;
7201
7202                 time = cpu_clock(this);
7203         }
7204
7205         if (sched_feat(SIS_UTIL)) {
7206                 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7207                 if (sd_share) {
7208                         /* because !--nr is the condition to stop scan */
7209                         nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7210                         /* overloaded LLC is unlikely to have idle cpu/core */
7211                         if (nr == 1)
7212                                 return -1;
7213                 }
7214         }
7215
7216         for_each_cpu_wrap(cpu, cpus, target + 1) {
7217                 if (has_idle_core) {
7218                         i = select_idle_core(p, cpu, cpus, &idle_cpu);
7219                         if ((unsigned int)i < nr_cpumask_bits)
7220                                 return i;
7221
7222                 } else {
7223                         if (!--nr)
7224                                 return -1;
7225                         idle_cpu = __select_idle_cpu(cpu, p);
7226                         if ((unsigned int)idle_cpu < nr_cpumask_bits)
7227                                 break;
7228                 }
7229         }
7230
7231         if (has_idle_core)
7232                 set_idle_cores(target, false);
7233
7234         if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7235                 time = cpu_clock(this) - time;
7236
7237                 /*
7238                  * Account for the scan cost of wakeups against the average
7239                  * idle time.
7240                  */
7241                 this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7242
7243                 update_avg(&this_sd->avg_scan_cost, time);
7244         }
7245
7246         return idle_cpu;
7247 }
7248
7249 /*
7250  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7251  * the task fits. If no CPU is big enough, but there are idle ones, try to
7252  * maximize capacity.
7253  */
7254 static int
7255 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7256 {
7257         unsigned long task_util, util_min, util_max, best_cap = 0;
7258         int fits, best_fits = 0;
7259         int cpu, best_cpu = -1;
7260         struct cpumask *cpus;
7261
7262         cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7263         cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7264
7265         task_util = task_util_est(p);
7266         util_min = uclamp_eff_value(p, UCLAMP_MIN);
7267         util_max = uclamp_eff_value(p, UCLAMP_MAX);
7268
7269         for_each_cpu_wrap(cpu, cpus, target) {
7270                 unsigned long cpu_cap = capacity_of(cpu);
7271
7272                 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7273                         continue;
7274
7275                 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7276
7277                 /* This CPU fits with all requirements */
7278                 if (fits > 0)
7279                         return cpu;
7280                 /*
7281                  * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7282                  * Look for the CPU with best capacity.
7283                  */
7284                 else if (fits < 0)
7285                         cpu_cap = capacity_orig_of(cpu) - thermal_load_avg(cpu_rq(cpu));
7286
7287                 /*
7288                  * First, select CPU which fits better (-1 being better than 0).
7289                  * Then, select the one with best capacity at same level.
7290                  */
7291                 if ((fits < best_fits) ||
7292                     ((fits == best_fits) && (cpu_cap > best_cap))) {
7293                         best_cap = cpu_cap;
7294                         best_cpu = cpu;
7295                         best_fits = fits;
7296                 }
7297         }
7298
7299         return best_cpu;
7300 }
7301
7302 static inline bool asym_fits_cpu(unsigned long util,
7303                                  unsigned long util_min,
7304                                  unsigned long util_max,
7305                                  int cpu)
7306 {
7307         if (sched_asym_cpucap_active())
7308                 /*
7309                  * Return true only if the cpu fully fits the task requirements
7310                  * which include the utilization and the performance hints.
7311                  */
7312                 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7313
7314         return true;
7315 }
7316
7317 /*
7318  * Try and locate an idle core/thread in the LLC cache domain.
7319  */
7320 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7321 {
7322         bool has_idle_core = false;
7323         struct sched_domain *sd;
7324         unsigned long task_util, util_min, util_max;
7325         int i, recent_used_cpu;
7326
7327         /*
7328          * On asymmetric system, update task utilization because we will check
7329          * that the task fits with cpu's capacity.
7330          */
7331         if (sched_asym_cpucap_active()) {
7332                 sync_entity_load_avg(&p->se);
7333                 task_util = task_util_est(p);
7334                 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7335                 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7336         }
7337
7338         /*
7339          * per-cpu select_rq_mask usage
7340          */
7341         lockdep_assert_irqs_disabled();
7342
7343         if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7344             asym_fits_cpu(task_util, util_min, util_max, target))
7345                 return target;
7346
7347         /*
7348          * If the previous CPU is cache affine and idle, don't be stupid:
7349          */
7350         if (prev != target && cpus_share_cache(prev, target) &&
7351             (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7352             asym_fits_cpu(task_util, util_min, util_max, prev))
7353                 return prev;
7354
7355         /*
7356          * Allow a per-cpu kthread to stack with the wakee if the
7357          * kworker thread and the tasks previous CPUs are the same.
7358          * The assumption is that the wakee queued work for the
7359          * per-cpu kthread that is now complete and the wakeup is
7360          * essentially a sync wakeup. An obvious example of this
7361          * pattern is IO completions.
7362          */
7363         if (is_per_cpu_kthread(current) &&
7364             in_task() &&
7365             prev == smp_processor_id() &&
7366             this_rq()->nr_running <= 1 &&
7367             asym_fits_cpu(task_util, util_min, util_max, prev)) {
7368                 return prev;
7369         }
7370
7371         /* Check a recently used CPU as a potential idle candidate: */
7372         recent_used_cpu = p->recent_used_cpu;
7373         p->recent_used_cpu = prev;
7374         if (recent_used_cpu != prev &&
7375             recent_used_cpu != target &&
7376             cpus_share_cache(recent_used_cpu, target) &&
7377             (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7378             cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7379             asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7380                 return recent_used_cpu;
7381         }
7382
7383         /*
7384          * For asymmetric CPU capacity systems, our domain of interest is
7385          * sd_asym_cpucapacity rather than sd_llc.
7386          */
7387         if (sched_asym_cpucap_active()) {
7388                 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7389                 /*
7390                  * On an asymmetric CPU capacity system where an exclusive
7391                  * cpuset defines a symmetric island (i.e. one unique
7392                  * capacity_orig value through the cpuset), the key will be set
7393                  * but the CPUs within that cpuset will not have a domain with
7394                  * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7395                  * capacity path.
7396                  */
7397                 if (sd) {
7398                         i = select_idle_capacity(p, sd, target);
7399                         return ((unsigned)i < nr_cpumask_bits) ? i : target;
7400                 }
7401         }
7402
7403         sd = rcu_dereference(per_cpu(sd_llc, target));
7404         if (!sd)
7405                 return target;
7406
7407         if (sched_smt_active()) {
7408                 has_idle_core = test_idle_cores(target);
7409
7410                 if (!has_idle_core && cpus_share_cache(prev, target)) {
7411                         i = select_idle_smt(p, prev);
7412                         if ((unsigned int)i < nr_cpumask_bits)
7413                                 return i;
7414                 }
7415         }
7416
7417         i = select_idle_cpu(p, sd, has_idle_core, target);
7418         if ((unsigned)i < nr_cpumask_bits)
7419                 return i;
7420
7421         return target;
7422 }
7423
7424 /**
7425  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7426  * @cpu: the CPU to get the utilization for
7427  * @p: task for which the CPU utilization should be predicted or NULL
7428  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7429  * @boost: 1 to enable boosting, otherwise 0
7430  *
7431  * The unit of the return value must be the same as the one of CPU capacity
7432  * so that CPU utilization can be compared with CPU capacity.
7433  *
7434  * CPU utilization is the sum of running time of runnable tasks plus the
7435  * recent utilization of currently non-runnable tasks on that CPU.
7436  * It represents the amount of CPU capacity currently used by CFS tasks in
7437  * the range [0..max CPU capacity] with max CPU capacity being the CPU
7438  * capacity at f_max.
7439  *
7440  * The estimated CPU utilization is defined as the maximum between CPU
7441  * utilization and sum of the estimated utilization of the currently
7442  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7443  * previously-executed tasks, which helps better deduce how busy a CPU will
7444  * be when a long-sleeping task wakes up. The contribution to CPU utilization
7445  * of such a task would be significantly decayed at this point of time.
7446  *
7447  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7448  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7449  * utilization. Boosting is implemented in cpu_util() so that internal
7450  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7451  * latter via cpu_util_cfs_boost().
7452  *
7453  * CPU utilization can be higher than the current CPU capacity
7454  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7455  * of rounding errors as well as task migrations or wakeups of new tasks.
7456  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7457  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7458  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7459  * capacity. CPU utilization is allowed to overshoot current CPU capacity
7460  * though since this is useful for predicting the CPU capacity required
7461  * after task migrations (scheduler-driven DVFS).
7462  *
7463  * Return: (Boosted) (estimated) utilization for the specified CPU.
7464  */
7465 static unsigned long
7466 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7467 {
7468         struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7469         unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7470         unsigned long runnable;
7471
7472         if (boost) {
7473                 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7474                 util = max(util, runnable);
7475         }
7476
7477         /*
7478          * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7479          * contribution. If @p migrates from another CPU to @cpu add its
7480          * contribution. In all the other cases @cpu is not impacted by the
7481          * migration so its util_avg is already correct.
7482          */
7483         if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7484                 lsub_positive(&util, task_util(p));
7485         else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7486                 util += task_util(p);
7487
7488         if (sched_feat(UTIL_EST)) {
7489                 unsigned long util_est;
7490
7491                 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7492
7493                 /*
7494                  * During wake-up @p isn't enqueued yet and doesn't contribute
7495                  * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7496                  * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7497                  * has been enqueued.
7498                  *
7499                  * During exec (@dst_cpu = -1) @p is enqueued and does
7500                  * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7501                  * Remove it to "simulate" cpu_util without @p's contribution.
7502                  *
7503                  * Despite the task_on_rq_queued(@p) check there is still a
7504                  * small window for a possible race when an exec
7505                  * select_task_rq_fair() races with LB's detach_task().
7506                  *
7507                  *   detach_task()
7508                  *     deactivate_task()
7509                  *       p->on_rq = TASK_ON_RQ_MIGRATING;
7510                  *       -------------------------------- A
7511                  *       dequeue_task()                    \
7512                  *         dequeue_task_fair()              + Race Time
7513                  *           util_est_dequeue()            /
7514                  *       -------------------------------- B
7515                  *
7516                  * The additional check "current == p" is required to further
7517                  * reduce the race window.
7518                  */
7519                 if (dst_cpu == cpu)
7520                         util_est += _task_util_est(p);
7521                 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7522                         lsub_positive(&util_est, _task_util_est(p));
7523
7524                 util = max(util, util_est);
7525         }
7526
7527         return min(util, capacity_orig_of(cpu));
7528 }
7529
7530 unsigned long cpu_util_cfs(int cpu)
7531 {
7532         return cpu_util(cpu, NULL, -1, 0);
7533 }
7534
7535 unsigned long cpu_util_cfs_boost(int cpu)
7536 {
7537         return cpu_util(cpu, NULL, -1, 1);
7538 }
7539
7540 /*
7541  * cpu_util_without: compute cpu utilization without any contributions from *p
7542  * @cpu: the CPU which utilization is requested
7543  * @p: the task which utilization should be discounted
7544  *
7545  * The utilization of a CPU is defined by the utilization of tasks currently
7546  * enqueued on that CPU as well as tasks which are currently sleeping after an
7547  * execution on that CPU.
7548  *
7549  * This method returns the utilization of the specified CPU by discounting the
7550  * utilization of the specified task, whenever the task is currently
7551  * contributing to the CPU utilization.
7552  */
7553 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7554 {
7555         /* Task has no contribution or is new */
7556         if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7557                 p = NULL;
7558
7559         return cpu_util(cpu, p, -1, 0);
7560 }
7561
7562 /*
7563  * energy_env - Utilization landscape for energy estimation.
7564  * @task_busy_time: Utilization contribution by the task for which we test the
7565  *                  placement. Given by eenv_task_busy_time().
7566  * @pd_busy_time:   Utilization of the whole perf domain without the task
7567  *                  contribution. Given by eenv_pd_busy_time().
7568  * @cpu_cap:        Maximum CPU capacity for the perf domain.
7569  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7570  */
7571 struct energy_env {
7572         unsigned long task_busy_time;
7573         unsigned long pd_busy_time;
7574         unsigned long cpu_cap;
7575         unsigned long pd_cap;
7576 };
7577
7578 /*
7579  * Compute the task busy time for compute_energy(). This time cannot be
7580  * injected directly into effective_cpu_util() because of the IRQ scaling.
7581  * The latter only makes sense with the most recent CPUs where the task has
7582  * run.
7583  */
7584 static inline void eenv_task_busy_time(struct energy_env *eenv,
7585                                        struct task_struct *p, int prev_cpu)
7586 {
7587         unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7588         unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7589
7590         if (unlikely(irq >= max_cap))
7591                 busy_time = max_cap;
7592         else
7593                 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7594
7595         eenv->task_busy_time = busy_time;
7596 }
7597
7598 /*
7599  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7600  * utilization for each @pd_cpus, it however doesn't take into account
7601  * clamping since the ratio (utilization / cpu_capacity) is already enough to
7602  * scale the EM reported power consumption at the (eventually clamped)
7603  * cpu_capacity.
7604  *
7605  * The contribution of the task @p for which we want to estimate the
7606  * energy cost is removed (by cpu_util()) and must be calculated
7607  * separately (see eenv_task_busy_time). This ensures:
7608  *
7609  *   - A stable PD utilization, no matter which CPU of that PD we want to place
7610  *     the task on.
7611  *
7612  *   - A fair comparison between CPUs as the task contribution (task_util())
7613  *     will always be the same no matter which CPU utilization we rely on
7614  *     (util_avg or util_est).
7615  *
7616  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7617  * exceed @eenv->pd_cap.
7618  */
7619 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7620                                      struct cpumask *pd_cpus,
7621                                      struct task_struct *p)
7622 {
7623         unsigned long busy_time = 0;
7624         int cpu;
7625
7626         for_each_cpu(cpu, pd_cpus) {
7627                 unsigned long util = cpu_util(cpu, p, -1, 0);
7628
7629                 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7630         }
7631
7632         eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7633 }
7634
7635 /*
7636  * Compute the maximum utilization for compute_energy() when the task @p
7637  * is placed on the cpu @dst_cpu.
7638  *
7639  * Returns the maximum utilization among @eenv->cpus. This utilization can't
7640  * exceed @eenv->cpu_cap.
7641  */
7642 static inline unsigned long
7643 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7644                  struct task_struct *p, int dst_cpu)
7645 {
7646         unsigned long max_util = 0;
7647         int cpu;
7648
7649         for_each_cpu(cpu, pd_cpus) {
7650                 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7651                 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7652                 unsigned long eff_util;
7653
7654                 /*
7655                  * Performance domain frequency: utilization clamping
7656                  * must be considered since it affects the selection
7657                  * of the performance domain frequency.
7658                  * NOTE: in case RT tasks are running, by default the
7659                  * FREQUENCY_UTIL's utilization can be max OPP.
7660                  */
7661                 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7662                 max_util = max(max_util, eff_util);
7663         }
7664
7665         return min(max_util, eenv->cpu_cap);
7666 }
7667
7668 /*
7669  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7670  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7671  * contribution is ignored.
7672  */
7673 static inline unsigned long
7674 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7675                struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7676 {
7677         unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7678         unsigned long busy_time = eenv->pd_busy_time;
7679
7680         if (dst_cpu >= 0)
7681                 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7682
7683         return em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7684 }
7685
7686 /*
7687  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7688  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7689  * spare capacity in each performance domain and uses it as a potential
7690  * candidate to execute the task. Then, it uses the Energy Model to figure
7691  * out which of the CPU candidates is the most energy-efficient.
7692  *
7693  * The rationale for this heuristic is as follows. In a performance domain,
7694  * all the most energy efficient CPU candidates (according to the Energy
7695  * Model) are those for which we'll request a low frequency. When there are
7696  * several CPUs for which the frequency request will be the same, we don't
7697  * have enough data to break the tie between them, because the Energy Model
7698  * only includes active power costs. With this model, if we assume that
7699  * frequency requests follow utilization (e.g. using schedutil), the CPU with
7700  * the maximum spare capacity in a performance domain is guaranteed to be among
7701  * the best candidates of the performance domain.
7702  *
7703  * In practice, it could be preferable from an energy standpoint to pack
7704  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7705  * but that could also hurt our chances to go cluster idle, and we have no
7706  * ways to tell with the current Energy Model if this is actually a good
7707  * idea or not. So, find_energy_efficient_cpu() basically favors
7708  * cluster-packing, and spreading inside a cluster. That should at least be
7709  * a good thing for latency, and this is consistent with the idea that most
7710  * of the energy savings of EAS come from the asymmetry of the system, and
7711  * not so much from breaking the tie between identical CPUs. That's also the
7712  * reason why EAS is enabled in the topology code only for systems where
7713  * SD_ASYM_CPUCAPACITY is set.
7714  *
7715  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7716  * they don't have any useful utilization data yet and it's not possible to
7717  * forecast their impact on energy consumption. Consequently, they will be
7718  * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7719  * to be energy-inefficient in some use-cases. The alternative would be to
7720  * bias new tasks towards specific types of CPUs first, or to try to infer
7721  * their util_avg from the parent task, but those heuristics could hurt
7722  * other use-cases too. So, until someone finds a better way to solve this,
7723  * let's keep things simple by re-using the existing slow path.
7724  */
7725 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7726 {
7727         struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7728         unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7729         unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7730         unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7731         struct root_domain *rd = this_rq()->rd;
7732         int cpu, best_energy_cpu, target = -1;
7733         int prev_fits = -1, best_fits = -1;
7734         unsigned long best_thermal_cap = 0;
7735         unsigned long prev_thermal_cap = 0;
7736         struct sched_domain *sd;
7737         struct perf_domain *pd;
7738         struct energy_env eenv;
7739
7740         rcu_read_lock();
7741         pd = rcu_dereference(rd->pd);
7742         if (!pd || READ_ONCE(rd->overutilized))
7743                 goto unlock;
7744
7745         /*
7746          * Energy-aware wake-up happens on the lowest sched_domain starting
7747          * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7748          */
7749         sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7750         while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7751                 sd = sd->parent;
7752         if (!sd)
7753                 goto unlock;
7754
7755         target = prev_cpu;
7756
7757         sync_entity_load_avg(&p->se);
7758         if (!uclamp_task_util(p, p_util_min, p_util_max))
7759                 goto unlock;
7760
7761         eenv_task_busy_time(&eenv, p, prev_cpu);
7762
7763         for (; pd; pd = pd->next) {
7764                 unsigned long util_min = p_util_min, util_max = p_util_max;
7765                 unsigned long cpu_cap, cpu_thermal_cap, util;
7766                 unsigned long cur_delta, max_spare_cap = 0;
7767                 unsigned long rq_util_min, rq_util_max;
7768                 unsigned long prev_spare_cap = 0;
7769                 int max_spare_cap_cpu = -1;
7770                 unsigned long base_energy;
7771                 int fits, max_fits = -1;
7772
7773                 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7774
7775                 if (cpumask_empty(cpus))
7776                         continue;
7777
7778                 /* Account thermal pressure for the energy estimation */
7779                 cpu = cpumask_first(cpus);
7780                 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7781                 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7782
7783                 eenv.cpu_cap = cpu_thermal_cap;
7784                 eenv.pd_cap = 0;
7785
7786                 for_each_cpu(cpu, cpus) {
7787                         struct rq *rq = cpu_rq(cpu);
7788
7789                         eenv.pd_cap += cpu_thermal_cap;
7790
7791                         if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7792                                 continue;
7793
7794                         if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7795                                 continue;
7796
7797                         util = cpu_util(cpu, p, cpu, 0);
7798                         cpu_cap = capacity_of(cpu);
7799
7800                         /*
7801                          * Skip CPUs that cannot satisfy the capacity request.
7802                          * IOW, placing the task there would make the CPU
7803                          * overutilized. Take uclamp into account to see how
7804                          * much capacity we can get out of the CPU; this is
7805                          * aligned with sched_cpu_util().
7806                          */
7807                         if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7808                                 /*
7809                                  * Open code uclamp_rq_util_with() except for
7810                                  * the clamp() part. Ie: apply max aggregation
7811                                  * only. util_fits_cpu() logic requires to
7812                                  * operate on non clamped util but must use the
7813                                  * max-aggregated uclamp_{min, max}.
7814                                  */
7815                                 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7816                                 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7817
7818                                 util_min = max(rq_util_min, p_util_min);
7819                                 util_max = max(rq_util_max, p_util_max);
7820                         }
7821
7822                         fits = util_fits_cpu(util, util_min, util_max, cpu);
7823                         if (!fits)
7824                                 continue;
7825
7826                         lsub_positive(&cpu_cap, util);
7827
7828                         if (cpu == prev_cpu) {
7829                                 /* Always use prev_cpu as a candidate. */
7830                                 prev_spare_cap = cpu_cap;
7831                                 prev_fits = fits;
7832                         } else if ((fits > max_fits) ||
7833                                    ((fits == max_fits) && (cpu_cap > max_spare_cap))) {
7834                                 /*
7835                                  * Find the CPU with the maximum spare capacity
7836                                  * among the remaining CPUs in the performance
7837                                  * domain.
7838                                  */
7839                                 max_spare_cap = cpu_cap;
7840                                 max_spare_cap_cpu = cpu;
7841                                 max_fits = fits;
7842                         }
7843                 }
7844
7845                 if (max_spare_cap_cpu < 0 && prev_spare_cap == 0)
7846                         continue;
7847
7848                 eenv_pd_busy_time(&eenv, cpus, p);
7849                 /* Compute the 'base' energy of the pd, without @p */
7850                 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
7851
7852                 /* Evaluate the energy impact of using prev_cpu. */
7853                 if (prev_spare_cap > 0) {
7854                         prev_delta = compute_energy(&eenv, pd, cpus, p,
7855                                                     prev_cpu);
7856                         /* CPU utilization has changed */
7857                         if (prev_delta < base_energy)
7858                                 goto unlock;
7859                         prev_delta -= base_energy;
7860                         prev_thermal_cap = cpu_thermal_cap;
7861                         best_delta = min(best_delta, prev_delta);
7862                 }
7863
7864                 /* Evaluate the energy impact of using max_spare_cap_cpu. */
7865                 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
7866                         /* Current best energy cpu fits better */
7867                         if (max_fits < best_fits)
7868                                 continue;
7869
7870                         /*
7871                          * Both don't fit performance hint (i.e. uclamp_min)
7872                          * but best energy cpu has better capacity.
7873                          */
7874                         if ((max_fits < 0) &&
7875                             (cpu_thermal_cap <= best_thermal_cap))
7876                                 continue;
7877
7878                         cur_delta = compute_energy(&eenv, pd, cpus, p,
7879                                                    max_spare_cap_cpu);
7880                         /* CPU utilization has changed */
7881                         if (cur_delta < base_energy)
7882                                 goto unlock;
7883                         cur_delta -= base_energy;
7884
7885                         /*
7886                          * Both fit for the task but best energy cpu has lower
7887                          * energy impact.
7888                          */
7889                         if ((max_fits > 0) && (best_fits > 0) &&
7890                             (cur_delta >= best_delta))
7891                                 continue;
7892
7893                         best_delta = cur_delta;
7894                         best_energy_cpu = max_spare_cap_cpu;
7895                         best_fits = max_fits;
7896                         best_thermal_cap = cpu_thermal_cap;
7897                 }
7898         }
7899         rcu_read_unlock();
7900
7901         if ((best_fits > prev_fits) ||
7902             ((best_fits > 0) && (best_delta < prev_delta)) ||
7903             ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
7904                 target = best_energy_cpu;
7905
7906         return target;
7907
7908 unlock:
7909         rcu_read_unlock();
7910
7911         return target;
7912 }
7913
7914 /*
7915  * select_task_rq_fair: Select target runqueue for the waking task in domains
7916  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
7917  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7918  *
7919  * Balances load by selecting the idlest CPU in the idlest group, or under
7920  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
7921  *
7922  * Returns the target CPU number.
7923  */
7924 static int
7925 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
7926 {
7927         int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
7928         struct sched_domain *tmp, *sd = NULL;
7929         int cpu = smp_processor_id();
7930         int new_cpu = prev_cpu;
7931         int want_affine = 0;
7932         /* SD_flags and WF_flags share the first nibble */
7933         int sd_flag = wake_flags & 0xF;
7934
7935         /*
7936          * required for stable ->cpus_allowed
7937          */
7938         lockdep_assert_held(&p->pi_lock);
7939         if (wake_flags & WF_TTWU) {
7940                 record_wakee(p);
7941
7942                 if ((wake_flags & WF_CURRENT_CPU) &&
7943                     cpumask_test_cpu(cpu, p->cpus_ptr))
7944                         return cpu;
7945
7946                 if (sched_energy_enabled()) {
7947                         new_cpu = find_energy_efficient_cpu(p, prev_cpu);
7948                         if (new_cpu >= 0)
7949                                 return new_cpu;
7950                         new_cpu = prev_cpu;
7951                 }
7952
7953                 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
7954         }
7955
7956         rcu_read_lock();
7957         for_each_domain(cpu, tmp) {
7958                 /*
7959                  * If both 'cpu' and 'prev_cpu' are part of this domain,
7960                  * cpu is a valid SD_WAKE_AFFINE target.
7961                  */
7962                 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
7963                     cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
7964                         if (cpu != prev_cpu)
7965                                 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
7966
7967                         sd = NULL; /* Prefer wake_affine over balance flags */
7968                         break;
7969                 }
7970
7971                 /*
7972                  * Usually only true for WF_EXEC and WF_FORK, as sched_domains
7973                  * usually do not have SD_BALANCE_WAKE set. That means wakeup
7974                  * will usually go to the fast path.
7975                  */
7976                 if (tmp->flags & sd_flag)
7977                         sd = tmp;
7978                 else if (!want_affine)
7979                         break;
7980         }
7981
7982         if (unlikely(sd)) {
7983                 /* Slow path */
7984                 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
7985         } else if (wake_flags & WF_TTWU) { /* XXX always ? */
7986                 /* Fast path */
7987                 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
7988         }
7989         rcu_read_unlock();
7990
7991         return new_cpu;
7992 }
7993
7994 /*
7995  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
7996  * cfs_rq_of(p) references at time of call are still valid and identify the
7997  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7998  */
7999 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8000 {
8001         struct sched_entity *se = &p->se;
8002
8003         if (!task_on_rq_migrating(p)) {
8004                 remove_entity_load_avg(se);
8005
8006                 /*
8007                  * Here, the task's PELT values have been updated according to
8008                  * the current rq's clock. But if that clock hasn't been
8009                  * updated in a while, a substantial idle time will be missed,
8010                  * leading to an inflation after wake-up on the new rq.
8011                  *
8012                  * Estimate the missing time from the cfs_rq last_update_time
8013                  * and update sched_avg to improve the PELT continuity after
8014                  * migration.
8015                  */
8016                 migrate_se_pelt_lag(se);
8017         }
8018
8019         /* Tell new CPU we are migrated */
8020         se->avg.last_update_time = 0;
8021
8022         update_scan_period(p, new_cpu);
8023 }
8024
8025 static void task_dead_fair(struct task_struct *p)
8026 {
8027         remove_entity_load_avg(&p->se);
8028 }
8029
8030 static int
8031 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8032 {
8033         if (rq->nr_running)
8034                 return 1;
8035
8036         return newidle_balance(rq, rf) != 0;
8037 }
8038 #endif /* CONFIG_SMP */
8039
8040 static void set_next_buddy(struct sched_entity *se)
8041 {
8042         for_each_sched_entity(se) {
8043                 if (SCHED_WARN_ON(!se->on_rq))
8044                         return;
8045                 if (se_is_idle(se))
8046                         return;
8047                 cfs_rq_of(se)->next = se;
8048         }
8049 }
8050
8051 /*
8052  * Preempt the current task with a newly woken task if needed:
8053  */
8054 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
8055 {
8056         struct task_struct *curr = rq->curr;
8057         struct sched_entity *se = &curr->se, *pse = &p->se;
8058         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8059         int next_buddy_marked = 0;
8060         int cse_is_idle, pse_is_idle;
8061
8062         if (unlikely(se == pse))
8063                 return;
8064
8065         /*
8066          * This is possible from callers such as attach_tasks(), in which we
8067          * unconditionally check_preempt_curr() after an enqueue (which may have
8068          * lead to a throttle).  This both saves work and prevents false
8069          * next-buddy nomination below.
8070          */
8071         if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8072                 return;
8073
8074         if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8075                 set_next_buddy(pse);
8076                 next_buddy_marked = 1;
8077         }
8078
8079         /*
8080          * We can come here with TIF_NEED_RESCHED already set from new task
8081          * wake up path.
8082          *
8083          * Note: this also catches the edge-case of curr being in a throttled
8084          * group (e.g. via set_curr_task), since update_curr() (in the
8085          * enqueue of curr) will have resulted in resched being set.  This
8086          * prevents us from potentially nominating it as a false LAST_BUDDY
8087          * below.
8088          */
8089         if (test_tsk_need_resched(curr))
8090                 return;
8091
8092         /* Idle tasks are by definition preempted by non-idle tasks. */
8093         if (unlikely(task_has_idle_policy(curr)) &&
8094             likely(!task_has_idle_policy(p)))
8095                 goto preempt;
8096
8097         /*
8098          * Batch and idle tasks do not preempt non-idle tasks (their preemption
8099          * is driven by the tick):
8100          */
8101         if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8102                 return;
8103
8104         find_matching_se(&se, &pse);
8105         WARN_ON_ONCE(!pse);
8106
8107         cse_is_idle = se_is_idle(se);
8108         pse_is_idle = se_is_idle(pse);
8109
8110         /*
8111          * Preempt an idle group in favor of a non-idle group (and don't preempt
8112          * in the inverse case).
8113          */
8114         if (cse_is_idle && !pse_is_idle)
8115                 goto preempt;
8116         if (cse_is_idle != pse_is_idle)
8117                 return;
8118
8119         cfs_rq = cfs_rq_of(se);
8120         update_curr(cfs_rq);
8121
8122         /*
8123          * XXX pick_eevdf(cfs_rq) != se ?
8124          */
8125         if (pick_eevdf(cfs_rq) == pse)
8126                 goto preempt;
8127
8128         return;
8129
8130 preempt:
8131         resched_curr(rq);
8132 }
8133
8134 #ifdef CONFIG_SMP
8135 static struct task_struct *pick_task_fair(struct rq *rq)
8136 {
8137         struct sched_entity *se;
8138         struct cfs_rq *cfs_rq;
8139
8140 again:
8141         cfs_rq = &rq->cfs;
8142         if (!cfs_rq->nr_running)
8143                 return NULL;
8144
8145         do {
8146                 struct sched_entity *curr = cfs_rq->curr;
8147
8148                 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8149                 if (curr) {
8150                         if (curr->on_rq)
8151                                 update_curr(cfs_rq);
8152                         else
8153                                 curr = NULL;
8154
8155                         if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8156                                 goto again;
8157                 }
8158
8159                 se = pick_next_entity(cfs_rq, curr);
8160                 cfs_rq = group_cfs_rq(se);
8161         } while (cfs_rq);
8162
8163         return task_of(se);
8164 }
8165 #endif
8166
8167 struct task_struct *
8168 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8169 {
8170         struct cfs_rq *cfs_rq = &rq->cfs;
8171         struct sched_entity *se;
8172         struct task_struct *p;
8173         int new_tasks;
8174
8175 again:
8176         if (!sched_fair_runnable(rq))
8177                 goto idle;
8178
8179 #ifdef CONFIG_FAIR_GROUP_SCHED
8180         if (!prev || prev->sched_class != &fair_sched_class)
8181                 goto simple;
8182
8183         /*
8184          * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8185          * likely that a next task is from the same cgroup as the current.
8186          *
8187          * Therefore attempt to avoid putting and setting the entire cgroup
8188          * hierarchy, only change the part that actually changes.
8189          */
8190
8191         do {
8192                 struct sched_entity *curr = cfs_rq->curr;
8193
8194                 /*
8195                  * Since we got here without doing put_prev_entity() we also
8196                  * have to consider cfs_rq->curr. If it is still a runnable
8197                  * entity, update_curr() will update its vruntime, otherwise
8198                  * forget we've ever seen it.
8199                  */
8200                 if (curr) {
8201                         if (curr->on_rq)
8202                                 update_curr(cfs_rq);
8203                         else
8204                                 curr = NULL;
8205
8206                         /*
8207                          * This call to check_cfs_rq_runtime() will do the
8208                          * throttle and dequeue its entity in the parent(s).
8209                          * Therefore the nr_running test will indeed
8210                          * be correct.
8211                          */
8212                         if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8213                                 cfs_rq = &rq->cfs;
8214
8215                                 if (!cfs_rq->nr_running)
8216                                         goto idle;
8217
8218                                 goto simple;
8219                         }
8220                 }
8221
8222                 se = pick_next_entity(cfs_rq, curr);
8223                 cfs_rq = group_cfs_rq(se);
8224         } while (cfs_rq);
8225
8226         p = task_of(se);
8227
8228         /*
8229          * Since we haven't yet done put_prev_entity and if the selected task
8230          * is a different task than we started out with, try and touch the
8231          * least amount of cfs_rqs.
8232          */
8233         if (prev != p) {
8234                 struct sched_entity *pse = &prev->se;
8235
8236                 while (!(cfs_rq = is_same_group(se, pse))) {
8237                         int se_depth = se->depth;
8238                         int pse_depth = pse->depth;
8239
8240                         if (se_depth <= pse_depth) {
8241                                 put_prev_entity(cfs_rq_of(pse), pse);
8242                                 pse = parent_entity(pse);
8243                         }
8244                         if (se_depth >= pse_depth) {
8245                                 set_next_entity(cfs_rq_of(se), se);
8246                                 se = parent_entity(se);
8247                         }
8248                 }
8249
8250                 put_prev_entity(cfs_rq, pse);
8251                 set_next_entity(cfs_rq, se);
8252         }
8253
8254         goto done;
8255 simple:
8256 #endif
8257         if (prev)
8258                 put_prev_task(rq, prev);
8259
8260         do {
8261                 se = pick_next_entity(cfs_rq, NULL);
8262                 set_next_entity(cfs_rq, se);
8263                 cfs_rq = group_cfs_rq(se);
8264         } while (cfs_rq);
8265
8266         p = task_of(se);
8267
8268 done: __maybe_unused;
8269 #ifdef CONFIG_SMP
8270         /*
8271          * Move the next running task to the front of
8272          * the list, so our cfs_tasks list becomes MRU
8273          * one.
8274          */
8275         list_move(&p->se.group_node, &rq->cfs_tasks);
8276 #endif
8277
8278         if (hrtick_enabled_fair(rq))
8279                 hrtick_start_fair(rq, p);
8280
8281         update_misfit_status(p, rq);
8282         sched_fair_update_stop_tick(rq, p);
8283
8284         return p;
8285
8286 idle:
8287         if (!rf)
8288                 return NULL;
8289
8290         new_tasks = newidle_balance(rq, rf);
8291
8292         /*
8293          * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8294          * possible for any higher priority task to appear. In that case we
8295          * must re-start the pick_next_entity() loop.
8296          */
8297         if (new_tasks < 0)
8298                 return RETRY_TASK;
8299
8300         if (new_tasks > 0)
8301                 goto again;
8302
8303         /*
8304          * rq is about to be idle, check if we need to update the
8305          * lost_idle_time of clock_pelt
8306          */
8307         update_idle_rq_clock_pelt(rq);
8308
8309         return NULL;
8310 }
8311
8312 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8313 {
8314         return pick_next_task_fair(rq, NULL, NULL);
8315 }
8316
8317 /*
8318  * Account for a descheduled task:
8319  */
8320 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8321 {
8322         struct sched_entity *se = &prev->se;
8323         struct cfs_rq *cfs_rq;
8324
8325         for_each_sched_entity(se) {
8326                 cfs_rq = cfs_rq_of(se);
8327                 put_prev_entity(cfs_rq, se);
8328         }
8329 }
8330
8331 /*
8332  * sched_yield() is very simple
8333  */
8334 static void yield_task_fair(struct rq *rq)
8335 {
8336         struct task_struct *curr = rq->curr;
8337         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8338         struct sched_entity *se = &curr->se;
8339
8340         /*
8341          * Are we the only task in the tree?
8342          */
8343         if (unlikely(rq->nr_running == 1))
8344                 return;
8345
8346         clear_buddies(cfs_rq, se);
8347
8348         update_rq_clock(rq);
8349         /*
8350          * Update run-time statistics of the 'current'.
8351          */
8352         update_curr(cfs_rq);
8353         /*
8354          * Tell update_rq_clock() that we've just updated,
8355          * so we don't do microscopic update in schedule()
8356          * and double the fastpath cost.
8357          */
8358         rq_clock_skip_update(rq);
8359
8360         se->deadline += calc_delta_fair(se->slice, se);
8361 }
8362
8363 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8364 {
8365         struct sched_entity *se = &p->se;
8366
8367         /* throttled hierarchies are not runnable */
8368         if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8369                 return false;
8370
8371         /* Tell the scheduler that we'd really like pse to run next. */
8372         set_next_buddy(se);
8373
8374         yield_task_fair(rq);
8375
8376         return true;
8377 }
8378
8379 #ifdef CONFIG_SMP
8380 /**************************************************
8381  * Fair scheduling class load-balancing methods.
8382  *
8383  * BASICS
8384  *
8385  * The purpose of load-balancing is to achieve the same basic fairness the
8386  * per-CPU scheduler provides, namely provide a proportional amount of compute
8387  * time to each task. This is expressed in the following equation:
8388  *
8389  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
8390  *
8391  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8392  * W_i,0 is defined as:
8393  *
8394  *   W_i,0 = \Sum_j w_i,j                                             (2)
8395  *
8396  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8397  * is derived from the nice value as per sched_prio_to_weight[].
8398  *
8399  * The weight average is an exponential decay average of the instantaneous
8400  * weight:
8401  *
8402  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
8403  *
8404  * C_i is the compute capacity of CPU i, typically it is the
8405  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8406  * can also include other factors [XXX].
8407  *
8408  * To achieve this balance we define a measure of imbalance which follows
8409  * directly from (1):
8410  *
8411  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
8412  *
8413  * We them move tasks around to minimize the imbalance. In the continuous
8414  * function space it is obvious this converges, in the discrete case we get
8415  * a few fun cases generally called infeasible weight scenarios.
8416  *
8417  * [XXX expand on:
8418  *     - infeasible weights;
8419  *     - local vs global optima in the discrete case. ]
8420  *
8421  *
8422  * SCHED DOMAINS
8423  *
8424  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8425  * for all i,j solution, we create a tree of CPUs that follows the hardware
8426  * topology where each level pairs two lower groups (or better). This results
8427  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8428  * tree to only the first of the previous level and we decrease the frequency
8429  * of load-balance at each level inv. proportional to the number of CPUs in
8430  * the groups.
8431  *
8432  * This yields:
8433  *
8434  *     log_2 n     1     n
8435  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
8436  *     i = 0      2^i   2^i
8437  *                               `- size of each group
8438  *         |         |     `- number of CPUs doing load-balance
8439  *         |         `- freq
8440  *         `- sum over all levels
8441  *
8442  * Coupled with a limit on how many tasks we can migrate every balance pass,
8443  * this makes (5) the runtime complexity of the balancer.
8444  *
8445  * An important property here is that each CPU is still (indirectly) connected
8446  * to every other CPU in at most O(log n) steps:
8447  *
8448  * The adjacency matrix of the resulting graph is given by:
8449  *
8450  *             log_2 n
8451  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
8452  *             k = 0
8453  *
8454  * And you'll find that:
8455  *
8456  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
8457  *
8458  * Showing there's indeed a path between every CPU in at most O(log n) steps.
8459  * The task movement gives a factor of O(m), giving a convergence complexity
8460  * of:
8461  *
8462  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
8463  *
8464  *
8465  * WORK CONSERVING
8466  *
8467  * In order to avoid CPUs going idle while there's still work to do, new idle
8468  * balancing is more aggressive and has the newly idle CPU iterate up the domain
8469  * tree itself instead of relying on other CPUs to bring it work.
8470  *
8471  * This adds some complexity to both (5) and (8) but it reduces the total idle
8472  * time.
8473  *
8474  * [XXX more?]
8475  *
8476  *
8477  * CGROUPS
8478  *
8479  * Cgroups make a horror show out of (2), instead of a simple sum we get:
8480  *
8481  *                                s_k,i
8482  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
8483  *                                 S_k
8484  *
8485  * Where
8486  *
8487  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
8488  *
8489  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8490  *
8491  * The big problem is S_k, its a global sum needed to compute a local (W_i)
8492  * property.
8493  *
8494  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8495  *      rewrite all of this once again.]
8496  */
8497
8498 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8499
8500 enum fbq_type { regular, remote, all };
8501
8502 /*
8503  * 'group_type' describes the group of CPUs at the moment of load balancing.
8504  *
8505  * The enum is ordered by pulling priority, with the group with lowest priority
8506  * first so the group_type can simply be compared when selecting the busiest
8507  * group. See update_sd_pick_busiest().
8508  */
8509 enum group_type {
8510         /* The group has spare capacity that can be used to run more tasks.  */
8511         group_has_spare = 0,
8512         /*
8513          * The group is fully used and the tasks don't compete for more CPU
8514          * cycles. Nevertheless, some tasks might wait before running.
8515          */
8516         group_fully_busy,
8517         /*
8518          * One task doesn't fit with CPU's capacity and must be migrated to a
8519          * more powerful CPU.
8520          */
8521         group_misfit_task,
8522         /*
8523          * Balance SMT group that's fully busy. Can benefit from migration
8524          * a task on SMT with busy sibling to another CPU on idle core.
8525          */
8526         group_smt_balance,
8527         /*
8528          * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8529          * and the task should be migrated to it instead of running on the
8530          * current CPU.
8531          */
8532         group_asym_packing,
8533         /*
8534          * The tasks' affinity constraints previously prevented the scheduler
8535          * from balancing the load across the system.
8536          */
8537         group_imbalanced,
8538         /*
8539          * The CPU is overloaded and can't provide expected CPU cycles to all
8540          * tasks.
8541          */
8542         group_overloaded
8543 };
8544
8545 enum migration_type {
8546         migrate_load = 0,
8547         migrate_util,
8548         migrate_task,
8549         migrate_misfit
8550 };
8551
8552 #define LBF_ALL_PINNED  0x01
8553 #define LBF_NEED_BREAK  0x02
8554 #define LBF_DST_PINNED  0x04
8555 #define LBF_SOME_PINNED 0x08
8556 #define LBF_ACTIVE_LB   0x10
8557
8558 struct lb_env {
8559         struct sched_domain     *sd;
8560
8561         struct rq               *src_rq;
8562         int                     src_cpu;
8563
8564         int                     dst_cpu;
8565         struct rq               *dst_rq;
8566
8567         struct cpumask          *dst_grpmask;
8568         int                     new_dst_cpu;
8569         enum cpu_idle_type      idle;
8570         long                    imbalance;
8571         /* The set of CPUs under consideration for load-balancing */
8572         struct cpumask          *cpus;
8573
8574         unsigned int            flags;
8575
8576         unsigned int            loop;
8577         unsigned int            loop_break;
8578         unsigned int            loop_max;
8579
8580         enum fbq_type           fbq_type;
8581         enum migration_type     migration_type;
8582         struct list_head        tasks;
8583 };
8584
8585 /*
8586  * Is this task likely cache-hot:
8587  */
8588 static int task_hot(struct task_struct *p, struct lb_env *env)
8589 {
8590         s64 delta;
8591
8592         lockdep_assert_rq_held(env->src_rq);
8593
8594         if (p->sched_class != &fair_sched_class)
8595                 return 0;
8596
8597         if (unlikely(task_has_idle_policy(p)))
8598                 return 0;
8599
8600         /* SMT siblings share cache */
8601         if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8602                 return 0;
8603
8604         /*
8605          * Buddy candidates are cache hot:
8606          */
8607         if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8608             (&p->se == cfs_rq_of(&p->se)->next))
8609                 return 1;
8610
8611         if (sysctl_sched_migration_cost == -1)
8612                 return 1;
8613
8614         /*
8615          * Don't migrate task if the task's cookie does not match
8616          * with the destination CPU's core cookie.
8617          */
8618         if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8619                 return 1;
8620
8621         if (sysctl_sched_migration_cost == 0)
8622                 return 0;
8623
8624         delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8625
8626         return delta < (s64)sysctl_sched_migration_cost;
8627 }
8628
8629 #ifdef CONFIG_NUMA_BALANCING
8630 /*
8631  * Returns 1, if task migration degrades locality
8632  * Returns 0, if task migration improves locality i.e migration preferred.
8633  * Returns -1, if task migration is not affected by locality.
8634  */
8635 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8636 {
8637         struct numa_group *numa_group = rcu_dereference(p->numa_group);
8638         unsigned long src_weight, dst_weight;
8639         int src_nid, dst_nid, dist;
8640
8641         if (!static_branch_likely(&sched_numa_balancing))
8642                 return -1;
8643
8644         if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8645                 return -1;
8646
8647         src_nid = cpu_to_node(env->src_cpu);
8648         dst_nid = cpu_to_node(env->dst_cpu);
8649
8650         if (src_nid == dst_nid)
8651                 return -1;
8652
8653         /* Migrating away from the preferred node is always bad. */
8654         if (src_nid == p->numa_preferred_nid) {
8655                 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8656                         return 1;
8657                 else
8658                         return -1;
8659         }
8660
8661         /* Encourage migration to the preferred node. */
8662         if (dst_nid == p->numa_preferred_nid)
8663                 return 0;
8664
8665         /* Leaving a core idle is often worse than degrading locality. */
8666         if (env->idle == CPU_IDLE)
8667                 return -1;
8668
8669         dist = node_distance(src_nid, dst_nid);
8670         if (numa_group) {
8671                 src_weight = group_weight(p, src_nid, dist);
8672                 dst_weight = group_weight(p, dst_nid, dist);
8673         } else {
8674                 src_weight = task_weight(p, src_nid, dist);
8675                 dst_weight = task_weight(p, dst_nid, dist);
8676         }
8677
8678         return dst_weight < src_weight;
8679 }
8680
8681 #else
8682 static inline int migrate_degrades_locality(struct task_struct *p,
8683                                              struct lb_env *env)
8684 {
8685         return -1;
8686 }
8687 #endif
8688
8689 /*
8690  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8691  */
8692 static
8693 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8694 {
8695         int tsk_cache_hot;
8696
8697         lockdep_assert_rq_held(env->src_rq);
8698
8699         /*
8700          * We do not migrate tasks that are:
8701          * 1) throttled_lb_pair, or
8702          * 2) cannot be migrated to this CPU due to cpus_ptr, or
8703          * 3) running (obviously), or
8704          * 4) are cache-hot on their current CPU.
8705          */
8706         if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8707                 return 0;
8708
8709         /* Disregard pcpu kthreads; they are where they need to be. */
8710         if (kthread_is_per_cpu(p))
8711                 return 0;
8712
8713         if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8714                 int cpu;
8715
8716                 schedstat_inc(p->stats.nr_failed_migrations_affine);
8717
8718                 env->flags |= LBF_SOME_PINNED;
8719
8720                 /*
8721                  * Remember if this task can be migrated to any other CPU in
8722                  * our sched_group. We may want to revisit it if we couldn't
8723                  * meet load balance goals by pulling other tasks on src_cpu.
8724                  *
8725                  * Avoid computing new_dst_cpu
8726                  * - for NEWLY_IDLE
8727                  * - if we have already computed one in current iteration
8728                  * - if it's an active balance
8729                  */
8730                 if (env->idle == CPU_NEWLY_IDLE ||
8731                     env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8732                         return 0;
8733
8734                 /* Prevent to re-select dst_cpu via env's CPUs: */
8735                 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8736                         if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8737                                 env->flags |= LBF_DST_PINNED;
8738                                 env->new_dst_cpu = cpu;
8739                                 break;
8740                         }
8741                 }
8742
8743                 return 0;
8744         }
8745
8746         /* Record that we found at least one task that could run on dst_cpu */
8747         env->flags &= ~LBF_ALL_PINNED;
8748
8749         if (task_on_cpu(env->src_rq, p)) {
8750                 schedstat_inc(p->stats.nr_failed_migrations_running);
8751                 return 0;
8752         }
8753
8754         /*
8755          * Aggressive migration if:
8756          * 1) active balance
8757          * 2) destination numa is preferred
8758          * 3) task is cache cold, or
8759          * 4) too many balance attempts have failed.
8760          */
8761         if (env->flags & LBF_ACTIVE_LB)
8762                 return 1;
8763
8764         tsk_cache_hot = migrate_degrades_locality(p, env);
8765         if (tsk_cache_hot == -1)
8766                 tsk_cache_hot = task_hot(p, env);
8767
8768         if (tsk_cache_hot <= 0 ||
8769             env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
8770                 if (tsk_cache_hot == 1) {
8771                         schedstat_inc(env->sd->lb_hot_gained[env->idle]);
8772                         schedstat_inc(p->stats.nr_forced_migrations);
8773                 }
8774                 return 1;
8775         }
8776
8777         schedstat_inc(p->stats.nr_failed_migrations_hot);
8778         return 0;
8779 }
8780
8781 /*
8782  * detach_task() -- detach the task for the migration specified in env
8783  */
8784 static void detach_task(struct task_struct *p, struct lb_env *env)
8785 {
8786         lockdep_assert_rq_held(env->src_rq);
8787
8788         deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8789         set_task_cpu(p, env->dst_cpu);
8790 }
8791
8792 /*
8793  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8794  * part of active balancing operations within "domain".
8795  *
8796  * Returns a task if successful and NULL otherwise.
8797  */
8798 static struct task_struct *detach_one_task(struct lb_env *env)
8799 {
8800         struct task_struct *p;
8801
8802         lockdep_assert_rq_held(env->src_rq);
8803
8804         list_for_each_entry_reverse(p,
8805                         &env->src_rq->cfs_tasks, se.group_node) {
8806                 if (!can_migrate_task(p, env))
8807                         continue;
8808
8809                 detach_task(p, env);
8810
8811                 /*
8812                  * Right now, this is only the second place where
8813                  * lb_gained[env->idle] is updated (other is detach_tasks)
8814                  * so we can safely collect stats here rather than
8815                  * inside detach_tasks().
8816                  */
8817                 schedstat_inc(env->sd->lb_gained[env->idle]);
8818                 return p;
8819         }
8820         return NULL;
8821 }
8822
8823 /*
8824  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8825  * busiest_rq, as part of a balancing operation within domain "sd".
8826  *
8827  * Returns number of detached tasks if successful and 0 otherwise.
8828  */
8829 static int detach_tasks(struct lb_env *env)
8830 {
8831         struct list_head *tasks = &env->src_rq->cfs_tasks;
8832         unsigned long util, load;
8833         struct task_struct *p;
8834         int detached = 0;
8835
8836         lockdep_assert_rq_held(env->src_rq);
8837
8838         /*
8839          * Source run queue has been emptied by another CPU, clear
8840          * LBF_ALL_PINNED flag as we will not test any task.
8841          */
8842         if (env->src_rq->nr_running <= 1) {
8843                 env->flags &= ~LBF_ALL_PINNED;
8844                 return 0;
8845         }
8846
8847         if (env->imbalance <= 0)
8848                 return 0;
8849
8850         while (!list_empty(tasks)) {
8851                 /*
8852                  * We don't want to steal all, otherwise we may be treated likewise,
8853                  * which could at worst lead to a livelock crash.
8854                  */
8855                 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
8856                         break;
8857
8858                 env->loop++;
8859                 /*
8860                  * We've more or less seen every task there is, call it quits
8861                  * unless we haven't found any movable task yet.
8862                  */
8863                 if (env->loop > env->loop_max &&
8864                     !(env->flags & LBF_ALL_PINNED))
8865                         break;
8866
8867                 /* take a breather every nr_migrate tasks */
8868                 if (env->loop > env->loop_break) {
8869                         env->loop_break += SCHED_NR_MIGRATE_BREAK;
8870                         env->flags |= LBF_NEED_BREAK;
8871                         break;
8872                 }
8873
8874                 p = list_last_entry(tasks, struct task_struct, se.group_node);
8875
8876                 if (!can_migrate_task(p, env))
8877                         goto next;
8878
8879                 switch (env->migration_type) {
8880                 case migrate_load:
8881                         /*
8882                          * Depending of the number of CPUs and tasks and the
8883                          * cgroup hierarchy, task_h_load() can return a null
8884                          * value. Make sure that env->imbalance decreases
8885                          * otherwise detach_tasks() will stop only after
8886                          * detaching up to loop_max tasks.
8887                          */
8888                         load = max_t(unsigned long, task_h_load(p), 1);
8889
8890                         if (sched_feat(LB_MIN) &&
8891                             load < 16 && !env->sd->nr_balance_failed)
8892                                 goto next;
8893
8894                         /*
8895                          * Make sure that we don't migrate too much load.
8896                          * Nevertheless, let relax the constraint if
8897                          * scheduler fails to find a good waiting task to
8898                          * migrate.
8899                          */
8900                         if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
8901                                 goto next;
8902
8903                         env->imbalance -= load;
8904                         break;
8905
8906                 case migrate_util:
8907                         util = task_util_est(p);
8908
8909                         if (util > env->imbalance)
8910                                 goto next;
8911
8912                         env->imbalance -= util;
8913                         break;
8914
8915                 case migrate_task:
8916                         env->imbalance--;
8917                         break;
8918
8919                 case migrate_misfit:
8920                         /* This is not a misfit task */
8921                         if (task_fits_cpu(p, env->src_cpu))
8922                                 goto next;
8923
8924                         env->imbalance = 0;
8925                         break;
8926                 }
8927
8928                 detach_task(p, env);
8929                 list_add(&p->se.group_node, &env->tasks);
8930
8931                 detached++;
8932
8933 #ifdef CONFIG_PREEMPTION
8934                 /*
8935                  * NEWIDLE balancing is a source of latency, so preemptible
8936                  * kernels will stop after the first task is detached to minimize
8937                  * the critical section.
8938                  */
8939                 if (env->idle == CPU_NEWLY_IDLE)
8940                         break;
8941 #endif
8942
8943                 /*
8944                  * We only want to steal up to the prescribed amount of
8945                  * load/util/tasks.
8946                  */
8947                 if (env->imbalance <= 0)
8948                         break;
8949
8950                 continue;
8951 next:
8952                 list_move(&p->se.group_node, tasks);
8953         }
8954
8955         /*
8956          * Right now, this is one of only two places we collect this stat
8957          * so we can safely collect detach_one_task() stats here rather
8958          * than inside detach_one_task().
8959          */
8960         schedstat_add(env->sd->lb_gained[env->idle], detached);
8961
8962         return detached;
8963 }
8964
8965 /*
8966  * attach_task() -- attach the task detached by detach_task() to its new rq.
8967  */
8968 static void attach_task(struct rq *rq, struct task_struct *p)
8969 {
8970         lockdep_assert_rq_held(rq);
8971
8972         WARN_ON_ONCE(task_rq(p) != rq);
8973         activate_task(rq, p, ENQUEUE_NOCLOCK);
8974         check_preempt_curr(rq, p, 0);
8975 }
8976
8977 /*
8978  * attach_one_task() -- attaches the task returned from detach_one_task() to
8979  * its new rq.
8980  */
8981 static void attach_one_task(struct rq *rq, struct task_struct *p)
8982 {
8983         struct rq_flags rf;
8984
8985         rq_lock(rq, &rf);
8986         update_rq_clock(rq);
8987         attach_task(rq, p);
8988         rq_unlock(rq, &rf);
8989 }
8990
8991 /*
8992  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8993  * new rq.
8994  */
8995 static void attach_tasks(struct lb_env *env)
8996 {
8997         struct list_head *tasks = &env->tasks;
8998         struct task_struct *p;
8999         struct rq_flags rf;
9000
9001         rq_lock(env->dst_rq, &rf);
9002         update_rq_clock(env->dst_rq);
9003
9004         while (!list_empty(tasks)) {
9005                 p = list_first_entry(tasks, struct task_struct, se.group_node);
9006                 list_del_init(&p->se.group_node);
9007
9008                 attach_task(env->dst_rq, p);
9009         }
9010
9011         rq_unlock(env->dst_rq, &rf);
9012 }
9013
9014 #ifdef CONFIG_NO_HZ_COMMON
9015 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9016 {
9017         if (cfs_rq->avg.load_avg)
9018                 return true;
9019
9020         if (cfs_rq->avg.util_avg)
9021                 return true;
9022
9023         return false;
9024 }
9025
9026 static inline bool others_have_blocked(struct rq *rq)
9027 {
9028         if (READ_ONCE(rq->avg_rt.util_avg))
9029                 return true;
9030
9031         if (READ_ONCE(rq->avg_dl.util_avg))
9032                 return true;
9033
9034         if (thermal_load_avg(rq))
9035                 return true;
9036
9037 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
9038         if (READ_ONCE(rq->avg_irq.util_avg))
9039                 return true;
9040 #endif
9041
9042         return false;
9043 }
9044
9045 static inline void update_blocked_load_tick(struct rq *rq)
9046 {
9047         WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9048 }
9049
9050 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9051 {
9052         if (!has_blocked)
9053                 rq->has_blocked_load = 0;
9054 }
9055 #else
9056 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
9057 static inline bool others_have_blocked(struct rq *rq) { return false; }
9058 static inline void update_blocked_load_tick(struct rq *rq) {}
9059 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9060 #endif
9061
9062 static bool __update_blocked_others(struct rq *rq, bool *done)
9063 {
9064         const struct sched_class *curr_class;
9065         u64 now = rq_clock_pelt(rq);
9066         unsigned long thermal_pressure;
9067         bool decayed;
9068
9069         /*
9070          * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9071          * DL and IRQ signals have been updated before updating CFS.
9072          */
9073         curr_class = rq->curr->sched_class;
9074
9075         thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9076
9077         decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9078                   update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9079                   update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9080                   update_irq_load_avg(rq, 0);
9081
9082         if (others_have_blocked(rq))
9083                 *done = false;
9084
9085         return decayed;
9086 }
9087
9088 #ifdef CONFIG_FAIR_GROUP_SCHED
9089
9090 static bool __update_blocked_fair(struct rq *rq, bool *done)
9091 {
9092         struct cfs_rq *cfs_rq, *pos;
9093         bool decayed = false;
9094         int cpu = cpu_of(rq);
9095
9096         /*
9097          * Iterates the task_group tree in a bottom up fashion, see
9098          * list_add_leaf_cfs_rq() for details.
9099          */
9100         for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9101                 struct sched_entity *se;
9102
9103                 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9104                         update_tg_load_avg(cfs_rq);
9105
9106                         if (cfs_rq->nr_running == 0)
9107                                 update_idle_cfs_rq_clock_pelt(cfs_rq);
9108
9109                         if (cfs_rq == &rq->cfs)
9110                                 decayed = true;
9111                 }
9112
9113                 /* Propagate pending load changes to the parent, if any: */
9114                 se = cfs_rq->tg->se[cpu];
9115                 if (se && !skip_blocked_update(se))
9116                         update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9117
9118                 /*
9119                  * There can be a lot of idle CPU cgroups.  Don't let fully
9120                  * decayed cfs_rqs linger on the list.
9121                  */
9122                 if (cfs_rq_is_decayed(cfs_rq))
9123                         list_del_leaf_cfs_rq(cfs_rq);
9124
9125                 /* Don't need periodic decay once load/util_avg are null */
9126                 if (cfs_rq_has_blocked(cfs_rq))
9127                         *done = false;
9128         }
9129
9130         return decayed;
9131 }
9132
9133 /*
9134  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9135  * This needs to be done in a top-down fashion because the load of a child
9136  * group is a fraction of its parents load.
9137  */
9138 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9139 {
9140         struct rq *rq = rq_of(cfs_rq);
9141         struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9142         unsigned long now = jiffies;
9143         unsigned long load;
9144
9145         if (cfs_rq->last_h_load_update == now)
9146                 return;
9147
9148         WRITE_ONCE(cfs_rq->h_load_next, NULL);
9149         for_each_sched_entity(se) {
9150                 cfs_rq = cfs_rq_of(se);
9151                 WRITE_ONCE(cfs_rq->h_load_next, se);
9152                 if (cfs_rq->last_h_load_update == now)
9153                         break;
9154         }
9155
9156         if (!se) {
9157                 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9158                 cfs_rq->last_h_load_update = now;
9159         }
9160
9161         while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9162                 load = cfs_rq->h_load;
9163                 load = div64_ul(load * se->avg.load_avg,
9164                         cfs_rq_load_avg(cfs_rq) + 1);
9165                 cfs_rq = group_cfs_rq(se);
9166                 cfs_rq->h_load = load;
9167                 cfs_rq->last_h_load_update = now;
9168         }
9169 }
9170
9171 static unsigned long task_h_load(struct task_struct *p)
9172 {
9173         struct cfs_rq *cfs_rq = task_cfs_rq(p);
9174
9175         update_cfs_rq_h_load(cfs_rq);
9176         return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9177                         cfs_rq_load_avg(cfs_rq) + 1);
9178 }
9179 #else
9180 static bool __update_blocked_fair(struct rq *rq, bool *done)
9181 {
9182         struct cfs_rq *cfs_rq = &rq->cfs;
9183         bool decayed;
9184
9185         decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9186         if (cfs_rq_has_blocked(cfs_rq))
9187                 *done = false;
9188
9189         return decayed;
9190 }
9191
9192 static unsigned long task_h_load(struct task_struct *p)
9193 {
9194         return p->se.avg.load_avg;
9195 }
9196 #endif
9197
9198 static void update_blocked_averages(int cpu)
9199 {
9200         bool decayed = false, done = true;
9201         struct rq *rq = cpu_rq(cpu);
9202         struct rq_flags rf;
9203
9204         rq_lock_irqsave(rq, &rf);
9205         update_blocked_load_tick(rq);
9206         update_rq_clock(rq);
9207
9208         decayed |= __update_blocked_others(rq, &done);
9209         decayed |= __update_blocked_fair(rq, &done);
9210
9211         update_blocked_load_status(rq, !done);
9212         if (decayed)
9213                 cpufreq_update_util(rq, 0);
9214         rq_unlock_irqrestore(rq, &rf);
9215 }
9216
9217 /********** Helpers for find_busiest_group ************************/
9218
9219 /*
9220  * sg_lb_stats - stats of a sched_group required for load_balancing
9221  */
9222 struct sg_lb_stats {
9223         unsigned long avg_load; /*Avg load across the CPUs of the group */
9224         unsigned long group_load; /* Total load over the CPUs of the group */
9225         unsigned long group_capacity;
9226         unsigned long group_util; /* Total utilization over the CPUs of the group */
9227         unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9228         unsigned int sum_nr_running; /* Nr of tasks running in the group */
9229         unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9230         unsigned int idle_cpus;
9231         unsigned int group_weight;
9232         enum group_type group_type;
9233         unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9234         unsigned int group_smt_balance;  /* Task on busy SMT be moved */
9235         unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9236 #ifdef CONFIG_NUMA_BALANCING
9237         unsigned int nr_numa_running;
9238         unsigned int nr_preferred_running;
9239 #endif
9240 };
9241
9242 /*
9243  * sd_lb_stats - Structure to store the statistics of a sched_domain
9244  *               during load balancing.
9245  */
9246 struct sd_lb_stats {
9247         struct sched_group *busiest;    /* Busiest group in this sd */
9248         struct sched_group *local;      /* Local group in this sd */
9249         unsigned long total_load;       /* Total load of all groups in sd */
9250         unsigned long total_capacity;   /* Total capacity of all groups in sd */
9251         unsigned long avg_load; /* Average load across all groups in sd */
9252         unsigned int prefer_sibling; /* tasks should go to sibling first */
9253
9254         struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9255         struct sg_lb_stats local_stat;  /* Statistics of the local group */
9256 };
9257
9258 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9259 {
9260         /*
9261          * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9262          * local_stat because update_sg_lb_stats() does a full clear/assignment.
9263          * We must however set busiest_stat::group_type and
9264          * busiest_stat::idle_cpus to the worst busiest group because
9265          * update_sd_pick_busiest() reads these before assignment.
9266          */
9267         *sds = (struct sd_lb_stats){
9268                 .busiest = NULL,
9269                 .local = NULL,
9270                 .total_load = 0UL,
9271                 .total_capacity = 0UL,
9272                 .busiest_stat = {
9273                         .idle_cpus = UINT_MAX,
9274                         .group_type = group_has_spare,
9275                 },
9276         };
9277 }
9278
9279 static unsigned long scale_rt_capacity(int cpu)
9280 {
9281         struct rq *rq = cpu_rq(cpu);
9282         unsigned long max = arch_scale_cpu_capacity(cpu);
9283         unsigned long used, free;
9284         unsigned long irq;
9285
9286         irq = cpu_util_irq(rq);
9287
9288         if (unlikely(irq >= max))
9289                 return 1;
9290
9291         /*
9292          * avg_rt.util_avg and avg_dl.util_avg track binary signals
9293          * (running and not running) with weights 0 and 1024 respectively.
9294          * avg_thermal.load_avg tracks thermal pressure and the weighted
9295          * average uses the actual delta max capacity(load).
9296          */
9297         used = READ_ONCE(rq->avg_rt.util_avg);
9298         used += READ_ONCE(rq->avg_dl.util_avg);
9299         used += thermal_load_avg(rq);
9300
9301         if (unlikely(used >= max))
9302                 return 1;
9303
9304         free = max - used;
9305
9306         return scale_irq_capacity(free, irq, max);
9307 }
9308
9309 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9310 {
9311         unsigned long capacity = scale_rt_capacity(cpu);
9312         struct sched_group *sdg = sd->groups;
9313
9314         cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
9315
9316         if (!capacity)
9317                 capacity = 1;
9318
9319         cpu_rq(cpu)->cpu_capacity = capacity;
9320         trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9321
9322         sdg->sgc->capacity = capacity;
9323         sdg->sgc->min_capacity = capacity;
9324         sdg->sgc->max_capacity = capacity;
9325 }
9326
9327 void update_group_capacity(struct sched_domain *sd, int cpu)
9328 {
9329         struct sched_domain *child = sd->child;
9330         struct sched_group *group, *sdg = sd->groups;
9331         unsigned long capacity, min_capacity, max_capacity;
9332         unsigned long interval;
9333
9334         interval = msecs_to_jiffies(sd->balance_interval);
9335         interval = clamp(interval, 1UL, max_load_balance_interval);
9336         sdg->sgc->next_update = jiffies + interval;
9337
9338         if (!child) {
9339                 update_cpu_capacity(sd, cpu);
9340                 return;
9341         }
9342
9343         capacity = 0;
9344         min_capacity = ULONG_MAX;
9345         max_capacity = 0;
9346
9347         if (child->flags & SD_OVERLAP) {
9348                 /*
9349                  * SD_OVERLAP domains cannot assume that child groups
9350                  * span the current group.
9351                  */
9352
9353                 for_each_cpu(cpu, sched_group_span(sdg)) {
9354                         unsigned long cpu_cap = capacity_of(cpu);
9355
9356                         capacity += cpu_cap;
9357                         min_capacity = min(cpu_cap, min_capacity);
9358                         max_capacity = max(cpu_cap, max_capacity);
9359                 }
9360         } else  {
9361                 /*
9362                  * !SD_OVERLAP domains can assume that child groups
9363                  * span the current group.
9364                  */
9365
9366                 group = child->groups;
9367                 do {
9368                         struct sched_group_capacity *sgc = group->sgc;
9369
9370                         capacity += sgc->capacity;
9371                         min_capacity = min(sgc->min_capacity, min_capacity);
9372                         max_capacity = max(sgc->max_capacity, max_capacity);
9373                         group = group->next;
9374                 } while (group != child->groups);
9375         }
9376
9377         sdg->sgc->capacity = capacity;
9378         sdg->sgc->min_capacity = min_capacity;
9379         sdg->sgc->max_capacity = max_capacity;
9380 }
9381
9382 /*
9383  * Check whether the capacity of the rq has been noticeably reduced by side
9384  * activity. The imbalance_pct is used for the threshold.
9385  * Return true is the capacity is reduced
9386  */
9387 static inline int
9388 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9389 {
9390         return ((rq->cpu_capacity * sd->imbalance_pct) <
9391                                 (rq->cpu_capacity_orig * 100));
9392 }
9393
9394 /*
9395  * Check whether a rq has a misfit task and if it looks like we can actually
9396  * help that task: we can migrate the task to a CPU of higher capacity, or
9397  * the task's current CPU is heavily pressured.
9398  */
9399 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9400 {
9401         return rq->misfit_task_load &&
9402                 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
9403                  check_cpu_capacity(rq, sd));
9404 }
9405
9406 /*
9407  * Group imbalance indicates (and tries to solve) the problem where balancing
9408  * groups is inadequate due to ->cpus_ptr constraints.
9409  *
9410  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9411  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9412  * Something like:
9413  *
9414  *      { 0 1 2 3 } { 4 5 6 7 }
9415  *              *     * * *
9416  *
9417  * If we were to balance group-wise we'd place two tasks in the first group and
9418  * two tasks in the second group. Clearly this is undesired as it will overload
9419  * cpu 3 and leave one of the CPUs in the second group unused.
9420  *
9421  * The current solution to this issue is detecting the skew in the first group
9422  * by noticing the lower domain failed to reach balance and had difficulty
9423  * moving tasks due to affinity constraints.
9424  *
9425  * When this is so detected; this group becomes a candidate for busiest; see
9426  * update_sd_pick_busiest(). And calculate_imbalance() and
9427  * find_busiest_group() avoid some of the usual balance conditions to allow it
9428  * to create an effective group imbalance.
9429  *
9430  * This is a somewhat tricky proposition since the next run might not find the
9431  * group imbalance and decide the groups need to be balanced again. A most
9432  * subtle and fragile situation.
9433  */
9434
9435 static inline int sg_imbalanced(struct sched_group *group)
9436 {
9437         return group->sgc->imbalance;
9438 }
9439
9440 /*
9441  * group_has_capacity returns true if the group has spare capacity that could
9442  * be used by some tasks.
9443  * We consider that a group has spare capacity if the number of task is
9444  * smaller than the number of CPUs or if the utilization is lower than the
9445  * available capacity for CFS tasks.
9446  * For the latter, we use a threshold to stabilize the state, to take into
9447  * account the variance of the tasks' load and to return true if the available
9448  * capacity in meaningful for the load balancer.
9449  * As an example, an available capacity of 1% can appear but it doesn't make
9450  * any benefit for the load balance.
9451  */
9452 static inline bool
9453 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9454 {
9455         if (sgs->sum_nr_running < sgs->group_weight)
9456                 return true;
9457
9458         if ((sgs->group_capacity * imbalance_pct) <
9459                         (sgs->group_runnable * 100))
9460                 return false;
9461
9462         if ((sgs->group_capacity * 100) >
9463                         (sgs->group_util * imbalance_pct))
9464                 return true;
9465
9466         return false;
9467 }
9468
9469 /*
9470  *  group_is_overloaded returns true if the group has more tasks than it can
9471  *  handle.
9472  *  group_is_overloaded is not equals to !group_has_capacity because a group
9473  *  with the exact right number of tasks, has no more spare capacity but is not
9474  *  overloaded so both group_has_capacity and group_is_overloaded return
9475  *  false.
9476  */
9477 static inline bool
9478 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9479 {
9480         if (sgs->sum_nr_running <= sgs->group_weight)
9481                 return false;
9482
9483         if ((sgs->group_capacity * 100) <
9484                         (sgs->group_util * imbalance_pct))
9485                 return true;
9486
9487         if ((sgs->group_capacity * imbalance_pct) <
9488                         (sgs->group_runnable * 100))
9489                 return true;
9490
9491         return false;
9492 }
9493
9494 static inline enum
9495 group_type group_classify(unsigned int imbalance_pct,
9496                           struct sched_group *group,
9497                           struct sg_lb_stats *sgs)
9498 {
9499         if (group_is_overloaded(imbalance_pct, sgs))
9500                 return group_overloaded;
9501
9502         if (sg_imbalanced(group))
9503                 return group_imbalanced;
9504
9505         if (sgs->group_asym_packing)
9506                 return group_asym_packing;
9507
9508         if (sgs->group_smt_balance)
9509                 return group_smt_balance;
9510
9511         if (sgs->group_misfit_task_load)
9512                 return group_misfit_task;
9513
9514         if (!group_has_capacity(imbalance_pct, sgs))
9515                 return group_fully_busy;
9516
9517         return group_has_spare;
9518 }
9519
9520 /**
9521  * sched_use_asym_prio - Check whether asym_packing priority must be used
9522  * @sd:         The scheduling domain of the load balancing
9523  * @cpu:        A CPU
9524  *
9525  * Always use CPU priority when balancing load between SMT siblings. When
9526  * balancing load between cores, it is not sufficient that @cpu is idle. Only
9527  * use CPU priority if the whole core is idle.
9528  *
9529  * Returns: True if the priority of @cpu must be followed. False otherwise.
9530  */
9531 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9532 {
9533         if (!sched_smt_active())
9534                 return true;
9535
9536         return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9537 }
9538
9539 /**
9540  * sched_asym - Check if the destination CPU can do asym_packing load balance
9541  * @env:        The load balancing environment
9542  * @sds:        Load-balancing data with statistics of the local group
9543  * @sgs:        Load-balancing statistics of the candidate busiest group
9544  * @group:      The candidate busiest group
9545  *
9546  * @env::dst_cpu can do asym_packing if it has higher priority than the
9547  * preferred CPU of @group.
9548  *
9549  * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9550  * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9551  * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9552  * imbalances in the number of CPUS are dealt with in find_busiest_group().
9553  *
9554  * If we are balancing load within an SMT core, or at DIE domain level, always
9555  * proceed.
9556  *
9557  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9558  * otherwise.
9559  */
9560 static inline bool
9561 sched_asym(struct lb_env *env, struct sd_lb_stats *sds,  struct sg_lb_stats *sgs,
9562            struct sched_group *group)
9563 {
9564         /* Ensure that the whole local core is idle, if applicable. */
9565         if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9566                 return false;
9567
9568         /*
9569          * CPU priorities does not make sense for SMT cores with more than one
9570          * busy sibling.
9571          */
9572         if (group->flags & SD_SHARE_CPUCAPACITY) {
9573                 if (sgs->group_weight - sgs->idle_cpus != 1)
9574                         return false;
9575         }
9576
9577         return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9578 }
9579
9580 /* One group has more than one SMT CPU while the other group does not */
9581 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9582                                     struct sched_group *sg2)
9583 {
9584         if (!sg1 || !sg2)
9585                 return false;
9586
9587         return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9588                 (sg2->flags & SD_SHARE_CPUCAPACITY);
9589 }
9590
9591 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9592                                struct sched_group *group)
9593 {
9594         if (env->idle == CPU_NOT_IDLE)
9595                 return false;
9596
9597         /*
9598          * For SMT source group, it is better to move a task
9599          * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9600          * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9601          * will not be on.
9602          */
9603         if (group->flags & SD_SHARE_CPUCAPACITY &&
9604             sgs->sum_h_nr_running > 1)
9605                 return true;
9606
9607         return false;
9608 }
9609
9610 static inline long sibling_imbalance(struct lb_env *env,
9611                                     struct sd_lb_stats *sds,
9612                                     struct sg_lb_stats *busiest,
9613                                     struct sg_lb_stats *local)
9614 {
9615         int ncores_busiest, ncores_local;
9616         long imbalance;
9617
9618         if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9619                 return 0;
9620
9621         ncores_busiest = sds->busiest->cores;
9622         ncores_local = sds->local->cores;
9623
9624         if (ncores_busiest == ncores_local) {
9625                 imbalance = busiest->sum_nr_running;
9626                 lsub_positive(&imbalance, local->sum_nr_running);
9627                 return imbalance;
9628         }
9629
9630         /* Balance such that nr_running/ncores ratio are same on both groups */
9631         imbalance = ncores_local * busiest->sum_nr_running;
9632         lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9633         /* Normalize imbalance and do rounding on normalization */
9634         imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9635         imbalance /= ncores_local + ncores_busiest;
9636
9637         /* Take advantage of resource in an empty sched group */
9638         if (imbalance <= 1 && local->sum_nr_running == 0 &&
9639             busiest->sum_nr_running > 1)
9640                 imbalance = 2;
9641
9642         return imbalance;
9643 }
9644
9645 static inline bool
9646 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9647 {
9648         /*
9649          * When there is more than 1 task, the group_overloaded case already
9650          * takes care of cpu with reduced capacity
9651          */
9652         if (rq->cfs.h_nr_running != 1)
9653                 return false;
9654
9655         return check_cpu_capacity(rq, sd);
9656 }
9657
9658 /**
9659  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9660  * @env: The load balancing environment.
9661  * @sds: Load-balancing data with statistics of the local group.
9662  * @group: sched_group whose statistics are to be updated.
9663  * @sgs: variable to hold the statistics for this group.
9664  * @sg_status: Holds flag indicating the status of the sched_group
9665  */
9666 static inline void update_sg_lb_stats(struct lb_env *env,
9667                                       struct sd_lb_stats *sds,
9668                                       struct sched_group *group,
9669                                       struct sg_lb_stats *sgs,
9670                                       int *sg_status)
9671 {
9672         int i, nr_running, local_group;
9673
9674         memset(sgs, 0, sizeof(*sgs));
9675
9676         local_group = group == sds->local;
9677
9678         for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9679                 struct rq *rq = cpu_rq(i);
9680                 unsigned long load = cpu_load(rq);
9681
9682                 sgs->group_load += load;
9683                 sgs->group_util += cpu_util_cfs(i);
9684                 sgs->group_runnable += cpu_runnable(rq);
9685                 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9686
9687                 nr_running = rq->nr_running;
9688                 sgs->sum_nr_running += nr_running;
9689
9690                 if (nr_running > 1)
9691                         *sg_status |= SG_OVERLOAD;
9692
9693                 if (cpu_overutilized(i))
9694                         *sg_status |= SG_OVERUTILIZED;
9695
9696 #ifdef CONFIG_NUMA_BALANCING
9697                 sgs->nr_numa_running += rq->nr_numa_running;
9698                 sgs->nr_preferred_running += rq->nr_preferred_running;
9699 #endif
9700                 /*
9701                  * No need to call idle_cpu() if nr_running is not 0
9702                  */
9703                 if (!nr_running && idle_cpu(i)) {
9704                         sgs->idle_cpus++;
9705                         /* Idle cpu can't have misfit task */
9706                         continue;
9707                 }
9708
9709                 if (local_group)
9710                         continue;
9711
9712                 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9713                         /* Check for a misfit task on the cpu */
9714                         if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9715                                 sgs->group_misfit_task_load = rq->misfit_task_load;
9716                                 *sg_status |= SG_OVERLOAD;
9717                         }
9718                 } else if ((env->idle != CPU_NOT_IDLE) &&
9719                            sched_reduced_capacity(rq, env->sd)) {
9720                         /* Check for a task running on a CPU with reduced capacity */
9721                         if (sgs->group_misfit_task_load < load)
9722                                 sgs->group_misfit_task_load = load;
9723                 }
9724         }
9725
9726         sgs->group_capacity = group->sgc->capacity;
9727
9728         sgs->group_weight = group->group_weight;
9729
9730         /* Check if dst CPU is idle and preferred to this group */
9731         if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9732             env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9733             sched_asym(env, sds, sgs, group)) {
9734                 sgs->group_asym_packing = 1;
9735         }
9736
9737         /* Check for loaded SMT group to be balanced to dst CPU */
9738         if (!local_group && smt_balance(env, sgs, group))
9739                 sgs->group_smt_balance = 1;
9740
9741         sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
9742
9743         /* Computing avg_load makes sense only when group is overloaded */
9744         if (sgs->group_type == group_overloaded)
9745                 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9746                                 sgs->group_capacity;
9747 }
9748
9749 /**
9750  * update_sd_pick_busiest - return 1 on busiest group
9751  * @env: The load balancing environment.
9752  * @sds: sched_domain statistics
9753  * @sg: sched_group candidate to be checked for being the busiest
9754  * @sgs: sched_group statistics
9755  *
9756  * Determine if @sg is a busier group than the previously selected
9757  * busiest group.
9758  *
9759  * Return: %true if @sg is a busier group than the previously selected
9760  * busiest group. %false otherwise.
9761  */
9762 static bool update_sd_pick_busiest(struct lb_env *env,
9763                                    struct sd_lb_stats *sds,
9764                                    struct sched_group *sg,
9765                                    struct sg_lb_stats *sgs)
9766 {
9767         struct sg_lb_stats *busiest = &sds->busiest_stat;
9768
9769         /* Make sure that there is at least one task to pull */
9770         if (!sgs->sum_h_nr_running)
9771                 return false;
9772
9773         /*
9774          * Don't try to pull misfit tasks we can't help.
9775          * We can use max_capacity here as reduction in capacity on some
9776          * CPUs in the group should either be possible to resolve
9777          * internally or be covered by avg_load imbalance (eventually).
9778          */
9779         if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9780             (sgs->group_type == group_misfit_task) &&
9781             (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
9782              sds->local_stat.group_type != group_has_spare))
9783                 return false;
9784
9785         if (sgs->group_type > busiest->group_type)
9786                 return true;
9787
9788         if (sgs->group_type < busiest->group_type)
9789                 return false;
9790
9791         /*
9792          * The candidate and the current busiest group are the same type of
9793          * group. Let check which one is the busiest according to the type.
9794          */
9795
9796         switch (sgs->group_type) {
9797         case group_overloaded:
9798                 /* Select the overloaded group with highest avg_load. */
9799                 if (sgs->avg_load <= busiest->avg_load)
9800                         return false;
9801                 break;
9802
9803         case group_imbalanced:
9804                 /*
9805                  * Select the 1st imbalanced group as we don't have any way to
9806                  * choose one more than another.
9807                  */
9808                 return false;
9809
9810         case group_asym_packing:
9811                 /* Prefer to move from lowest priority CPU's work */
9812                 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
9813                         return false;
9814                 break;
9815
9816         case group_misfit_task:
9817                 /*
9818                  * If we have more than one misfit sg go with the biggest
9819                  * misfit.
9820                  */
9821                 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
9822                         return false;
9823                 break;
9824
9825         case group_smt_balance:
9826                 /*
9827                  * Check if we have spare CPUs on either SMT group to
9828                  * choose has spare or fully busy handling.
9829                  */
9830                 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
9831                         goto has_spare;
9832
9833                 fallthrough;
9834
9835         case group_fully_busy:
9836                 /*
9837                  * Select the fully busy group with highest avg_load. In
9838                  * theory, there is no need to pull task from such kind of
9839                  * group because tasks have all compute capacity that they need
9840                  * but we can still improve the overall throughput by reducing
9841                  * contention when accessing shared HW resources.
9842                  *
9843                  * XXX for now avg_load is not computed and always 0 so we
9844                  * select the 1st one, except if @sg is composed of SMT
9845                  * siblings.
9846                  */
9847
9848                 if (sgs->avg_load < busiest->avg_load)
9849                         return false;
9850
9851                 if (sgs->avg_load == busiest->avg_load) {
9852                         /*
9853                          * SMT sched groups need more help than non-SMT groups.
9854                          * If @sg happens to also be SMT, either choice is good.
9855                          */
9856                         if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
9857                                 return false;
9858                 }
9859
9860                 break;
9861
9862         case group_has_spare:
9863                 /*
9864                  * Do not pick sg with SMT CPUs over sg with pure CPUs,
9865                  * as we do not want to pull task off SMT core with one task
9866                  * and make the core idle.
9867                  */
9868                 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
9869                         if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
9870                                 return false;
9871                         else
9872                                 return true;
9873                 }
9874 has_spare:
9875
9876                 /*
9877                  * Select not overloaded group with lowest number of idle cpus
9878                  * and highest number of running tasks. We could also compare
9879                  * the spare capacity which is more stable but it can end up
9880                  * that the group has less spare capacity but finally more idle
9881                  * CPUs which means less opportunity to pull tasks.
9882                  */
9883                 if (sgs->idle_cpus > busiest->idle_cpus)
9884                         return false;
9885                 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
9886                          (sgs->sum_nr_running <= busiest->sum_nr_running))
9887                         return false;
9888
9889                 break;
9890         }
9891
9892         /*
9893          * Candidate sg has no more than one task per CPU and has higher
9894          * per-CPU capacity. Migrating tasks to less capable CPUs may harm
9895          * throughput. Maximize throughput, power/energy consequences are not
9896          * considered.
9897          */
9898         if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9899             (sgs->group_type <= group_fully_busy) &&
9900             (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
9901                 return false;
9902
9903         return true;
9904 }
9905
9906 #ifdef CONFIG_NUMA_BALANCING
9907 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9908 {
9909         if (sgs->sum_h_nr_running > sgs->nr_numa_running)
9910                 return regular;
9911         if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
9912                 return remote;
9913         return all;
9914 }
9915
9916 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9917 {
9918         if (rq->nr_running > rq->nr_numa_running)
9919                 return regular;
9920         if (rq->nr_running > rq->nr_preferred_running)
9921                 return remote;
9922         return all;
9923 }
9924 #else
9925 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9926 {
9927         return all;
9928 }
9929
9930 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9931 {
9932         return regular;
9933 }
9934 #endif /* CONFIG_NUMA_BALANCING */
9935
9936
9937 struct sg_lb_stats;
9938
9939 /*
9940  * task_running_on_cpu - return 1 if @p is running on @cpu.
9941  */
9942
9943 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
9944 {
9945         /* Task has no contribution or is new */
9946         if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9947                 return 0;
9948
9949         if (task_on_rq_queued(p))
9950                 return 1;
9951
9952         return 0;
9953 }
9954
9955 /**
9956  * idle_cpu_without - would a given CPU be idle without p ?
9957  * @cpu: the processor on which idleness is tested.
9958  * @p: task which should be ignored.
9959  *
9960  * Return: 1 if the CPU would be idle. 0 otherwise.
9961  */
9962 static int idle_cpu_without(int cpu, struct task_struct *p)
9963 {
9964         struct rq *rq = cpu_rq(cpu);
9965
9966         if (rq->curr != rq->idle && rq->curr != p)
9967                 return 0;
9968
9969         /*
9970          * rq->nr_running can't be used but an updated version without the
9971          * impact of p on cpu must be used instead. The updated nr_running
9972          * be computed and tested before calling idle_cpu_without().
9973          */
9974
9975 #ifdef CONFIG_SMP
9976         if (rq->ttwu_pending)
9977                 return 0;
9978 #endif
9979
9980         return 1;
9981 }
9982
9983 /*
9984  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
9985  * @sd: The sched_domain level to look for idlest group.
9986  * @group: sched_group whose statistics are to be updated.
9987  * @sgs: variable to hold the statistics for this group.
9988  * @p: The task for which we look for the idlest group/CPU.
9989  */
9990 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
9991                                           struct sched_group *group,
9992                                           struct sg_lb_stats *sgs,
9993                                           struct task_struct *p)
9994 {
9995         int i, nr_running;
9996
9997         memset(sgs, 0, sizeof(*sgs));
9998
9999         /* Assume that task can't fit any CPU of the group */
10000         if (sd->flags & SD_ASYM_CPUCAPACITY)
10001                 sgs->group_misfit_task_load = 1;
10002
10003         for_each_cpu(i, sched_group_span(group)) {
10004                 struct rq *rq = cpu_rq(i);
10005                 unsigned int local;
10006
10007                 sgs->group_load += cpu_load_without(rq, p);
10008                 sgs->group_util += cpu_util_without(i, p);
10009                 sgs->group_runnable += cpu_runnable_without(rq, p);
10010                 local = task_running_on_cpu(i, p);
10011                 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10012
10013                 nr_running = rq->nr_running - local;
10014                 sgs->sum_nr_running += nr_running;
10015
10016                 /*
10017                  * No need to call idle_cpu_without() if nr_running is not 0
10018                  */
10019                 if (!nr_running && idle_cpu_without(i, p))
10020                         sgs->idle_cpus++;
10021
10022                 /* Check if task fits in the CPU */
10023                 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10024                     sgs->group_misfit_task_load &&
10025                     task_fits_cpu(p, i))
10026                         sgs->group_misfit_task_load = 0;
10027
10028         }
10029
10030         sgs->group_capacity = group->sgc->capacity;
10031
10032         sgs->group_weight = group->group_weight;
10033
10034         sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10035
10036         /*
10037          * Computing avg_load makes sense only when group is fully busy or
10038          * overloaded
10039          */
10040         if (sgs->group_type == group_fully_busy ||
10041                 sgs->group_type == group_overloaded)
10042                 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10043                                 sgs->group_capacity;
10044 }
10045
10046 static bool update_pick_idlest(struct sched_group *idlest,
10047                                struct sg_lb_stats *idlest_sgs,
10048                                struct sched_group *group,
10049                                struct sg_lb_stats *sgs)
10050 {
10051         if (sgs->group_type < idlest_sgs->group_type)
10052                 return true;
10053
10054         if (sgs->group_type > idlest_sgs->group_type)
10055                 return false;
10056
10057         /*
10058          * The candidate and the current idlest group are the same type of
10059          * group. Let check which one is the idlest according to the type.
10060          */
10061
10062         switch (sgs->group_type) {
10063         case group_overloaded:
10064         case group_fully_busy:
10065                 /* Select the group with lowest avg_load. */
10066                 if (idlest_sgs->avg_load <= sgs->avg_load)
10067                         return false;
10068                 break;
10069
10070         case group_imbalanced:
10071         case group_asym_packing:
10072         case group_smt_balance:
10073                 /* Those types are not used in the slow wakeup path */
10074                 return false;
10075
10076         case group_misfit_task:
10077                 /* Select group with the highest max capacity */
10078                 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10079                         return false;
10080                 break;
10081
10082         case group_has_spare:
10083                 /* Select group with most idle CPUs */
10084                 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10085                         return false;
10086
10087                 /* Select group with lowest group_util */
10088                 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10089                         idlest_sgs->group_util <= sgs->group_util)
10090                         return false;
10091
10092                 break;
10093         }
10094
10095         return true;
10096 }
10097
10098 /*
10099  * find_idlest_group() finds and returns the least busy CPU group within the
10100  * domain.
10101  *
10102  * Assumes p is allowed on at least one CPU in sd.
10103  */
10104 static struct sched_group *
10105 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10106 {
10107         struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10108         struct sg_lb_stats local_sgs, tmp_sgs;
10109         struct sg_lb_stats *sgs;
10110         unsigned long imbalance;
10111         struct sg_lb_stats idlest_sgs = {
10112                         .avg_load = UINT_MAX,
10113                         .group_type = group_overloaded,
10114         };
10115
10116         do {
10117                 int local_group;
10118
10119                 /* Skip over this group if it has no CPUs allowed */
10120                 if (!cpumask_intersects(sched_group_span(group),
10121                                         p->cpus_ptr))
10122                         continue;
10123
10124                 /* Skip over this group if no cookie matched */
10125                 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10126                         continue;
10127
10128                 local_group = cpumask_test_cpu(this_cpu,
10129                                                sched_group_span(group));
10130
10131                 if (local_group) {
10132                         sgs = &local_sgs;
10133                         local = group;
10134                 } else {
10135                         sgs = &tmp_sgs;
10136                 }
10137
10138                 update_sg_wakeup_stats(sd, group, sgs, p);
10139
10140                 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10141                         idlest = group;
10142                         idlest_sgs = *sgs;
10143                 }
10144
10145         } while (group = group->next, group != sd->groups);
10146
10147
10148         /* There is no idlest group to push tasks to */
10149         if (!idlest)
10150                 return NULL;
10151
10152         /* The local group has been skipped because of CPU affinity */
10153         if (!local)
10154                 return idlest;
10155
10156         /*
10157          * If the local group is idler than the selected idlest group
10158          * don't try and push the task.
10159          */
10160         if (local_sgs.group_type < idlest_sgs.group_type)
10161                 return NULL;
10162
10163         /*
10164          * If the local group is busier than the selected idlest group
10165          * try and push the task.
10166          */
10167         if (local_sgs.group_type > idlest_sgs.group_type)
10168                 return idlest;
10169
10170         switch (local_sgs.group_type) {
10171         case group_overloaded:
10172         case group_fully_busy:
10173
10174                 /* Calculate allowed imbalance based on load */
10175                 imbalance = scale_load_down(NICE_0_LOAD) *
10176                                 (sd->imbalance_pct-100) / 100;
10177
10178                 /*
10179                  * When comparing groups across NUMA domains, it's possible for
10180                  * the local domain to be very lightly loaded relative to the
10181                  * remote domains but "imbalance" skews the comparison making
10182                  * remote CPUs look much more favourable. When considering
10183                  * cross-domain, add imbalance to the load on the remote node
10184                  * and consider staying local.
10185                  */
10186
10187                 if ((sd->flags & SD_NUMA) &&
10188                     ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10189                         return NULL;
10190
10191                 /*
10192                  * If the local group is less loaded than the selected
10193                  * idlest group don't try and push any tasks.
10194                  */
10195                 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10196                         return NULL;
10197
10198                 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10199                         return NULL;
10200                 break;
10201
10202         case group_imbalanced:
10203         case group_asym_packing:
10204         case group_smt_balance:
10205                 /* Those type are not used in the slow wakeup path */
10206                 return NULL;
10207
10208         case group_misfit_task:
10209                 /* Select group with the highest max capacity */
10210                 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10211                         return NULL;
10212                 break;
10213
10214         case group_has_spare:
10215 #ifdef CONFIG_NUMA
10216                 if (sd->flags & SD_NUMA) {
10217                         int imb_numa_nr = sd->imb_numa_nr;
10218 #ifdef CONFIG_NUMA_BALANCING
10219                         int idlest_cpu;
10220                         /*
10221                          * If there is spare capacity at NUMA, try to select
10222                          * the preferred node
10223                          */
10224                         if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10225                                 return NULL;
10226
10227                         idlest_cpu = cpumask_first(sched_group_span(idlest));
10228                         if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10229                                 return idlest;
10230 #endif /* CONFIG_NUMA_BALANCING */
10231                         /*
10232                          * Otherwise, keep the task close to the wakeup source
10233                          * and improve locality if the number of running tasks
10234                          * would remain below threshold where an imbalance is
10235                          * allowed while accounting for the possibility the
10236                          * task is pinned to a subset of CPUs. If there is a
10237                          * real need of migration, periodic load balance will
10238                          * take care of it.
10239                          */
10240                         if (p->nr_cpus_allowed != NR_CPUS) {
10241                                 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10242
10243                                 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10244                                 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10245                         }
10246
10247                         imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10248                         if (!adjust_numa_imbalance(imbalance,
10249                                                    local_sgs.sum_nr_running + 1,
10250                                                    imb_numa_nr)) {
10251                                 return NULL;
10252                         }
10253                 }
10254 #endif /* CONFIG_NUMA */
10255
10256                 /*
10257                  * Select group with highest number of idle CPUs. We could also
10258                  * compare the utilization which is more stable but it can end
10259                  * up that the group has less spare capacity but finally more
10260                  * idle CPUs which means more opportunity to run task.
10261                  */
10262                 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10263                         return NULL;
10264                 break;
10265         }
10266
10267         return idlest;
10268 }
10269
10270 static void update_idle_cpu_scan(struct lb_env *env,
10271                                  unsigned long sum_util)
10272 {
10273         struct sched_domain_shared *sd_share;
10274         int llc_weight, pct;
10275         u64 x, y, tmp;
10276         /*
10277          * Update the number of CPUs to scan in LLC domain, which could
10278          * be used as a hint in select_idle_cpu(). The update of sd_share
10279          * could be expensive because it is within a shared cache line.
10280          * So the write of this hint only occurs during periodic load
10281          * balancing, rather than CPU_NEWLY_IDLE, because the latter
10282          * can fire way more frequently than the former.
10283          */
10284         if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10285                 return;
10286
10287         llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10288         if (env->sd->span_weight != llc_weight)
10289                 return;
10290
10291         sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10292         if (!sd_share)
10293                 return;
10294
10295         /*
10296          * The number of CPUs to search drops as sum_util increases, when
10297          * sum_util hits 85% or above, the scan stops.
10298          * The reason to choose 85% as the threshold is because this is the
10299          * imbalance_pct(117) when a LLC sched group is overloaded.
10300          *
10301          * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
10302          * and y'= y / SCHED_CAPACITY_SCALE
10303          *
10304          * x is the ratio of sum_util compared to the CPU capacity:
10305          * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10306          * y' is the ratio of CPUs to be scanned in the LLC domain,
10307          * and the number of CPUs to scan is calculated by:
10308          *
10309          * nr_scan = llc_weight * y'                                    [2]
10310          *
10311          * When x hits the threshold of overloaded, AKA, when
10312          * x = 100 / pct, y drops to 0. According to [1],
10313          * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10314          *
10315          * Scale x by SCHED_CAPACITY_SCALE:
10316          * x' = sum_util / llc_weight;                                  [3]
10317          *
10318          * and finally [1] becomes:
10319          * y = SCHED_CAPACITY_SCALE -
10320          *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
10321          *
10322          */
10323         /* equation [3] */
10324         x = sum_util;
10325         do_div(x, llc_weight);
10326
10327         /* equation [4] */
10328         pct = env->sd->imbalance_pct;
10329         tmp = x * x * pct * pct;
10330         do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10331         tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10332         y = SCHED_CAPACITY_SCALE - tmp;
10333
10334         /* equation [2] */
10335         y *= llc_weight;
10336         do_div(y, SCHED_CAPACITY_SCALE);
10337         if ((int)y != sd_share->nr_idle_scan)
10338                 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10339 }
10340
10341 /**
10342  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10343  * @env: The load balancing environment.
10344  * @sds: variable to hold the statistics for this sched_domain.
10345  */
10346
10347 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10348 {
10349         struct sched_group *sg = env->sd->groups;
10350         struct sg_lb_stats *local = &sds->local_stat;
10351         struct sg_lb_stats tmp_sgs;
10352         unsigned long sum_util = 0;
10353         int sg_status = 0;
10354
10355         do {
10356                 struct sg_lb_stats *sgs = &tmp_sgs;
10357                 int local_group;
10358
10359                 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10360                 if (local_group) {
10361                         sds->local = sg;
10362                         sgs = local;
10363
10364                         if (env->idle != CPU_NEWLY_IDLE ||
10365                             time_after_eq(jiffies, sg->sgc->next_update))
10366                                 update_group_capacity(env->sd, env->dst_cpu);
10367                 }
10368
10369                 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10370
10371                 if (local_group)
10372                         goto next_group;
10373
10374
10375                 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10376                         sds->busiest = sg;
10377                         sds->busiest_stat = *sgs;
10378                 }
10379
10380 next_group:
10381                 /* Now, start updating sd_lb_stats */
10382                 sds->total_load += sgs->group_load;
10383                 sds->total_capacity += sgs->group_capacity;
10384
10385                 sum_util += sgs->group_util;
10386                 sg = sg->next;
10387         } while (sg != env->sd->groups);
10388
10389         /*
10390          * Indicate that the child domain of the busiest group prefers tasks
10391          * go to a child's sibling domains first. NB the flags of a sched group
10392          * are those of the child domain.
10393          */
10394         if (sds->busiest)
10395                 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10396
10397
10398         if (env->sd->flags & SD_NUMA)
10399                 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10400
10401         if (!env->sd->parent) {
10402                 struct root_domain *rd = env->dst_rq->rd;
10403
10404                 /* update overload indicator if we are at root domain */
10405                 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10406
10407                 /* Update over-utilization (tipping point, U >= 0) indicator */
10408                 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10409                 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10410         } else if (sg_status & SG_OVERUTILIZED) {
10411                 struct root_domain *rd = env->dst_rq->rd;
10412
10413                 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10414                 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10415         }
10416
10417         update_idle_cpu_scan(env, sum_util);
10418 }
10419
10420 /**
10421  * calculate_imbalance - Calculate the amount of imbalance present within the
10422  *                       groups of a given sched_domain during load balance.
10423  * @env: load balance environment
10424  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10425  */
10426 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10427 {
10428         struct sg_lb_stats *local, *busiest;
10429
10430         local = &sds->local_stat;
10431         busiest = &sds->busiest_stat;
10432
10433         if (busiest->group_type == group_misfit_task) {
10434                 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10435                         /* Set imbalance to allow misfit tasks to be balanced. */
10436                         env->migration_type = migrate_misfit;
10437                         env->imbalance = 1;
10438                 } else {
10439                         /*
10440                          * Set load imbalance to allow moving task from cpu
10441                          * with reduced capacity.
10442                          */
10443                         env->migration_type = migrate_load;
10444                         env->imbalance = busiest->group_misfit_task_load;
10445                 }
10446                 return;
10447         }
10448
10449         if (busiest->group_type == group_asym_packing) {
10450                 /*
10451                  * In case of asym capacity, we will try to migrate all load to
10452                  * the preferred CPU.
10453                  */
10454                 env->migration_type = migrate_task;
10455                 env->imbalance = busiest->sum_h_nr_running;
10456                 return;
10457         }
10458
10459         if (busiest->group_type == group_smt_balance) {
10460                 /* Reduce number of tasks sharing CPU capacity */
10461                 env->migration_type = migrate_task;
10462                 env->imbalance = 1;
10463                 return;
10464         }
10465
10466         if (busiest->group_type == group_imbalanced) {
10467                 /*
10468                  * In the group_imb case we cannot rely on group-wide averages
10469                  * to ensure CPU-load equilibrium, try to move any task to fix
10470                  * the imbalance. The next load balance will take care of
10471                  * balancing back the system.
10472                  */
10473                 env->migration_type = migrate_task;
10474                 env->imbalance = 1;
10475                 return;
10476         }
10477
10478         /*
10479          * Try to use spare capacity of local group without overloading it or
10480          * emptying busiest.
10481          */
10482         if (local->group_type == group_has_spare) {
10483                 if ((busiest->group_type > group_fully_busy) &&
10484                     !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10485                         /*
10486                          * If busiest is overloaded, try to fill spare
10487                          * capacity. This might end up creating spare capacity
10488                          * in busiest or busiest still being overloaded but
10489                          * there is no simple way to directly compute the
10490                          * amount of load to migrate in order to balance the
10491                          * system.
10492                          */
10493                         env->migration_type = migrate_util;
10494                         env->imbalance = max(local->group_capacity, local->group_util) -
10495                                          local->group_util;
10496
10497                         /*
10498                          * In some cases, the group's utilization is max or even
10499                          * higher than capacity because of migrations but the
10500                          * local CPU is (newly) idle. There is at least one
10501                          * waiting task in this overloaded busiest group. Let's
10502                          * try to pull it.
10503                          */
10504                         if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10505                                 env->migration_type = migrate_task;
10506                                 env->imbalance = 1;
10507                         }
10508
10509                         return;
10510                 }
10511
10512                 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10513                         /*
10514                          * When prefer sibling, evenly spread running tasks on
10515                          * groups.
10516                          */
10517                         env->migration_type = migrate_task;
10518                         env->imbalance = sibling_imbalance(env, sds, busiest, local);
10519                 } else {
10520
10521                         /*
10522                          * If there is no overload, we just want to even the number of
10523                          * idle cpus.
10524                          */
10525                         env->migration_type = migrate_task;
10526                         env->imbalance = max_t(long, 0,
10527                                                (local->idle_cpus - busiest->idle_cpus));
10528                 }
10529
10530 #ifdef CONFIG_NUMA
10531                 /* Consider allowing a small imbalance between NUMA groups */
10532                 if (env->sd->flags & SD_NUMA) {
10533                         env->imbalance = adjust_numa_imbalance(env->imbalance,
10534                                                                local->sum_nr_running + 1,
10535                                                                env->sd->imb_numa_nr);
10536                 }
10537 #endif
10538
10539                 /* Number of tasks to move to restore balance */
10540                 env->imbalance >>= 1;
10541
10542                 return;
10543         }
10544
10545         /*
10546          * Local is fully busy but has to take more load to relieve the
10547          * busiest group
10548          */
10549         if (local->group_type < group_overloaded) {
10550                 /*
10551                  * Local will become overloaded so the avg_load metrics are
10552                  * finally needed.
10553                  */
10554
10555                 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10556                                   local->group_capacity;
10557
10558                 /*
10559                  * If the local group is more loaded than the selected
10560                  * busiest group don't try to pull any tasks.
10561                  */
10562                 if (local->avg_load >= busiest->avg_load) {
10563                         env->imbalance = 0;
10564                         return;
10565                 }
10566
10567                 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10568                                 sds->total_capacity;
10569
10570                 /*
10571                  * If the local group is more loaded than the average system
10572                  * load, don't try to pull any tasks.
10573                  */
10574                 if (local->avg_load >= sds->avg_load) {
10575                         env->imbalance = 0;
10576                         return;
10577                 }
10578
10579         }
10580
10581         /*
10582          * Both group are or will become overloaded and we're trying to get all
10583          * the CPUs to the average_load, so we don't want to push ourselves
10584          * above the average load, nor do we wish to reduce the max loaded CPU
10585          * below the average load. At the same time, we also don't want to
10586          * reduce the group load below the group capacity. Thus we look for
10587          * the minimum possible imbalance.
10588          */
10589         env->migration_type = migrate_load;
10590         env->imbalance = min(
10591                 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10592                 (sds->avg_load - local->avg_load) * local->group_capacity
10593         ) / SCHED_CAPACITY_SCALE;
10594 }
10595
10596 /******* find_busiest_group() helpers end here *********************/
10597
10598 /*
10599  * Decision matrix according to the local and busiest group type:
10600  *
10601  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10602  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
10603  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
10604  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
10605  * asym_packing     force     force      N/A    N/A  force      force
10606  * imbalanced       force     force      N/A    N/A  force      force
10607  * overloaded       force     force      N/A    N/A  force      avg_load
10608  *
10609  * N/A :      Not Applicable because already filtered while updating
10610  *            statistics.
10611  * balanced : The system is balanced for these 2 groups.
10612  * force :    Calculate the imbalance as load migration is probably needed.
10613  * avg_load : Only if imbalance is significant enough.
10614  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
10615  *            different in groups.
10616  */
10617
10618 /**
10619  * find_busiest_group - Returns the busiest group within the sched_domain
10620  * if there is an imbalance.
10621  * @env: The load balancing environment.
10622  *
10623  * Also calculates the amount of runnable load which should be moved
10624  * to restore balance.
10625  *
10626  * Return:      - The busiest group if imbalance exists.
10627  */
10628 static struct sched_group *find_busiest_group(struct lb_env *env)
10629 {
10630         struct sg_lb_stats *local, *busiest;
10631         struct sd_lb_stats sds;
10632
10633         init_sd_lb_stats(&sds);
10634
10635         /*
10636          * Compute the various statistics relevant for load balancing at
10637          * this level.
10638          */
10639         update_sd_lb_stats(env, &sds);
10640
10641         /* There is no busy sibling group to pull tasks from */
10642         if (!sds.busiest)
10643                 goto out_balanced;
10644
10645         busiest = &sds.busiest_stat;
10646
10647         /* Misfit tasks should be dealt with regardless of the avg load */
10648         if (busiest->group_type == group_misfit_task)
10649                 goto force_balance;
10650
10651         if (sched_energy_enabled()) {
10652                 struct root_domain *rd = env->dst_rq->rd;
10653
10654                 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10655                         goto out_balanced;
10656         }
10657
10658         /* ASYM feature bypasses nice load balance check */
10659         if (busiest->group_type == group_asym_packing)
10660                 goto force_balance;
10661
10662         /*
10663          * If the busiest group is imbalanced the below checks don't
10664          * work because they assume all things are equal, which typically
10665          * isn't true due to cpus_ptr constraints and the like.
10666          */
10667         if (busiest->group_type == group_imbalanced)
10668                 goto force_balance;
10669
10670         local = &sds.local_stat;
10671         /*
10672          * If the local group is busier than the selected busiest group
10673          * don't try and pull any tasks.
10674          */
10675         if (local->group_type > busiest->group_type)
10676                 goto out_balanced;
10677
10678         /*
10679          * When groups are overloaded, use the avg_load to ensure fairness
10680          * between tasks.
10681          */
10682         if (local->group_type == group_overloaded) {
10683                 /*
10684                  * If the local group is more loaded than the selected
10685                  * busiest group don't try to pull any tasks.
10686                  */
10687                 if (local->avg_load >= busiest->avg_load)
10688                         goto out_balanced;
10689
10690                 /* XXX broken for overlapping NUMA groups */
10691                 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10692                                 sds.total_capacity;
10693
10694                 /*
10695                  * Don't pull any tasks if this group is already above the
10696                  * domain average load.
10697                  */
10698                 if (local->avg_load >= sds.avg_load)
10699                         goto out_balanced;
10700
10701                 /*
10702                  * If the busiest group is more loaded, use imbalance_pct to be
10703                  * conservative.
10704                  */
10705                 if (100 * busiest->avg_load <=
10706                                 env->sd->imbalance_pct * local->avg_load)
10707                         goto out_balanced;
10708         }
10709
10710         /*
10711          * Try to move all excess tasks to a sibling domain of the busiest
10712          * group's child domain.
10713          */
10714         if (sds.prefer_sibling && local->group_type == group_has_spare &&
10715             sibling_imbalance(env, &sds, busiest, local) > 1)
10716                 goto force_balance;
10717
10718         if (busiest->group_type != group_overloaded) {
10719                 if (env->idle == CPU_NOT_IDLE) {
10720                         /*
10721                          * If the busiest group is not overloaded (and as a
10722                          * result the local one too) but this CPU is already
10723                          * busy, let another idle CPU try to pull task.
10724                          */
10725                         goto out_balanced;
10726                 }
10727
10728                 if (busiest->group_type == group_smt_balance &&
10729                     smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10730                         /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10731                         goto force_balance;
10732                 }
10733
10734                 if (busiest->group_weight > 1 &&
10735                     local->idle_cpus <= (busiest->idle_cpus + 1)) {
10736                         /*
10737                          * If the busiest group is not overloaded
10738                          * and there is no imbalance between this and busiest
10739                          * group wrt idle CPUs, it is balanced. The imbalance
10740                          * becomes significant if the diff is greater than 1
10741                          * otherwise we might end up to just move the imbalance
10742                          * on another group. Of course this applies only if
10743                          * there is more than 1 CPU per group.
10744                          */
10745                         goto out_balanced;
10746                 }
10747
10748                 if (busiest->sum_h_nr_running == 1) {
10749                         /*
10750                          * busiest doesn't have any tasks waiting to run
10751                          */
10752                         goto out_balanced;
10753                 }
10754         }
10755
10756 force_balance:
10757         /* Looks like there is an imbalance. Compute it */
10758         calculate_imbalance(env, &sds);
10759         return env->imbalance ? sds.busiest : NULL;
10760
10761 out_balanced:
10762         env->imbalance = 0;
10763         return NULL;
10764 }
10765
10766 /*
10767  * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
10768  */
10769 static struct rq *find_busiest_queue(struct lb_env *env,
10770                                      struct sched_group *group)
10771 {
10772         struct rq *busiest = NULL, *rq;
10773         unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
10774         unsigned int busiest_nr = 0;
10775         int i;
10776
10777         for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10778                 unsigned long capacity, load, util;
10779                 unsigned int nr_running;
10780                 enum fbq_type rt;
10781
10782                 rq = cpu_rq(i);
10783                 rt = fbq_classify_rq(rq);
10784
10785                 /*
10786                  * We classify groups/runqueues into three groups:
10787                  *  - regular: there are !numa tasks
10788                  *  - remote:  there are numa tasks that run on the 'wrong' node
10789                  *  - all:     there is no distinction
10790                  *
10791                  * In order to avoid migrating ideally placed numa tasks,
10792                  * ignore those when there's better options.
10793                  *
10794                  * If we ignore the actual busiest queue to migrate another
10795                  * task, the next balance pass can still reduce the busiest
10796                  * queue by moving tasks around inside the node.
10797                  *
10798                  * If we cannot move enough load due to this classification
10799                  * the next pass will adjust the group classification and
10800                  * allow migration of more tasks.
10801                  *
10802                  * Both cases only affect the total convergence complexity.
10803                  */
10804                 if (rt > env->fbq_type)
10805                         continue;
10806
10807                 nr_running = rq->cfs.h_nr_running;
10808                 if (!nr_running)
10809                         continue;
10810
10811                 capacity = capacity_of(i);
10812
10813                 /*
10814                  * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
10815                  * eventually lead to active_balancing high->low capacity.
10816                  * Higher per-CPU capacity is considered better than balancing
10817                  * average load.
10818                  */
10819                 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
10820                     !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
10821                     nr_running == 1)
10822                         continue;
10823
10824                 /*
10825                  * Make sure we only pull tasks from a CPU of lower priority
10826                  * when balancing between SMT siblings.
10827                  *
10828                  * If balancing between cores, let lower priority CPUs help
10829                  * SMT cores with more than one busy sibling.
10830                  */
10831                 if ((env->sd->flags & SD_ASYM_PACKING) &&
10832                     sched_use_asym_prio(env->sd, i) &&
10833                     sched_asym_prefer(i, env->dst_cpu) &&
10834                     nr_running == 1)
10835                         continue;
10836
10837                 switch (env->migration_type) {
10838                 case migrate_load:
10839                         /*
10840                          * When comparing with load imbalance, use cpu_load()
10841                          * which is not scaled with the CPU capacity.
10842                          */
10843                         load = cpu_load(rq);
10844
10845                         if (nr_running == 1 && load > env->imbalance &&
10846                             !check_cpu_capacity(rq, env->sd))
10847                                 break;
10848
10849                         /*
10850                          * For the load comparisons with the other CPUs,
10851                          * consider the cpu_load() scaled with the CPU
10852                          * capacity, so that the load can be moved away
10853                          * from the CPU that is potentially running at a
10854                          * lower capacity.
10855                          *
10856                          * Thus we're looking for max(load_i / capacity_i),
10857                          * crosswise multiplication to rid ourselves of the
10858                          * division works out to:
10859                          * load_i * capacity_j > load_j * capacity_i;
10860                          * where j is our previous maximum.
10861                          */
10862                         if (load * busiest_capacity > busiest_load * capacity) {
10863                                 busiest_load = load;
10864                                 busiest_capacity = capacity;
10865                                 busiest = rq;
10866                         }
10867                         break;
10868
10869                 case migrate_util:
10870                         util = cpu_util_cfs_boost(i);
10871
10872                         /*
10873                          * Don't try to pull utilization from a CPU with one
10874                          * running task. Whatever its utilization, we will fail
10875                          * detach the task.
10876                          */
10877                         if (nr_running <= 1)
10878                                 continue;
10879
10880                         if (busiest_util < util) {
10881                                 busiest_util = util;
10882                                 busiest = rq;
10883                         }
10884                         break;
10885
10886                 case migrate_task:
10887                         if (busiest_nr < nr_running) {
10888                                 busiest_nr = nr_running;
10889                                 busiest = rq;
10890                         }
10891                         break;
10892
10893                 case migrate_misfit:
10894                         /*
10895                          * For ASYM_CPUCAPACITY domains with misfit tasks we
10896                          * simply seek the "biggest" misfit task.
10897                          */
10898                         if (rq->misfit_task_load > busiest_load) {
10899                                 busiest_load = rq->misfit_task_load;
10900                                 busiest = rq;
10901                         }
10902
10903                         break;
10904
10905                 }
10906         }
10907
10908         return busiest;
10909 }
10910
10911 /*
10912  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
10913  * so long as it is large enough.
10914  */
10915 #define MAX_PINNED_INTERVAL     512
10916
10917 static inline bool
10918 asym_active_balance(struct lb_env *env)
10919 {
10920         /*
10921          * ASYM_PACKING needs to force migrate tasks from busy but lower
10922          * priority CPUs in order to pack all tasks in the highest priority
10923          * CPUs. When done between cores, do it only if the whole core if the
10924          * whole core is idle.
10925          *
10926          * If @env::src_cpu is an SMT core with busy siblings, let
10927          * the lower priority @env::dst_cpu help it. Do not follow
10928          * CPU priority.
10929          */
10930         return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
10931                sched_use_asym_prio(env->sd, env->dst_cpu) &&
10932                (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
10933                 !sched_use_asym_prio(env->sd, env->src_cpu));
10934 }
10935
10936 static inline bool
10937 imbalanced_active_balance(struct lb_env *env)
10938 {
10939         struct sched_domain *sd = env->sd;
10940
10941         /*
10942          * The imbalanced case includes the case of pinned tasks preventing a fair
10943          * distribution of the load on the system but also the even distribution of the
10944          * threads on a system with spare capacity
10945          */
10946         if ((env->migration_type == migrate_task) &&
10947             (sd->nr_balance_failed > sd->cache_nice_tries+2))
10948                 return 1;
10949
10950         return 0;
10951 }
10952
10953 static int need_active_balance(struct lb_env *env)
10954 {
10955         struct sched_domain *sd = env->sd;
10956
10957         if (asym_active_balance(env))
10958                 return 1;
10959
10960         if (imbalanced_active_balance(env))
10961                 return 1;
10962
10963         /*
10964          * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
10965          * It's worth migrating the task if the src_cpu's capacity is reduced
10966          * because of other sched_class or IRQs if more capacity stays
10967          * available on dst_cpu.
10968          */
10969         if ((env->idle != CPU_NOT_IDLE) &&
10970             (env->src_rq->cfs.h_nr_running == 1)) {
10971                 if ((check_cpu_capacity(env->src_rq, sd)) &&
10972                     (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
10973                         return 1;
10974         }
10975
10976         if (env->migration_type == migrate_misfit)
10977                 return 1;
10978
10979         return 0;
10980 }
10981
10982 static int active_load_balance_cpu_stop(void *data);
10983
10984 static int should_we_balance(struct lb_env *env)
10985 {
10986         struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
10987         struct sched_group *sg = env->sd->groups;
10988         int cpu, idle_smt = -1;
10989
10990         /*
10991          * Ensure the balancing environment is consistent; can happen
10992          * when the softirq triggers 'during' hotplug.
10993          */
10994         if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
10995                 return 0;
10996
10997         /*
10998          * In the newly idle case, we will allow all the CPUs
10999          * to do the newly idle load balance.
11000          *
11001          * However, we bail out if we already have tasks or a wakeup pending,
11002          * to optimize wakeup latency.
11003          */
11004         if (env->idle == CPU_NEWLY_IDLE) {
11005                 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11006                         return 0;
11007                 return 1;
11008         }
11009
11010         cpumask_copy(swb_cpus, group_balance_mask(sg));
11011         /* Try to find first idle CPU */
11012         for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11013                 if (!idle_cpu(cpu))
11014                         continue;
11015
11016                 /*
11017                  * Don't balance to idle SMT in busy core right away when
11018                  * balancing cores, but remember the first idle SMT CPU for
11019                  * later consideration.  Find CPU on an idle core first.
11020                  */
11021                 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11022                         if (idle_smt == -1)
11023                                 idle_smt = cpu;
11024                         /*
11025                          * If the core is not idle, and first SMT sibling which is
11026                          * idle has been found, then its not needed to check other
11027                          * SMT siblings for idleness:
11028                          */
11029 #ifdef CONFIG_SCHED_SMT
11030                         cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11031 #endif
11032                         continue;
11033                 }
11034
11035                 /* Are we the first idle CPU? */
11036                 return cpu == env->dst_cpu;
11037         }
11038
11039         if (idle_smt == env->dst_cpu)
11040                 return true;
11041
11042         /* Are we the first CPU of this group ? */
11043         return group_balance_cpu(sg) == env->dst_cpu;
11044 }
11045
11046 /*
11047  * Check this_cpu to ensure it is balanced within domain. Attempt to move
11048  * tasks if there is an imbalance.
11049  */
11050 static int load_balance(int this_cpu, struct rq *this_rq,
11051                         struct sched_domain *sd, enum cpu_idle_type idle,
11052                         int *continue_balancing)
11053 {
11054         int ld_moved, cur_ld_moved, active_balance = 0;
11055         struct sched_domain *sd_parent = sd->parent;
11056         struct sched_group *group;
11057         struct rq *busiest;
11058         struct rq_flags rf;
11059         struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11060         struct lb_env env = {
11061                 .sd             = sd,
11062                 .dst_cpu        = this_cpu,
11063                 .dst_rq         = this_rq,
11064                 .dst_grpmask    = group_balance_mask(sd->groups),
11065                 .idle           = idle,
11066                 .loop_break     = SCHED_NR_MIGRATE_BREAK,
11067                 .cpus           = cpus,
11068                 .fbq_type       = all,
11069                 .tasks          = LIST_HEAD_INIT(env.tasks),
11070         };
11071
11072         cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11073
11074         schedstat_inc(sd->lb_count[idle]);
11075
11076 redo:
11077         if (!should_we_balance(&env)) {
11078                 *continue_balancing = 0;
11079                 goto out_balanced;
11080         }
11081
11082         group = find_busiest_group(&env);
11083         if (!group) {
11084                 schedstat_inc(sd->lb_nobusyg[idle]);
11085                 goto out_balanced;
11086         }
11087
11088         busiest = find_busiest_queue(&env, group);
11089         if (!busiest) {
11090                 schedstat_inc(sd->lb_nobusyq[idle]);
11091                 goto out_balanced;
11092         }
11093
11094         WARN_ON_ONCE(busiest == env.dst_rq);
11095
11096         schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11097
11098         env.src_cpu = busiest->cpu;
11099         env.src_rq = busiest;
11100
11101         ld_moved = 0;
11102         /* Clear this flag as soon as we find a pullable task */
11103         env.flags |= LBF_ALL_PINNED;
11104         if (busiest->nr_running > 1) {
11105                 /*
11106                  * Attempt to move tasks. If find_busiest_group has found
11107                  * an imbalance but busiest->nr_running <= 1, the group is
11108                  * still unbalanced. ld_moved simply stays zero, so it is
11109                  * correctly treated as an imbalance.
11110                  */
11111                 env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
11112
11113 more_balance:
11114                 rq_lock_irqsave(busiest, &rf);
11115                 update_rq_clock(busiest);
11116
11117                 /*
11118                  * cur_ld_moved - load moved in current iteration
11119                  * ld_moved     - cumulative load moved across iterations
11120                  */
11121                 cur_ld_moved = detach_tasks(&env);
11122
11123                 /*
11124                  * We've detached some tasks from busiest_rq. Every
11125                  * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11126                  * unlock busiest->lock, and we are able to be sure
11127                  * that nobody can manipulate the tasks in parallel.
11128                  * See task_rq_lock() family for the details.
11129                  */
11130
11131                 rq_unlock(busiest, &rf);
11132
11133                 if (cur_ld_moved) {
11134                         attach_tasks(&env);
11135                         ld_moved += cur_ld_moved;
11136                 }
11137
11138                 local_irq_restore(rf.flags);
11139
11140                 if (env.flags & LBF_NEED_BREAK) {
11141                         env.flags &= ~LBF_NEED_BREAK;
11142                         /* Stop if we tried all running tasks */
11143                         if (env.loop < busiest->nr_running)
11144                                 goto more_balance;
11145                 }
11146
11147                 /*
11148                  * Revisit (affine) tasks on src_cpu that couldn't be moved to
11149                  * us and move them to an alternate dst_cpu in our sched_group
11150                  * where they can run. The upper limit on how many times we
11151                  * iterate on same src_cpu is dependent on number of CPUs in our
11152                  * sched_group.
11153                  *
11154                  * This changes load balance semantics a bit on who can move
11155                  * load to a given_cpu. In addition to the given_cpu itself
11156                  * (or a ilb_cpu acting on its behalf where given_cpu is
11157                  * nohz-idle), we now have balance_cpu in a position to move
11158                  * load to given_cpu. In rare situations, this may cause
11159                  * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11160                  * _independently_ and at _same_ time to move some load to
11161                  * given_cpu) causing excess load to be moved to given_cpu.
11162                  * This however should not happen so much in practice and
11163                  * moreover subsequent load balance cycles should correct the
11164                  * excess load moved.
11165                  */
11166                 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11167
11168                         /* Prevent to re-select dst_cpu via env's CPUs */
11169                         __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11170
11171                         env.dst_rq       = cpu_rq(env.new_dst_cpu);
11172                         env.dst_cpu      = env.new_dst_cpu;
11173                         env.flags       &= ~LBF_DST_PINNED;
11174                         env.loop         = 0;
11175                         env.loop_break   = SCHED_NR_MIGRATE_BREAK;
11176
11177                         /*
11178                          * Go back to "more_balance" rather than "redo" since we
11179                          * need to continue with same src_cpu.
11180                          */
11181                         goto more_balance;
11182                 }
11183
11184                 /*
11185                  * We failed to reach balance because of affinity.
11186                  */
11187                 if (sd_parent) {
11188                         int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11189
11190                         if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11191                                 *group_imbalance = 1;
11192                 }
11193
11194                 /* All tasks on this runqueue were pinned by CPU affinity */
11195                 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11196                         __cpumask_clear_cpu(cpu_of(busiest), cpus);
11197                         /*
11198                          * Attempting to continue load balancing at the current
11199                          * sched_domain level only makes sense if there are
11200                          * active CPUs remaining as possible busiest CPUs to
11201                          * pull load from which are not contained within the
11202                          * destination group that is receiving any migrated
11203                          * load.
11204                          */
11205                         if (!cpumask_subset(cpus, env.dst_grpmask)) {
11206                                 env.loop = 0;
11207                                 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11208                                 goto redo;
11209                         }
11210                         goto out_all_pinned;
11211                 }
11212         }
11213
11214         if (!ld_moved) {
11215                 schedstat_inc(sd->lb_failed[idle]);
11216                 /*
11217                  * Increment the failure counter only on periodic balance.
11218                  * We do not want newidle balance, which can be very
11219                  * frequent, pollute the failure counter causing
11220                  * excessive cache_hot migrations and active balances.
11221                  */
11222                 if (idle != CPU_NEWLY_IDLE)
11223                         sd->nr_balance_failed++;
11224
11225                 if (need_active_balance(&env)) {
11226                         unsigned long flags;
11227
11228                         raw_spin_rq_lock_irqsave(busiest, flags);
11229
11230                         /*
11231                          * Don't kick the active_load_balance_cpu_stop,
11232                          * if the curr task on busiest CPU can't be
11233                          * moved to this_cpu:
11234                          */
11235                         if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11236                                 raw_spin_rq_unlock_irqrestore(busiest, flags);
11237                                 goto out_one_pinned;
11238                         }
11239
11240                         /* Record that we found at least one task that could run on this_cpu */
11241                         env.flags &= ~LBF_ALL_PINNED;
11242
11243                         /*
11244                          * ->active_balance synchronizes accesses to
11245                          * ->active_balance_work.  Once set, it's cleared
11246                          * only after active load balance is finished.
11247                          */
11248                         if (!busiest->active_balance) {
11249                                 busiest->active_balance = 1;
11250                                 busiest->push_cpu = this_cpu;
11251                                 active_balance = 1;
11252                         }
11253                         raw_spin_rq_unlock_irqrestore(busiest, flags);
11254
11255                         if (active_balance) {
11256                                 stop_one_cpu_nowait(cpu_of(busiest),
11257                                         active_load_balance_cpu_stop, busiest,
11258                                         &busiest->active_balance_work);
11259                         }
11260                 }
11261         } else {
11262                 sd->nr_balance_failed = 0;
11263         }
11264
11265         if (likely(!active_balance) || need_active_balance(&env)) {
11266                 /* We were unbalanced, so reset the balancing interval */
11267                 sd->balance_interval = sd->min_interval;
11268         }
11269
11270         goto out;
11271
11272 out_balanced:
11273         /*
11274          * We reach balance although we may have faced some affinity
11275          * constraints. Clear the imbalance flag only if other tasks got
11276          * a chance to move and fix the imbalance.
11277          */
11278         if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11279                 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11280
11281                 if (*group_imbalance)
11282                         *group_imbalance = 0;
11283         }
11284
11285 out_all_pinned:
11286         /*
11287          * We reach balance because all tasks are pinned at this level so
11288          * we can't migrate them. Let the imbalance flag set so parent level
11289          * can try to migrate them.
11290          */
11291         schedstat_inc(sd->lb_balanced[idle]);
11292
11293         sd->nr_balance_failed = 0;
11294
11295 out_one_pinned:
11296         ld_moved = 0;
11297
11298         /*
11299          * newidle_balance() disregards balance intervals, so we could
11300          * repeatedly reach this code, which would lead to balance_interval
11301          * skyrocketing in a short amount of time. Skip the balance_interval
11302          * increase logic to avoid that.
11303          */
11304         if (env.idle == CPU_NEWLY_IDLE)
11305                 goto out;
11306
11307         /* tune up the balancing interval */
11308         if ((env.flags & LBF_ALL_PINNED &&
11309              sd->balance_interval < MAX_PINNED_INTERVAL) ||
11310             sd->balance_interval < sd->max_interval)
11311                 sd->balance_interval *= 2;
11312 out:
11313         return ld_moved;
11314 }
11315
11316 static inline unsigned long
11317 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11318 {
11319         unsigned long interval = sd->balance_interval;
11320
11321         if (cpu_busy)
11322                 interval *= sd->busy_factor;
11323
11324         /* scale ms to jiffies */
11325         interval = msecs_to_jiffies(interval);
11326
11327         /*
11328          * Reduce likelihood of busy balancing at higher domains racing with
11329          * balancing at lower domains by preventing their balancing periods
11330          * from being multiples of each other.
11331          */
11332         if (cpu_busy)
11333                 interval -= 1;
11334
11335         interval = clamp(interval, 1UL, max_load_balance_interval);
11336
11337         return interval;
11338 }
11339
11340 static inline void
11341 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11342 {
11343         unsigned long interval, next;
11344
11345         /* used by idle balance, so cpu_busy = 0 */
11346         interval = get_sd_balance_interval(sd, 0);
11347         next = sd->last_balance + interval;
11348
11349         if (time_after(*next_balance, next))
11350                 *next_balance = next;
11351 }
11352
11353 /*
11354  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11355  * running tasks off the busiest CPU onto idle CPUs. It requires at
11356  * least 1 task to be running on each physical CPU where possible, and
11357  * avoids physical / logical imbalances.
11358  */
11359 static int active_load_balance_cpu_stop(void *data)
11360 {
11361         struct rq *busiest_rq = data;
11362         int busiest_cpu = cpu_of(busiest_rq);
11363         int target_cpu = busiest_rq->push_cpu;
11364         struct rq *target_rq = cpu_rq(target_cpu);
11365         struct sched_domain *sd;
11366         struct task_struct *p = NULL;
11367         struct rq_flags rf;
11368
11369         rq_lock_irq(busiest_rq, &rf);
11370         /*
11371          * Between queueing the stop-work and running it is a hole in which
11372          * CPUs can become inactive. We should not move tasks from or to
11373          * inactive CPUs.
11374          */
11375         if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11376                 goto out_unlock;
11377
11378         /* Make sure the requested CPU hasn't gone down in the meantime: */
11379         if (unlikely(busiest_cpu != smp_processor_id() ||
11380                      !busiest_rq->active_balance))
11381                 goto out_unlock;
11382
11383         /* Is there any task to move? */
11384         if (busiest_rq->nr_running <= 1)
11385                 goto out_unlock;
11386
11387         /*
11388          * This condition is "impossible", if it occurs
11389          * we need to fix it. Originally reported by
11390          * Bjorn Helgaas on a 128-CPU setup.
11391          */
11392         WARN_ON_ONCE(busiest_rq == target_rq);
11393
11394         /* Search for an sd spanning us and the target CPU. */
11395         rcu_read_lock();
11396         for_each_domain(target_cpu, sd) {
11397                 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11398                         break;
11399         }
11400
11401         if (likely(sd)) {
11402                 struct lb_env env = {
11403                         .sd             = sd,
11404                         .dst_cpu        = target_cpu,
11405                         .dst_rq         = target_rq,
11406                         .src_cpu        = busiest_rq->cpu,
11407                         .src_rq         = busiest_rq,
11408                         .idle           = CPU_IDLE,
11409                         .flags          = LBF_ACTIVE_LB,
11410                 };
11411
11412                 schedstat_inc(sd->alb_count);
11413                 update_rq_clock(busiest_rq);
11414
11415                 p = detach_one_task(&env);
11416                 if (p) {
11417                         schedstat_inc(sd->alb_pushed);
11418                         /* Active balancing done, reset the failure counter. */
11419                         sd->nr_balance_failed = 0;
11420                 } else {
11421                         schedstat_inc(sd->alb_failed);
11422                 }
11423         }
11424         rcu_read_unlock();
11425 out_unlock:
11426         busiest_rq->active_balance = 0;
11427         rq_unlock(busiest_rq, &rf);
11428
11429         if (p)
11430                 attach_one_task(target_rq, p);
11431
11432         local_irq_enable();
11433
11434         return 0;
11435 }
11436
11437 static DEFINE_SPINLOCK(balancing);
11438
11439 /*
11440  * Scale the max load_balance interval with the number of CPUs in the system.
11441  * This trades load-balance latency on larger machines for less cross talk.
11442  */
11443 void update_max_interval(void)
11444 {
11445         max_load_balance_interval = HZ*num_online_cpus()/10;
11446 }
11447
11448 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11449 {
11450         if (cost > sd->max_newidle_lb_cost) {
11451                 /*
11452                  * Track max cost of a domain to make sure to not delay the
11453                  * next wakeup on the CPU.
11454                  */
11455                 sd->max_newidle_lb_cost = cost;
11456                 sd->last_decay_max_lb_cost = jiffies;
11457         } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11458                 /*
11459                  * Decay the newidle max times by ~1% per second to ensure that
11460                  * it is not outdated and the current max cost is actually
11461                  * shorter.
11462                  */
11463                 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11464                 sd->last_decay_max_lb_cost = jiffies;
11465
11466                 return true;
11467         }
11468
11469         return false;
11470 }
11471
11472 /*
11473  * It checks each scheduling domain to see if it is due to be balanced,
11474  * and initiates a balancing operation if so.
11475  *
11476  * Balancing parameters are set up in init_sched_domains.
11477  */
11478 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11479 {
11480         int continue_balancing = 1;
11481         int cpu = rq->cpu;
11482         int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11483         unsigned long interval;
11484         struct sched_domain *sd;
11485         /* Earliest time when we have to do rebalance again */
11486         unsigned long next_balance = jiffies + 60*HZ;
11487         int update_next_balance = 0;
11488         int need_serialize, need_decay = 0;
11489         u64 max_cost = 0;
11490
11491         rcu_read_lock();
11492         for_each_domain(cpu, sd) {
11493                 /*
11494                  * Decay the newidle max times here because this is a regular
11495                  * visit to all the domains.
11496                  */
11497                 need_decay = update_newidle_cost(sd, 0);
11498                 max_cost += sd->max_newidle_lb_cost;
11499
11500                 /*
11501                  * Stop the load balance at this level. There is another
11502                  * CPU in our sched group which is doing load balancing more
11503                  * actively.
11504                  */
11505                 if (!continue_balancing) {
11506                         if (need_decay)
11507                                 continue;
11508                         break;
11509                 }
11510
11511                 interval = get_sd_balance_interval(sd, busy);
11512
11513                 need_serialize = sd->flags & SD_SERIALIZE;
11514                 if (need_serialize) {
11515                         if (!spin_trylock(&balancing))
11516                                 goto out;
11517                 }
11518
11519                 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11520                         if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11521                                 /*
11522                                  * The LBF_DST_PINNED logic could have changed
11523                                  * env->dst_cpu, so we can't know our idle
11524                                  * state even if we migrated tasks. Update it.
11525                                  */
11526                                 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11527                                 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11528                         }
11529                         sd->last_balance = jiffies;
11530                         interval = get_sd_balance_interval(sd, busy);
11531                 }
11532                 if (need_serialize)
11533                         spin_unlock(&balancing);
11534 out:
11535                 if (time_after(next_balance, sd->last_balance + interval)) {
11536                         next_balance = sd->last_balance + interval;
11537                         update_next_balance = 1;
11538                 }
11539         }
11540         if (need_decay) {
11541                 /*
11542                  * Ensure the rq-wide value also decays but keep it at a
11543                  * reasonable floor to avoid funnies with rq->avg_idle.
11544                  */
11545                 rq->max_idle_balance_cost =
11546                         max((u64)sysctl_sched_migration_cost, max_cost);
11547         }
11548         rcu_read_unlock();
11549
11550         /*
11551          * next_balance will be updated only when there is a need.
11552          * When the cpu is attached to null domain for ex, it will not be
11553          * updated.
11554          */
11555         if (likely(update_next_balance))
11556                 rq->next_balance = next_balance;
11557
11558 }
11559
11560 static inline int on_null_domain(struct rq *rq)
11561 {
11562         return unlikely(!rcu_dereference_sched(rq->sd));
11563 }
11564
11565 #ifdef CONFIG_NO_HZ_COMMON
11566 /*
11567  * idle load balancing details
11568  * - When one of the busy CPUs notice that there may be an idle rebalancing
11569  *   needed, they will kick the idle load balancer, which then does idle
11570  *   load balancing for all the idle CPUs.
11571  * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED not set
11572  *   anywhere yet.
11573  */
11574
11575 static inline int find_new_ilb(void)
11576 {
11577         int ilb;
11578         const struct cpumask *hk_mask;
11579
11580         hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11581
11582         for_each_cpu_and(ilb, nohz.idle_cpus_mask, hk_mask) {
11583
11584                 if (ilb == smp_processor_id())
11585                         continue;
11586
11587                 if (idle_cpu(ilb))
11588                         return ilb;
11589         }
11590
11591         return nr_cpu_ids;
11592 }
11593
11594 /*
11595  * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
11596  * idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11597  */
11598 static void kick_ilb(unsigned int flags)
11599 {
11600         int ilb_cpu;
11601
11602         /*
11603          * Increase nohz.next_balance only when if full ilb is triggered but
11604          * not if we only update stats.
11605          */
11606         if (flags & NOHZ_BALANCE_KICK)
11607                 nohz.next_balance = jiffies+1;
11608
11609         ilb_cpu = find_new_ilb();
11610
11611         if (ilb_cpu >= nr_cpu_ids)
11612                 return;
11613
11614         /*
11615          * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11616          * the first flag owns it; cleared by nohz_csd_func().
11617          */
11618         flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11619         if (flags & NOHZ_KICK_MASK)
11620                 return;
11621
11622         /*
11623          * This way we generate an IPI on the target CPU which
11624          * is idle. And the softirq performing nohz idle load balance
11625          * will be run before returning from the IPI.
11626          */
11627         smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11628 }
11629
11630 /*
11631  * Current decision point for kicking the idle load balancer in the presence
11632  * of idle CPUs in the system.
11633  */
11634 static void nohz_balancer_kick(struct rq *rq)
11635 {
11636         unsigned long now = jiffies;
11637         struct sched_domain_shared *sds;
11638         struct sched_domain *sd;
11639         int nr_busy, i, cpu = rq->cpu;
11640         unsigned int flags = 0;
11641
11642         if (unlikely(rq->idle_balance))
11643                 return;
11644
11645         /*
11646          * We may be recently in ticked or tickless idle mode. At the first
11647          * busy tick after returning from idle, we will update the busy stats.
11648          */
11649         nohz_balance_exit_idle(rq);
11650
11651         /*
11652          * None are in tickless mode and hence no need for NOHZ idle load
11653          * balancing.
11654          */
11655         if (likely(!atomic_read(&nohz.nr_cpus)))
11656                 return;
11657
11658         if (READ_ONCE(nohz.has_blocked) &&
11659             time_after(now, READ_ONCE(nohz.next_blocked)))
11660                 flags = NOHZ_STATS_KICK;
11661
11662         if (time_before(now, nohz.next_balance))
11663                 goto out;
11664
11665         if (rq->nr_running >= 2) {
11666                 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11667                 goto out;
11668         }
11669
11670         rcu_read_lock();
11671
11672         sd = rcu_dereference(rq->sd);
11673         if (sd) {
11674                 /*
11675                  * If there's a CFS task and the current CPU has reduced
11676                  * capacity; kick the ILB to see if there's a better CPU to run
11677                  * on.
11678                  */
11679                 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11680                         flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11681                         goto unlock;
11682                 }
11683         }
11684
11685         sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11686         if (sd) {
11687                 /*
11688                  * When ASYM_PACKING; see if there's a more preferred CPU
11689                  * currently idle; in which case, kick the ILB to move tasks
11690                  * around.
11691                  *
11692                  * When balancing betwen cores, all the SMT siblings of the
11693                  * preferred CPU must be idle.
11694                  */
11695                 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11696                         if (sched_use_asym_prio(sd, i) &&
11697                             sched_asym_prefer(i, cpu)) {
11698                                 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11699                                 goto unlock;
11700                         }
11701                 }
11702         }
11703
11704         sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11705         if (sd) {
11706                 /*
11707                  * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11708                  * to run the misfit task on.
11709                  */
11710                 if (check_misfit_status(rq, sd)) {
11711                         flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11712                         goto unlock;
11713                 }
11714
11715                 /*
11716                  * For asymmetric systems, we do not want to nicely balance
11717                  * cache use, instead we want to embrace asymmetry and only
11718                  * ensure tasks have enough CPU capacity.
11719                  *
11720                  * Skip the LLC logic because it's not relevant in that case.
11721                  */
11722                 goto unlock;
11723         }
11724
11725         sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11726         if (sds) {
11727                 /*
11728                  * If there is an imbalance between LLC domains (IOW we could
11729                  * increase the overall cache use), we need some less-loaded LLC
11730                  * domain to pull some load. Likewise, we may need to spread
11731                  * load within the current LLC domain (e.g. packed SMT cores but
11732                  * other CPUs are idle). We can't really know from here how busy
11733                  * the others are - so just get a nohz balance going if it looks
11734                  * like this LLC domain has tasks we could move.
11735                  */
11736                 nr_busy = atomic_read(&sds->nr_busy_cpus);
11737                 if (nr_busy > 1) {
11738                         flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11739                         goto unlock;
11740                 }
11741         }
11742 unlock:
11743         rcu_read_unlock();
11744 out:
11745         if (READ_ONCE(nohz.needs_update))
11746                 flags |= NOHZ_NEXT_KICK;
11747
11748         if (flags)
11749                 kick_ilb(flags);
11750 }
11751
11752 static void set_cpu_sd_state_busy(int cpu)
11753 {
11754         struct sched_domain *sd;
11755
11756         rcu_read_lock();
11757         sd = rcu_dereference(per_cpu(sd_llc, cpu));
11758
11759         if (!sd || !sd->nohz_idle)
11760                 goto unlock;
11761         sd->nohz_idle = 0;
11762
11763         atomic_inc(&sd->shared->nr_busy_cpus);
11764 unlock:
11765         rcu_read_unlock();
11766 }
11767
11768 void nohz_balance_exit_idle(struct rq *rq)
11769 {
11770         SCHED_WARN_ON(rq != this_rq());
11771
11772         if (likely(!rq->nohz_tick_stopped))
11773                 return;
11774
11775         rq->nohz_tick_stopped = 0;
11776         cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
11777         atomic_dec(&nohz.nr_cpus);
11778
11779         set_cpu_sd_state_busy(rq->cpu);
11780 }
11781
11782 static void set_cpu_sd_state_idle(int cpu)
11783 {
11784         struct sched_domain *sd;
11785
11786         rcu_read_lock();
11787         sd = rcu_dereference(per_cpu(sd_llc, cpu));
11788
11789         if (!sd || sd->nohz_idle)
11790                 goto unlock;
11791         sd->nohz_idle = 1;
11792
11793         atomic_dec(&sd->shared->nr_busy_cpus);
11794 unlock:
11795         rcu_read_unlock();
11796 }
11797
11798 /*
11799  * This routine will record that the CPU is going idle with tick stopped.
11800  * This info will be used in performing idle load balancing in the future.
11801  */
11802 void nohz_balance_enter_idle(int cpu)
11803 {
11804         struct rq *rq = cpu_rq(cpu);
11805
11806         SCHED_WARN_ON(cpu != smp_processor_id());
11807
11808         /* If this CPU is going down, then nothing needs to be done: */
11809         if (!cpu_active(cpu))
11810                 return;
11811
11812         /* Spare idle load balancing on CPUs that don't want to be disturbed: */
11813         if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
11814                 return;
11815
11816         /*
11817          * Can be set safely without rq->lock held
11818          * If a clear happens, it will have evaluated last additions because
11819          * rq->lock is held during the check and the clear
11820          */
11821         rq->has_blocked_load = 1;
11822
11823         /*
11824          * The tick is still stopped but load could have been added in the
11825          * meantime. We set the nohz.has_blocked flag to trig a check of the
11826          * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
11827          * of nohz.has_blocked can only happen after checking the new load
11828          */
11829         if (rq->nohz_tick_stopped)
11830                 goto out;
11831
11832         /* If we're a completely isolated CPU, we don't play: */
11833         if (on_null_domain(rq))
11834                 return;
11835
11836         rq->nohz_tick_stopped = 1;
11837
11838         cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
11839         atomic_inc(&nohz.nr_cpus);
11840
11841         /*
11842          * Ensures that if nohz_idle_balance() fails to observe our
11843          * @idle_cpus_mask store, it must observe the @has_blocked
11844          * and @needs_update stores.
11845          */
11846         smp_mb__after_atomic();
11847
11848         set_cpu_sd_state_idle(cpu);
11849
11850         WRITE_ONCE(nohz.needs_update, 1);
11851 out:
11852         /*
11853          * Each time a cpu enter idle, we assume that it has blocked load and
11854          * enable the periodic update of the load of idle cpus
11855          */
11856         WRITE_ONCE(nohz.has_blocked, 1);
11857 }
11858
11859 static bool update_nohz_stats(struct rq *rq)
11860 {
11861         unsigned int cpu = rq->cpu;
11862
11863         if (!rq->has_blocked_load)
11864                 return false;
11865
11866         if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
11867                 return false;
11868
11869         if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
11870                 return true;
11871
11872         update_blocked_averages(cpu);
11873
11874         return rq->has_blocked_load;
11875 }
11876
11877 /*
11878  * Internal function that runs load balance for all idle cpus. The load balance
11879  * can be a simple update of blocked load or a complete load balance with
11880  * tasks movement depending of flags.
11881  */
11882 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
11883 {
11884         /* Earliest time when we have to do rebalance again */
11885         unsigned long now = jiffies;
11886         unsigned long next_balance = now + 60*HZ;
11887         bool has_blocked_load = false;
11888         int update_next_balance = 0;
11889         int this_cpu = this_rq->cpu;
11890         int balance_cpu;
11891         struct rq *rq;
11892
11893         SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
11894
11895         /*
11896          * We assume there will be no idle load after this update and clear
11897          * the has_blocked flag. If a cpu enters idle in the mean time, it will
11898          * set the has_blocked flag and trigger another update of idle load.
11899          * Because a cpu that becomes idle, is added to idle_cpus_mask before
11900          * setting the flag, we are sure to not clear the state and not
11901          * check the load of an idle cpu.
11902          *
11903          * Same applies to idle_cpus_mask vs needs_update.
11904          */
11905         if (flags & NOHZ_STATS_KICK)
11906                 WRITE_ONCE(nohz.has_blocked, 0);
11907         if (flags & NOHZ_NEXT_KICK)
11908                 WRITE_ONCE(nohz.needs_update, 0);
11909
11910         /*
11911          * Ensures that if we miss the CPU, we must see the has_blocked
11912          * store from nohz_balance_enter_idle().
11913          */
11914         smp_mb();
11915
11916         /*
11917          * Start with the next CPU after this_cpu so we will end with this_cpu and let a
11918          * chance for other idle cpu to pull load.
11919          */
11920         for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
11921                 if (!idle_cpu(balance_cpu))
11922                         continue;
11923
11924                 /*
11925                  * If this CPU gets work to do, stop the load balancing
11926                  * work being done for other CPUs. Next load
11927                  * balancing owner will pick it up.
11928                  */
11929                 if (need_resched()) {
11930                         if (flags & NOHZ_STATS_KICK)
11931                                 has_blocked_load = true;
11932                         if (flags & NOHZ_NEXT_KICK)
11933                                 WRITE_ONCE(nohz.needs_update, 1);
11934                         goto abort;
11935                 }
11936
11937                 rq = cpu_rq(balance_cpu);
11938
11939                 if (flags & NOHZ_STATS_KICK)
11940                         has_blocked_load |= update_nohz_stats(rq);
11941
11942                 /*
11943                  * If time for next balance is due,
11944                  * do the balance.
11945                  */
11946                 if (time_after_eq(jiffies, rq->next_balance)) {
11947                         struct rq_flags rf;
11948
11949                         rq_lock_irqsave(rq, &rf);
11950                         update_rq_clock(rq);
11951                         rq_unlock_irqrestore(rq, &rf);
11952
11953                         if (flags & NOHZ_BALANCE_KICK)
11954                                 rebalance_domains(rq, CPU_IDLE);
11955                 }
11956
11957                 if (time_after(next_balance, rq->next_balance)) {
11958                         next_balance = rq->next_balance;
11959                         update_next_balance = 1;
11960                 }
11961         }
11962
11963         /*
11964          * next_balance will be updated only when there is a need.
11965          * When the CPU is attached to null domain for ex, it will not be
11966          * updated.
11967          */
11968         if (likely(update_next_balance))
11969                 nohz.next_balance = next_balance;
11970
11971         if (flags & NOHZ_STATS_KICK)
11972                 WRITE_ONCE(nohz.next_blocked,
11973                            now + msecs_to_jiffies(LOAD_AVG_PERIOD));
11974
11975 abort:
11976         /* There is still blocked load, enable periodic update */
11977         if (has_blocked_load)
11978                 WRITE_ONCE(nohz.has_blocked, 1);
11979 }
11980
11981 /*
11982  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
11983  * rebalancing for all the cpus for whom scheduler ticks are stopped.
11984  */
11985 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
11986 {
11987         unsigned int flags = this_rq->nohz_idle_balance;
11988
11989         if (!flags)
11990                 return false;
11991
11992         this_rq->nohz_idle_balance = 0;
11993
11994         if (idle != CPU_IDLE)
11995                 return false;
11996
11997         _nohz_idle_balance(this_rq, flags);
11998
11999         return true;
12000 }
12001
12002 /*
12003  * Check if we need to run the ILB for updating blocked load before entering
12004  * idle state.
12005  */
12006 void nohz_run_idle_balance(int cpu)
12007 {
12008         unsigned int flags;
12009
12010         flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12011
12012         /*
12013          * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12014          * (ie NOHZ_STATS_KICK set) and will do the same.
12015          */
12016         if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12017                 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12018 }
12019
12020 static void nohz_newidle_balance(struct rq *this_rq)
12021 {
12022         int this_cpu = this_rq->cpu;
12023
12024         /*
12025          * This CPU doesn't want to be disturbed by scheduler
12026          * housekeeping
12027          */
12028         if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
12029                 return;
12030
12031         /* Will wake up very soon. No time for doing anything else*/
12032         if (this_rq->avg_idle < sysctl_sched_migration_cost)
12033                 return;
12034
12035         /* Don't need to update blocked load of idle CPUs*/
12036         if (!READ_ONCE(nohz.has_blocked) ||
12037             time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12038                 return;
12039
12040         /*
12041          * Set the need to trigger ILB in order to update blocked load
12042          * before entering idle state.
12043          */
12044         atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12045 }
12046
12047 #else /* !CONFIG_NO_HZ_COMMON */
12048 static inline void nohz_balancer_kick(struct rq *rq) { }
12049
12050 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12051 {
12052         return false;
12053 }
12054
12055 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12056 #endif /* CONFIG_NO_HZ_COMMON */
12057
12058 /*
12059  * newidle_balance is called by schedule() if this_cpu is about to become
12060  * idle. Attempts to pull tasks from other CPUs.
12061  *
12062  * Returns:
12063  *   < 0 - we released the lock and there are !fair tasks present
12064  *     0 - failed, no new tasks
12065  *   > 0 - success, new (fair) tasks present
12066  */
12067 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12068 {
12069         unsigned long next_balance = jiffies + HZ;
12070         int this_cpu = this_rq->cpu;
12071         u64 t0, t1, curr_cost = 0;
12072         struct sched_domain *sd;
12073         int pulled_task = 0;
12074
12075         update_misfit_status(NULL, this_rq);
12076
12077         /*
12078          * There is a task waiting to run. No need to search for one.
12079          * Return 0; the task will be enqueued when switching to idle.
12080          */
12081         if (this_rq->ttwu_pending)
12082                 return 0;
12083
12084         /*
12085          * We must set idle_stamp _before_ calling idle_balance(), such that we
12086          * measure the duration of idle_balance() as idle time.
12087          */
12088         this_rq->idle_stamp = rq_clock(this_rq);
12089
12090         /*
12091          * Do not pull tasks towards !active CPUs...
12092          */
12093         if (!cpu_active(this_cpu))
12094                 return 0;
12095
12096         /*
12097          * This is OK, because current is on_cpu, which avoids it being picked
12098          * for load-balance and preemption/IRQs are still disabled avoiding
12099          * further scheduler activity on it and we're being very careful to
12100          * re-start the picking loop.
12101          */
12102         rq_unpin_lock(this_rq, rf);
12103
12104         rcu_read_lock();
12105         sd = rcu_dereference_check_sched_domain(this_rq->sd);
12106
12107         if (!READ_ONCE(this_rq->rd->overload) ||
12108             (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12109
12110                 if (sd)
12111                         update_next_balance(sd, &next_balance);
12112                 rcu_read_unlock();
12113
12114                 goto out;
12115         }
12116         rcu_read_unlock();
12117
12118         raw_spin_rq_unlock(this_rq);
12119
12120         t0 = sched_clock_cpu(this_cpu);
12121         update_blocked_averages(this_cpu);
12122
12123         rcu_read_lock();
12124         for_each_domain(this_cpu, sd) {
12125                 int continue_balancing = 1;
12126                 u64 domain_cost;
12127
12128                 update_next_balance(sd, &next_balance);
12129
12130                 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12131                         break;
12132
12133                 if (sd->flags & SD_BALANCE_NEWIDLE) {
12134
12135                         pulled_task = load_balance(this_cpu, this_rq,
12136                                                    sd, CPU_NEWLY_IDLE,
12137                                                    &continue_balancing);
12138
12139                         t1 = sched_clock_cpu(this_cpu);
12140                         domain_cost = t1 - t0;
12141                         update_newidle_cost(sd, domain_cost);
12142
12143                         curr_cost += domain_cost;
12144                         t0 = t1;
12145                 }
12146
12147                 /*
12148                  * Stop searching for tasks to pull if there are
12149                  * now runnable tasks on this rq.
12150                  */
12151                 if (pulled_task || this_rq->nr_running > 0 ||
12152                     this_rq->ttwu_pending)
12153                         break;
12154         }
12155         rcu_read_unlock();
12156
12157         raw_spin_rq_lock(this_rq);
12158
12159         if (curr_cost > this_rq->max_idle_balance_cost)
12160                 this_rq->max_idle_balance_cost = curr_cost;
12161
12162         /*
12163          * While browsing the domains, we released the rq lock, a task could
12164          * have been enqueued in the meantime. Since we're not going idle,
12165          * pretend we pulled a task.
12166          */
12167         if (this_rq->cfs.h_nr_running && !pulled_task)
12168                 pulled_task = 1;
12169
12170         /* Is there a task of a high priority class? */
12171         if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12172                 pulled_task = -1;
12173
12174 out:
12175         /* Move the next balance forward */
12176         if (time_after(this_rq->next_balance, next_balance))
12177                 this_rq->next_balance = next_balance;
12178
12179         if (pulled_task)
12180                 this_rq->idle_stamp = 0;
12181         else
12182                 nohz_newidle_balance(this_rq);
12183
12184         rq_repin_lock(this_rq, rf);
12185
12186         return pulled_task;
12187 }
12188
12189 /*
12190  * run_rebalance_domains is triggered when needed from the scheduler tick.
12191  * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12192  */
12193 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12194 {
12195         struct rq *this_rq = this_rq();
12196         enum cpu_idle_type idle = this_rq->idle_balance ?
12197                                                 CPU_IDLE : CPU_NOT_IDLE;
12198
12199         /*
12200          * If this CPU has a pending nohz_balance_kick, then do the
12201          * balancing on behalf of the other idle CPUs whose ticks are
12202          * stopped. Do nohz_idle_balance *before* rebalance_domains to
12203          * give the idle CPUs a chance to load balance. Else we may
12204          * load balance only within the local sched_domain hierarchy
12205          * and abort nohz_idle_balance altogether if we pull some load.
12206          */
12207         if (nohz_idle_balance(this_rq, idle))
12208                 return;
12209
12210         /* normal load balance */
12211         update_blocked_averages(this_rq->cpu);
12212         rebalance_domains(this_rq, idle);
12213 }
12214
12215 /*
12216  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12217  */
12218 void trigger_load_balance(struct rq *rq)
12219 {
12220         /*
12221          * Don't need to rebalance while attached to NULL domain or
12222          * runqueue CPU is not active
12223          */
12224         if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12225                 return;
12226
12227         if (time_after_eq(jiffies, rq->next_balance))
12228                 raise_softirq(SCHED_SOFTIRQ);
12229
12230         nohz_balancer_kick(rq);
12231 }
12232
12233 static void rq_online_fair(struct rq *rq)
12234 {
12235         update_sysctl();
12236
12237         update_runtime_enabled(rq);
12238 }
12239
12240 static void rq_offline_fair(struct rq *rq)
12241 {
12242         update_sysctl();
12243
12244         /* Ensure any throttled groups are reachable by pick_next_task */
12245         unthrottle_offline_cfs_rqs(rq);
12246 }
12247
12248 #endif /* CONFIG_SMP */
12249
12250 #ifdef CONFIG_SCHED_CORE
12251 static inline bool
12252 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12253 {
12254         u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12255         u64 slice = se->slice;
12256
12257         return (rtime * min_nr_tasks > slice);
12258 }
12259
12260 #define MIN_NR_TASKS_DURING_FORCEIDLE   2
12261 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12262 {
12263         if (!sched_core_enabled(rq))
12264                 return;
12265
12266         /*
12267          * If runqueue has only one task which used up its slice and
12268          * if the sibling is forced idle, then trigger schedule to
12269          * give forced idle task a chance.
12270          *
12271          * sched_slice() considers only this active rq and it gets the
12272          * whole slice. But during force idle, we have siblings acting
12273          * like a single runqueue and hence we need to consider runnable
12274          * tasks on this CPU and the forced idle CPU. Ideally, we should
12275          * go through the forced idle rq, but that would be a perf hit.
12276          * We can assume that the forced idle CPU has at least
12277          * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12278          * if we need to give up the CPU.
12279          */
12280         if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12281             __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12282                 resched_curr(rq);
12283 }
12284
12285 /*
12286  * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12287  */
12288 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12289                          bool forceidle)
12290 {
12291         for_each_sched_entity(se) {
12292                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12293
12294                 if (forceidle) {
12295                         if (cfs_rq->forceidle_seq == fi_seq)
12296                                 break;
12297                         cfs_rq->forceidle_seq = fi_seq;
12298                 }
12299
12300                 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12301         }
12302 }
12303
12304 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12305 {
12306         struct sched_entity *se = &p->se;
12307
12308         if (p->sched_class != &fair_sched_class)
12309                 return;
12310
12311         se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12312 }
12313
12314 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12315                         bool in_fi)
12316 {
12317         struct rq *rq = task_rq(a);
12318         const struct sched_entity *sea = &a->se;
12319         const struct sched_entity *seb = &b->se;
12320         struct cfs_rq *cfs_rqa;
12321         struct cfs_rq *cfs_rqb;
12322         s64 delta;
12323
12324         SCHED_WARN_ON(task_rq(b)->core != rq->core);
12325
12326 #ifdef CONFIG_FAIR_GROUP_SCHED
12327         /*
12328          * Find an se in the hierarchy for tasks a and b, such that the se's
12329          * are immediate siblings.
12330          */
12331         while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12332                 int sea_depth = sea->depth;
12333                 int seb_depth = seb->depth;
12334
12335                 if (sea_depth >= seb_depth)
12336                         sea = parent_entity(sea);
12337                 if (sea_depth <= seb_depth)
12338                         seb = parent_entity(seb);
12339         }
12340
12341         se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12342         se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12343
12344         cfs_rqa = sea->cfs_rq;
12345         cfs_rqb = seb->cfs_rq;
12346 #else
12347         cfs_rqa = &task_rq(a)->cfs;
12348         cfs_rqb = &task_rq(b)->cfs;
12349 #endif
12350
12351         /*
12352          * Find delta after normalizing se's vruntime with its cfs_rq's
12353          * min_vruntime_fi, which would have been updated in prior calls
12354          * to se_fi_update().
12355          */
12356         delta = (s64)(sea->vruntime - seb->vruntime) +
12357                 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12358
12359         return delta > 0;
12360 }
12361
12362 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12363 {
12364         struct cfs_rq *cfs_rq;
12365
12366 #ifdef CONFIG_FAIR_GROUP_SCHED
12367         cfs_rq = task_group(p)->cfs_rq[cpu];
12368 #else
12369         cfs_rq = &cpu_rq(cpu)->cfs;
12370 #endif
12371         return throttled_hierarchy(cfs_rq);
12372 }
12373 #else
12374 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12375 #endif
12376
12377 /*
12378  * scheduler tick hitting a task of our scheduling class.
12379  *
12380  * NOTE: This function can be called remotely by the tick offload that
12381  * goes along full dynticks. Therefore no local assumption can be made
12382  * and everything must be accessed through the @rq and @curr passed in
12383  * parameters.
12384  */
12385 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12386 {
12387         struct cfs_rq *cfs_rq;
12388         struct sched_entity *se = &curr->se;
12389
12390         for_each_sched_entity(se) {
12391                 cfs_rq = cfs_rq_of(se);
12392                 entity_tick(cfs_rq, se, queued);
12393         }
12394
12395         if (static_branch_unlikely(&sched_numa_balancing))
12396                 task_tick_numa(rq, curr);
12397
12398         update_misfit_status(curr, rq);
12399         update_overutilized_status(task_rq(curr));
12400
12401         task_tick_core(rq, curr);
12402 }
12403
12404 /*
12405  * called on fork with the child task as argument from the parent's context
12406  *  - child not yet on the tasklist
12407  *  - preemption disabled
12408  */
12409 static void task_fork_fair(struct task_struct *p)
12410 {
12411         struct sched_entity *se = &p->se, *curr;
12412         struct cfs_rq *cfs_rq;
12413         struct rq *rq = this_rq();
12414         struct rq_flags rf;
12415
12416         rq_lock(rq, &rf);
12417         update_rq_clock(rq);
12418
12419         cfs_rq = task_cfs_rq(current);
12420         curr = cfs_rq->curr;
12421         if (curr)
12422                 update_curr(cfs_rq);
12423         place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12424         rq_unlock(rq, &rf);
12425 }
12426
12427 /*
12428  * Priority of the task has changed. Check to see if we preempt
12429  * the current task.
12430  */
12431 static void
12432 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12433 {
12434         if (!task_on_rq_queued(p))
12435                 return;
12436
12437         if (rq->cfs.nr_running == 1)
12438                 return;
12439
12440         /*
12441          * Reschedule if we are currently running on this runqueue and
12442          * our priority decreased, or if we are not currently running on
12443          * this runqueue and our priority is higher than the current's
12444          */
12445         if (task_current(rq, p)) {
12446                 if (p->prio > oldprio)
12447                         resched_curr(rq);
12448         } else
12449                 check_preempt_curr(rq, p, 0);
12450 }
12451
12452 #ifdef CONFIG_FAIR_GROUP_SCHED
12453 /*
12454  * Propagate the changes of the sched_entity across the tg tree to make it
12455  * visible to the root
12456  */
12457 static void propagate_entity_cfs_rq(struct sched_entity *se)
12458 {
12459         struct cfs_rq *cfs_rq = cfs_rq_of(se);
12460
12461         if (cfs_rq_throttled(cfs_rq))
12462                 return;
12463
12464         if (!throttled_hierarchy(cfs_rq))
12465                 list_add_leaf_cfs_rq(cfs_rq);
12466
12467         /* Start to propagate at parent */
12468         se = se->parent;
12469
12470         for_each_sched_entity(se) {
12471                 cfs_rq = cfs_rq_of(se);
12472
12473                 update_load_avg(cfs_rq, se, UPDATE_TG);
12474
12475                 if (cfs_rq_throttled(cfs_rq))
12476                         break;
12477
12478                 if (!throttled_hierarchy(cfs_rq))
12479                         list_add_leaf_cfs_rq(cfs_rq);
12480         }
12481 }
12482 #else
12483 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12484 #endif
12485
12486 static void detach_entity_cfs_rq(struct sched_entity *se)
12487 {
12488         struct cfs_rq *cfs_rq = cfs_rq_of(se);
12489
12490 #ifdef CONFIG_SMP
12491         /*
12492          * In case the task sched_avg hasn't been attached:
12493          * - A forked task which hasn't been woken up by wake_up_new_task().
12494          * - A task which has been woken up by try_to_wake_up() but is
12495          *   waiting for actually being woken up by sched_ttwu_pending().
12496          */
12497         if (!se->avg.last_update_time)
12498                 return;
12499 #endif
12500
12501         /* Catch up with the cfs_rq and remove our load when we leave */
12502         update_load_avg(cfs_rq, se, 0);
12503         detach_entity_load_avg(cfs_rq, se);
12504         update_tg_load_avg(cfs_rq);
12505         propagate_entity_cfs_rq(se);
12506 }
12507
12508 static void attach_entity_cfs_rq(struct sched_entity *se)
12509 {
12510         struct cfs_rq *cfs_rq = cfs_rq_of(se);
12511
12512         /* Synchronize entity with its cfs_rq */
12513         update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12514         attach_entity_load_avg(cfs_rq, se);
12515         update_tg_load_avg(cfs_rq);
12516         propagate_entity_cfs_rq(se);
12517 }
12518
12519 static void detach_task_cfs_rq(struct task_struct *p)
12520 {
12521         struct sched_entity *se = &p->se;
12522
12523         detach_entity_cfs_rq(se);
12524 }
12525
12526 static void attach_task_cfs_rq(struct task_struct *p)
12527 {
12528         struct sched_entity *se = &p->se;
12529
12530         attach_entity_cfs_rq(se);
12531 }
12532
12533 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12534 {
12535         detach_task_cfs_rq(p);
12536 }
12537
12538 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12539 {
12540         attach_task_cfs_rq(p);
12541
12542         if (task_on_rq_queued(p)) {
12543                 /*
12544                  * We were most likely switched from sched_rt, so
12545                  * kick off the schedule if running, otherwise just see
12546                  * if we can still preempt the current task.
12547                  */
12548                 if (task_current(rq, p))
12549                         resched_curr(rq);
12550                 else
12551                         check_preempt_curr(rq, p, 0);
12552         }
12553 }
12554
12555 /* Account for a task changing its policy or group.
12556  *
12557  * This routine is mostly called to set cfs_rq->curr field when a task
12558  * migrates between groups/classes.
12559  */
12560 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12561 {
12562         struct sched_entity *se = &p->se;
12563
12564 #ifdef CONFIG_SMP
12565         if (task_on_rq_queued(p)) {
12566                 /*
12567                  * Move the next running task to the front of the list, so our
12568                  * cfs_tasks list becomes MRU one.
12569                  */
12570                 list_move(&se->group_node, &rq->cfs_tasks);
12571         }
12572 #endif
12573
12574         for_each_sched_entity(se) {
12575                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12576
12577                 set_next_entity(cfs_rq, se);
12578                 /* ensure bandwidth has been allocated on our new cfs_rq */
12579                 account_cfs_rq_runtime(cfs_rq, 0);
12580         }
12581 }
12582
12583 void init_cfs_rq(struct cfs_rq *cfs_rq)
12584 {
12585         cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12586         u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12587 #ifdef CONFIG_SMP
12588         raw_spin_lock_init(&cfs_rq->removed.lock);
12589 #endif
12590 }
12591
12592 #ifdef CONFIG_FAIR_GROUP_SCHED
12593 static void task_change_group_fair(struct task_struct *p)
12594 {
12595         /*
12596          * We couldn't detach or attach a forked task which
12597          * hasn't been woken up by wake_up_new_task().
12598          */
12599         if (READ_ONCE(p->__state) == TASK_NEW)
12600                 return;
12601
12602         detach_task_cfs_rq(p);
12603
12604 #ifdef CONFIG_SMP
12605         /* Tell se's cfs_rq has been changed -- migrated */
12606         p->se.avg.last_update_time = 0;
12607 #endif
12608         set_task_rq(p, task_cpu(p));
12609         attach_task_cfs_rq(p);
12610 }
12611
12612 void free_fair_sched_group(struct task_group *tg)
12613 {
12614         int i;
12615
12616         for_each_possible_cpu(i) {
12617                 if (tg->cfs_rq)
12618                         kfree(tg->cfs_rq[i]);
12619                 if (tg->se)
12620                         kfree(tg->se[i]);
12621         }
12622
12623         kfree(tg->cfs_rq);
12624         kfree(tg->se);
12625 }
12626
12627 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12628 {
12629         struct sched_entity *se;
12630         struct cfs_rq *cfs_rq;
12631         int i;
12632
12633         tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12634         if (!tg->cfs_rq)
12635                 goto err;
12636         tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12637         if (!tg->se)
12638                 goto err;
12639
12640         tg->shares = NICE_0_LOAD;
12641
12642         init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12643
12644         for_each_possible_cpu(i) {
12645                 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12646                                       GFP_KERNEL, cpu_to_node(i));
12647                 if (!cfs_rq)
12648                         goto err;
12649
12650                 se = kzalloc_node(sizeof(struct sched_entity_stats),
12651                                   GFP_KERNEL, cpu_to_node(i));
12652                 if (!se)
12653                         goto err_free_rq;
12654
12655                 init_cfs_rq(cfs_rq);
12656                 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12657                 init_entity_runnable_average(se);
12658         }
12659
12660         return 1;
12661
12662 err_free_rq:
12663         kfree(cfs_rq);
12664 err:
12665         return 0;
12666 }
12667
12668 void online_fair_sched_group(struct task_group *tg)
12669 {
12670         struct sched_entity *se;
12671         struct rq_flags rf;
12672         struct rq *rq;
12673         int i;
12674
12675         for_each_possible_cpu(i) {
12676                 rq = cpu_rq(i);
12677                 se = tg->se[i];
12678                 rq_lock_irq(rq, &rf);
12679                 update_rq_clock(rq);
12680                 attach_entity_cfs_rq(se);
12681                 sync_throttle(tg, i);
12682                 rq_unlock_irq(rq, &rf);
12683         }
12684 }
12685
12686 void unregister_fair_sched_group(struct task_group *tg)
12687 {
12688         unsigned long flags;
12689         struct rq *rq;
12690         int cpu;
12691
12692         destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12693
12694         for_each_possible_cpu(cpu) {
12695                 if (tg->se[cpu])
12696                         remove_entity_load_avg(tg->se[cpu]);
12697
12698                 /*
12699                  * Only empty task groups can be destroyed; so we can speculatively
12700                  * check on_list without danger of it being re-added.
12701                  */
12702                 if (!tg->cfs_rq[cpu]->on_list)
12703                         continue;
12704
12705                 rq = cpu_rq(cpu);
12706
12707                 raw_spin_rq_lock_irqsave(rq, flags);
12708                 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12709                 raw_spin_rq_unlock_irqrestore(rq, flags);
12710         }
12711 }
12712
12713 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12714                         struct sched_entity *se, int cpu,
12715                         struct sched_entity *parent)
12716 {
12717         struct rq *rq = cpu_rq(cpu);
12718
12719         cfs_rq->tg = tg;
12720         cfs_rq->rq = rq;
12721         init_cfs_rq_runtime(cfs_rq);
12722
12723         tg->cfs_rq[cpu] = cfs_rq;
12724         tg->se[cpu] = se;
12725
12726         /* se could be NULL for root_task_group */
12727         if (!se)
12728                 return;
12729
12730         if (!parent) {
12731                 se->cfs_rq = &rq->cfs;
12732                 se->depth = 0;
12733         } else {
12734                 se->cfs_rq = parent->my_q;
12735                 se->depth = parent->depth + 1;
12736         }
12737
12738         se->my_q = cfs_rq;
12739         /* guarantee group entities always have weight */
12740         update_load_set(&se->load, NICE_0_LOAD);
12741         se->parent = parent;
12742 }
12743
12744 static DEFINE_MUTEX(shares_mutex);
12745
12746 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
12747 {
12748         int i;
12749
12750         lockdep_assert_held(&shares_mutex);
12751
12752         /*
12753          * We can't change the weight of the root cgroup.
12754          */
12755         if (!tg->se[0])
12756                 return -EINVAL;
12757
12758         shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
12759
12760         if (tg->shares == shares)
12761                 return 0;
12762
12763         tg->shares = shares;
12764         for_each_possible_cpu(i) {
12765                 struct rq *rq = cpu_rq(i);
12766                 struct sched_entity *se = tg->se[i];
12767                 struct rq_flags rf;
12768
12769                 /* Propagate contribution to hierarchy */
12770                 rq_lock_irqsave(rq, &rf);
12771                 update_rq_clock(rq);
12772                 for_each_sched_entity(se) {
12773                         update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
12774                         update_cfs_group(se);
12775                 }
12776                 rq_unlock_irqrestore(rq, &rf);
12777         }
12778
12779         return 0;
12780 }
12781
12782 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
12783 {
12784         int ret;
12785
12786         mutex_lock(&shares_mutex);
12787         if (tg_is_idle(tg))
12788                 ret = -EINVAL;
12789         else
12790                 ret = __sched_group_set_shares(tg, shares);
12791         mutex_unlock(&shares_mutex);
12792
12793         return ret;
12794 }
12795
12796 int sched_group_set_idle(struct task_group *tg, long idle)
12797 {
12798         int i;
12799
12800         if (tg == &root_task_group)
12801                 return -EINVAL;
12802
12803         if (idle < 0 || idle > 1)
12804                 return -EINVAL;
12805
12806         mutex_lock(&shares_mutex);
12807
12808         if (tg->idle == idle) {
12809                 mutex_unlock(&shares_mutex);
12810                 return 0;
12811         }
12812
12813         tg->idle = idle;
12814
12815         for_each_possible_cpu(i) {
12816                 struct rq *rq = cpu_rq(i);
12817                 struct sched_entity *se = tg->se[i];
12818                 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
12819                 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
12820                 long idle_task_delta;
12821                 struct rq_flags rf;
12822
12823                 rq_lock_irqsave(rq, &rf);
12824
12825                 grp_cfs_rq->idle = idle;
12826                 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
12827                         goto next_cpu;
12828
12829                 if (se->on_rq) {
12830                         parent_cfs_rq = cfs_rq_of(se);
12831                         if (cfs_rq_is_idle(grp_cfs_rq))
12832                                 parent_cfs_rq->idle_nr_running++;
12833                         else
12834                                 parent_cfs_rq->idle_nr_running--;
12835                 }
12836
12837                 idle_task_delta = grp_cfs_rq->h_nr_running -
12838                                   grp_cfs_rq->idle_h_nr_running;
12839                 if (!cfs_rq_is_idle(grp_cfs_rq))
12840                         idle_task_delta *= -1;
12841
12842                 for_each_sched_entity(se) {
12843                         struct cfs_rq *cfs_rq = cfs_rq_of(se);
12844
12845                         if (!se->on_rq)
12846                                 break;
12847
12848                         cfs_rq->idle_h_nr_running += idle_task_delta;
12849
12850                         /* Already accounted at parent level and above. */
12851                         if (cfs_rq_is_idle(cfs_rq))
12852                                 break;
12853                 }
12854
12855 next_cpu:
12856                 rq_unlock_irqrestore(rq, &rf);
12857         }
12858
12859         /* Idle groups have minimum weight. */
12860         if (tg_is_idle(tg))
12861                 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
12862         else
12863                 __sched_group_set_shares(tg, NICE_0_LOAD);
12864
12865         mutex_unlock(&shares_mutex);
12866         return 0;
12867 }
12868
12869 #else /* CONFIG_FAIR_GROUP_SCHED */
12870
12871 void free_fair_sched_group(struct task_group *tg) { }
12872
12873 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12874 {
12875         return 1;
12876 }
12877
12878 void online_fair_sched_group(struct task_group *tg) { }
12879
12880 void unregister_fair_sched_group(struct task_group *tg) { }
12881
12882 #endif /* CONFIG_FAIR_GROUP_SCHED */
12883
12884
12885 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
12886 {
12887         struct sched_entity *se = &task->se;
12888         unsigned int rr_interval = 0;
12889
12890         /*
12891          * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
12892          * idle runqueue:
12893          */
12894         if (rq->cfs.load.weight)
12895                 rr_interval = NS_TO_JIFFIES(se->slice);
12896
12897         return rr_interval;
12898 }
12899
12900 /*
12901  * All the scheduling class methods:
12902  */
12903 DEFINE_SCHED_CLASS(fair) = {
12904
12905         .enqueue_task           = enqueue_task_fair,
12906         .dequeue_task           = dequeue_task_fair,
12907         .yield_task             = yield_task_fair,
12908         .yield_to_task          = yield_to_task_fair,
12909
12910         .check_preempt_curr     = check_preempt_wakeup,
12911
12912         .pick_next_task         = __pick_next_task_fair,
12913         .put_prev_task          = put_prev_task_fair,
12914         .set_next_task          = set_next_task_fair,
12915
12916 #ifdef CONFIG_SMP
12917         .balance                = balance_fair,
12918         .pick_task              = pick_task_fair,
12919         .select_task_rq         = select_task_rq_fair,
12920         .migrate_task_rq        = migrate_task_rq_fair,
12921
12922         .rq_online              = rq_online_fair,
12923         .rq_offline             = rq_offline_fair,
12924
12925         .task_dead              = task_dead_fair,
12926         .set_cpus_allowed       = set_cpus_allowed_common,
12927 #endif
12928
12929         .task_tick              = task_tick_fair,
12930         .task_fork              = task_fork_fair,
12931
12932         .prio_changed           = prio_changed_fair,
12933         .switched_from          = switched_from_fair,
12934         .switched_to            = switched_to_fair,
12935
12936         .get_rr_interval        = get_rr_interval_fair,
12937
12938         .update_curr            = update_curr_fair,
12939
12940 #ifdef CONFIG_FAIR_GROUP_SCHED
12941         .task_change_group      = task_change_group_fair,
12942 #endif
12943
12944 #ifdef CONFIG_SCHED_CORE
12945         .task_is_throttled      = task_is_throttled_fair,
12946 #endif
12947
12948 #ifdef CONFIG_UCLAMP_TASK
12949         .uclamp_enabled         = 1,
12950 #endif
12951 };
12952
12953 #ifdef CONFIG_SCHED_DEBUG
12954 void print_cfs_stats(struct seq_file *m, int cpu)
12955 {
12956         struct cfs_rq *cfs_rq, *pos;
12957
12958         rcu_read_lock();
12959         for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
12960                 print_cfs_rq(m, cpu, cfs_rq);
12961         rcu_read_unlock();
12962 }
12963
12964 #ifdef CONFIG_NUMA_BALANCING
12965 void show_numa_stats(struct task_struct *p, struct seq_file *m)
12966 {
12967         int node;
12968         unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
12969         struct numa_group *ng;
12970
12971         rcu_read_lock();
12972         ng = rcu_dereference(p->numa_group);
12973         for_each_online_node(node) {
12974                 if (p->numa_faults) {
12975                         tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
12976                         tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
12977                 }
12978                 if (ng) {
12979                         gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
12980                         gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
12981                 }
12982                 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
12983         }
12984         rcu_read_unlock();
12985 }
12986 #endif /* CONFIG_NUMA_BALANCING */
12987 #endif /* CONFIG_SCHED_DEBUG */
12988
12989 __init void init_sched_fair_class(void)
12990 {
12991 #ifdef CONFIG_SMP
12992         int i;
12993
12994         for_each_possible_cpu(i) {
12995                 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
12996                 zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
12997                 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
12998                                         GFP_KERNEL, cpu_to_node(i));
12999
13000 #ifdef CONFIG_CFS_BANDWIDTH
13001                 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13002                 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13003 #endif
13004         }
13005
13006         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
13007
13008 #ifdef CONFIG_NO_HZ_COMMON
13009         nohz.next_balance = jiffies;
13010         nohz.next_blocked = jiffies;
13011         zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13012 #endif
13013 #endif /* SMP */
13014
13015 }