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