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