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