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