xref: /linux/kernel/sched/fair.c (revision 99d2592023e5d0a31f5f5a83c694df48239a1e6c)
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 #include <linux/sched/prio.h>
41 
42 #include <linux/cpuidle.h>
43 #include <linux/interrupt.h>
44 #include <linux/memory-tiers.h>
45 #include <linux/mempolicy.h>
46 #include <linux/mutex_api.h>
47 #include <linux/profile.h>
48 #include <linux/psi.h>
49 #include <linux/ratelimit.h>
50 #include <linux/task_work.h>
51 #include <linux/rbtree_augmented.h>
52 
53 #include <asm/switch_to.h>
54 
55 #include <uapi/linux/sched/types.h>
56 
57 #include "sched.h"
58 #include "stats.h"
59 #include "autogroup.h"
60 
61 /*
62  * The initial- and re-scaling of tunables is configurable
63  *
64  * Options are:
65  *
66  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
67  *   SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
68  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
69  *
70  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
71  */
72 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
73 
74 /*
75  * Minimal preemption granularity for CPU-bound tasks:
76  *
77  * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
78  */
79 unsigned int sysctl_sched_base_slice			= 700000ULL;
80 static unsigned int normalized_sysctl_sched_base_slice	= 700000ULL;
81 
82 __read_mostly unsigned int sysctl_sched_migration_cost	= 500000UL;
83 
84 static int __init setup_sched_thermal_decay_shift(char *str)
85 {
86 	pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
87 	return 1;
88 }
89 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
90 
91 /*
92  * For asym packing, by default the lower numbered CPU has higher priority.
93  */
94 int __weak arch_asym_cpu_priority(int cpu)
95 {
96 	return -cpu;
97 }
98 
99 /*
100  * The margin used when comparing utilization with CPU capacity.
101  *
102  * (default: ~20%)
103  */
104 #define fits_capacity(cap, max)	((cap) * 1280 < (max) * 1024)
105 
106 /*
107  * The margin used when comparing CPU capacities.
108  * is 'cap1' noticeably greater than 'cap2'
109  *
110  * (default: ~5%)
111  */
112 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
113 
114 #ifdef CONFIG_CFS_BANDWIDTH
115 /*
116  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
117  * each time a cfs_rq requests quota.
118  *
119  * Note: in the case that the slice exceeds the runtime remaining (either due
120  * to consumption or the quota being specified to be smaller than the slice)
121  * we will always only issue the remaining available time.
122  *
123  * (default: 5 msec, units: microseconds)
124  */
125 static unsigned int sysctl_sched_cfs_bandwidth_slice		= 5000UL;
126 #endif
127 
128 #ifdef CONFIG_NUMA_BALANCING
129 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
130 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
131 #endif
132 
133 #ifdef CONFIG_SYSCTL
134 static const struct ctl_table sched_fair_sysctls[] = {
135 #ifdef CONFIG_CFS_BANDWIDTH
136 	{
137 		.procname       = "sched_cfs_bandwidth_slice_us",
138 		.data           = &sysctl_sched_cfs_bandwidth_slice,
139 		.maxlen         = sizeof(unsigned int),
140 		.mode           = 0644,
141 		.proc_handler   = proc_dointvec_minmax,
142 		.extra1         = SYSCTL_ONE,
143 	},
144 #endif
145 #ifdef CONFIG_NUMA_BALANCING
146 	{
147 		.procname	= "numa_balancing_promote_rate_limit_MBps",
148 		.data		= &sysctl_numa_balancing_promote_rate_limit,
149 		.maxlen		= sizeof(unsigned int),
150 		.mode		= 0644,
151 		.proc_handler	= proc_dointvec_minmax,
152 		.extra1		= SYSCTL_ZERO,
153 	},
154 #endif /* CONFIG_NUMA_BALANCING */
155 };
156 
157 static int __init sched_fair_sysctl_init(void)
158 {
159 	register_sysctl_init("kernel", sched_fair_sysctls);
160 	return 0;
161 }
162 late_initcall(sched_fair_sysctl_init);
163 #endif /* CONFIG_SYSCTL */
164 
165 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
166 {
167 	lw->weight += inc;
168 	lw->inv_weight = 0;
169 }
170 
171 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
172 {
173 	lw->weight -= dec;
174 	lw->inv_weight = 0;
175 }
176 
177 static inline void update_load_set(struct load_weight *lw, unsigned long w)
178 {
179 	lw->weight = w;
180 	lw->inv_weight = 0;
181 }
182 
183 /*
184  * Increase the granularity value when there are more CPUs,
185  * because with more CPUs the 'effective latency' as visible
186  * to users decreases. But the relationship is not linear,
187  * so pick a second-best guess by going with the log2 of the
188  * number of CPUs.
189  *
190  * This idea comes from the SD scheduler of Con Kolivas:
191  */
192 static unsigned int get_update_sysctl_factor(void)
193 {
194 	unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
195 	unsigned int factor;
196 
197 	switch (sysctl_sched_tunable_scaling) {
198 	case SCHED_TUNABLESCALING_NONE:
199 		factor = 1;
200 		break;
201 	case SCHED_TUNABLESCALING_LINEAR:
202 		factor = cpus;
203 		break;
204 	case SCHED_TUNABLESCALING_LOG:
205 	default:
206 		factor = 1 + ilog2(cpus);
207 		break;
208 	}
209 
210 	return factor;
211 }
212 
213 static void update_sysctl(void)
214 {
215 	unsigned int factor = get_update_sysctl_factor();
216 
217 #define SET_SYSCTL(name) \
218 	(sysctl_##name = (factor) * normalized_sysctl_##name)
219 	SET_SYSCTL(sched_base_slice);
220 #undef SET_SYSCTL
221 }
222 
223 void __init sched_init_granularity(void)
224 {
225 	update_sysctl();
226 }
227 
228 #define WMULT_CONST	(~0U)
229 #define WMULT_SHIFT	32
230 
231 static void __update_inv_weight(struct load_weight *lw)
232 {
233 	unsigned long w;
234 
235 	if (likely(lw->inv_weight))
236 		return;
237 
238 	w = scale_load_down(lw->weight);
239 
240 	if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
241 		lw->inv_weight = 1;
242 	else if (unlikely(!w))
243 		lw->inv_weight = WMULT_CONST;
244 	else
245 		lw->inv_weight = WMULT_CONST / w;
246 }
247 
248 /*
249  * delta_exec * weight / lw.weight
250  *   OR
251  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
252  *
253  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
254  * we're guaranteed shift stays positive because inv_weight is guaranteed to
255  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
256  *
257  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
258  * weight/lw.weight <= 1, and therefore our shift will also be positive.
259  */
260 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
261 {
262 	u64 fact = scale_load_down(weight);
263 	u32 fact_hi = (u32)(fact >> 32);
264 	int shift = WMULT_SHIFT;
265 	int fs;
266 
267 	__update_inv_weight(lw);
268 
269 	if (unlikely(fact_hi)) {
270 		fs = fls(fact_hi);
271 		shift -= fs;
272 		fact >>= fs;
273 	}
274 
275 	fact = mul_u32_u32(fact, lw->inv_weight);
276 
277 	fact_hi = (u32)(fact >> 32);
278 	if (fact_hi) {
279 		fs = fls(fact_hi);
280 		shift -= fs;
281 		fact >>= fs;
282 	}
283 
284 	return mul_u64_u32_shr(delta_exec, fact, shift);
285 }
286 
287 /*
288  * delta /= w
289  */
290 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
291 {
292 	if (unlikely(se->load.weight != NICE_0_LOAD))
293 		delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
294 
295 	return delta;
296 }
297 
298 const struct sched_class fair_sched_class;
299 
300 /**************************************************************
301  * CFS operations on generic schedulable entities:
302  */
303 
304 #ifdef CONFIG_FAIR_GROUP_SCHED
305 
306 /* Walk up scheduling entities hierarchy */
307 #define for_each_sched_entity(se) \
308 		for (; se; se = se->parent)
309 
310 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
311 {
312 	struct rq *rq = rq_of(cfs_rq);
313 	int cpu = cpu_of(rq);
314 
315 	if (cfs_rq->on_list)
316 		return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
317 
318 	cfs_rq->on_list = 1;
319 
320 	/*
321 	 * Ensure we either appear before our parent (if already
322 	 * enqueued) or force our parent to appear after us when it is
323 	 * enqueued. The fact that we always enqueue bottom-up
324 	 * reduces this to two cases and a special case for the root
325 	 * cfs_rq. Furthermore, it also means that we will always reset
326 	 * tmp_alone_branch either when the branch is connected
327 	 * to a tree or when we reach the top of the tree
328 	 */
329 	if (cfs_rq->tg->parent &&
330 	    cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
331 		/*
332 		 * If parent is already on the list, we add the child
333 		 * just before. Thanks to circular linked property of
334 		 * the list, this means to put the child at the tail
335 		 * of the list that starts by parent.
336 		 */
337 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
338 			&(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
339 		/*
340 		 * The branch is now connected to its tree so we can
341 		 * reset tmp_alone_branch to the beginning of the
342 		 * list.
343 		 */
344 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
345 		return true;
346 	}
347 
348 	if (!cfs_rq->tg->parent) {
349 		/*
350 		 * cfs rq without parent should be put
351 		 * at the tail of the list.
352 		 */
353 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
354 			&rq->leaf_cfs_rq_list);
355 		/*
356 		 * We have reach the top of a tree so we can reset
357 		 * tmp_alone_branch to the beginning of the list.
358 		 */
359 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
360 		return true;
361 	}
362 
363 	/*
364 	 * The parent has not already been added so we want to
365 	 * make sure that it will be put after us.
366 	 * tmp_alone_branch points to the begin of the branch
367 	 * where we will add parent.
368 	 */
369 	list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
370 	/*
371 	 * update tmp_alone_branch to points to the new begin
372 	 * of the branch
373 	 */
374 	rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
375 	return false;
376 }
377 
378 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
379 {
380 	if (cfs_rq->on_list) {
381 		struct rq *rq = rq_of(cfs_rq);
382 
383 		/*
384 		 * With cfs_rq being unthrottled/throttled during an enqueue,
385 		 * it can happen the tmp_alone_branch points to the leaf that
386 		 * we finally want to delete. In this case, tmp_alone_branch moves
387 		 * to the prev element but it will point to rq->leaf_cfs_rq_list
388 		 * at the end of the enqueue.
389 		 */
390 		if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
391 			rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
392 
393 		list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
394 		cfs_rq->on_list = 0;
395 	}
396 }
397 
398 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
399 {
400 	WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
401 }
402 
403 /* Iterate through all leaf cfs_rq's on a runqueue */
404 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)			\
405 	list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,	\
406 				 leaf_cfs_rq_list)
407 
408 /* Do the two (enqueued) entities belong to the same group ? */
409 static inline struct cfs_rq *
410 is_same_group(struct sched_entity *se, struct sched_entity *pse)
411 {
412 	if (se->cfs_rq == pse->cfs_rq)
413 		return se->cfs_rq;
414 
415 	return NULL;
416 }
417 
418 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
419 {
420 	return se->parent;
421 }
422 
423 static void
424 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
425 {
426 	int se_depth, pse_depth;
427 
428 	/*
429 	 * preemption test can be made between sibling entities who are in the
430 	 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
431 	 * both tasks until we find their ancestors who are siblings of common
432 	 * parent.
433 	 */
434 
435 	/* First walk up until both entities are at same depth */
436 	se_depth = (*se)->depth;
437 	pse_depth = (*pse)->depth;
438 
439 	while (se_depth > pse_depth) {
440 		se_depth--;
441 		*se = parent_entity(*se);
442 	}
443 
444 	while (pse_depth > se_depth) {
445 		pse_depth--;
446 		*pse = parent_entity(*pse);
447 	}
448 
449 	while (!is_same_group(*se, *pse)) {
450 		*se = parent_entity(*se);
451 		*pse = parent_entity(*pse);
452 	}
453 }
454 
455 static int tg_is_idle(struct task_group *tg)
456 {
457 	return tg->idle > 0;
458 }
459 
460 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
461 {
462 	return cfs_rq->idle > 0;
463 }
464 
465 static int se_is_idle(struct sched_entity *se)
466 {
467 	if (entity_is_task(se))
468 		return task_has_idle_policy(task_of(se));
469 	return cfs_rq_is_idle(group_cfs_rq(se));
470 }
471 
472 #else /* !CONFIG_FAIR_GROUP_SCHED: */
473 
474 #define for_each_sched_entity(se) \
475 		for (; se; se = NULL)
476 
477 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
478 {
479 	return true;
480 }
481 
482 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
483 {
484 }
485 
486 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
487 {
488 }
489 
490 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
491 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
492 
493 static inline struct sched_entity *parent_entity(struct sched_entity *se)
494 {
495 	return NULL;
496 }
497 
498 static inline void
499 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
500 {
501 }
502 
503 static inline int tg_is_idle(struct task_group *tg)
504 {
505 	return 0;
506 }
507 
508 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
509 {
510 	return 0;
511 }
512 
513 static int se_is_idle(struct sched_entity *se)
514 {
515 	return task_has_idle_policy(task_of(se));
516 }
517 
518 #endif /* !CONFIG_FAIR_GROUP_SCHED */
519 
520 static __always_inline
521 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
522 
523 /**************************************************************
524  * Scheduling class tree data structure manipulation methods:
525  */
526 
527 extern void __BUILD_BUG_vruntime_cmp(void);
528 
529 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */
530 
531 #define vruntime_cmp(A, CMP_STR, B) ({				\
532 	int __res = 0;						\
533 								\
534 	if (!__builtin_strcmp(CMP_STR, "<")) {			\
535 		__res = ((s64)((A)-(B)) < 0);			\
536 	} else if (!__builtin_strcmp(CMP_STR, "<=")) {		\
537 		__res = ((s64)((A)-(B)) <= 0);			\
538 	} else if (!__builtin_strcmp(CMP_STR, ">")) {		\
539 		__res = ((s64)((A)-(B)) > 0);			\
540 	} else if (!__builtin_strcmp(CMP_STR, ">=")) {		\
541 		__res = ((s64)((A)-(B)) >= 0);			\
542 	} else {						\
543 		/* Unknown operator throws linker error: */	\
544 		__BUILD_BUG_vruntime_cmp();			\
545 	}							\
546 								\
547 	__res;							\
548 })
549 
550 extern void __BUILD_BUG_vruntime_op(void);
551 
552 #define vruntime_op(A, OP_STR, B) ({				\
553 	s64 __res = 0;						\
554 								\
555 	if (!__builtin_strcmp(OP_STR, "-")) {			\
556 		__res = (s64)((A)-(B));				\
557 	} else {						\
558 		/* Unknown operator throws linker error: */	\
559 		__BUILD_BUG_vruntime_op();			\
560 	}							\
561 								\
562 	__res;						\
563 })
564 
565 
566 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
567 {
568 	if (vruntime_cmp(vruntime, ">", max_vruntime))
569 		max_vruntime = vruntime;
570 
571 	return max_vruntime;
572 }
573 
574 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
575 {
576 	if (vruntime_cmp(vruntime, "<", min_vruntime))
577 		min_vruntime = vruntime;
578 
579 	return min_vruntime;
580 }
581 
582 static inline bool entity_before(const struct sched_entity *a,
583 				 const struct sched_entity *b)
584 {
585 	/*
586 	 * Tiebreak on vruntime seems unnecessary since it can
587 	 * hardly happen.
588 	 */
589 	return vruntime_cmp(a->deadline, "<", b->deadline);
590 }
591 
592 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
593 {
594 	return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime);
595 }
596 
597 #define __node_2_se(node) \
598 	rb_entry((node), struct sched_entity, run_node)
599 
600 /*
601  * Compute virtual time from the per-task service numbers:
602  *
603  * Fair schedulers conserve lag:
604  *
605  *   \Sum lag_i = 0
606  *
607  * Where lag_i is given by:
608  *
609  *   lag_i = S - s_i = w_i * (V - v_i)
610  *
611  * Where S is the ideal service time and V is it's virtual time counterpart.
612  * Therefore:
613  *
614  *   \Sum lag_i = 0
615  *   \Sum w_i * (V - v_i) = 0
616  *   \Sum (w_i * V - w_i * v_i) = 0
617  *
618  * From which we can solve an expression for V in v_i (which we have in
619  * se->vruntime):
620  *
621  *       \Sum v_i * w_i   \Sum v_i * w_i
622  *   V = -------------- = --------------
623  *          \Sum w_i            W
624  *
625  * Specifically, this is the weighted average of all entity virtual runtimes.
626  *
627  * [[ NOTE: this is only equal to the ideal scheduler under the condition
628  *          that join/leave operations happen at lag_i = 0, otherwise the
629  *          virtual time has non-contiguous motion equivalent to:
630  *
631  *	      V +-= lag_i / W
632  *
633  *	    Also see the comment in place_entity() that deals with this. ]]
634  *
635  * However, since v_i is u64, and the multiplication could easily overflow
636  * transform it into a relative form that uses smaller quantities:
637  *
638  * Substitute: v_i == (v_i - v0) + v0
639  *
640  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
641  * V = ---------------------------- = --------------------- + v0
642  *                  W                            W
643  *
644  * Which we track using:
645  *
646  *                    v0 := cfs_rq->zero_vruntime
647  * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime
648  *              \Sum w_i := cfs_rq->sum_weight
649  *
650  * Since zero_vruntime closely tracks the per-task service, these
651  * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag
652  * induced in the system due to quantisation.
653  *
654  * Also, we use scale_load_down() to reduce the size.
655  *
656  * As measured, the max (key * weight) value was ~44 bits for a kernel build.
657  */
658 static void
659 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
660 {
661 	unsigned long weight = scale_load_down(se->load.weight);
662 	s64 key = entity_key(cfs_rq, se);
663 
664 	cfs_rq->sum_w_vruntime += key * weight;
665 	cfs_rq->sum_weight += weight;
666 }
667 
668 static void
669 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
670 {
671 	unsigned long weight = scale_load_down(se->load.weight);
672 	s64 key = entity_key(cfs_rq, se);
673 
674 	cfs_rq->sum_w_vruntime -= key * weight;
675 	cfs_rq->sum_weight -= weight;
676 }
677 
678 static inline
679 void sum_w_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
680 {
681 	/*
682 	 * v' = v + d ==> sum_w_vruntime' = sum_runtime - d*sum_weight
683 	 */
684 	cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta;
685 }
686 
687 /*
688  * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
689  * For this to be so, the result of this function must have a left bias.
690  */
691 u64 avg_vruntime(struct cfs_rq *cfs_rq)
692 {
693 	struct sched_entity *curr = cfs_rq->curr;
694 	s64 avg = cfs_rq->sum_w_vruntime;
695 	long load = cfs_rq->sum_weight;
696 
697 	if (curr && curr->on_rq) {
698 		unsigned long weight = scale_load_down(curr->load.weight);
699 
700 		avg += entity_key(cfs_rq, curr) * weight;
701 		load += weight;
702 	}
703 
704 	if (load) {
705 		/* sign flips effective floor / ceiling */
706 		if (avg < 0)
707 			avg -= (load - 1);
708 		avg = div_s64(avg, load);
709 	}
710 
711 	return cfs_rq->zero_vruntime + avg;
712 }
713 
714 /*
715  * lag_i = S - s_i = w_i * (V - v_i)
716  *
717  * However, since V is approximated by the weighted average of all entities it
718  * is possible -- by addition/removal/reweight to the tree -- to move V around
719  * and end up with a larger lag than we started with.
720  *
721  * Limit this to either double the slice length with a minimum of TICK_NSEC
722  * since that is the timing granularity.
723  *
724  * EEVDF gives the following limit for a steady state system:
725  *
726  *   -r_max < lag < max(r_max, q)
727  *
728  * XXX could add max_slice to the augmented data to track this.
729  */
730 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
731 {
732 	s64 vlag, limit;
733 
734 	WARN_ON_ONCE(!se->on_rq);
735 
736 	vlag = avg_vruntime(cfs_rq) - se->vruntime;
737 	limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
738 
739 	se->vlag = clamp(vlag, -limit, limit);
740 }
741 
742 /*
743  * Entity is eligible once it received less service than it ought to have,
744  * eg. lag >= 0.
745  *
746  * lag_i = S - s_i = w_i*(V - v_i)
747  *
748  * lag_i >= 0 -> V >= v_i
749  *
750  *     \Sum (v_i - v)*w_i
751  * V = ------------------ + v
752  *          \Sum w_i
753  *
754  * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
755  *
756  * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
757  *       to the loss in precision caused by the division.
758  */
759 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
760 {
761 	struct sched_entity *curr = cfs_rq->curr;
762 	s64 avg = cfs_rq->sum_w_vruntime;
763 	long load = cfs_rq->sum_weight;
764 
765 	if (curr && curr->on_rq) {
766 		unsigned long weight = scale_load_down(curr->load.weight);
767 
768 		avg += entity_key(cfs_rq, curr) * weight;
769 		load += weight;
770 	}
771 
772 	return avg >= vruntime_op(vruntime, "-", cfs_rq->zero_vruntime) * load;
773 }
774 
775 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
776 {
777 	return vruntime_eligible(cfs_rq, se->vruntime);
778 }
779 
780 static void update_zero_vruntime(struct cfs_rq *cfs_rq)
781 {
782 	u64 vruntime = avg_vruntime(cfs_rq);
783 	s64 delta = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime);
784 
785 	sum_w_vruntime_update(cfs_rq, delta);
786 
787 	cfs_rq->zero_vruntime = vruntime;
788 }
789 
790 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
791 {
792 	struct sched_entity *root = __pick_root_entity(cfs_rq);
793 	struct sched_entity *curr = cfs_rq->curr;
794 	u64 min_slice = ~0ULL;
795 
796 	if (curr && curr->on_rq)
797 		min_slice = curr->slice;
798 
799 	if (root)
800 		min_slice = min(min_slice, root->min_slice);
801 
802 	return min_slice;
803 }
804 
805 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
806 {
807 	return entity_before(__node_2_se(a), __node_2_se(b));
808 }
809 
810 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
811 {
812 	if (node) {
813 		struct sched_entity *rse = __node_2_se(node);
814 
815 		if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime))
816 			se->min_vruntime = rse->min_vruntime;
817 	}
818 }
819 
820 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
821 {
822 	if (node) {
823 		struct sched_entity *rse = __node_2_se(node);
824 		if (rse->min_slice < se->min_slice)
825 			se->min_slice = rse->min_slice;
826 	}
827 }
828 
829 /*
830  * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
831  */
832 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
833 {
834 	u64 old_min_vruntime = se->min_vruntime;
835 	u64 old_min_slice = se->min_slice;
836 	struct rb_node *node = &se->run_node;
837 
838 	se->min_vruntime = se->vruntime;
839 	__min_vruntime_update(se, node->rb_right);
840 	__min_vruntime_update(se, node->rb_left);
841 
842 	se->min_slice = se->slice;
843 	__min_slice_update(se, node->rb_right);
844 	__min_slice_update(se, node->rb_left);
845 
846 	return se->min_vruntime == old_min_vruntime &&
847 	       se->min_slice == old_min_slice;
848 }
849 
850 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
851 		     run_node, min_vruntime, min_vruntime_update);
852 
853 /*
854  * Enqueue an entity into the rb-tree:
855  */
856 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
857 {
858 	sum_w_vruntime_add(cfs_rq, se);
859 	update_zero_vruntime(cfs_rq);
860 	se->min_vruntime = se->vruntime;
861 	se->min_slice = se->slice;
862 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
863 				__entity_less, &min_vruntime_cb);
864 }
865 
866 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
867 {
868 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
869 				  &min_vruntime_cb);
870 	sum_w_vruntime_sub(cfs_rq, se);
871 	update_zero_vruntime(cfs_rq);
872 }
873 
874 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
875 {
876 	struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
877 
878 	if (!root)
879 		return NULL;
880 
881 	return __node_2_se(root);
882 }
883 
884 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
885 {
886 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
887 
888 	if (!left)
889 		return NULL;
890 
891 	return __node_2_se(left);
892 }
893 
894 /*
895  * Set the vruntime up to which an entity can run before looking
896  * for another entity to pick.
897  * In case of run to parity, we use the shortest slice of the enqueued
898  * entities to set the protected period.
899  * When run to parity is disabled, we give a minimum quantum to the running
900  * entity to ensure progress.
901  */
902 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
903 {
904 	u64 slice = normalized_sysctl_sched_base_slice;
905 	u64 vprot = se->deadline;
906 
907 	if (sched_feat(RUN_TO_PARITY))
908 		slice = cfs_rq_min_slice(cfs_rq);
909 
910 	slice = min(slice, se->slice);
911 	if (slice != se->slice)
912 		vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
913 
914 	se->vprot = vprot;
915 }
916 
917 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
918 {
919 	u64 slice = cfs_rq_min_slice(cfs_rq);
920 
921 	se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se));
922 }
923 
924 static inline bool protect_slice(struct sched_entity *se)
925 {
926 	return vruntime_cmp(se->vruntime, "<", se->vprot);
927 }
928 
929 static inline void cancel_protect_slice(struct sched_entity *se)
930 {
931 	if (protect_slice(se))
932 		se->vprot = se->vruntime;
933 }
934 
935 /*
936  * Earliest Eligible Virtual Deadline First
937  *
938  * In order to provide latency guarantees for different request sizes
939  * EEVDF selects the best runnable task from two criteria:
940  *
941  *  1) the task must be eligible (must be owed service)
942  *
943  *  2) from those tasks that meet 1), we select the one
944  *     with the earliest virtual deadline.
945  *
946  * We can do this in O(log n) time due to an augmented RB-tree. The
947  * tree keeps the entries sorted on deadline, but also functions as a
948  * heap based on the vruntime by keeping:
949  *
950  *  se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
951  *
952  * Which allows tree pruning through eligibility.
953  */
954 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
955 {
956 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
957 	struct sched_entity *se = __pick_first_entity(cfs_rq);
958 	struct sched_entity *curr = cfs_rq->curr;
959 	struct sched_entity *best = NULL;
960 
961 	/*
962 	 * We can safely skip eligibility check if there is only one entity
963 	 * in this cfs_rq, saving some cycles.
964 	 */
965 	if (cfs_rq->nr_queued == 1)
966 		return curr && curr->on_rq ? curr : se;
967 
968 	/*
969 	 * Picking the ->next buddy will affect latency but not fairness.
970 	 */
971 	if (sched_feat(PICK_BUDDY) &&
972 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
973 		/* ->next will never be delayed */
974 		WARN_ON_ONCE(cfs_rq->next->sched_delayed);
975 		return cfs_rq->next;
976 	}
977 
978 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
979 		curr = NULL;
980 
981 	if (curr && protect && protect_slice(curr))
982 		return curr;
983 
984 	/* Pick the leftmost entity if it's eligible */
985 	if (se && entity_eligible(cfs_rq, se)) {
986 		best = se;
987 		goto found;
988 	}
989 
990 	/* Heap search for the EEVD entity */
991 	while (node) {
992 		struct rb_node *left = node->rb_left;
993 
994 		/*
995 		 * Eligible entities in left subtree are always better
996 		 * choices, since they have earlier deadlines.
997 		 */
998 		if (left && vruntime_eligible(cfs_rq,
999 					__node_2_se(left)->min_vruntime)) {
1000 			node = left;
1001 			continue;
1002 		}
1003 
1004 		se = __node_2_se(node);
1005 
1006 		/*
1007 		 * The left subtree either is empty or has no eligible
1008 		 * entity, so check the current node since it is the one
1009 		 * with earliest deadline that might be eligible.
1010 		 */
1011 		if (entity_eligible(cfs_rq, se)) {
1012 			best = se;
1013 			break;
1014 		}
1015 
1016 		node = node->rb_right;
1017 	}
1018 found:
1019 	if (!best || (curr && entity_before(curr, best)))
1020 		best = curr;
1021 
1022 	return best;
1023 }
1024 
1025 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
1026 {
1027 	return __pick_eevdf(cfs_rq, true);
1028 }
1029 
1030 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1031 {
1032 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1033 
1034 	if (!last)
1035 		return NULL;
1036 
1037 	return __node_2_se(last);
1038 }
1039 
1040 /**************************************************************
1041  * Scheduling class statistics methods:
1042  */
1043 int sched_update_scaling(void)
1044 {
1045 	unsigned int factor = get_update_sysctl_factor();
1046 
1047 #define WRT_SYSCTL(name) \
1048 	(normalized_sysctl_##name = sysctl_##name / (factor))
1049 	WRT_SYSCTL(sched_base_slice);
1050 #undef WRT_SYSCTL
1051 
1052 	return 0;
1053 }
1054 
1055 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1056 
1057 /*
1058  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1059  * this is probably good enough.
1060  */
1061 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1062 {
1063 	if (vruntime_cmp(se->vruntime, "<", se->deadline))
1064 		return false;
1065 
1066 	/*
1067 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1068 	 * nice) while the request time r_i is determined by
1069 	 * sysctl_sched_base_slice.
1070 	 */
1071 	if (!se->custom_slice)
1072 		se->slice = sysctl_sched_base_slice;
1073 
1074 	/*
1075 	 * EEVDF: vd_i = ve_i + r_i / w_i
1076 	 */
1077 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1078 
1079 	/*
1080 	 * The task has consumed its request, reschedule.
1081 	 */
1082 	return true;
1083 }
1084 
1085 #include "pelt.h"
1086 
1087 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1088 static unsigned long task_h_load(struct task_struct *p);
1089 static unsigned long capacity_of(int cpu);
1090 
1091 /* Give new sched_entity start runnable values to heavy its load in infant time */
1092 void init_entity_runnable_average(struct sched_entity *se)
1093 {
1094 	struct sched_avg *sa = &se->avg;
1095 
1096 	memset(sa, 0, sizeof(*sa));
1097 
1098 	/*
1099 	 * Tasks are initialized with full load to be seen as heavy tasks until
1100 	 * they get a chance to stabilize to their real load level.
1101 	 * Group entities are initialized with zero load to reflect the fact that
1102 	 * nothing has been attached to the task group yet.
1103 	 */
1104 	if (entity_is_task(se))
1105 		sa->load_avg = scale_load_down(se->load.weight);
1106 
1107 	/* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1108 }
1109 
1110 /*
1111  * With new tasks being created, their initial util_avgs are extrapolated
1112  * based on the cfs_rq's current util_avg:
1113  *
1114  *   util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1115  *		* se_weight(se)
1116  *
1117  * However, in many cases, the above util_avg does not give a desired
1118  * value. Moreover, the sum of the util_avgs may be divergent, such
1119  * as when the series is a harmonic series.
1120  *
1121  * To solve this problem, we also cap the util_avg of successive tasks to
1122  * only 1/2 of the left utilization budget:
1123  *
1124  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1125  *
1126  * where n denotes the nth task and cpu_scale the CPU capacity.
1127  *
1128  * For example, for a CPU with 1024 of capacity, a simplest series from
1129  * the beginning would be like:
1130  *
1131  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1132  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1133  *
1134  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1135  * if util_avg > util_avg_cap.
1136  */
1137 void post_init_entity_util_avg(struct task_struct *p)
1138 {
1139 	struct sched_entity *se = &p->se;
1140 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1141 	struct sched_avg *sa = &se->avg;
1142 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1143 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1144 
1145 	if (p->sched_class != &fair_sched_class) {
1146 		/*
1147 		 * For !fair tasks do:
1148 		 *
1149 		update_cfs_rq_load_avg(now, cfs_rq);
1150 		attach_entity_load_avg(cfs_rq, se);
1151 		switched_from_fair(rq, p);
1152 		 *
1153 		 * such that the next switched_to_fair() has the
1154 		 * expected state.
1155 		 */
1156 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1157 		return;
1158 	}
1159 
1160 	if (cap > 0) {
1161 		if (cfs_rq->avg.util_avg != 0) {
1162 			sa->util_avg  = cfs_rq->avg.util_avg * se_weight(se);
1163 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1164 
1165 			if (sa->util_avg > cap)
1166 				sa->util_avg = cap;
1167 		} else {
1168 			sa->util_avg = cap;
1169 		}
1170 	}
1171 
1172 	sa->runnable_avg = sa->util_avg;
1173 }
1174 
1175 static s64 update_se(struct rq *rq, struct sched_entity *se)
1176 {
1177 	u64 now = rq_clock_task(rq);
1178 	s64 delta_exec;
1179 
1180 	delta_exec = now - se->exec_start;
1181 	if (unlikely(delta_exec <= 0))
1182 		return delta_exec;
1183 
1184 	se->exec_start = now;
1185 	if (entity_is_task(se)) {
1186 		struct task_struct *donor = task_of(se);
1187 		struct task_struct *running = rq->curr;
1188 		/*
1189 		 * If se is a task, we account the time against the running
1190 		 * task, as w/ proxy-exec they may not be the same.
1191 		 */
1192 		running->se.exec_start = now;
1193 		running->se.sum_exec_runtime += delta_exec;
1194 
1195 		trace_sched_stat_runtime(running, delta_exec);
1196 		account_group_exec_runtime(running, delta_exec);
1197 
1198 		/* cgroup time is always accounted against the donor */
1199 		cgroup_account_cputime(donor, delta_exec);
1200 	} else {
1201 		/* If not task, account the time against donor se  */
1202 		se->sum_exec_runtime += delta_exec;
1203 	}
1204 
1205 	if (schedstat_enabled()) {
1206 		struct sched_statistics *stats;
1207 
1208 		stats = __schedstats_from_se(se);
1209 		__schedstat_set(stats->exec_max,
1210 				max(delta_exec, stats->exec_max));
1211 	}
1212 
1213 	return delta_exec;
1214 }
1215 
1216 static void set_next_buddy(struct sched_entity *se);
1217 
1218 /*
1219  * Used by other classes to account runtime.
1220  */
1221 s64 update_curr_common(struct rq *rq)
1222 {
1223 	return update_se(rq, &rq->donor->se);
1224 }
1225 
1226 /*
1227  * Update the current task's runtime statistics.
1228  */
1229 static void update_curr(struct cfs_rq *cfs_rq)
1230 {
1231 	/*
1232 	 * Note: cfs_rq->curr corresponds to the task picked to
1233 	 * run (ie: rq->donor.se) which due to proxy-exec may
1234 	 * not necessarily be the actual task running
1235 	 * (rq->curr.se). This is easy to confuse!
1236 	 */
1237 	struct sched_entity *curr = cfs_rq->curr;
1238 	struct rq *rq = rq_of(cfs_rq);
1239 	s64 delta_exec;
1240 	bool resched;
1241 
1242 	if (unlikely(!curr))
1243 		return;
1244 
1245 	delta_exec = update_se(rq, curr);
1246 	if (unlikely(delta_exec <= 0))
1247 		return;
1248 
1249 	curr->vruntime += calc_delta_fair(delta_exec, curr);
1250 	resched = update_deadline(cfs_rq, curr);
1251 
1252 	if (entity_is_task(curr)) {
1253 		/*
1254 		 * If the fair_server is active, we need to account for the
1255 		 * fair_server time whether or not the task is running on
1256 		 * behalf of fair_server or not:
1257 		 *  - If the task is running on behalf of fair_server, we need
1258 		 *    to limit its time based on the assigned runtime.
1259 		 *  - Fair task that runs outside of fair_server should account
1260 		 *    against fair_server such that it can account for this time
1261 		 *    and possibly avoid running this period.
1262 		 */
1263 		dl_server_update(&rq->fair_server, delta_exec);
1264 	}
1265 
1266 	account_cfs_rq_runtime(cfs_rq, delta_exec);
1267 
1268 	if (cfs_rq->nr_queued == 1)
1269 		return;
1270 
1271 	if (resched || !protect_slice(curr)) {
1272 		resched_curr_lazy(rq);
1273 		clear_buddies(cfs_rq, curr);
1274 	}
1275 }
1276 
1277 static void update_curr_fair(struct rq *rq)
1278 {
1279 	update_curr(cfs_rq_of(&rq->donor->se));
1280 }
1281 
1282 static inline void
1283 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1284 {
1285 	struct sched_statistics *stats;
1286 	struct task_struct *p = NULL;
1287 
1288 	if (!schedstat_enabled())
1289 		return;
1290 
1291 	stats = __schedstats_from_se(se);
1292 
1293 	if (entity_is_task(se))
1294 		p = task_of(se);
1295 
1296 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
1297 }
1298 
1299 static inline void
1300 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1301 {
1302 	struct sched_statistics *stats;
1303 	struct task_struct *p = NULL;
1304 
1305 	if (!schedstat_enabled())
1306 		return;
1307 
1308 	stats = __schedstats_from_se(se);
1309 
1310 	/*
1311 	 * When the sched_schedstat changes from 0 to 1, some sched se
1312 	 * maybe already in the runqueue, the se->statistics.wait_start
1313 	 * will be 0.So it will let the delta wrong. We need to avoid this
1314 	 * scenario.
1315 	 */
1316 	if (unlikely(!schedstat_val(stats->wait_start)))
1317 		return;
1318 
1319 	if (entity_is_task(se))
1320 		p = task_of(se);
1321 
1322 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
1323 }
1324 
1325 static inline void
1326 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1327 {
1328 	struct sched_statistics *stats;
1329 	struct task_struct *tsk = NULL;
1330 
1331 	if (!schedstat_enabled())
1332 		return;
1333 
1334 	stats = __schedstats_from_se(se);
1335 
1336 	if (entity_is_task(se))
1337 		tsk = task_of(se);
1338 
1339 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1340 }
1341 
1342 /*
1343  * Task is being enqueued - update stats:
1344  */
1345 static inline void
1346 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1347 {
1348 	if (!schedstat_enabled())
1349 		return;
1350 
1351 	/*
1352 	 * Are we enqueueing a waiting task? (for current tasks
1353 	 * a dequeue/enqueue event is a NOP)
1354 	 */
1355 	if (se != cfs_rq->curr)
1356 		update_stats_wait_start_fair(cfs_rq, se);
1357 
1358 	if (flags & ENQUEUE_WAKEUP)
1359 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
1360 }
1361 
1362 static inline void
1363 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1364 {
1365 
1366 	if (!schedstat_enabled())
1367 		return;
1368 
1369 	/*
1370 	 * Mark the end of the wait period if dequeueing a
1371 	 * waiting task:
1372 	 */
1373 	if (se != cfs_rq->curr)
1374 		update_stats_wait_end_fair(cfs_rq, se);
1375 
1376 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1377 		struct task_struct *tsk = task_of(se);
1378 		unsigned int state;
1379 
1380 		/* XXX racy against TTWU */
1381 		state = READ_ONCE(tsk->__state);
1382 		if (state & TASK_INTERRUPTIBLE)
1383 			__schedstat_set(tsk->stats.sleep_start,
1384 				      rq_clock(rq_of(cfs_rq)));
1385 		if (state & TASK_UNINTERRUPTIBLE)
1386 			__schedstat_set(tsk->stats.block_start,
1387 				      rq_clock(rq_of(cfs_rq)));
1388 	}
1389 }
1390 
1391 /*
1392  * We are picking a new current task - update its stats:
1393  */
1394 static inline void
1395 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1396 {
1397 	/*
1398 	 * We are starting a new run period:
1399 	 */
1400 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
1401 }
1402 
1403 /**************************************************
1404  * Scheduling class queueing methods:
1405  */
1406 
1407 static inline bool is_core_idle(int cpu)
1408 {
1409 #ifdef CONFIG_SCHED_SMT
1410 	int sibling;
1411 
1412 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1413 		if (cpu == sibling)
1414 			continue;
1415 
1416 		if (!idle_cpu(sibling))
1417 			return false;
1418 	}
1419 #endif
1420 
1421 	return true;
1422 }
1423 
1424 #ifdef CONFIG_NUMA
1425 #define NUMA_IMBALANCE_MIN 2
1426 
1427 static inline long
1428 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1429 {
1430 	/*
1431 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1432 	 * threshold. Above this threshold, individual tasks may be contending
1433 	 * for both memory bandwidth and any shared HT resources.  This is an
1434 	 * approximation as the number of running tasks may not be related to
1435 	 * the number of busy CPUs due to sched_setaffinity.
1436 	 */
1437 	if (dst_running > imb_numa_nr)
1438 		return imbalance;
1439 
1440 	/*
1441 	 * Allow a small imbalance based on a simple pair of communicating
1442 	 * tasks that remain local when the destination is lightly loaded.
1443 	 */
1444 	if (imbalance <= NUMA_IMBALANCE_MIN)
1445 		return 0;
1446 
1447 	return imbalance;
1448 }
1449 #endif /* CONFIG_NUMA */
1450 
1451 #ifdef CONFIG_NUMA_BALANCING
1452 /*
1453  * Approximate time to scan a full NUMA task in ms. The task scan period is
1454  * calculated based on the tasks virtual memory size and
1455  * numa_balancing_scan_size.
1456  */
1457 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1458 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1459 
1460 /* Portion of address space to scan in MB */
1461 unsigned int sysctl_numa_balancing_scan_size = 256;
1462 
1463 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1464 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1465 
1466 /* The page with hint page fault latency < threshold in ms is considered hot */
1467 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1468 
1469 struct numa_group {
1470 	refcount_t refcount;
1471 
1472 	spinlock_t lock; /* nr_tasks, tasks */
1473 	int nr_tasks;
1474 	pid_t gid;
1475 	int active_nodes;
1476 
1477 	struct rcu_head rcu;
1478 	unsigned long total_faults;
1479 	unsigned long max_faults_cpu;
1480 	/*
1481 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
1482 	 *
1483 	 * Faults_cpu is used to decide whether memory should move
1484 	 * towards the CPU. As a consequence, these stats are weighted
1485 	 * more by CPU use than by memory faults.
1486 	 */
1487 	unsigned long faults[];
1488 };
1489 
1490 /*
1491  * For functions that can be called in multiple contexts that permit reading
1492  * ->numa_group (see struct task_struct for locking rules).
1493  */
1494 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1495 {
1496 	return rcu_dereference_check(p->numa_group, p == current ||
1497 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1498 }
1499 
1500 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1501 {
1502 	return rcu_dereference_protected(p->numa_group, p == current);
1503 }
1504 
1505 static inline unsigned long group_faults_priv(struct numa_group *ng);
1506 static inline unsigned long group_faults_shared(struct numa_group *ng);
1507 
1508 static unsigned int task_nr_scan_windows(struct task_struct *p)
1509 {
1510 	unsigned long rss = 0;
1511 	unsigned long nr_scan_pages;
1512 
1513 	/*
1514 	 * Calculations based on RSS as non-present and empty pages are skipped
1515 	 * by the PTE scanner and NUMA hinting faults should be trapped based
1516 	 * on resident pages
1517 	 */
1518 	nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
1519 	rss = get_mm_rss(p->mm);
1520 	if (!rss)
1521 		rss = nr_scan_pages;
1522 
1523 	rss = round_up(rss, nr_scan_pages);
1524 	return rss / nr_scan_pages;
1525 }
1526 
1527 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1528 #define MAX_SCAN_WINDOW 2560
1529 
1530 static unsigned int task_scan_min(struct task_struct *p)
1531 {
1532 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1533 	unsigned int scan, floor;
1534 	unsigned int windows = 1;
1535 
1536 	if (scan_size < MAX_SCAN_WINDOW)
1537 		windows = MAX_SCAN_WINDOW / scan_size;
1538 	floor = 1000 / windows;
1539 
1540 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1541 	return max_t(unsigned int, floor, scan);
1542 }
1543 
1544 static unsigned int task_scan_start(struct task_struct *p)
1545 {
1546 	unsigned long smin = task_scan_min(p);
1547 	unsigned long period = smin;
1548 	struct numa_group *ng;
1549 
1550 	/* Scale the maximum scan period with the amount of shared memory. */
1551 	rcu_read_lock();
1552 	ng = rcu_dereference_all(p->numa_group);
1553 	if (ng) {
1554 		unsigned long shared = group_faults_shared(ng);
1555 		unsigned long private = group_faults_priv(ng);
1556 
1557 		period *= refcount_read(&ng->refcount);
1558 		period *= shared + 1;
1559 		period /= private + shared + 1;
1560 	}
1561 	rcu_read_unlock();
1562 
1563 	return max(smin, period);
1564 }
1565 
1566 static unsigned int task_scan_max(struct task_struct *p)
1567 {
1568 	unsigned long smin = task_scan_min(p);
1569 	unsigned long smax;
1570 	struct numa_group *ng;
1571 
1572 	/* Watch for min being lower than max due to floor calculations */
1573 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1574 
1575 	/* Scale the maximum scan period with the amount of shared memory. */
1576 	ng = deref_curr_numa_group(p);
1577 	if (ng) {
1578 		unsigned long shared = group_faults_shared(ng);
1579 		unsigned long private = group_faults_priv(ng);
1580 		unsigned long period = smax;
1581 
1582 		period *= refcount_read(&ng->refcount);
1583 		period *= shared + 1;
1584 		period /= private + shared + 1;
1585 
1586 		smax = max(smax, period);
1587 	}
1588 
1589 	return max(smin, smax);
1590 }
1591 
1592 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1593 {
1594 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1595 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1596 }
1597 
1598 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1599 {
1600 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1601 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1602 }
1603 
1604 /* Shared or private faults. */
1605 #define NR_NUMA_HINT_FAULT_TYPES 2
1606 
1607 /* Memory and CPU locality */
1608 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1609 
1610 /* Averaged statistics, and temporary buffers. */
1611 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1612 
1613 pid_t task_numa_group_id(struct task_struct *p)
1614 {
1615 	struct numa_group *ng;
1616 	pid_t gid = 0;
1617 
1618 	rcu_read_lock();
1619 	ng = rcu_dereference_all(p->numa_group);
1620 	if (ng)
1621 		gid = ng->gid;
1622 	rcu_read_unlock();
1623 
1624 	return gid;
1625 }
1626 
1627 /*
1628  * The averaged statistics, shared & private, memory & CPU,
1629  * occupy the first half of the array. The second half of the
1630  * array is for current counters, which are averaged into the
1631  * first set by task_numa_placement.
1632  */
1633 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1634 {
1635 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1636 }
1637 
1638 static inline unsigned long task_faults(struct task_struct *p, int nid)
1639 {
1640 	if (!p->numa_faults)
1641 		return 0;
1642 
1643 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1644 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1645 }
1646 
1647 static inline unsigned long group_faults(struct task_struct *p, int nid)
1648 {
1649 	struct numa_group *ng = deref_task_numa_group(p);
1650 
1651 	if (!ng)
1652 		return 0;
1653 
1654 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1655 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1656 }
1657 
1658 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1659 {
1660 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1661 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1662 }
1663 
1664 static inline unsigned long group_faults_priv(struct numa_group *ng)
1665 {
1666 	unsigned long faults = 0;
1667 	int node;
1668 
1669 	for_each_online_node(node) {
1670 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1671 	}
1672 
1673 	return faults;
1674 }
1675 
1676 static inline unsigned long group_faults_shared(struct numa_group *ng)
1677 {
1678 	unsigned long faults = 0;
1679 	int node;
1680 
1681 	for_each_online_node(node) {
1682 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1683 	}
1684 
1685 	return faults;
1686 }
1687 
1688 /*
1689  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1690  * considered part of a numa group's pseudo-interleaving set. Migrations
1691  * between these nodes are slowed down, to allow things to settle down.
1692  */
1693 #define ACTIVE_NODE_FRACTION 3
1694 
1695 static bool numa_is_active_node(int nid, struct numa_group *ng)
1696 {
1697 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1698 }
1699 
1700 /* Handle placement on systems where not all nodes are directly connected. */
1701 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1702 					int lim_dist, bool task)
1703 {
1704 	unsigned long score = 0;
1705 	int node, max_dist;
1706 
1707 	/*
1708 	 * All nodes are directly connected, and the same distance
1709 	 * from each other. No need for fancy placement algorithms.
1710 	 */
1711 	if (sched_numa_topology_type == NUMA_DIRECT)
1712 		return 0;
1713 
1714 	/* sched_max_numa_distance may be changed in parallel. */
1715 	max_dist = READ_ONCE(sched_max_numa_distance);
1716 	/*
1717 	 * This code is called for each node, introducing N^2 complexity,
1718 	 * which should be OK given the number of nodes rarely exceeds 8.
1719 	 */
1720 	for_each_online_node(node) {
1721 		unsigned long faults;
1722 		int dist = node_distance(nid, node);
1723 
1724 		/*
1725 		 * The furthest away nodes in the system are not interesting
1726 		 * for placement; nid was already counted.
1727 		 */
1728 		if (dist >= max_dist || node == nid)
1729 			continue;
1730 
1731 		/*
1732 		 * On systems with a backplane NUMA topology, compare groups
1733 		 * of nodes, and move tasks towards the group with the most
1734 		 * memory accesses. When comparing two nodes at distance
1735 		 * "hoplimit", only nodes closer by than "hoplimit" are part
1736 		 * of each group. Skip other nodes.
1737 		 */
1738 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1739 			continue;
1740 
1741 		/* Add up the faults from nearby nodes. */
1742 		if (task)
1743 			faults = task_faults(p, node);
1744 		else
1745 			faults = group_faults(p, node);
1746 
1747 		/*
1748 		 * On systems with a glueless mesh NUMA topology, there are
1749 		 * no fixed "groups of nodes". Instead, nodes that are not
1750 		 * directly connected bounce traffic through intermediate
1751 		 * nodes; a numa_group can occupy any set of nodes.
1752 		 * The further away a node is, the less the faults count.
1753 		 * This seems to result in good task placement.
1754 		 */
1755 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1756 			faults *= (max_dist - dist);
1757 			faults /= (max_dist - LOCAL_DISTANCE);
1758 		}
1759 
1760 		score += faults;
1761 	}
1762 
1763 	return score;
1764 }
1765 
1766 /*
1767  * These return the fraction of accesses done by a particular task, or
1768  * task group, on a particular numa node.  The group weight is given a
1769  * larger multiplier, in order to group tasks together that are almost
1770  * evenly spread out between numa nodes.
1771  */
1772 static inline unsigned long task_weight(struct task_struct *p, int nid,
1773 					int dist)
1774 {
1775 	unsigned long faults, total_faults;
1776 
1777 	if (!p->numa_faults)
1778 		return 0;
1779 
1780 	total_faults = p->total_numa_faults;
1781 
1782 	if (!total_faults)
1783 		return 0;
1784 
1785 	faults = task_faults(p, nid);
1786 	faults += score_nearby_nodes(p, nid, dist, true);
1787 
1788 	return 1000 * faults / total_faults;
1789 }
1790 
1791 static inline unsigned long group_weight(struct task_struct *p, int nid,
1792 					 int dist)
1793 {
1794 	struct numa_group *ng = deref_task_numa_group(p);
1795 	unsigned long faults, total_faults;
1796 
1797 	if (!ng)
1798 		return 0;
1799 
1800 	total_faults = ng->total_faults;
1801 
1802 	if (!total_faults)
1803 		return 0;
1804 
1805 	faults = group_faults(p, nid);
1806 	faults += score_nearby_nodes(p, nid, dist, false);
1807 
1808 	return 1000 * faults / total_faults;
1809 }
1810 
1811 /*
1812  * If memory tiering mode is enabled, cpupid of slow memory page is
1813  * used to record scan time instead of CPU and PID.  When tiering mode
1814  * is disabled at run time, the scan time (in cpupid) will be
1815  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
1816  * access out of array bound.
1817  */
1818 static inline bool cpupid_valid(int cpupid)
1819 {
1820 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1821 }
1822 
1823 /*
1824  * For memory tiering mode, if there are enough free pages (more than
1825  * enough watermark defined here) in fast memory node, to take full
1826  * advantage of fast memory capacity, all recently accessed slow
1827  * memory pages will be migrated to fast memory node without
1828  * considering hot threshold.
1829  */
1830 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1831 {
1832 	int z;
1833 	unsigned long enough_wmark;
1834 
1835 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1836 			   pgdat->node_present_pages >> 4);
1837 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1838 		struct zone *zone = pgdat->node_zones + z;
1839 
1840 		if (!populated_zone(zone))
1841 			continue;
1842 
1843 		if (zone_watermark_ok(zone, 0,
1844 				      promo_wmark_pages(zone) + enough_wmark,
1845 				      ZONE_MOVABLE, 0))
1846 			return true;
1847 	}
1848 	return false;
1849 }
1850 
1851 /*
1852  * For memory tiering mode, when page tables are scanned, the scan
1853  * time will be recorded in struct page in addition to make page
1854  * PROT_NONE for slow memory page.  So when the page is accessed, in
1855  * hint page fault handler, the hint page fault latency is calculated
1856  * via,
1857  *
1858  *	hint page fault latency = hint page fault time - scan time
1859  *
1860  * The smaller the hint page fault latency, the higher the possibility
1861  * for the page to be hot.
1862  */
1863 static int numa_hint_fault_latency(struct folio *folio)
1864 {
1865 	int last_time, time;
1866 
1867 	time = jiffies_to_msecs(jiffies);
1868 	last_time = folio_xchg_access_time(folio, time);
1869 
1870 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1871 }
1872 
1873 /*
1874  * For memory tiering mode, too high promotion/demotion throughput may
1875  * hurt application latency.  So we provide a mechanism to rate limit
1876  * the number of pages that are tried to be promoted.
1877  */
1878 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1879 				      unsigned long rate_limit, int nr)
1880 {
1881 	unsigned long nr_cand;
1882 	unsigned int now, start;
1883 
1884 	now = jiffies_to_msecs(jiffies);
1885 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1886 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1887 	start = pgdat->nbp_rl_start;
1888 	if (now - start > MSEC_PER_SEC &&
1889 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1890 		pgdat->nbp_rl_nr_cand = nr_cand;
1891 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1892 		return true;
1893 	return false;
1894 }
1895 
1896 #define NUMA_MIGRATION_ADJUST_STEPS	16
1897 
1898 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1899 					    unsigned long rate_limit,
1900 					    unsigned int ref_th)
1901 {
1902 	unsigned int now, start, th_period, unit_th, th;
1903 	unsigned long nr_cand, ref_cand, diff_cand;
1904 
1905 	now = jiffies_to_msecs(jiffies);
1906 	th_period = sysctl_numa_balancing_scan_period_max;
1907 	start = pgdat->nbp_th_start;
1908 	if (now - start > th_period &&
1909 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1910 		ref_cand = rate_limit *
1911 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1912 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1913 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1914 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1915 		th = pgdat->nbp_threshold ? : ref_th;
1916 		if (diff_cand > ref_cand * 11 / 10)
1917 			th = max(th - unit_th, unit_th);
1918 		else if (diff_cand < ref_cand * 9 / 10)
1919 			th = min(th + unit_th, ref_th * 2);
1920 		pgdat->nbp_th_nr_cand = nr_cand;
1921 		pgdat->nbp_threshold = th;
1922 	}
1923 }
1924 
1925 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1926 				int src_nid, int dst_cpu)
1927 {
1928 	struct numa_group *ng = deref_curr_numa_group(p);
1929 	int dst_nid = cpu_to_node(dst_cpu);
1930 	int last_cpupid, this_cpupid;
1931 
1932 	/*
1933 	 * Cannot migrate to memoryless nodes.
1934 	 */
1935 	if (!node_state(dst_nid, N_MEMORY))
1936 		return false;
1937 
1938 	/*
1939 	 * The pages in slow memory node should be migrated according
1940 	 * to hot/cold instead of private/shared.
1941 	 */
1942 	if (folio_use_access_time(folio)) {
1943 		struct pglist_data *pgdat;
1944 		unsigned long rate_limit;
1945 		unsigned int latency, th, def_th;
1946 		long nr = folio_nr_pages(folio);
1947 
1948 		pgdat = NODE_DATA(dst_nid);
1949 		if (pgdat_free_space_enough(pgdat)) {
1950 			/* workload changed, reset hot threshold */
1951 			pgdat->nbp_threshold = 0;
1952 			mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
1953 			return true;
1954 		}
1955 
1956 		def_th = sysctl_numa_balancing_hot_threshold;
1957 		rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
1958 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1959 
1960 		th = pgdat->nbp_threshold ? : def_th;
1961 		latency = numa_hint_fault_latency(folio);
1962 		if (latency >= th)
1963 			return false;
1964 
1965 		return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
1966 	}
1967 
1968 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1969 	last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
1970 
1971 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1972 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1973 		return false;
1974 
1975 	/*
1976 	 * Allow first faults or private faults to migrate immediately early in
1977 	 * the lifetime of a task. The magic number 4 is based on waiting for
1978 	 * two full passes of the "multi-stage node selection" test that is
1979 	 * executed below.
1980 	 */
1981 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1982 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1983 		return true;
1984 
1985 	/*
1986 	 * Multi-stage node selection is used in conjunction with a periodic
1987 	 * migration fault to build a temporal task<->page relation. By using
1988 	 * a two-stage filter we remove short/unlikely relations.
1989 	 *
1990 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1991 	 * a task's usage of a particular page (n_p) per total usage of this
1992 	 * page (n_t) (in a given time-span) to a probability.
1993 	 *
1994 	 * Our periodic faults will sample this probability and getting the
1995 	 * same result twice in a row, given these samples are fully
1996 	 * independent, is then given by P(n)^2, provided our sample period
1997 	 * is sufficiently short compared to the usage pattern.
1998 	 *
1999 	 * This quadric squishes small probabilities, making it less likely we
2000 	 * act on an unlikely task<->page relation.
2001 	 */
2002 	if (!cpupid_pid_unset(last_cpupid) &&
2003 				cpupid_to_nid(last_cpupid) != dst_nid)
2004 		return false;
2005 
2006 	/* Always allow migrate on private faults */
2007 	if (cpupid_match_pid(p, last_cpupid))
2008 		return true;
2009 
2010 	/* A shared fault, but p->numa_group has not been set up yet. */
2011 	if (!ng)
2012 		return true;
2013 
2014 	/*
2015 	 * Destination node is much more heavily used than the source
2016 	 * node? Allow migration.
2017 	 */
2018 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2019 					ACTIVE_NODE_FRACTION)
2020 		return true;
2021 
2022 	/*
2023 	 * Distribute memory according to CPU & memory use on each node,
2024 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2025 	 *
2026 	 * faults_cpu(dst)   3   faults_cpu(src)
2027 	 * --------------- * - > ---------------
2028 	 * faults_mem(dst)   4   faults_mem(src)
2029 	 */
2030 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2031 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2032 }
2033 
2034 /*
2035  * 'numa_type' describes the node at the moment of load balancing.
2036  */
2037 enum numa_type {
2038 	/* The node has spare capacity that can be used to run more tasks.  */
2039 	node_has_spare = 0,
2040 	/*
2041 	 * The node is fully used and the tasks don't compete for more CPU
2042 	 * cycles. Nevertheless, some tasks might wait before running.
2043 	 */
2044 	node_fully_busy,
2045 	/*
2046 	 * The node is overloaded and can't provide expected CPU cycles to all
2047 	 * tasks.
2048 	 */
2049 	node_overloaded
2050 };
2051 
2052 /* Cached statistics for all CPUs within a node */
2053 struct numa_stats {
2054 	unsigned long load;
2055 	unsigned long runnable;
2056 	unsigned long util;
2057 	/* Total compute capacity of CPUs on a node */
2058 	unsigned long compute_capacity;
2059 	unsigned int nr_running;
2060 	unsigned int weight;
2061 	enum numa_type node_type;
2062 	int idle_cpu;
2063 };
2064 
2065 struct task_numa_env {
2066 	struct task_struct *p;
2067 
2068 	int src_cpu, src_nid;
2069 	int dst_cpu, dst_nid;
2070 	int imb_numa_nr;
2071 
2072 	struct numa_stats src_stats, dst_stats;
2073 
2074 	int imbalance_pct;
2075 	int dist;
2076 
2077 	struct task_struct *best_task;
2078 	long best_imp;
2079 	int best_cpu;
2080 };
2081 
2082 static unsigned long cpu_load(struct rq *rq);
2083 static unsigned long cpu_runnable(struct rq *rq);
2084 
2085 static inline enum
2086 numa_type numa_classify(unsigned int imbalance_pct,
2087 			 struct numa_stats *ns)
2088 {
2089 	if ((ns->nr_running > ns->weight) &&
2090 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2091 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2092 		return node_overloaded;
2093 
2094 	if ((ns->nr_running < ns->weight) ||
2095 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2096 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2097 		return node_has_spare;
2098 
2099 	return node_fully_busy;
2100 }
2101 
2102 #ifdef CONFIG_SCHED_SMT
2103 /* Forward declarations of select_idle_sibling helpers */
2104 static inline bool test_idle_cores(int cpu);
2105 static inline int numa_idle_core(int idle_core, int cpu)
2106 {
2107 	if (!static_branch_likely(&sched_smt_present) ||
2108 	    idle_core >= 0 || !test_idle_cores(cpu))
2109 		return idle_core;
2110 
2111 	/*
2112 	 * Prefer cores instead of packing HT siblings
2113 	 * and triggering future load balancing.
2114 	 */
2115 	if (is_core_idle(cpu))
2116 		idle_core = cpu;
2117 
2118 	return idle_core;
2119 }
2120 #else /* !CONFIG_SCHED_SMT: */
2121 static inline int numa_idle_core(int idle_core, int cpu)
2122 {
2123 	return idle_core;
2124 }
2125 #endif /* !CONFIG_SCHED_SMT */
2126 
2127 /*
2128  * Gather all necessary information to make NUMA balancing placement
2129  * decisions that are compatible with standard load balancer. This
2130  * borrows code and logic from update_sg_lb_stats but sharing a
2131  * common implementation is impractical.
2132  */
2133 static void update_numa_stats(struct task_numa_env *env,
2134 			      struct numa_stats *ns, int nid,
2135 			      bool find_idle)
2136 {
2137 	int cpu, idle_core = -1;
2138 
2139 	memset(ns, 0, sizeof(*ns));
2140 	ns->idle_cpu = -1;
2141 
2142 	rcu_read_lock();
2143 	for_each_cpu(cpu, cpumask_of_node(nid)) {
2144 		struct rq *rq = cpu_rq(cpu);
2145 
2146 		ns->load += cpu_load(rq);
2147 		ns->runnable += cpu_runnable(rq);
2148 		ns->util += cpu_util_cfs(cpu);
2149 		ns->nr_running += rq->cfs.h_nr_runnable;
2150 		ns->compute_capacity += capacity_of(cpu);
2151 
2152 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2153 			if (READ_ONCE(rq->numa_migrate_on) ||
2154 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2155 				continue;
2156 
2157 			if (ns->idle_cpu == -1)
2158 				ns->idle_cpu = cpu;
2159 
2160 			idle_core = numa_idle_core(idle_core, cpu);
2161 		}
2162 	}
2163 	rcu_read_unlock();
2164 
2165 	ns->weight = cpumask_weight(cpumask_of_node(nid));
2166 
2167 	ns->node_type = numa_classify(env->imbalance_pct, ns);
2168 
2169 	if (idle_core >= 0)
2170 		ns->idle_cpu = idle_core;
2171 }
2172 
2173 static void task_numa_assign(struct task_numa_env *env,
2174 			     struct task_struct *p, long imp)
2175 {
2176 	struct rq *rq = cpu_rq(env->dst_cpu);
2177 
2178 	/* Check if run-queue part of active NUMA balance. */
2179 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2180 		int cpu;
2181 		int start = env->dst_cpu;
2182 
2183 		/* Find alternative idle CPU. */
2184 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2185 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2186 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2187 				continue;
2188 			}
2189 
2190 			env->dst_cpu = cpu;
2191 			rq = cpu_rq(env->dst_cpu);
2192 			if (!xchg(&rq->numa_migrate_on, 1))
2193 				goto assign;
2194 		}
2195 
2196 		/* Failed to find an alternative idle CPU */
2197 		return;
2198 	}
2199 
2200 assign:
2201 	/*
2202 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
2203 	 * found a better CPU to move/swap.
2204 	 */
2205 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2206 		rq = cpu_rq(env->best_cpu);
2207 		WRITE_ONCE(rq->numa_migrate_on, 0);
2208 	}
2209 
2210 	if (env->best_task)
2211 		put_task_struct(env->best_task);
2212 	if (p)
2213 		get_task_struct(p);
2214 
2215 	env->best_task = p;
2216 	env->best_imp = imp;
2217 	env->best_cpu = env->dst_cpu;
2218 }
2219 
2220 static bool load_too_imbalanced(long src_load, long dst_load,
2221 				struct task_numa_env *env)
2222 {
2223 	long imb, old_imb;
2224 	long orig_src_load, orig_dst_load;
2225 	long src_capacity, dst_capacity;
2226 
2227 	/*
2228 	 * The load is corrected for the CPU capacity available on each node.
2229 	 *
2230 	 * src_load        dst_load
2231 	 * ------------ vs ---------
2232 	 * src_capacity    dst_capacity
2233 	 */
2234 	src_capacity = env->src_stats.compute_capacity;
2235 	dst_capacity = env->dst_stats.compute_capacity;
2236 
2237 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2238 
2239 	orig_src_load = env->src_stats.load;
2240 	orig_dst_load = env->dst_stats.load;
2241 
2242 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2243 
2244 	/* Would this change make things worse? */
2245 	return (imb > old_imb);
2246 }
2247 
2248 /*
2249  * Maximum NUMA importance can be 1998 (2*999);
2250  * SMALLIMP @ 30 would be close to 1998/64.
2251  * Used to deter task migration.
2252  */
2253 #define SMALLIMP	30
2254 
2255 /*
2256  * This checks if the overall compute and NUMA accesses of the system would
2257  * be improved if the source tasks was migrated to the target dst_cpu taking
2258  * into account that it might be best if task running on the dst_cpu should
2259  * be exchanged with the source task
2260  */
2261 static bool task_numa_compare(struct task_numa_env *env,
2262 			      long taskimp, long groupimp, bool maymove)
2263 {
2264 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2265 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
2266 	long imp = p_ng ? groupimp : taskimp;
2267 	struct task_struct *cur;
2268 	long src_load, dst_load;
2269 	int dist = env->dist;
2270 	long moveimp = imp;
2271 	long load;
2272 	bool stopsearch = false;
2273 
2274 	if (READ_ONCE(dst_rq->numa_migrate_on))
2275 		return false;
2276 
2277 	rcu_read_lock();
2278 	cur = rcu_dereference_all(dst_rq->curr);
2279 	if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
2280 		    !cur->mm))
2281 		cur = NULL;
2282 
2283 	/*
2284 	 * Because we have preemption enabled we can get migrated around and
2285 	 * end try selecting ourselves (current == env->p) as a swap candidate.
2286 	 */
2287 	if (cur == env->p) {
2288 		stopsearch = true;
2289 		goto unlock;
2290 	}
2291 
2292 	if (!cur) {
2293 		if (maymove && moveimp >= env->best_imp)
2294 			goto assign;
2295 		else
2296 			goto unlock;
2297 	}
2298 
2299 	/* Skip this swap candidate if cannot move to the source cpu. */
2300 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2301 		goto unlock;
2302 
2303 	/*
2304 	 * Skip this swap candidate if it is not moving to its preferred
2305 	 * node and the best task is.
2306 	 */
2307 	if (env->best_task &&
2308 	    env->best_task->numa_preferred_nid == env->src_nid &&
2309 	    cur->numa_preferred_nid != env->src_nid) {
2310 		goto unlock;
2311 	}
2312 
2313 	/*
2314 	 * "imp" is the fault differential for the source task between the
2315 	 * source and destination node. Calculate the total differential for
2316 	 * the source task and potential destination task. The more negative
2317 	 * the value is, the more remote accesses that would be expected to
2318 	 * be incurred if the tasks were swapped.
2319 	 *
2320 	 * If dst and source tasks are in the same NUMA group, or not
2321 	 * in any group then look only at task weights.
2322 	 */
2323 	cur_ng = rcu_dereference_all(cur->numa_group);
2324 	if (cur_ng == p_ng) {
2325 		/*
2326 		 * Do not swap within a group or between tasks that have
2327 		 * no group if there is spare capacity. Swapping does
2328 		 * not address the load imbalance and helps one task at
2329 		 * the cost of punishing another.
2330 		 */
2331 		if (env->dst_stats.node_type == node_has_spare)
2332 			goto unlock;
2333 
2334 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
2335 		      task_weight(cur, env->dst_nid, dist);
2336 		/*
2337 		 * Add some hysteresis to prevent swapping the
2338 		 * tasks within a group over tiny differences.
2339 		 */
2340 		if (cur_ng)
2341 			imp -= imp / 16;
2342 	} else {
2343 		/*
2344 		 * Compare the group weights. If a task is all by itself
2345 		 * (not part of a group), use the task weight instead.
2346 		 */
2347 		if (cur_ng && p_ng)
2348 			imp += group_weight(cur, env->src_nid, dist) -
2349 			       group_weight(cur, env->dst_nid, dist);
2350 		else
2351 			imp += task_weight(cur, env->src_nid, dist) -
2352 			       task_weight(cur, env->dst_nid, dist);
2353 	}
2354 
2355 	/* Discourage picking a task already on its preferred node */
2356 	if (cur->numa_preferred_nid == env->dst_nid)
2357 		imp -= imp / 16;
2358 
2359 	/*
2360 	 * Encourage picking a task that moves to its preferred node.
2361 	 * This potentially makes imp larger than it's maximum of
2362 	 * 1998 (see SMALLIMP and task_weight for why) but in this
2363 	 * case, it does not matter.
2364 	 */
2365 	if (cur->numa_preferred_nid == env->src_nid)
2366 		imp += imp / 8;
2367 
2368 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
2369 		imp = moveimp;
2370 		cur = NULL;
2371 		goto assign;
2372 	}
2373 
2374 	/*
2375 	 * Prefer swapping with a task moving to its preferred node over a
2376 	 * task that is not.
2377 	 */
2378 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2379 	    env->best_task->numa_preferred_nid != env->src_nid) {
2380 		goto assign;
2381 	}
2382 
2383 	/*
2384 	 * If the NUMA importance is less than SMALLIMP,
2385 	 * task migration might only result in ping pong
2386 	 * of tasks and also hurt performance due to cache
2387 	 * misses.
2388 	 */
2389 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2390 		goto unlock;
2391 
2392 	/*
2393 	 * In the overloaded case, try and keep the load balanced.
2394 	 */
2395 	load = task_h_load(env->p) - task_h_load(cur);
2396 	if (!load)
2397 		goto assign;
2398 
2399 	dst_load = env->dst_stats.load + load;
2400 	src_load = env->src_stats.load - load;
2401 
2402 	if (load_too_imbalanced(src_load, dst_load, env))
2403 		goto unlock;
2404 
2405 assign:
2406 	/* Evaluate an idle CPU for a task numa move. */
2407 	if (!cur) {
2408 		int cpu = env->dst_stats.idle_cpu;
2409 
2410 		/* Nothing cached so current CPU went idle since the search. */
2411 		if (cpu < 0)
2412 			cpu = env->dst_cpu;
2413 
2414 		/*
2415 		 * If the CPU is no longer truly idle and the previous best CPU
2416 		 * is, keep using it.
2417 		 */
2418 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2419 		    idle_cpu(env->best_cpu)) {
2420 			cpu = env->best_cpu;
2421 		}
2422 
2423 		env->dst_cpu = cpu;
2424 	}
2425 
2426 	task_numa_assign(env, cur, imp);
2427 
2428 	/*
2429 	 * If a move to idle is allowed because there is capacity or load
2430 	 * balance improves then stop the search. While a better swap
2431 	 * candidate may exist, a search is not free.
2432 	 */
2433 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2434 		stopsearch = true;
2435 
2436 	/*
2437 	 * If a swap candidate must be identified and the current best task
2438 	 * moves its preferred node then stop the search.
2439 	 */
2440 	if (!maymove && env->best_task &&
2441 	    env->best_task->numa_preferred_nid == env->src_nid) {
2442 		stopsearch = true;
2443 	}
2444 unlock:
2445 	rcu_read_unlock();
2446 
2447 	return stopsearch;
2448 }
2449 
2450 static void task_numa_find_cpu(struct task_numa_env *env,
2451 				long taskimp, long groupimp)
2452 {
2453 	bool maymove = false;
2454 	int cpu;
2455 
2456 	/*
2457 	 * If dst node has spare capacity, then check if there is an
2458 	 * imbalance that would be overruled by the load balancer.
2459 	 */
2460 	if (env->dst_stats.node_type == node_has_spare) {
2461 		unsigned int imbalance;
2462 		int src_running, dst_running;
2463 
2464 		/*
2465 		 * Would movement cause an imbalance? Note that if src has
2466 		 * more running tasks that the imbalance is ignored as the
2467 		 * move improves the imbalance from the perspective of the
2468 		 * CPU load balancer.
2469 		 * */
2470 		src_running = env->src_stats.nr_running - 1;
2471 		dst_running = env->dst_stats.nr_running + 1;
2472 		imbalance = max(0, dst_running - src_running);
2473 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
2474 						  env->imb_numa_nr);
2475 
2476 		/* Use idle CPU if there is no imbalance */
2477 		if (!imbalance) {
2478 			maymove = true;
2479 			if (env->dst_stats.idle_cpu >= 0) {
2480 				env->dst_cpu = env->dst_stats.idle_cpu;
2481 				task_numa_assign(env, NULL, 0);
2482 				return;
2483 			}
2484 		}
2485 	} else {
2486 		long src_load, dst_load, load;
2487 		/*
2488 		 * If the improvement from just moving env->p direction is better
2489 		 * than swapping tasks around, check if a move is possible.
2490 		 */
2491 		load = task_h_load(env->p);
2492 		dst_load = env->dst_stats.load + load;
2493 		src_load = env->src_stats.load - load;
2494 		maymove = !load_too_imbalanced(src_load, dst_load, env);
2495 	}
2496 
2497 	/* Skip CPUs if the source task cannot migrate */
2498 	for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) {
2499 		env->dst_cpu = cpu;
2500 		if (task_numa_compare(env, taskimp, groupimp, maymove))
2501 			break;
2502 	}
2503 }
2504 
2505 static int task_numa_migrate(struct task_struct *p)
2506 {
2507 	struct task_numa_env env = {
2508 		.p = p,
2509 
2510 		.src_cpu = task_cpu(p),
2511 		.src_nid = task_node(p),
2512 
2513 		.imbalance_pct = 112,
2514 
2515 		.best_task = NULL,
2516 		.best_imp = 0,
2517 		.best_cpu = -1,
2518 	};
2519 	unsigned long taskweight, groupweight;
2520 	struct sched_domain *sd;
2521 	long taskimp, groupimp;
2522 	struct numa_group *ng;
2523 	struct rq *best_rq;
2524 	int nid, ret, dist;
2525 
2526 	/*
2527 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
2528 	 * imbalance and would be the first to start moving tasks about.
2529 	 *
2530 	 * And we want to avoid any moving of tasks about, as that would create
2531 	 * random movement of tasks -- counter the numa conditions we're trying
2532 	 * to satisfy here.
2533 	 */
2534 	rcu_read_lock();
2535 	sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu));
2536 	if (sd) {
2537 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2538 		env.imb_numa_nr = sd->imb_numa_nr;
2539 	}
2540 	rcu_read_unlock();
2541 
2542 	/*
2543 	 * Cpusets can break the scheduler domain tree into smaller
2544 	 * balance domains, some of which do not cross NUMA boundaries.
2545 	 * Tasks that are "trapped" in such domains cannot be migrated
2546 	 * elsewhere, so there is no point in (re)trying.
2547 	 */
2548 	if (unlikely(!sd)) {
2549 		sched_setnuma(p, task_node(p));
2550 		return -EINVAL;
2551 	}
2552 
2553 	env.dst_nid = p->numa_preferred_nid;
2554 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2555 	taskweight = task_weight(p, env.src_nid, dist);
2556 	groupweight = group_weight(p, env.src_nid, dist);
2557 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2558 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2559 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2560 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2561 
2562 	/* Try to find a spot on the preferred nid. */
2563 	task_numa_find_cpu(&env, taskimp, groupimp);
2564 
2565 	/*
2566 	 * Look at other nodes in these cases:
2567 	 * - there is no space available on the preferred_nid
2568 	 * - the task is part of a numa_group that is interleaved across
2569 	 *   multiple NUMA nodes; in order to better consolidate the group,
2570 	 *   we need to check other locations.
2571 	 */
2572 	ng = deref_curr_numa_group(p);
2573 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2574 		for_each_node_state(nid, N_CPU) {
2575 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
2576 				continue;
2577 
2578 			dist = node_distance(env.src_nid, env.dst_nid);
2579 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
2580 						dist != env.dist) {
2581 				taskweight = task_weight(p, env.src_nid, dist);
2582 				groupweight = group_weight(p, env.src_nid, dist);
2583 			}
2584 
2585 			/* Only consider nodes where both task and groups benefit */
2586 			taskimp = task_weight(p, nid, dist) - taskweight;
2587 			groupimp = group_weight(p, nid, dist) - groupweight;
2588 			if (taskimp < 0 && groupimp < 0)
2589 				continue;
2590 
2591 			env.dist = dist;
2592 			env.dst_nid = nid;
2593 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2594 			task_numa_find_cpu(&env, taskimp, groupimp);
2595 		}
2596 	}
2597 
2598 	/*
2599 	 * If the task is part of a workload that spans multiple NUMA nodes,
2600 	 * and is migrating into one of the workload's active nodes, remember
2601 	 * this node as the task's preferred numa node, so the workload can
2602 	 * settle down.
2603 	 * A task that migrated to a second choice node will be better off
2604 	 * trying for a better one later. Do not set the preferred node here.
2605 	 */
2606 	if (ng) {
2607 		if (env.best_cpu == -1)
2608 			nid = env.src_nid;
2609 		else
2610 			nid = cpu_to_node(env.best_cpu);
2611 
2612 		if (nid != p->numa_preferred_nid)
2613 			sched_setnuma(p, nid);
2614 	}
2615 
2616 	/* No better CPU than the current one was found. */
2617 	if (env.best_cpu == -1) {
2618 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2619 		return -EAGAIN;
2620 	}
2621 
2622 	best_rq = cpu_rq(env.best_cpu);
2623 	if (env.best_task == NULL) {
2624 		ret = migrate_task_to(p, env.best_cpu);
2625 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
2626 		if (ret != 0)
2627 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2628 		return ret;
2629 	}
2630 
2631 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2632 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
2633 
2634 	if (ret != 0)
2635 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2636 	put_task_struct(env.best_task);
2637 	return ret;
2638 }
2639 
2640 /* Attempt to migrate a task to a CPU on the preferred node. */
2641 static void numa_migrate_preferred(struct task_struct *p)
2642 {
2643 	unsigned long interval = HZ;
2644 
2645 	/* This task has no NUMA fault statistics yet */
2646 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2647 		return;
2648 
2649 	/* Periodically retry migrating the task to the preferred node */
2650 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2651 	p->numa_migrate_retry = jiffies + interval;
2652 
2653 	/* Success if task is already running on preferred CPU */
2654 	if (task_node(p) == p->numa_preferred_nid)
2655 		return;
2656 
2657 	/* Otherwise, try migrate to a CPU on the preferred node */
2658 	task_numa_migrate(p);
2659 }
2660 
2661 /*
2662  * Find out how many nodes the workload is actively running on. Do this by
2663  * tracking the nodes from which NUMA hinting faults are triggered. This can
2664  * be different from the set of nodes where the workload's memory is currently
2665  * located.
2666  */
2667 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2668 {
2669 	unsigned long faults, max_faults = 0;
2670 	int nid, active_nodes = 0;
2671 
2672 	for_each_node_state(nid, N_CPU) {
2673 		faults = group_faults_cpu(numa_group, nid);
2674 		if (faults > max_faults)
2675 			max_faults = faults;
2676 	}
2677 
2678 	for_each_node_state(nid, N_CPU) {
2679 		faults = group_faults_cpu(numa_group, nid);
2680 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
2681 			active_nodes++;
2682 	}
2683 
2684 	numa_group->max_faults_cpu = max_faults;
2685 	numa_group->active_nodes = active_nodes;
2686 }
2687 
2688 /*
2689  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2690  * increments. The more local the fault statistics are, the higher the scan
2691  * period will be for the next scan window. If local/(local+remote) ratio is
2692  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2693  * the scan period will decrease. Aim for 70% local accesses.
2694  */
2695 #define NUMA_PERIOD_SLOTS 10
2696 #define NUMA_PERIOD_THRESHOLD 7
2697 
2698 /*
2699  * Increase the scan period (slow down scanning) if the majority of
2700  * our memory is already on our local node, or if the majority of
2701  * the page accesses are shared with other processes.
2702  * Otherwise, decrease the scan period.
2703  */
2704 static void update_task_scan_period(struct task_struct *p,
2705 			unsigned long shared, unsigned long private)
2706 {
2707 	unsigned int period_slot;
2708 	int lr_ratio, ps_ratio;
2709 	int diff;
2710 
2711 	unsigned long remote = p->numa_faults_locality[0];
2712 	unsigned long local = p->numa_faults_locality[1];
2713 
2714 	/*
2715 	 * If there were no record hinting faults then either the task is
2716 	 * completely idle or all activity is in areas that are not of interest
2717 	 * to automatic numa balancing. Related to that, if there were failed
2718 	 * migration then it implies we are migrating too quickly or the local
2719 	 * node is overloaded. In either case, scan slower
2720 	 */
2721 	if (local + shared == 0 || p->numa_faults_locality[2]) {
2722 		p->numa_scan_period = min(p->numa_scan_period_max,
2723 			p->numa_scan_period << 1);
2724 
2725 		p->mm->numa_next_scan = jiffies +
2726 			msecs_to_jiffies(p->numa_scan_period);
2727 
2728 		return;
2729 	}
2730 
2731 	/*
2732 	 * Prepare to scale scan period relative to the current period.
2733 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
2734 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2735 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2736 	 */
2737 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2738 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2739 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2740 
2741 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2742 		/*
2743 		 * Most memory accesses are local. There is no need to
2744 		 * do fast NUMA scanning, since memory is already local.
2745 		 */
2746 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2747 		if (!slot)
2748 			slot = 1;
2749 		diff = slot * period_slot;
2750 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2751 		/*
2752 		 * Most memory accesses are shared with other tasks.
2753 		 * There is no point in continuing fast NUMA scanning,
2754 		 * since other tasks may just move the memory elsewhere.
2755 		 */
2756 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2757 		if (!slot)
2758 			slot = 1;
2759 		diff = slot * period_slot;
2760 	} else {
2761 		/*
2762 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2763 		 * yet they are not on the local NUMA node. Speed up
2764 		 * NUMA scanning to get the memory moved over.
2765 		 */
2766 		int ratio = max(lr_ratio, ps_ratio);
2767 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2768 	}
2769 
2770 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
2771 			task_scan_min(p), task_scan_max(p));
2772 	memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2773 }
2774 
2775 /*
2776  * Get the fraction of time the task has been running since the last
2777  * NUMA placement cycle. The scheduler keeps similar statistics, but
2778  * decays those on a 32ms period, which is orders of magnitude off
2779  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2780  * stats only if the task is so new there are no NUMA statistics yet.
2781  */
2782 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2783 {
2784 	u64 runtime, delta, now;
2785 	/* Use the start of this time slice to avoid calculations. */
2786 	now = p->se.exec_start;
2787 	runtime = p->se.sum_exec_runtime;
2788 
2789 	if (p->last_task_numa_placement) {
2790 		delta = runtime - p->last_sum_exec_runtime;
2791 		*period = now - p->last_task_numa_placement;
2792 
2793 		/* Avoid time going backwards, prevent potential divide error: */
2794 		if (unlikely((s64)*period < 0))
2795 			*period = 0;
2796 	} else {
2797 		delta = p->se.avg.load_sum;
2798 		*period = LOAD_AVG_MAX;
2799 	}
2800 
2801 	p->last_sum_exec_runtime = runtime;
2802 	p->last_task_numa_placement = now;
2803 
2804 	return delta;
2805 }
2806 
2807 /*
2808  * Determine the preferred nid for a task in a numa_group. This needs to
2809  * be done in a way that produces consistent results with group_weight,
2810  * otherwise workloads might not converge.
2811  */
2812 static int preferred_group_nid(struct task_struct *p, int nid)
2813 {
2814 	nodemask_t nodes;
2815 	int dist;
2816 
2817 	/* Direct connections between all NUMA nodes. */
2818 	if (sched_numa_topology_type == NUMA_DIRECT)
2819 		return nid;
2820 
2821 	/*
2822 	 * On a system with glueless mesh NUMA topology, group_weight
2823 	 * scores nodes according to the number of NUMA hinting faults on
2824 	 * both the node itself, and on nearby nodes.
2825 	 */
2826 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2827 		unsigned long score, max_score = 0;
2828 		int node, max_node = nid;
2829 
2830 		dist = sched_max_numa_distance;
2831 
2832 		for_each_node_state(node, N_CPU) {
2833 			score = group_weight(p, node, dist);
2834 			if (score > max_score) {
2835 				max_score = score;
2836 				max_node = node;
2837 			}
2838 		}
2839 		return max_node;
2840 	}
2841 
2842 	/*
2843 	 * Finding the preferred nid in a system with NUMA backplane
2844 	 * interconnect topology is more involved. The goal is to locate
2845 	 * tasks from numa_groups near each other in the system, and
2846 	 * untangle workloads from different sides of the system. This requires
2847 	 * searching down the hierarchy of node groups, recursively searching
2848 	 * inside the highest scoring group of nodes. The nodemask tricks
2849 	 * keep the complexity of the search down.
2850 	 */
2851 	nodes = node_states[N_CPU];
2852 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2853 		unsigned long max_faults = 0;
2854 		nodemask_t max_group = NODE_MASK_NONE;
2855 		int a, b;
2856 
2857 		/* Are there nodes at this distance from each other? */
2858 		if (!find_numa_distance(dist))
2859 			continue;
2860 
2861 		for_each_node_mask(a, nodes) {
2862 			unsigned long faults = 0;
2863 			nodemask_t this_group;
2864 			nodes_clear(this_group);
2865 
2866 			/* Sum group's NUMA faults; includes a==b case. */
2867 			for_each_node_mask(b, nodes) {
2868 				if (node_distance(a, b) < dist) {
2869 					faults += group_faults(p, b);
2870 					node_set(b, this_group);
2871 					node_clear(b, nodes);
2872 				}
2873 			}
2874 
2875 			/* Remember the top group. */
2876 			if (faults > max_faults) {
2877 				max_faults = faults;
2878 				max_group = this_group;
2879 				/*
2880 				 * subtle: at the smallest distance there is
2881 				 * just one node left in each "group", the
2882 				 * winner is the preferred nid.
2883 				 */
2884 				nid = a;
2885 			}
2886 		}
2887 		/* Next round, evaluate the nodes within max_group. */
2888 		if (!max_faults)
2889 			break;
2890 		nodes = max_group;
2891 	}
2892 	return nid;
2893 }
2894 
2895 static void task_numa_placement(struct task_struct *p)
2896 {
2897 	int seq, nid, max_nid = NUMA_NO_NODE;
2898 	unsigned long max_faults = 0;
2899 	unsigned long fault_types[2] = { 0, 0 };
2900 	unsigned long total_faults;
2901 	u64 runtime, period;
2902 	spinlock_t *group_lock = NULL;
2903 	struct numa_group *ng;
2904 
2905 	/*
2906 	 * The p->mm->numa_scan_seq field gets updated without
2907 	 * exclusive access. Use READ_ONCE() here to ensure
2908 	 * that the field is read in a single access:
2909 	 */
2910 	seq = READ_ONCE(p->mm->numa_scan_seq);
2911 	if (p->numa_scan_seq == seq)
2912 		return;
2913 	p->numa_scan_seq = seq;
2914 	p->numa_scan_period_max = task_scan_max(p);
2915 
2916 	total_faults = p->numa_faults_locality[0] +
2917 		       p->numa_faults_locality[1];
2918 	runtime = numa_get_avg_runtime(p, &period);
2919 
2920 	/* If the task is part of a group prevent parallel updates to group stats */
2921 	ng = deref_curr_numa_group(p);
2922 	if (ng) {
2923 		group_lock = &ng->lock;
2924 		spin_lock_irq(group_lock);
2925 	}
2926 
2927 	/* Find the node with the highest number of faults */
2928 	for_each_online_node(nid) {
2929 		/* Keep track of the offsets in numa_faults array */
2930 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2931 		unsigned long faults = 0, group_faults = 0;
2932 		int priv;
2933 
2934 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2935 			long diff, f_diff, f_weight;
2936 
2937 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2938 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2939 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2940 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2941 
2942 			/* Decay existing window, copy faults since last scan */
2943 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2944 			fault_types[priv] += p->numa_faults[membuf_idx];
2945 			p->numa_faults[membuf_idx] = 0;
2946 
2947 			/*
2948 			 * Normalize the faults_from, so all tasks in a group
2949 			 * count according to CPU use, instead of by the raw
2950 			 * number of faults. Tasks with little runtime have
2951 			 * little over-all impact on throughput, and thus their
2952 			 * faults are less important.
2953 			 */
2954 			f_weight = div64_u64(runtime << 16, period + 1);
2955 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2956 				   (total_faults + 1);
2957 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2958 			p->numa_faults[cpubuf_idx] = 0;
2959 
2960 			p->numa_faults[mem_idx] += diff;
2961 			p->numa_faults[cpu_idx] += f_diff;
2962 			faults += p->numa_faults[mem_idx];
2963 			p->total_numa_faults += diff;
2964 			if (ng) {
2965 				/*
2966 				 * safe because we can only change our own group
2967 				 *
2968 				 * mem_idx represents the offset for a given
2969 				 * nid and priv in a specific region because it
2970 				 * is at the beginning of the numa_faults array.
2971 				 */
2972 				ng->faults[mem_idx] += diff;
2973 				ng->faults[cpu_idx] += f_diff;
2974 				ng->total_faults += diff;
2975 				group_faults += ng->faults[mem_idx];
2976 			}
2977 		}
2978 
2979 		if (!ng) {
2980 			if (faults > max_faults) {
2981 				max_faults = faults;
2982 				max_nid = nid;
2983 			}
2984 		} else if (group_faults > max_faults) {
2985 			max_faults = group_faults;
2986 			max_nid = nid;
2987 		}
2988 	}
2989 
2990 	/* Cannot migrate task to CPU-less node */
2991 	max_nid = numa_nearest_node(max_nid, N_CPU);
2992 
2993 	if (ng) {
2994 		numa_group_count_active_nodes(ng);
2995 		spin_unlock_irq(group_lock);
2996 		max_nid = preferred_group_nid(p, max_nid);
2997 	}
2998 
2999 	if (max_faults) {
3000 		/* Set the new preferred node */
3001 		if (max_nid != p->numa_preferred_nid)
3002 			sched_setnuma(p, max_nid);
3003 	}
3004 
3005 	update_task_scan_period(p, fault_types[0], fault_types[1]);
3006 }
3007 
3008 static inline int get_numa_group(struct numa_group *grp)
3009 {
3010 	return refcount_inc_not_zero(&grp->refcount);
3011 }
3012 
3013 static inline void put_numa_group(struct numa_group *grp)
3014 {
3015 	if (refcount_dec_and_test(&grp->refcount))
3016 		kfree_rcu(grp, rcu);
3017 }
3018 
3019 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3020 			int *priv)
3021 {
3022 	struct numa_group *grp, *my_grp;
3023 	struct task_struct *tsk;
3024 	bool join = false;
3025 	int cpu = cpupid_to_cpu(cpupid);
3026 	int i;
3027 
3028 	if (unlikely(!deref_curr_numa_group(p))) {
3029 		unsigned int size = sizeof(struct numa_group) +
3030 				    NR_NUMA_HINT_FAULT_STATS *
3031 				    nr_node_ids * sizeof(unsigned long);
3032 
3033 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3034 		if (!grp)
3035 			return;
3036 
3037 		refcount_set(&grp->refcount, 1);
3038 		grp->active_nodes = 1;
3039 		grp->max_faults_cpu = 0;
3040 		spin_lock_init(&grp->lock);
3041 		grp->gid = p->pid;
3042 
3043 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3044 			grp->faults[i] = p->numa_faults[i];
3045 
3046 		grp->total_faults = p->total_numa_faults;
3047 
3048 		grp->nr_tasks++;
3049 		rcu_assign_pointer(p->numa_group, grp);
3050 	}
3051 
3052 	rcu_read_lock();
3053 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
3054 
3055 	if (!cpupid_match_pid(tsk, cpupid))
3056 		goto no_join;
3057 
3058 	grp = rcu_dereference_all(tsk->numa_group);
3059 	if (!grp)
3060 		goto no_join;
3061 
3062 	my_grp = deref_curr_numa_group(p);
3063 	if (grp == my_grp)
3064 		goto no_join;
3065 
3066 	/*
3067 	 * Only join the other group if its bigger; if we're the bigger group,
3068 	 * the other task will join us.
3069 	 */
3070 	if (my_grp->nr_tasks > grp->nr_tasks)
3071 		goto no_join;
3072 
3073 	/*
3074 	 * Tie-break on the grp address.
3075 	 */
3076 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3077 		goto no_join;
3078 
3079 	/* Always join threads in the same process. */
3080 	if (tsk->mm == current->mm)
3081 		join = true;
3082 
3083 	/* Simple filter to avoid false positives due to PID collisions */
3084 	if (flags & TNF_SHARED)
3085 		join = true;
3086 
3087 	/* Update priv based on whether false sharing was detected */
3088 	*priv = !join;
3089 
3090 	if (join && !get_numa_group(grp))
3091 		goto no_join;
3092 
3093 	rcu_read_unlock();
3094 
3095 	if (!join)
3096 		return;
3097 
3098 	WARN_ON_ONCE(irqs_disabled());
3099 	double_lock_irq(&my_grp->lock, &grp->lock);
3100 
3101 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3102 		my_grp->faults[i] -= p->numa_faults[i];
3103 		grp->faults[i] += p->numa_faults[i];
3104 	}
3105 	my_grp->total_faults -= p->total_numa_faults;
3106 	grp->total_faults += p->total_numa_faults;
3107 
3108 	my_grp->nr_tasks--;
3109 	grp->nr_tasks++;
3110 
3111 	spin_unlock(&my_grp->lock);
3112 	spin_unlock_irq(&grp->lock);
3113 
3114 	rcu_assign_pointer(p->numa_group, grp);
3115 
3116 	put_numa_group(my_grp);
3117 	return;
3118 
3119 no_join:
3120 	rcu_read_unlock();
3121 	return;
3122 }
3123 
3124 /*
3125  * Get rid of NUMA statistics associated with a task (either current or dead).
3126  * If @final is set, the task is dead and has reached refcount zero, so we can
3127  * safely free all relevant data structures. Otherwise, there might be
3128  * concurrent reads from places like load balancing and procfs, and we should
3129  * reset the data back to default state without freeing ->numa_faults.
3130  */
3131 void task_numa_free(struct task_struct *p, bool final)
3132 {
3133 	/* safe: p either is current or is being freed by current */
3134 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3135 	unsigned long *numa_faults = p->numa_faults;
3136 	unsigned long flags;
3137 	int i;
3138 
3139 	if (!numa_faults)
3140 		return;
3141 
3142 	if (grp) {
3143 		spin_lock_irqsave(&grp->lock, flags);
3144 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3145 			grp->faults[i] -= p->numa_faults[i];
3146 		grp->total_faults -= p->total_numa_faults;
3147 
3148 		grp->nr_tasks--;
3149 		spin_unlock_irqrestore(&grp->lock, flags);
3150 		RCU_INIT_POINTER(p->numa_group, NULL);
3151 		put_numa_group(grp);
3152 	}
3153 
3154 	if (final) {
3155 		p->numa_faults = NULL;
3156 		kfree(numa_faults);
3157 	} else {
3158 		p->total_numa_faults = 0;
3159 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3160 			numa_faults[i] = 0;
3161 	}
3162 }
3163 
3164 /*
3165  * Got a PROT_NONE fault for a page on @node.
3166  */
3167 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3168 {
3169 	struct task_struct *p = current;
3170 	bool migrated = flags & TNF_MIGRATED;
3171 	int cpu_node = task_node(current);
3172 	int local = !!(flags & TNF_FAULT_LOCAL);
3173 	struct numa_group *ng;
3174 	int priv;
3175 
3176 	if (!static_branch_likely(&sched_numa_balancing))
3177 		return;
3178 
3179 	/* for example, ksmd faulting in a user's mm */
3180 	if (!p->mm)
3181 		return;
3182 
3183 	/*
3184 	 * NUMA faults statistics are unnecessary for the slow memory
3185 	 * node for memory tiering mode.
3186 	 */
3187 	if (!node_is_toptier(mem_node) &&
3188 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3189 	     !cpupid_valid(last_cpupid)))
3190 		return;
3191 
3192 	/* Allocate buffer to track faults on a per-node basis */
3193 	if (unlikely(!p->numa_faults)) {
3194 		int size = sizeof(*p->numa_faults) *
3195 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3196 
3197 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3198 		if (!p->numa_faults)
3199 			return;
3200 
3201 		p->total_numa_faults = 0;
3202 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3203 	}
3204 
3205 	/*
3206 	 * First accesses are treated as private, otherwise consider accesses
3207 	 * to be private if the accessing pid has not changed
3208 	 */
3209 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3210 		priv = 1;
3211 	} else {
3212 		priv = cpupid_match_pid(p, last_cpupid);
3213 		if (!priv && !(flags & TNF_NO_GROUP))
3214 			task_numa_group(p, last_cpupid, flags, &priv);
3215 	}
3216 
3217 	/*
3218 	 * If a workload spans multiple NUMA nodes, a shared fault that
3219 	 * occurs wholly within the set of nodes that the workload is
3220 	 * actively using should be counted as local. This allows the
3221 	 * scan rate to slow down when a workload has settled down.
3222 	 */
3223 	ng = deref_curr_numa_group(p);
3224 	if (!priv && !local && ng && ng->active_nodes > 1 &&
3225 				numa_is_active_node(cpu_node, ng) &&
3226 				numa_is_active_node(mem_node, ng))
3227 		local = 1;
3228 
3229 	/*
3230 	 * Retry to migrate task to preferred node periodically, in case it
3231 	 * previously failed, or the scheduler moved us.
3232 	 */
3233 	if (time_after(jiffies, p->numa_migrate_retry)) {
3234 		task_numa_placement(p);
3235 		numa_migrate_preferred(p);
3236 	}
3237 
3238 	if (migrated)
3239 		p->numa_pages_migrated += pages;
3240 	if (flags & TNF_MIGRATE_FAIL)
3241 		p->numa_faults_locality[2] += pages;
3242 
3243 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3244 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3245 	p->numa_faults_locality[local] += pages;
3246 }
3247 
3248 static void reset_ptenuma_scan(struct task_struct *p)
3249 {
3250 	/*
3251 	 * We only did a read acquisition of the mmap sem, so
3252 	 * p->mm->numa_scan_seq is written to without exclusive access
3253 	 * and the update is not guaranteed to be atomic. That's not
3254 	 * much of an issue though, since this is just used for
3255 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3256 	 * expensive, to avoid any form of compiler optimizations:
3257 	 */
3258 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3259 	p->mm->numa_scan_offset = 0;
3260 }
3261 
3262 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3263 {
3264 	unsigned long pids;
3265 	/*
3266 	 * Allow unconditional access first two times, so that all the (pages)
3267 	 * of VMAs get prot_none fault introduced irrespective of accesses.
3268 	 * This is also done to avoid any side effect of task scanning
3269 	 * amplifying the unfairness of disjoint set of VMAs' access.
3270 	 */
3271 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3272 		return true;
3273 
3274 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3275 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3276 		return true;
3277 
3278 	/*
3279 	 * Complete a scan that has already started regardless of PID access, or
3280 	 * some VMAs may never be scanned in multi-threaded applications:
3281 	 */
3282 	if (mm->numa_scan_offset > vma->vm_start) {
3283 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3284 		return true;
3285 	}
3286 
3287 	/*
3288 	 * This vma has not been accessed for a while, and if the number
3289 	 * the threads in the same process is low, which means no other
3290 	 * threads can help scan this vma, force a vma scan.
3291 	 */
3292 	if (READ_ONCE(mm->numa_scan_seq) >
3293 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3294 		return true;
3295 
3296 	return false;
3297 }
3298 
3299 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3300 
3301 /*
3302  * The expensive part of numa migration is done from task_work context.
3303  * Triggered from task_tick_numa().
3304  */
3305 static void task_numa_work(struct callback_head *work)
3306 {
3307 	unsigned long migrate, next_scan, now = jiffies;
3308 	struct task_struct *p = current;
3309 	struct mm_struct *mm = p->mm;
3310 	u64 runtime = p->se.sum_exec_runtime;
3311 	struct vm_area_struct *vma;
3312 	unsigned long start, end;
3313 	unsigned long nr_pte_updates = 0;
3314 	long pages, virtpages;
3315 	struct vma_iterator vmi;
3316 	bool vma_pids_skipped;
3317 	bool vma_pids_forced = false;
3318 
3319 	WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
3320 
3321 	work->next = work;
3322 	/*
3323 	 * Who cares about NUMA placement when they're dying.
3324 	 *
3325 	 * NOTE: make sure not to dereference p->mm before this check,
3326 	 * exit_task_work() happens _after_ exit_mm() so we could be called
3327 	 * without p->mm even though we still had it when we enqueued this
3328 	 * work.
3329 	 */
3330 	if (p->flags & PF_EXITING)
3331 		return;
3332 
3333 	/*
3334 	 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
3335 	 * no page can be migrated.
3336 	 */
3337 	if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
3338 		trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
3339 		return;
3340 	}
3341 
3342 	if (!mm->numa_next_scan) {
3343 		mm->numa_next_scan = now +
3344 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3345 	}
3346 
3347 	/*
3348 	 * Enforce maximal scan/migration frequency..
3349 	 */
3350 	migrate = mm->numa_next_scan;
3351 	if (time_before(now, migrate))
3352 		return;
3353 
3354 	if (p->numa_scan_period == 0) {
3355 		p->numa_scan_period_max = task_scan_max(p);
3356 		p->numa_scan_period = task_scan_start(p);
3357 	}
3358 
3359 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3360 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3361 		return;
3362 
3363 	/*
3364 	 * Delay this task enough that another task of this mm will likely win
3365 	 * the next time around.
3366 	 */
3367 	p->node_stamp += 2 * TICK_NSEC;
3368 
3369 	pages = sysctl_numa_balancing_scan_size;
3370 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3371 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
3372 	if (!pages)
3373 		return;
3374 
3375 
3376 	if (!mmap_read_trylock(mm))
3377 		return;
3378 
3379 	/*
3380 	 * VMAs are skipped if the current PID has not trapped a fault within
3381 	 * the VMA recently. Allow scanning to be forced if there is no
3382 	 * suitable VMA remaining.
3383 	 */
3384 	vma_pids_skipped = false;
3385 
3386 retry_pids:
3387 	start = mm->numa_scan_offset;
3388 	vma_iter_init(&vmi, mm, start);
3389 	vma = vma_next(&vmi);
3390 	if (!vma) {
3391 		reset_ptenuma_scan(p);
3392 		start = 0;
3393 		vma_iter_set(&vmi, start);
3394 		vma = vma_next(&vmi);
3395 	}
3396 
3397 	for (; vma; vma = vma_next(&vmi)) {
3398 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3399 			is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3400 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3401 			continue;
3402 		}
3403 
3404 		/*
3405 		 * Shared library pages mapped by multiple processes are not
3406 		 * migrated as it is expected they are cache replicated. Avoid
3407 		 * hinting faults in read-only file-backed mappings or the vDSO
3408 		 * as migrating the pages will be of marginal benefit.
3409 		 */
3410 		if (!vma->vm_mm ||
3411 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3412 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3413 			continue;
3414 		}
3415 
3416 		/*
3417 		 * Skip inaccessible VMAs to avoid any confusion between
3418 		 * PROT_NONE and NUMA hinting PTEs
3419 		 */
3420 		if (!vma_is_accessible(vma)) {
3421 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3422 			continue;
3423 		}
3424 
3425 		/* Initialise new per-VMA NUMAB state. */
3426 		if (!vma->numab_state) {
3427 			struct vma_numab_state *ptr;
3428 
3429 			ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3430 			if (!ptr)
3431 				continue;
3432 
3433 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3434 				kfree(ptr);
3435 				continue;
3436 			}
3437 
3438 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3439 
3440 			vma->numab_state->next_scan = now +
3441 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3442 
3443 			/* Reset happens after 4 times scan delay of scan start */
3444 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
3445 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3446 
3447 			/*
3448 			 * Ensure prev_scan_seq does not match numa_scan_seq,
3449 			 * to prevent VMAs being skipped prematurely on the
3450 			 * first scan:
3451 			 */
3452 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3453 		}
3454 
3455 		/*
3456 		 * Scanning the VMAs of short lived tasks add more overhead. So
3457 		 * delay the scan for new VMAs.
3458 		 */
3459 		if (mm->numa_scan_seq && time_before(jiffies,
3460 						vma->numab_state->next_scan)) {
3461 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3462 			continue;
3463 		}
3464 
3465 		/* RESET access PIDs regularly for old VMAs. */
3466 		if (mm->numa_scan_seq &&
3467 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
3468 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3469 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3470 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3471 			vma->numab_state->pids_active[1] = 0;
3472 		}
3473 
3474 		/* Do not rescan VMAs twice within the same sequence. */
3475 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3476 			mm->numa_scan_offset = vma->vm_end;
3477 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3478 			continue;
3479 		}
3480 
3481 		/*
3482 		 * Do not scan the VMA if task has not accessed it, unless no other
3483 		 * VMA candidate exists.
3484 		 */
3485 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3486 			vma_pids_skipped = true;
3487 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3488 			continue;
3489 		}
3490 
3491 		do {
3492 			start = max(start, vma->vm_start);
3493 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3494 			end = min(end, vma->vm_end);
3495 			nr_pte_updates = change_prot_numa(vma, start, end);
3496 
3497 			/*
3498 			 * Try to scan sysctl_numa_balancing_size worth of
3499 			 * hpages that have at least one present PTE that
3500 			 * is not already PTE-numa. If the VMA contains
3501 			 * areas that are unused or already full of prot_numa
3502 			 * PTEs, scan up to virtpages, to skip through those
3503 			 * areas faster.
3504 			 */
3505 			if (nr_pte_updates)
3506 				pages -= (end - start) >> PAGE_SHIFT;
3507 			virtpages -= (end - start) >> PAGE_SHIFT;
3508 
3509 			start = end;
3510 			if (pages <= 0 || virtpages <= 0)
3511 				goto out;
3512 
3513 			cond_resched();
3514 		} while (end != vma->vm_end);
3515 
3516 		/* VMA scan is complete, do not scan until next sequence. */
3517 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3518 
3519 		/*
3520 		 * Only force scan within one VMA at a time, to limit the
3521 		 * cost of scanning a potentially uninteresting VMA.
3522 		 */
3523 		if (vma_pids_forced)
3524 			break;
3525 	}
3526 
3527 	/*
3528 	 * If no VMAs are remaining and VMAs were skipped due to the PID
3529 	 * not accessing the VMA previously, then force a scan to ensure
3530 	 * forward progress:
3531 	 */
3532 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
3533 		vma_pids_forced = true;
3534 		goto retry_pids;
3535 	}
3536 
3537 out:
3538 	/*
3539 	 * It is possible to reach the end of the VMA list but the last few
3540 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3541 	 * would find the !migratable VMA on the next scan but not reset the
3542 	 * scanner to the start so check it now.
3543 	 */
3544 	if (vma)
3545 		mm->numa_scan_offset = start;
3546 	else
3547 		reset_ptenuma_scan(p);
3548 	mmap_read_unlock(mm);
3549 
3550 	/*
3551 	 * Make sure tasks use at least 32x as much time to run other code
3552 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3553 	 * Usually update_task_scan_period slows down scanning enough; on an
3554 	 * overloaded system we need to limit overhead on a per task basis.
3555 	 */
3556 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
3557 		u64 diff = p->se.sum_exec_runtime - runtime;
3558 		p->node_stamp += 32 * diff;
3559 	}
3560 }
3561 
3562 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
3563 {
3564 	int mm_users = 0;
3565 	struct mm_struct *mm = p->mm;
3566 
3567 	if (mm) {
3568 		mm_users = atomic_read(&mm->mm_users);
3569 		if (mm_users == 1) {
3570 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3571 			mm->numa_scan_seq = 0;
3572 		}
3573 	}
3574 	p->node_stamp			= 0;
3575 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
3576 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
3577 	p->numa_migrate_retry		= 0;
3578 	/* Protect against double add, see task_tick_numa and task_numa_work */
3579 	p->numa_work.next		= &p->numa_work;
3580 	p->numa_faults			= NULL;
3581 	p->numa_pages_migrated		= 0;
3582 	p->total_numa_faults		= 0;
3583 	RCU_INIT_POINTER(p->numa_group, NULL);
3584 	p->last_task_numa_placement	= 0;
3585 	p->last_sum_exec_runtime	= 0;
3586 
3587 	init_task_work(&p->numa_work, task_numa_work);
3588 
3589 	/* New address space, reset the preferred nid */
3590 	if (!(clone_flags & CLONE_VM)) {
3591 		p->numa_preferred_nid = NUMA_NO_NODE;
3592 		return;
3593 	}
3594 
3595 	/*
3596 	 * New thread, keep existing numa_preferred_nid which should be copied
3597 	 * already by arch_dup_task_struct but stagger when scans start.
3598 	 */
3599 	if (mm) {
3600 		unsigned int delay;
3601 
3602 		delay = min_t(unsigned int, task_scan_max(current),
3603 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3604 		delay += 2 * TICK_NSEC;
3605 		p->node_stamp = delay;
3606 	}
3607 }
3608 
3609 /*
3610  * Drive the periodic memory faults..
3611  */
3612 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3613 {
3614 	struct callback_head *work = &curr->numa_work;
3615 	u64 period, now;
3616 
3617 	/*
3618 	 * We don't care about NUMA placement if we don't have memory.
3619 	 */
3620 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3621 		return;
3622 
3623 	/*
3624 	 * Using runtime rather than walltime has the dual advantage that
3625 	 * we (mostly) drive the selection from busy threads and that the
3626 	 * task needs to have done some actual work before we bother with
3627 	 * NUMA placement.
3628 	 */
3629 	now = curr->se.sum_exec_runtime;
3630 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3631 
3632 	if (now > curr->node_stamp + period) {
3633 		if (!curr->node_stamp)
3634 			curr->numa_scan_period = task_scan_start(curr);
3635 		curr->node_stamp += period;
3636 
3637 		if (!time_before(jiffies, curr->mm->numa_next_scan))
3638 			task_work_add(curr, work, TWA_RESUME);
3639 	}
3640 }
3641 
3642 static void update_scan_period(struct task_struct *p, int new_cpu)
3643 {
3644 	int src_nid = cpu_to_node(task_cpu(p));
3645 	int dst_nid = cpu_to_node(new_cpu);
3646 
3647 	if (!static_branch_likely(&sched_numa_balancing))
3648 		return;
3649 
3650 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3651 		return;
3652 
3653 	if (src_nid == dst_nid)
3654 		return;
3655 
3656 	/*
3657 	 * Allow resets if faults have been trapped before one scan
3658 	 * has completed. This is most likely due to a new task that
3659 	 * is pulled cross-node due to wakeups or load balancing.
3660 	 */
3661 	if (p->numa_scan_seq) {
3662 		/*
3663 		 * Avoid scan adjustments if moving to the preferred
3664 		 * node or if the task was not previously running on
3665 		 * the preferred node.
3666 		 */
3667 		if (dst_nid == p->numa_preferred_nid ||
3668 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
3669 			src_nid != p->numa_preferred_nid))
3670 			return;
3671 	}
3672 
3673 	p->numa_scan_period = task_scan_start(p);
3674 }
3675 
3676 #else /* !CONFIG_NUMA_BALANCING: */
3677 
3678 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3679 {
3680 }
3681 
3682 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3683 {
3684 }
3685 
3686 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3687 {
3688 }
3689 
3690 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3691 {
3692 }
3693 
3694 #endif /* !CONFIG_NUMA_BALANCING */
3695 
3696 static void
3697 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3698 {
3699 	update_load_add(&cfs_rq->load, se->load.weight);
3700 	if (entity_is_task(se)) {
3701 		struct rq *rq = rq_of(cfs_rq);
3702 
3703 		account_numa_enqueue(rq, task_of(se));
3704 		list_add(&se->group_node, &rq->cfs_tasks);
3705 	}
3706 	cfs_rq->nr_queued++;
3707 }
3708 
3709 static void
3710 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3711 {
3712 	update_load_sub(&cfs_rq->load, se->load.weight);
3713 	if (entity_is_task(se)) {
3714 		account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3715 		list_del_init(&se->group_node);
3716 	}
3717 	cfs_rq->nr_queued--;
3718 }
3719 
3720 /*
3721  * Signed add and clamp on underflow.
3722  *
3723  * Explicitly do a load-store to ensure the intermediate value never hits
3724  * memory. This allows lockless observations without ever seeing the negative
3725  * values.
3726  */
3727 #define add_positive(_ptr, _val) do {                           \
3728 	typeof(_ptr) ptr = (_ptr);                              \
3729 	__signed_scalar_typeof(*ptr) val = (_val);              \
3730 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3731 								\
3732 	res = var + val;                                        \
3733 								\
3734 	if (val < 0 && res > var)                               \
3735 		res = 0;                                        \
3736 								\
3737 	WRITE_ONCE(*ptr, res);                                  \
3738 } while (0)
3739 
3740 /*
3741  * Remove and clamp on negative, from a local variable.
3742  *
3743  * A variant of sub_positive(), which does not use explicit load-store
3744  * and is thus optimized for local variable updates.
3745  */
3746 #define lsub_positive(_ptr, _val) do {				\
3747 	typeof(_ptr) ptr = (_ptr);				\
3748 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
3749 } while (0)
3750 
3751 
3752 /*
3753  * Because of rounding, se->util_sum might ends up being +1 more than
3754  * cfs->util_sum. Although this is not a problem by itself, detaching
3755  * a lot of tasks with the rounding problem between 2 updates of
3756  * util_avg (~1ms) can make cfs->util_sum becoming null whereas
3757  * cfs_util_avg is not.
3758  *
3759  * Check that util_sum is still above its lower bound for the new
3760  * util_avg. Given that period_contrib might have moved since the last
3761  * sync, we are only sure that util_sum must be above or equal to
3762  *    util_avg * minimum possible divider
3763  */
3764 #define __update_sa(sa, name, delta_avg, delta_sum) do {	\
3765 	add_positive(&(sa)->name##_avg, delta_avg);		\
3766 	add_positive(&(sa)->name##_sum, delta_sum);		\
3767 	(sa)->name##_sum = max_t(typeof((sa)->name##_sum),	\
3768 			       (sa)->name##_sum,		\
3769 			       (sa)->name##_avg * PELT_MIN_DIVIDER); \
3770 } while (0)
3771 
3772 static inline void
3773 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3774 {
3775 	__update_sa(&cfs_rq->avg, load, se->avg.load_avg,
3776 		    se_weight(se) * se->avg.load_sum);
3777 }
3778 
3779 static inline void
3780 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3781 {
3782 	__update_sa(&cfs_rq->avg, load, -se->avg.load_avg,
3783 		    se_weight(se) * -se->avg.load_sum);
3784 }
3785 
3786 static void place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags);
3787 
3788 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3789 			    unsigned long weight)
3790 {
3791 	bool curr = cfs_rq->curr == se;
3792 
3793 	if (se->on_rq) {
3794 		/* commit outstanding execution time */
3795 		update_curr(cfs_rq);
3796 		update_entity_lag(cfs_rq, se);
3797 		se->deadline -= se->vruntime;
3798 		se->rel_deadline = 1;
3799 		cfs_rq->nr_queued--;
3800 		if (!curr)
3801 			__dequeue_entity(cfs_rq, se);
3802 		update_load_sub(&cfs_rq->load, se->load.weight);
3803 	}
3804 	dequeue_load_avg(cfs_rq, se);
3805 
3806 	/*
3807 	 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3808 	 * we need to scale se->vlag when w_i changes.
3809 	 */
3810 	se->vlag = div_s64(se->vlag * se->load.weight, weight);
3811 	if (se->rel_deadline)
3812 		se->deadline = div_s64(se->deadline * se->load.weight, weight);
3813 
3814 	update_load_set(&se->load, weight);
3815 
3816 	do {
3817 		u32 divider = get_pelt_divider(&se->avg);
3818 
3819 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3820 	} while (0);
3821 
3822 	enqueue_load_avg(cfs_rq, se);
3823 	if (se->on_rq) {
3824 		place_entity(cfs_rq, se, 0);
3825 		update_load_add(&cfs_rq->load, se->load.weight);
3826 		if (!curr)
3827 			__enqueue_entity(cfs_rq, se);
3828 		cfs_rq->nr_queued++;
3829 	}
3830 }
3831 
3832 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
3833 			       const struct load_weight *lw)
3834 {
3835 	struct sched_entity *se = &p->se;
3836 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
3837 	struct load_weight *load = &se->load;
3838 
3839 	reweight_entity(cfs_rq, se, lw->weight);
3840 	load->inv_weight = lw->inv_weight;
3841 }
3842 
3843 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3844 
3845 #ifdef CONFIG_FAIR_GROUP_SCHED
3846 /*
3847  * All this does is approximate the hierarchical proportion which includes that
3848  * global sum we all love to hate.
3849  *
3850  * That is, the weight of a group entity, is the proportional share of the
3851  * group weight based on the group runqueue weights. That is:
3852  *
3853  *                     tg->weight * grq->load.weight
3854  *   ge->load.weight = -----------------------------               (1)
3855  *                       \Sum grq->load.weight
3856  *
3857  * Now, because computing that sum is prohibitively expensive to compute (been
3858  * there, done that) we approximate it with this average stuff. The average
3859  * moves slower and therefore the approximation is cheaper and more stable.
3860  *
3861  * So instead of the above, we substitute:
3862  *
3863  *   grq->load.weight -> grq->avg.load_avg                         (2)
3864  *
3865  * which yields the following:
3866  *
3867  *                     tg->weight * grq->avg.load_avg
3868  *   ge->load.weight = ------------------------------              (3)
3869  *                             tg->load_avg
3870  *
3871  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3872  *
3873  * That is shares_avg, and it is right (given the approximation (2)).
3874  *
3875  * The problem with it is that because the average is slow -- it was designed
3876  * to be exactly that of course -- this leads to transients in boundary
3877  * conditions. In specific, the case where the group was idle and we start the
3878  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3879  * yielding bad latency etc..
3880  *
3881  * Now, in that special case (1) reduces to:
3882  *
3883  *                     tg->weight * grq->load.weight
3884  *   ge->load.weight = ----------------------------- = tg->weight   (4)
3885  *                         grp->load.weight
3886  *
3887  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3888  *
3889  * So what we do is modify our approximation (3) to approach (4) in the (near)
3890  * UP case, like:
3891  *
3892  *   ge->load.weight =
3893  *
3894  *              tg->weight * grq->load.weight
3895  *     ---------------------------------------------------         (5)
3896  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
3897  *
3898  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3899  * we need to use grq->avg.load_avg as its lower bound, which then gives:
3900  *
3901  *
3902  *                     tg->weight * grq->load.weight
3903  *   ge->load.weight = -----------------------------		   (6)
3904  *                             tg_load_avg'
3905  *
3906  * Where:
3907  *
3908  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3909  *                  max(grq->load.weight, grq->avg.load_avg)
3910  *
3911  * And that is shares_weight and is icky. In the (near) UP case it approaches
3912  * (4) while in the normal case it approaches (3). It consistently
3913  * overestimates the ge->load.weight and therefore:
3914  *
3915  *   \Sum ge->load.weight >= tg->weight
3916  *
3917  * hence icky!
3918  */
3919 static long calc_group_shares(struct cfs_rq *cfs_rq)
3920 {
3921 	long tg_weight, tg_shares, load, shares;
3922 	struct task_group *tg = cfs_rq->tg;
3923 
3924 	tg_shares = READ_ONCE(tg->shares);
3925 
3926 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3927 
3928 	tg_weight = atomic_long_read(&tg->load_avg);
3929 
3930 	/* Ensure tg_weight >= load */
3931 	tg_weight -= cfs_rq->tg_load_avg_contrib;
3932 	tg_weight += load;
3933 
3934 	shares = (tg_shares * load);
3935 	if (tg_weight)
3936 		shares /= tg_weight;
3937 
3938 	/*
3939 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3940 	 * of a group with small tg->shares value. It is a floor value which is
3941 	 * assigned as a minimum load.weight to the sched_entity representing
3942 	 * the group on a CPU.
3943 	 *
3944 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3945 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3946 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3947 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3948 	 * instead of 0.
3949 	 */
3950 	return clamp_t(long, shares, MIN_SHARES, tg_shares);
3951 }
3952 
3953 /*
3954  * Recomputes the group entity based on the current state of its group
3955  * runqueue.
3956  */
3957 static void update_cfs_group(struct sched_entity *se)
3958 {
3959 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3960 	long shares;
3961 
3962 	/*
3963 	 * When a group becomes empty, preserve its weight. This matters for
3964 	 * DELAY_DEQUEUE.
3965 	 */
3966 	if (!gcfs_rq || !gcfs_rq->load.weight)
3967 		return;
3968 
3969 	shares = calc_group_shares(gcfs_rq);
3970 	if (unlikely(se->load.weight != shares))
3971 		reweight_entity(cfs_rq_of(se), se, shares);
3972 }
3973 
3974 #else /* !CONFIG_FAIR_GROUP_SCHED: */
3975 static inline void update_cfs_group(struct sched_entity *se)
3976 {
3977 }
3978 #endif /* !CONFIG_FAIR_GROUP_SCHED */
3979 
3980 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3981 {
3982 	struct rq *rq = rq_of(cfs_rq);
3983 
3984 	if (&rq->cfs == cfs_rq) {
3985 		/*
3986 		 * There are a few boundary cases this might miss but it should
3987 		 * get called often enough that that should (hopefully) not be
3988 		 * a real problem.
3989 		 *
3990 		 * It will not get called when we go idle, because the idle
3991 		 * thread is a different class (!fair), nor will the utilization
3992 		 * number include things like RT tasks.
3993 		 *
3994 		 * As is, the util number is not freq-invariant (we'd have to
3995 		 * implement arch_scale_freq_capacity() for that).
3996 		 *
3997 		 * See cpu_util_cfs().
3998 		 */
3999 		cpufreq_update_util(rq, flags);
4000 	}
4001 }
4002 
4003 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4004 {
4005 	if (sa->load_sum)
4006 		return false;
4007 
4008 	if (sa->util_sum)
4009 		return false;
4010 
4011 	if (sa->runnable_sum)
4012 		return false;
4013 
4014 	/*
4015 	 * _avg must be null when _sum are null because _avg = _sum / divider
4016 	 * Make sure that rounding and/or propagation of PELT values never
4017 	 * break this.
4018 	 */
4019 	WARN_ON_ONCE(sa->load_avg ||
4020 		      sa->util_avg ||
4021 		      sa->runnable_avg);
4022 
4023 	return true;
4024 }
4025 
4026 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4027 {
4028 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4029 				 cfs_rq->last_update_time_copy);
4030 }
4031 #ifdef CONFIG_FAIR_GROUP_SCHED
4032 /*
4033  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4034  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4035  * bottom-up, we only have to test whether the cfs_rq before us on the list
4036  * is our child.
4037  * If cfs_rq is not on the list, test whether a child needs its to be added to
4038  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
4039  */
4040 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4041 {
4042 	struct cfs_rq *prev_cfs_rq;
4043 	struct list_head *prev;
4044 	struct rq *rq = rq_of(cfs_rq);
4045 
4046 	if (cfs_rq->on_list) {
4047 		prev = cfs_rq->leaf_cfs_rq_list.prev;
4048 	} else {
4049 		prev = rq->tmp_alone_branch;
4050 	}
4051 
4052 	if (prev == &rq->leaf_cfs_rq_list)
4053 		return false;
4054 
4055 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4056 
4057 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4058 }
4059 
4060 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4061 {
4062 	if (cfs_rq->load.weight)
4063 		return false;
4064 
4065 	if (!load_avg_is_decayed(&cfs_rq->avg))
4066 		return false;
4067 
4068 	if (child_cfs_rq_on_list(cfs_rq))
4069 		return false;
4070 
4071 	if (cfs_rq->tg_load_avg_contrib)
4072 		return false;
4073 
4074 	return true;
4075 }
4076 
4077 /**
4078  * update_tg_load_avg - update the tg's load avg
4079  * @cfs_rq: the cfs_rq whose avg changed
4080  *
4081  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4082  * However, because tg->load_avg is a global value there are performance
4083  * considerations.
4084  *
4085  * In order to avoid having to look at the other cfs_rq's, we use a
4086  * differential update where we store the last value we propagated. This in
4087  * turn allows skipping updates if the differential is 'small'.
4088  *
4089  * Updating tg's load_avg is necessary before update_cfs_share().
4090  */
4091 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4092 {
4093 	long delta;
4094 	u64 now;
4095 
4096 	/*
4097 	 * No need to update load_avg for root_task_group as it is not used.
4098 	 */
4099 	if (cfs_rq->tg == &root_task_group)
4100 		return;
4101 
4102 	/* rq has been offline and doesn't contribute to the share anymore: */
4103 	if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4104 		return;
4105 
4106 	/*
4107 	 * For migration heavy workloads, access to tg->load_avg can be
4108 	 * unbound. Limit the update rate to at most once per ms.
4109 	 */
4110 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4111 	if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4112 		return;
4113 
4114 	delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4115 	if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4116 		atomic_long_add(delta, &cfs_rq->tg->load_avg);
4117 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4118 		cfs_rq->last_update_tg_load_avg = now;
4119 	}
4120 }
4121 
4122 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4123 {
4124 	long delta;
4125 	u64 now;
4126 
4127 	/*
4128 	 * No need to update load_avg for root_task_group, as it is not used.
4129 	 */
4130 	if (cfs_rq->tg == &root_task_group)
4131 		return;
4132 
4133 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4134 	delta = 0 - cfs_rq->tg_load_avg_contrib;
4135 	atomic_long_add(delta, &cfs_rq->tg->load_avg);
4136 	cfs_rq->tg_load_avg_contrib = 0;
4137 	cfs_rq->last_update_tg_load_avg = now;
4138 }
4139 
4140 /* CPU offline callback: */
4141 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4142 {
4143 	struct task_group *tg;
4144 
4145 	lockdep_assert_rq_held(rq);
4146 
4147 	/*
4148 	 * The rq clock has already been updated in
4149 	 * set_rq_offline(), so we should skip updating
4150 	 * the rq clock again in unthrottle_cfs_rq().
4151 	 */
4152 	rq_clock_start_loop_update(rq);
4153 
4154 	rcu_read_lock();
4155 	list_for_each_entry_rcu(tg, &task_groups, list) {
4156 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4157 
4158 		clear_tg_load_avg(cfs_rq);
4159 	}
4160 	rcu_read_unlock();
4161 
4162 	rq_clock_stop_loop_update(rq);
4163 }
4164 
4165 /*
4166  * Called within set_task_rq() right before setting a task's CPU. The
4167  * caller only guarantees p->pi_lock is held; no other assumptions,
4168  * including the state of rq->lock, should be made.
4169  */
4170 void set_task_rq_fair(struct sched_entity *se,
4171 		      struct cfs_rq *prev, struct cfs_rq *next)
4172 {
4173 	u64 p_last_update_time;
4174 	u64 n_last_update_time;
4175 
4176 	if (!sched_feat(ATTACH_AGE_LOAD))
4177 		return;
4178 
4179 	/*
4180 	 * We are supposed to update the task to "current" time, then its up to
4181 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4182 	 * getting what current time is, so simply throw away the out-of-date
4183 	 * time. This will result in the wakee task is less decayed, but giving
4184 	 * the wakee more load sounds not bad.
4185 	 */
4186 	if (!(se->avg.last_update_time && prev))
4187 		return;
4188 
4189 	p_last_update_time = cfs_rq_last_update_time(prev);
4190 	n_last_update_time = cfs_rq_last_update_time(next);
4191 
4192 	__update_load_avg_blocked_se(p_last_update_time, se);
4193 	se->avg.last_update_time = n_last_update_time;
4194 }
4195 
4196 /*
4197  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4198  * propagate its contribution. The key to this propagation is the invariant
4199  * that for each group:
4200  *
4201  *   ge->avg == grq->avg						(1)
4202  *
4203  * _IFF_ we look at the pure running and runnable sums. Because they
4204  * represent the very same entity, just at different points in the hierarchy.
4205  *
4206  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4207  * and simply copies the running/runnable sum over (but still wrong, because
4208  * the group entity and group rq do not have their PELT windows aligned).
4209  *
4210  * However, update_tg_cfs_load() is more complex. So we have:
4211  *
4212  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
4213  *
4214  * And since, like util, the runnable part should be directly transferable,
4215  * the following would _appear_ to be the straight forward approach:
4216  *
4217  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
4218  *
4219  * And per (1) we have:
4220  *
4221  *   ge->avg.runnable_avg == grq->avg.runnable_avg
4222  *
4223  * Which gives:
4224  *
4225  *                      ge->load.weight * grq->avg.load_avg
4226  *   ge->avg.load_avg = -----------------------------------		(4)
4227  *                               grq->load.weight
4228  *
4229  * Except that is wrong!
4230  *
4231  * Because while for entities historical weight is not important and we
4232  * really only care about our future and therefore can consider a pure
4233  * runnable sum, runqueues can NOT do this.
4234  *
4235  * We specifically want runqueues to have a load_avg that includes
4236  * historical weights. Those represent the blocked load, the load we expect
4237  * to (shortly) return to us. This only works by keeping the weights as
4238  * integral part of the sum. We therefore cannot decompose as per (3).
4239  *
4240  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4241  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4242  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4243  * runnable section of these tasks overlap (or not). If they were to perfectly
4244  * align the rq as a whole would be runnable 2/3 of the time. If however we
4245  * always have at least 1 runnable task, the rq as a whole is always runnable.
4246  *
4247  * So we'll have to approximate.. :/
4248  *
4249  * Given the constraint:
4250  *
4251  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4252  *
4253  * We can construct a rule that adds runnable to a rq by assuming minimal
4254  * overlap.
4255  *
4256  * On removal, we'll assume each task is equally runnable; which yields:
4257  *
4258  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4259  *
4260  * XXX: only do this for the part of runnable > running ?
4261  *
4262  */
4263 static inline void
4264 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4265 {
4266 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4267 	u32 new_sum, divider;
4268 
4269 	/* Nothing to update */
4270 	if (!delta_avg)
4271 		return;
4272 
4273 	/*
4274 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4275 	 * See ___update_load_avg() for details.
4276 	 */
4277 	divider = get_pelt_divider(&cfs_rq->avg);
4278 
4279 	/* Set new sched_entity's utilization */
4280 	se->avg.util_avg = gcfs_rq->avg.util_avg;
4281 	new_sum = se->avg.util_avg * divider;
4282 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
4283 	se->avg.util_sum = new_sum;
4284 
4285 	/* Update parent cfs_rq utilization */
4286 	__update_sa(&cfs_rq->avg, util, delta_avg, delta_sum);
4287 }
4288 
4289 static inline void
4290 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4291 {
4292 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4293 	u32 new_sum, divider;
4294 
4295 	/* Nothing to update */
4296 	if (!delta_avg)
4297 		return;
4298 
4299 	/*
4300 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4301 	 * See ___update_load_avg() for details.
4302 	 */
4303 	divider = get_pelt_divider(&cfs_rq->avg);
4304 
4305 	/* Set new sched_entity's runnable */
4306 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4307 	new_sum = se->avg.runnable_avg * divider;
4308 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4309 	se->avg.runnable_sum = new_sum;
4310 
4311 	/* Update parent cfs_rq runnable */
4312 	__update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum);
4313 }
4314 
4315 static inline void
4316 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4317 {
4318 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4319 	unsigned long load_avg;
4320 	u64 load_sum = 0;
4321 	s64 delta_sum;
4322 	u32 divider;
4323 
4324 	if (!runnable_sum)
4325 		return;
4326 
4327 	gcfs_rq->prop_runnable_sum = 0;
4328 
4329 	/*
4330 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4331 	 * See ___update_load_avg() for details.
4332 	 */
4333 	divider = get_pelt_divider(&cfs_rq->avg);
4334 
4335 	if (runnable_sum >= 0) {
4336 		/*
4337 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4338 		 * the CPU is saturated running == runnable.
4339 		 */
4340 		runnable_sum += se->avg.load_sum;
4341 		runnable_sum = min_t(long, runnable_sum, divider);
4342 	} else {
4343 		/*
4344 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4345 		 * assuming all tasks are equally runnable.
4346 		 */
4347 		if (scale_load_down(gcfs_rq->load.weight)) {
4348 			load_sum = div_u64(gcfs_rq->avg.load_sum,
4349 				scale_load_down(gcfs_rq->load.weight));
4350 		}
4351 
4352 		/* But make sure to not inflate se's runnable */
4353 		runnable_sum = min(se->avg.load_sum, load_sum);
4354 	}
4355 
4356 	/*
4357 	 * runnable_sum can't be lower than running_sum
4358 	 * Rescale running sum to be in the same range as runnable sum
4359 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
4360 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
4361 	 */
4362 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4363 	runnable_sum = max(runnable_sum, running_sum);
4364 
4365 	load_sum = se_weight(se) * runnable_sum;
4366 	load_avg = div_u64(load_sum, divider);
4367 
4368 	delta_avg = load_avg - se->avg.load_avg;
4369 	if (!delta_avg)
4370 		return;
4371 
4372 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4373 
4374 	se->avg.load_sum = runnable_sum;
4375 	se->avg.load_avg = load_avg;
4376 	__update_sa(&cfs_rq->avg, load, delta_avg, delta_sum);
4377 }
4378 
4379 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4380 {
4381 	cfs_rq->propagate = 1;
4382 	cfs_rq->prop_runnable_sum += runnable_sum;
4383 }
4384 
4385 /* Update task and its cfs_rq load average */
4386 static inline int propagate_entity_load_avg(struct sched_entity *se)
4387 {
4388 	struct cfs_rq *cfs_rq, *gcfs_rq;
4389 
4390 	if (entity_is_task(se))
4391 		return 0;
4392 
4393 	gcfs_rq = group_cfs_rq(se);
4394 	if (!gcfs_rq->propagate)
4395 		return 0;
4396 
4397 	gcfs_rq->propagate = 0;
4398 
4399 	cfs_rq = cfs_rq_of(se);
4400 
4401 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4402 
4403 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4404 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4405 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4406 
4407 	trace_pelt_cfs_tp(cfs_rq);
4408 	trace_pelt_se_tp(se);
4409 
4410 	return 1;
4411 }
4412 
4413 /*
4414  * Check if we need to update the load and the utilization of a blocked
4415  * group_entity:
4416  */
4417 static inline bool skip_blocked_update(struct sched_entity *se)
4418 {
4419 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4420 
4421 	/*
4422 	 * If sched_entity still have not zero load or utilization, we have to
4423 	 * decay it:
4424 	 */
4425 	if (se->avg.load_avg || se->avg.util_avg)
4426 		return false;
4427 
4428 	/*
4429 	 * If there is a pending propagation, we have to update the load and
4430 	 * the utilization of the sched_entity:
4431 	 */
4432 	if (gcfs_rq->propagate)
4433 		return false;
4434 
4435 	/*
4436 	 * Otherwise, the load and the utilization of the sched_entity is
4437 	 * already zero and there is no pending propagation, so it will be a
4438 	 * waste of time to try to decay it:
4439 	 */
4440 	return true;
4441 }
4442 
4443 #else /* !CONFIG_FAIR_GROUP_SCHED: */
4444 
4445 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4446 
4447 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4448 
4449 static inline int propagate_entity_load_avg(struct sched_entity *se)
4450 {
4451 	return 0;
4452 }
4453 
4454 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4455 
4456 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4457 
4458 #ifdef CONFIG_NO_HZ_COMMON
4459 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4460 {
4461 	u64 throttled = 0, now, lut;
4462 	struct cfs_rq *cfs_rq;
4463 	struct rq *rq;
4464 	bool is_idle;
4465 
4466 	if (load_avg_is_decayed(&se->avg))
4467 		return;
4468 
4469 	cfs_rq = cfs_rq_of(se);
4470 	rq = rq_of(cfs_rq);
4471 
4472 	rcu_read_lock();
4473 	is_idle = is_idle_task(rcu_dereference_all(rq->curr));
4474 	rcu_read_unlock();
4475 
4476 	/*
4477 	 * The lag estimation comes with a cost we don't want to pay all the
4478 	 * time. Hence, limiting to the case where the source CPU is idle and
4479 	 * we know we are at the greatest risk to have an outdated clock.
4480 	 */
4481 	if (!is_idle)
4482 		return;
4483 
4484 	/*
4485 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4486 	 *
4487 	 *   last_update_time (the cfs_rq's last_update_time)
4488 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
4489 	 *      = rq_clock_pelt()@cfs_rq_idle
4490 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
4491 	 *
4492 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
4493 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4494 	 *
4495 	 *   rq_idle_lag (delta between now and rq's update)
4496 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
4497 	 *
4498 	 * We can then write:
4499 	 *
4500 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4501 	 *          sched_clock_cpu() - rq_clock()@rq_idle
4502 	 * Where:
4503 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4504 	 *      rq_clock()@rq_idle      is rq->clock_idle
4505 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
4506 	 *                              is cfs_rq->throttled_pelt_idle
4507 	 */
4508 
4509 #ifdef CONFIG_CFS_BANDWIDTH
4510 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4511 	/* The clock has been stopped for throttling */
4512 	if (throttled == U64_MAX)
4513 		return;
4514 #endif
4515 	now = u64_u32_load(rq->clock_pelt_idle);
4516 	/*
4517 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4518 	 * is observed the old clock_pelt_idle value and the new clock_idle,
4519 	 * which lead to an underestimation. The opposite would lead to an
4520 	 * overestimation.
4521 	 */
4522 	smp_rmb();
4523 	lut = cfs_rq_last_update_time(cfs_rq);
4524 
4525 	now -= throttled;
4526 	if (now < lut)
4527 		/*
4528 		 * cfs_rq->avg.last_update_time is more recent than our
4529 		 * estimation, let's use it.
4530 		 */
4531 		now = lut;
4532 	else
4533 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4534 
4535 	__update_load_avg_blocked_se(now, se);
4536 }
4537 #else /* !CONFIG_NO_HZ_COMMON: */
4538 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4539 #endif /* !CONFIG_NO_HZ_COMMON */
4540 
4541 /**
4542  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4543  * @now: current time, as per cfs_rq_clock_pelt()
4544  * @cfs_rq: cfs_rq to update
4545  *
4546  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4547  * avg. The immediate corollary is that all (fair) tasks must be attached.
4548  *
4549  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4550  *
4551  * Return: true if the load decayed or we removed load.
4552  *
4553  * Since both these conditions indicate a changed cfs_rq->avg.load we should
4554  * call update_tg_load_avg() when this function returns true.
4555  */
4556 static inline int
4557 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4558 {
4559 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4560 	struct sched_avg *sa = &cfs_rq->avg;
4561 	int decayed = 0;
4562 
4563 	if (cfs_rq->removed.nr) {
4564 		unsigned long r;
4565 		u32 divider = get_pelt_divider(&cfs_rq->avg);
4566 
4567 		raw_spin_lock(&cfs_rq->removed.lock);
4568 		swap(cfs_rq->removed.util_avg, removed_util);
4569 		swap(cfs_rq->removed.load_avg, removed_load);
4570 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
4571 		cfs_rq->removed.nr = 0;
4572 		raw_spin_unlock(&cfs_rq->removed.lock);
4573 
4574 		r = removed_load;
4575 		__update_sa(sa, load, -r, -r*divider);
4576 
4577 		r = removed_util;
4578 		__update_sa(sa, util, -r, -r*divider);
4579 
4580 		r = removed_runnable;
4581 		__update_sa(sa, runnable, -r, -r*divider);
4582 
4583 		/*
4584 		 * removed_runnable is the unweighted version of removed_load so we
4585 		 * can use it to estimate removed_load_sum.
4586 		 */
4587 		add_tg_cfs_propagate(cfs_rq,
4588 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4589 
4590 		decayed = 1;
4591 	}
4592 
4593 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4594 	u64_u32_store_copy(sa->last_update_time,
4595 			   cfs_rq->last_update_time_copy,
4596 			   sa->last_update_time);
4597 	return decayed;
4598 }
4599 
4600 /**
4601  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4602  * @cfs_rq: cfs_rq to attach to
4603  * @se: sched_entity to attach
4604  *
4605  * Must call update_cfs_rq_load_avg() before this, since we rely on
4606  * cfs_rq->avg.last_update_time being current.
4607  */
4608 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4609 {
4610 	/*
4611 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4612 	 * See ___update_load_avg() for details.
4613 	 */
4614 	u32 divider = get_pelt_divider(&cfs_rq->avg);
4615 
4616 	/*
4617 	 * When we attach the @se to the @cfs_rq, we must align the decay
4618 	 * window because without that, really weird and wonderful things can
4619 	 * happen.
4620 	 *
4621 	 * XXX illustrate
4622 	 */
4623 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
4624 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
4625 
4626 	/*
4627 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4628 	 * period_contrib. This isn't strictly correct, but since we're
4629 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4630 	 * _sum a little.
4631 	 */
4632 	se->avg.util_sum = se->avg.util_avg * divider;
4633 
4634 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
4635 
4636 	se->avg.load_sum = se->avg.load_avg * divider;
4637 	if (se_weight(se) < se->avg.load_sum)
4638 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4639 	else
4640 		se->avg.load_sum = 1;
4641 
4642 	enqueue_load_avg(cfs_rq, se);
4643 	cfs_rq->avg.util_avg += se->avg.util_avg;
4644 	cfs_rq->avg.util_sum += se->avg.util_sum;
4645 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4646 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4647 
4648 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4649 
4650 	cfs_rq_util_change(cfs_rq, 0);
4651 
4652 	trace_pelt_cfs_tp(cfs_rq);
4653 }
4654 
4655 /**
4656  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4657  * @cfs_rq: cfs_rq to detach from
4658  * @se: sched_entity to detach
4659  *
4660  * Must call update_cfs_rq_load_avg() before this, since we rely on
4661  * cfs_rq->avg.last_update_time being current.
4662  */
4663 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4664 {
4665 	dequeue_load_avg(cfs_rq, se);
4666 	__update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum);
4667 	__update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum);
4668 
4669 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4670 
4671 	cfs_rq_util_change(cfs_rq, 0);
4672 
4673 	trace_pelt_cfs_tp(cfs_rq);
4674 }
4675 
4676 /*
4677  * Optional action to be done while updating the load average
4678  */
4679 #define UPDATE_TG	0x1
4680 #define SKIP_AGE_LOAD	0x2
4681 #define DO_ATTACH	0x4
4682 #define DO_DETACH	0x8
4683 
4684 /* Update task and its cfs_rq load average */
4685 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4686 {
4687 	u64 now = cfs_rq_clock_pelt(cfs_rq);
4688 	int decayed;
4689 
4690 	/*
4691 	 * Track task load average for carrying it to new CPU after migrated, and
4692 	 * track group sched_entity load average for task_h_load calculation in migration
4693 	 */
4694 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4695 		__update_load_avg_se(now, cfs_rq, se);
4696 
4697 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
4698 	decayed |= propagate_entity_load_avg(se);
4699 
4700 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4701 
4702 		/*
4703 		 * DO_ATTACH means we're here from enqueue_entity().
4704 		 * !last_update_time means we've passed through
4705 		 * migrate_task_rq_fair() indicating we migrated.
4706 		 *
4707 		 * IOW we're enqueueing a task on a new CPU.
4708 		 */
4709 		attach_entity_load_avg(cfs_rq, se);
4710 		update_tg_load_avg(cfs_rq);
4711 
4712 	} else if (flags & DO_DETACH) {
4713 		/*
4714 		 * DO_DETACH means we're here from dequeue_entity()
4715 		 * and we are migrating task out of the CPU.
4716 		 */
4717 		detach_entity_load_avg(cfs_rq, se);
4718 		update_tg_load_avg(cfs_rq);
4719 	} else if (decayed) {
4720 		cfs_rq_util_change(cfs_rq, 0);
4721 
4722 		if (flags & UPDATE_TG)
4723 			update_tg_load_avg(cfs_rq);
4724 	}
4725 }
4726 
4727 /*
4728  * Synchronize entity load avg of dequeued entity without locking
4729  * the previous rq.
4730  */
4731 static void sync_entity_load_avg(struct sched_entity *se)
4732 {
4733 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4734 	u64 last_update_time;
4735 
4736 	last_update_time = cfs_rq_last_update_time(cfs_rq);
4737 	__update_load_avg_blocked_se(last_update_time, se);
4738 }
4739 
4740 /*
4741  * Task first catches up with cfs_rq, and then subtract
4742  * itself from the cfs_rq (task must be off the queue now).
4743  */
4744 static void remove_entity_load_avg(struct sched_entity *se)
4745 {
4746 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4747 	unsigned long flags;
4748 
4749 	/*
4750 	 * tasks cannot exit without having gone through wake_up_new_task() ->
4751 	 * enqueue_task_fair() which will have added things to the cfs_rq,
4752 	 * so we can remove unconditionally.
4753 	 */
4754 
4755 	sync_entity_load_avg(se);
4756 
4757 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4758 	++cfs_rq->removed.nr;
4759 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
4760 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
4761 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
4762 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4763 }
4764 
4765 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4766 {
4767 	return cfs_rq->avg.runnable_avg;
4768 }
4769 
4770 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4771 {
4772 	return cfs_rq->avg.load_avg;
4773 }
4774 
4775 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
4776 
4777 static inline unsigned long task_util(struct task_struct *p)
4778 {
4779 	return READ_ONCE(p->se.avg.util_avg);
4780 }
4781 
4782 static inline unsigned long task_runnable(struct task_struct *p)
4783 {
4784 	return READ_ONCE(p->se.avg.runnable_avg);
4785 }
4786 
4787 static inline unsigned long _task_util_est(struct task_struct *p)
4788 {
4789 	return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
4790 }
4791 
4792 static inline unsigned long task_util_est(struct task_struct *p)
4793 {
4794 	return max(task_util(p), _task_util_est(p));
4795 }
4796 
4797 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4798 				    struct task_struct *p)
4799 {
4800 	unsigned int enqueued;
4801 
4802 	if (!sched_feat(UTIL_EST))
4803 		return;
4804 
4805 	/* Update root cfs_rq's estimated utilization */
4806 	enqueued  = cfs_rq->avg.util_est;
4807 	enqueued += _task_util_est(p);
4808 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4809 
4810 	trace_sched_util_est_cfs_tp(cfs_rq);
4811 }
4812 
4813 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4814 				    struct task_struct *p)
4815 {
4816 	unsigned int enqueued;
4817 
4818 	if (!sched_feat(UTIL_EST))
4819 		return;
4820 
4821 	/* Update root cfs_rq's estimated utilization */
4822 	enqueued  = cfs_rq->avg.util_est;
4823 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4824 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4825 
4826 	trace_sched_util_est_cfs_tp(cfs_rq);
4827 }
4828 
4829 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4830 
4831 static inline void util_est_update(struct cfs_rq *cfs_rq,
4832 				   struct task_struct *p,
4833 				   bool task_sleep)
4834 {
4835 	unsigned int ewma, dequeued, last_ewma_diff;
4836 
4837 	if (!sched_feat(UTIL_EST))
4838 		return;
4839 
4840 	/*
4841 	 * Skip update of task's estimated utilization when the task has not
4842 	 * yet completed an activation, e.g. being migrated.
4843 	 */
4844 	if (!task_sleep)
4845 		return;
4846 
4847 	/* Get current estimate of utilization */
4848 	ewma = READ_ONCE(p->se.avg.util_est);
4849 
4850 	/*
4851 	 * If the PELT values haven't changed since enqueue time,
4852 	 * skip the util_est update.
4853 	 */
4854 	if (ewma & UTIL_AVG_UNCHANGED)
4855 		return;
4856 
4857 	/* Get utilization at dequeue */
4858 	dequeued = task_util(p);
4859 
4860 	/*
4861 	 * Reset EWMA on utilization increases, the moving average is used only
4862 	 * to smooth utilization decreases.
4863 	 */
4864 	if (ewma <= dequeued) {
4865 		ewma = dequeued;
4866 		goto done;
4867 	}
4868 
4869 	/*
4870 	 * Skip update of task's estimated utilization when its members are
4871 	 * already ~1% close to its last activation value.
4872 	 */
4873 	last_ewma_diff = ewma - dequeued;
4874 	if (last_ewma_diff < UTIL_EST_MARGIN)
4875 		goto done;
4876 
4877 	/*
4878 	 * To avoid underestimate of task utilization, skip updates of EWMA if
4879 	 * we cannot grant that thread got all CPU time it wanted.
4880 	 */
4881 	if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
4882 		goto done;
4883 
4884 
4885 	/*
4886 	 * Update Task's estimated utilization
4887 	 *
4888 	 * When *p completes an activation we can consolidate another sample
4889 	 * of the task size. This is done by using this value to update the
4890 	 * Exponential Weighted Moving Average (EWMA):
4891 	 *
4892 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
4893 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
4894 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
4895 	 *          = w * (      -last_ewma_diff           ) +     ewma(t-1)
4896 	 *          = w * (-last_ewma_diff +  ewma(t-1) / w)
4897 	 *
4898 	 * Where 'w' is the weight of new samples, which is configured to be
4899 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4900 	 */
4901 	ewma <<= UTIL_EST_WEIGHT_SHIFT;
4902 	ewma  -= last_ewma_diff;
4903 	ewma >>= UTIL_EST_WEIGHT_SHIFT;
4904 done:
4905 	ewma |= UTIL_AVG_UNCHANGED;
4906 	WRITE_ONCE(p->se.avg.util_est, ewma);
4907 
4908 	trace_sched_util_est_se_tp(&p->se);
4909 }
4910 
4911 static inline unsigned long get_actual_cpu_capacity(int cpu)
4912 {
4913 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
4914 
4915 	capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
4916 
4917 	return capacity;
4918 }
4919 
4920 static inline int util_fits_cpu(unsigned long util,
4921 				unsigned long uclamp_min,
4922 				unsigned long uclamp_max,
4923 				int cpu)
4924 {
4925 	unsigned long capacity = capacity_of(cpu);
4926 	unsigned long capacity_orig;
4927 	bool fits, uclamp_max_fits;
4928 
4929 	/*
4930 	 * Check if the real util fits without any uclamp boost/cap applied.
4931 	 */
4932 	fits = fits_capacity(util, capacity);
4933 
4934 	if (!uclamp_is_used())
4935 		return fits;
4936 
4937 	/*
4938 	 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4939 	 * uclamp_max. We only care about capacity pressure (by using
4940 	 * capacity_of()) for comparing against the real util.
4941 	 *
4942 	 * If a task is boosted to 1024 for example, we don't want a tiny
4943 	 * pressure to skew the check whether it fits a CPU or not.
4944 	 *
4945 	 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4946 	 * should fit a little cpu even if there's some pressure.
4947 	 *
4948 	 * Only exception is for HW or cpufreq pressure since it has a direct impact
4949 	 * on available OPP of the system.
4950 	 *
4951 	 * We honour it for uclamp_min only as a drop in performance level
4952 	 * could result in not getting the requested minimum performance level.
4953 	 *
4954 	 * For uclamp_max, we can tolerate a drop in performance level as the
4955 	 * goal is to cap the task. So it's okay if it's getting less.
4956 	 */
4957 	capacity_orig = arch_scale_cpu_capacity(cpu);
4958 
4959 	/*
4960 	 * We want to force a task to fit a cpu as implied by uclamp_max.
4961 	 * But we do have some corner cases to cater for..
4962 	 *
4963 	 *
4964 	 *                                 C=z
4965 	 *   |                             ___
4966 	 *   |                  C=y       |   |
4967 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
4968 	 *   |      C=x        |   |      |   |
4969 	 *   |      ___        |   |      |   |
4970 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
4971 	 *   |     |   |       |   |      |   |
4972 	 *   |     |   |       |   |      |   |
4973 	 *   +----------------------------------------
4974 	 *         CPU0        CPU1       CPU2
4975 	 *
4976 	 *   In the above example if a task is capped to a specific performance
4977 	 *   point, y, then when:
4978 	 *
4979 	 *   * util = 80% of x then it does not fit on CPU0 and should migrate
4980 	 *     to CPU1
4981 	 *   * util = 80% of y then it is forced to fit on CPU1 to honour
4982 	 *     uclamp_max request.
4983 	 *
4984 	 *   which is what we're enforcing here. A task always fits if
4985 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4986 	 *   the normal upmigration rules should withhold still.
4987 	 *
4988 	 *   Only exception is when we are on max capacity, then we need to be
4989 	 *   careful not to block overutilized state. This is so because:
4990 	 *
4991 	 *     1. There's no concept of capping at max_capacity! We can't go
4992 	 *        beyond this performance level anyway.
4993 	 *     2. The system is being saturated when we're operating near
4994 	 *        max capacity, it doesn't make sense to block overutilized.
4995 	 */
4996 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4997 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4998 	fits = fits || uclamp_max_fits;
4999 
5000 	/*
5001 	 *
5002 	 *                                 C=z
5003 	 *   |                             ___       (region a, capped, util >= uclamp_max)
5004 	 *   |                  C=y       |   |
5005 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5006 	 *   |      C=x        |   |      |   |
5007 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
5008 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5009 	 *   |     |   |       |   |      |   |
5010 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
5011 	 *   +----------------------------------------
5012 	 *         CPU0        CPU1       CPU2
5013 	 *
5014 	 * a) If util > uclamp_max, then we're capped, we don't care about
5015 	 *    actual fitness value here. We only care if uclamp_max fits
5016 	 *    capacity without taking margin/pressure into account.
5017 	 *    See comment above.
5018 	 *
5019 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
5020 	 *    fits_capacity() rules apply. Except we need to ensure that we
5021 	 *    enforce we remain within uclamp_max, see comment above.
5022 	 *
5023 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5024 	 *    need to take into account the boosted value fits the CPU without
5025 	 *    taking margin/pressure into account.
5026 	 *
5027 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
5028 	 * just need to consider an extra check for case (c) after ensuring we
5029 	 * handle the case uclamp_min > uclamp_max.
5030 	 */
5031 	uclamp_min = min(uclamp_min, uclamp_max);
5032 	if (fits && (util < uclamp_min) &&
5033 	    (uclamp_min > get_actual_cpu_capacity(cpu)))
5034 		return -1;
5035 
5036 	return fits;
5037 }
5038 
5039 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5040 {
5041 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5042 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5043 	unsigned long util = task_util_est(p);
5044 	/*
5045 	 * Return true only if the cpu fully fits the task requirements, which
5046 	 * include the utilization but also the performance hints.
5047 	 */
5048 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5049 }
5050 
5051 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5052 {
5053 	int cpu = cpu_of(rq);
5054 
5055 	if (!sched_asym_cpucap_active())
5056 		return;
5057 
5058 	/*
5059 	 * Affinity allows us to go somewhere higher?  Or are we on biggest
5060 	 * available CPU already? Or do we fit into this CPU ?
5061 	 */
5062 	if (!p || (p->nr_cpus_allowed == 1) ||
5063 	    (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5064 	    task_fits_cpu(p, cpu)) {
5065 
5066 		rq->misfit_task_load = 0;
5067 		return;
5068 	}
5069 
5070 	/*
5071 	 * Make sure that misfit_task_load will not be null even if
5072 	 * task_h_load() returns 0.
5073 	 */
5074 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5075 }
5076 
5077 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5078 {
5079 	struct sched_entity *se = &p->se;
5080 
5081 	p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5082 	if (attr->sched_runtime) {
5083 		se->custom_slice = 1;
5084 		se->slice = clamp_t(u64, attr->sched_runtime,
5085 				      NSEC_PER_MSEC/10,   /* HZ=1000 * 10 */
5086 				      NSEC_PER_MSEC*100); /* HZ=100  / 10 */
5087 	} else {
5088 		se->custom_slice = 0;
5089 		se->slice = sysctl_sched_base_slice;
5090 	}
5091 }
5092 
5093 static void
5094 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5095 {
5096 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
5097 	s64 lag = 0;
5098 
5099 	if (!se->custom_slice)
5100 		se->slice = sysctl_sched_base_slice;
5101 	vslice = calc_delta_fair(se->slice, se);
5102 
5103 	/*
5104 	 * Due to how V is constructed as the weighted average of entities,
5105 	 * adding tasks with positive lag, or removing tasks with negative lag
5106 	 * will move 'time' backwards, this can screw around with the lag of
5107 	 * other tasks.
5108 	 *
5109 	 * EEVDF: placement strategy #1 / #2
5110 	 */
5111 	if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5112 		struct sched_entity *curr = cfs_rq->curr;
5113 		unsigned long load;
5114 
5115 		lag = se->vlag;
5116 
5117 		/*
5118 		 * If we want to place a task and preserve lag, we have to
5119 		 * consider the effect of the new entity on the weighted
5120 		 * average and compensate for this, otherwise lag can quickly
5121 		 * evaporate.
5122 		 *
5123 		 * Lag is defined as:
5124 		 *
5125 		 *   lag_i = S - s_i = w_i * (V - v_i)
5126 		 *
5127 		 * To avoid the 'w_i' term all over the place, we only track
5128 		 * the virtual lag:
5129 		 *
5130 		 *   vl_i = V - v_i <=> v_i = V - vl_i
5131 		 *
5132 		 * And we take V to be the weighted average of all v:
5133 		 *
5134 		 *   V = (\Sum w_j*v_j) / W
5135 		 *
5136 		 * Where W is: \Sum w_j
5137 		 *
5138 		 * Then, the weighted average after adding an entity with lag
5139 		 * vl_i is given by:
5140 		 *
5141 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5142 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
5143 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5144 		 *      = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
5145 		 *      = V - w_i*vl_i / (W + w_i)
5146 		 *
5147 		 * And the actual lag after adding an entity with vl_i is:
5148 		 *
5149 		 *   vl'_i = V' - v_i
5150 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5151 		 *         = vl_i - w_i*vl_i / (W + w_i)
5152 		 *
5153 		 * Which is strictly less than vl_i. So in order to preserve lag
5154 		 * we should inflate the lag before placement such that the
5155 		 * effective lag after placement comes out right.
5156 		 *
5157 		 * As such, invert the above relation for vl'_i to get the vl_i
5158 		 * we need to use such that the lag after placement is the lag
5159 		 * we computed before dequeue.
5160 		 *
5161 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
5162 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5163 		 *
5164 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5165 		 *                   = W*vl_i
5166 		 *
5167 		 *   vl_i = (W + w_i)*vl'_i / W
5168 		 */
5169 		load = cfs_rq->sum_weight;
5170 		if (curr && curr->on_rq)
5171 			load += scale_load_down(curr->load.weight);
5172 
5173 		lag *= load + scale_load_down(se->load.weight);
5174 		if (WARN_ON_ONCE(!load))
5175 			load = 1;
5176 		lag = div_s64(lag, load);
5177 	}
5178 
5179 	se->vruntime = vruntime - lag;
5180 
5181 	if (se->rel_deadline) {
5182 		se->deadline += se->vruntime;
5183 		se->rel_deadline = 0;
5184 		return;
5185 	}
5186 
5187 	/*
5188 	 * When joining the competition; the existing tasks will be,
5189 	 * on average, halfway through their slice, as such start tasks
5190 	 * off with half a slice to ease into the competition.
5191 	 */
5192 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5193 		vslice /= 2;
5194 
5195 	/*
5196 	 * EEVDF: vd_i = ve_i + r_i/w_i
5197 	 */
5198 	se->deadline = se->vruntime + vslice;
5199 }
5200 
5201 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5202 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5203 
5204 static void
5205 requeue_delayed_entity(struct sched_entity *se);
5206 
5207 static void
5208 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5209 {
5210 	bool curr = cfs_rq->curr == se;
5211 
5212 	/*
5213 	 * If we're the current task, we must renormalise before calling
5214 	 * update_curr().
5215 	 */
5216 	if (curr)
5217 		place_entity(cfs_rq, se, flags);
5218 
5219 	update_curr(cfs_rq);
5220 
5221 	/*
5222 	 * When enqueuing a sched_entity, we must:
5223 	 *   - Update loads to have both entity and cfs_rq synced with now.
5224 	 *   - For group_entity, update its runnable_weight to reflect the new
5225 	 *     h_nr_runnable of its group cfs_rq.
5226 	 *   - For group_entity, update its weight to reflect the new share of
5227 	 *     its group cfs_rq
5228 	 *   - Add its new weight to cfs_rq->load.weight
5229 	 */
5230 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5231 	se_update_runnable(se);
5232 	/*
5233 	 * XXX update_load_avg() above will have attached us to the pelt sum;
5234 	 * but update_cfs_group() here will re-adjust the weight and have to
5235 	 * undo/redo all that. Seems wasteful.
5236 	 */
5237 	update_cfs_group(se);
5238 
5239 	/*
5240 	 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5241 	 * we can place the entity.
5242 	 */
5243 	if (!curr)
5244 		place_entity(cfs_rq, se, flags);
5245 
5246 	account_entity_enqueue(cfs_rq, se);
5247 
5248 	/* Entity has migrated, no longer consider this task hot */
5249 	if (flags & ENQUEUE_MIGRATED)
5250 		se->exec_start = 0;
5251 
5252 	check_schedstat_required();
5253 	update_stats_enqueue_fair(cfs_rq, se, flags);
5254 	if (!curr)
5255 		__enqueue_entity(cfs_rq, se);
5256 	se->on_rq = 1;
5257 
5258 	if (cfs_rq->nr_queued == 1) {
5259 		check_enqueue_throttle(cfs_rq);
5260 		list_add_leaf_cfs_rq(cfs_rq);
5261 #ifdef CONFIG_CFS_BANDWIDTH
5262 		if (cfs_rq->pelt_clock_throttled) {
5263 			struct rq *rq = rq_of(cfs_rq);
5264 
5265 			cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5266 				cfs_rq->throttled_clock_pelt;
5267 			cfs_rq->pelt_clock_throttled = 0;
5268 		}
5269 #endif
5270 	}
5271 }
5272 
5273 static void __clear_buddies_next(struct sched_entity *se)
5274 {
5275 	for_each_sched_entity(se) {
5276 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5277 		if (cfs_rq->next != se)
5278 			break;
5279 
5280 		cfs_rq->next = NULL;
5281 	}
5282 }
5283 
5284 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5285 {
5286 	if (cfs_rq->next == se)
5287 		__clear_buddies_next(se);
5288 }
5289 
5290 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5291 
5292 static void set_delayed(struct sched_entity *se)
5293 {
5294 	se->sched_delayed = 1;
5295 
5296 	/*
5297 	 * Delayed se of cfs_rq have no tasks queued on them.
5298 	 * Do not adjust h_nr_runnable since dequeue_entities()
5299 	 * will account it for blocked tasks.
5300 	 */
5301 	if (!entity_is_task(se))
5302 		return;
5303 
5304 	for_each_sched_entity(se) {
5305 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5306 
5307 		cfs_rq->h_nr_runnable--;
5308 	}
5309 }
5310 
5311 static void clear_delayed(struct sched_entity *se)
5312 {
5313 	se->sched_delayed = 0;
5314 
5315 	/*
5316 	 * Delayed se of cfs_rq have no tasks queued on them.
5317 	 * Do not adjust h_nr_runnable since a dequeue has
5318 	 * already accounted for it or an enqueue of a task
5319 	 * below it will account for it in enqueue_task_fair().
5320 	 */
5321 	if (!entity_is_task(se))
5322 		return;
5323 
5324 	for_each_sched_entity(se) {
5325 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5326 
5327 		cfs_rq->h_nr_runnable++;
5328 	}
5329 }
5330 
5331 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5332 {
5333 	clear_delayed(se);
5334 	if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5335 		se->vlag = 0;
5336 }
5337 
5338 static bool
5339 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5340 {
5341 	bool sleep = flags & DEQUEUE_SLEEP;
5342 	int action = UPDATE_TG;
5343 
5344 	update_curr(cfs_rq);
5345 	clear_buddies(cfs_rq, se);
5346 
5347 	if (flags & DEQUEUE_DELAYED) {
5348 		WARN_ON_ONCE(!se->sched_delayed);
5349 	} else {
5350 		bool delay = sleep;
5351 		/*
5352 		 * DELAY_DEQUEUE relies on spurious wakeups, special task
5353 		 * states must not suffer spurious wakeups, excempt them.
5354 		 */
5355 		if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
5356 			delay = false;
5357 
5358 		WARN_ON_ONCE(delay && se->sched_delayed);
5359 
5360 		if (sched_feat(DELAY_DEQUEUE) && delay &&
5361 		    !entity_eligible(cfs_rq, se)) {
5362 			update_load_avg(cfs_rq, se, 0);
5363 			set_delayed(se);
5364 			return false;
5365 		}
5366 	}
5367 
5368 	if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5369 		action |= DO_DETACH;
5370 
5371 	/*
5372 	 * When dequeuing a sched_entity, we must:
5373 	 *   - Update loads to have both entity and cfs_rq synced with now.
5374 	 *   - For group_entity, update its runnable_weight to reflect the new
5375 	 *     h_nr_runnable of its group cfs_rq.
5376 	 *   - Subtract its previous weight from cfs_rq->load.weight.
5377 	 *   - For group entity, update its weight to reflect the new share
5378 	 *     of its group cfs_rq.
5379 	 */
5380 	update_load_avg(cfs_rq, se, action);
5381 	se_update_runnable(se);
5382 
5383 	update_stats_dequeue_fair(cfs_rq, se, flags);
5384 
5385 	update_entity_lag(cfs_rq, se);
5386 	if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5387 		se->deadline -= se->vruntime;
5388 		se->rel_deadline = 1;
5389 	}
5390 
5391 	if (se != cfs_rq->curr)
5392 		__dequeue_entity(cfs_rq, se);
5393 	se->on_rq = 0;
5394 	account_entity_dequeue(cfs_rq, se);
5395 
5396 	/* return excess runtime on last dequeue */
5397 	return_cfs_rq_runtime(cfs_rq);
5398 
5399 	update_cfs_group(se);
5400 
5401 	if (flags & DEQUEUE_DELAYED)
5402 		finish_delayed_dequeue_entity(se);
5403 
5404 	if (cfs_rq->nr_queued == 0) {
5405 		update_idle_cfs_rq_clock_pelt(cfs_rq);
5406 #ifdef CONFIG_CFS_BANDWIDTH
5407 		if (throttled_hierarchy(cfs_rq)) {
5408 			struct rq *rq = rq_of(cfs_rq);
5409 
5410 			list_del_leaf_cfs_rq(cfs_rq);
5411 			cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5412 			cfs_rq->pelt_clock_throttled = 1;
5413 		}
5414 #endif
5415 	}
5416 
5417 	return true;
5418 }
5419 
5420 static void
5421 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5422 {
5423 	clear_buddies(cfs_rq, se);
5424 
5425 	/* 'current' is not kept within the tree. */
5426 	if (se->on_rq) {
5427 		/*
5428 		 * Any task has to be enqueued before it get to execute on
5429 		 * a CPU. So account for the time it spent waiting on the
5430 		 * runqueue.
5431 		 */
5432 		update_stats_wait_end_fair(cfs_rq, se);
5433 		__dequeue_entity(cfs_rq, se);
5434 		update_load_avg(cfs_rq, se, UPDATE_TG);
5435 
5436 		set_protect_slice(cfs_rq, se);
5437 	}
5438 
5439 	update_stats_curr_start(cfs_rq, se);
5440 	WARN_ON_ONCE(cfs_rq->curr);
5441 	cfs_rq->curr = se;
5442 
5443 	/*
5444 	 * Track our maximum slice length, if the CPU's load is at
5445 	 * least twice that of our own weight (i.e. don't track it
5446 	 * when there are only lesser-weight tasks around):
5447 	 */
5448 	if (schedstat_enabled() &&
5449 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5450 		struct sched_statistics *stats;
5451 
5452 		stats = __schedstats_from_se(se);
5453 		__schedstat_set(stats->slice_max,
5454 				max((u64)stats->slice_max,
5455 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
5456 	}
5457 
5458 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
5459 }
5460 
5461 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5462 
5463 /*
5464  * Pick the next process, keeping these things in mind, in this order:
5465  * 1) keep things fair between processes/task groups
5466  * 2) pick the "next" process, since someone really wants that to run
5467  * 3) pick the "last" process, for cache locality
5468  * 4) do not run the "skip" process, if something else is available
5469  */
5470 static struct sched_entity *
5471 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5472 {
5473 	struct sched_entity *se;
5474 
5475 	se = pick_eevdf(cfs_rq);
5476 	if (se->sched_delayed) {
5477 		dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5478 		/*
5479 		 * Must not reference @se again, see __block_task().
5480 		 */
5481 		return NULL;
5482 	}
5483 	return se;
5484 }
5485 
5486 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5487 
5488 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5489 {
5490 	/*
5491 	 * If still on the runqueue then deactivate_task()
5492 	 * was not called and update_curr() has to be done:
5493 	 */
5494 	if (prev->on_rq)
5495 		update_curr(cfs_rq);
5496 
5497 	/* throttle cfs_rqs exceeding runtime */
5498 	check_cfs_rq_runtime(cfs_rq);
5499 
5500 	if (prev->on_rq) {
5501 		update_stats_wait_start_fair(cfs_rq, prev);
5502 		/* Put 'current' back into the tree. */
5503 		__enqueue_entity(cfs_rq, prev);
5504 		/* in !on_rq case, update occurred at dequeue */
5505 		update_load_avg(cfs_rq, prev, 0);
5506 	}
5507 	WARN_ON_ONCE(cfs_rq->curr != prev);
5508 	cfs_rq->curr = NULL;
5509 }
5510 
5511 static void
5512 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5513 {
5514 	/*
5515 	 * Update run-time statistics of the 'current'.
5516 	 */
5517 	update_curr(cfs_rq);
5518 
5519 	/*
5520 	 * Ensure that runnable average is periodically updated.
5521 	 */
5522 	update_load_avg(cfs_rq, curr, UPDATE_TG);
5523 	update_cfs_group(curr);
5524 
5525 #ifdef CONFIG_SCHED_HRTICK
5526 	/*
5527 	 * queued ticks are scheduled to match the slice, so don't bother
5528 	 * validating it and just reschedule.
5529 	 */
5530 	if (queued) {
5531 		resched_curr_lazy(rq_of(cfs_rq));
5532 		return;
5533 	}
5534 #endif
5535 }
5536 
5537 
5538 /**************************************************
5539  * CFS bandwidth control machinery
5540  */
5541 
5542 #ifdef CONFIG_CFS_BANDWIDTH
5543 
5544 #ifdef CONFIG_JUMP_LABEL
5545 static struct static_key __cfs_bandwidth_used;
5546 
5547 static inline bool cfs_bandwidth_used(void)
5548 {
5549 	return static_key_false(&__cfs_bandwidth_used);
5550 }
5551 
5552 void cfs_bandwidth_usage_inc(void)
5553 {
5554 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5555 }
5556 
5557 void cfs_bandwidth_usage_dec(void)
5558 {
5559 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5560 }
5561 #else /* !CONFIG_JUMP_LABEL: */
5562 static bool cfs_bandwidth_used(void)
5563 {
5564 	return true;
5565 }
5566 
5567 void cfs_bandwidth_usage_inc(void) {}
5568 void cfs_bandwidth_usage_dec(void) {}
5569 #endif /* !CONFIG_JUMP_LABEL */
5570 
5571 static inline u64 sched_cfs_bandwidth_slice(void)
5572 {
5573 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5574 }
5575 
5576 /*
5577  * Replenish runtime according to assigned quota. We use sched_clock_cpu
5578  * directly instead of rq->clock to avoid adding additional synchronization
5579  * around rq->lock.
5580  *
5581  * requires cfs_b->lock
5582  */
5583 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5584 {
5585 	s64 runtime;
5586 
5587 	if (unlikely(cfs_b->quota == RUNTIME_INF))
5588 		return;
5589 
5590 	cfs_b->runtime += cfs_b->quota;
5591 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
5592 	if (runtime > 0) {
5593 		cfs_b->burst_time += runtime;
5594 		cfs_b->nr_burst++;
5595 	}
5596 
5597 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5598 	cfs_b->runtime_snap = cfs_b->runtime;
5599 }
5600 
5601 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5602 {
5603 	return &tg->cfs_bandwidth;
5604 }
5605 
5606 /* returns 0 on failure to allocate runtime */
5607 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5608 				   struct cfs_rq *cfs_rq, u64 target_runtime)
5609 {
5610 	u64 min_amount, amount = 0;
5611 
5612 	lockdep_assert_held(&cfs_b->lock);
5613 
5614 	/* note: this is a positive sum as runtime_remaining <= 0 */
5615 	min_amount = target_runtime - cfs_rq->runtime_remaining;
5616 
5617 	if (cfs_b->quota == RUNTIME_INF)
5618 		amount = min_amount;
5619 	else {
5620 		start_cfs_bandwidth(cfs_b);
5621 
5622 		if (cfs_b->runtime > 0) {
5623 			amount = min(cfs_b->runtime, min_amount);
5624 			cfs_b->runtime -= amount;
5625 			cfs_b->idle = 0;
5626 		}
5627 	}
5628 
5629 	cfs_rq->runtime_remaining += amount;
5630 
5631 	return cfs_rq->runtime_remaining > 0;
5632 }
5633 
5634 /* returns 0 on failure to allocate runtime */
5635 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5636 {
5637 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5638 	int ret;
5639 
5640 	raw_spin_lock(&cfs_b->lock);
5641 	ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5642 	raw_spin_unlock(&cfs_b->lock);
5643 
5644 	return ret;
5645 }
5646 
5647 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5648 {
5649 	/* dock delta_exec before expiring quota (as it could span periods) */
5650 	cfs_rq->runtime_remaining -= delta_exec;
5651 
5652 	if (likely(cfs_rq->runtime_remaining > 0))
5653 		return;
5654 
5655 	if (cfs_rq->throttled)
5656 		return;
5657 	/*
5658 	 * if we're unable to extend our runtime we resched so that the active
5659 	 * hierarchy can be throttled
5660 	 */
5661 	if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5662 		resched_curr(rq_of(cfs_rq));
5663 }
5664 
5665 static __always_inline
5666 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5667 {
5668 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5669 		return;
5670 
5671 	__account_cfs_rq_runtime(cfs_rq, delta_exec);
5672 }
5673 
5674 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5675 {
5676 	return cfs_bandwidth_used() && cfs_rq->throttled;
5677 }
5678 
5679 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
5680 {
5681 	return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
5682 }
5683 
5684 /* check whether cfs_rq, or any parent, is throttled */
5685 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5686 {
5687 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
5688 }
5689 
5690 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
5691 {
5692 	return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]);
5693 }
5694 
5695 static inline bool task_is_throttled(struct task_struct *p)
5696 {
5697 	return cfs_bandwidth_used() && p->throttled;
5698 }
5699 
5700 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
5701 static void throttle_cfs_rq_work(struct callback_head *work)
5702 {
5703 	struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
5704 	struct sched_entity *se;
5705 	struct cfs_rq *cfs_rq;
5706 	struct rq *rq;
5707 
5708 	WARN_ON_ONCE(p != current);
5709 	p->sched_throttle_work.next = &p->sched_throttle_work;
5710 
5711 	/*
5712 	 * If task is exiting, then there won't be a return to userspace, so we
5713 	 * don't have to bother with any of this.
5714 	 */
5715 	if ((p->flags & PF_EXITING))
5716 		return;
5717 
5718 	scoped_guard(task_rq_lock, p) {
5719 		se = &p->se;
5720 		cfs_rq = cfs_rq_of(se);
5721 
5722 		/* Raced, forget */
5723 		if (p->sched_class != &fair_sched_class)
5724 			return;
5725 
5726 		/*
5727 		 * If not in limbo, then either replenish has happened or this
5728 		 * task got migrated out of the throttled cfs_rq, move along.
5729 		 */
5730 		if (!cfs_rq->throttle_count)
5731 			return;
5732 		rq = scope.rq;
5733 		update_rq_clock(rq);
5734 		WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
5735 		dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
5736 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5737 		/*
5738 		 * Must not set throttled before dequeue or dequeue will
5739 		 * mistakenly regard this task as an already throttled one.
5740 		 */
5741 		p->throttled = true;
5742 		resched_curr(rq);
5743 	}
5744 }
5745 
5746 void init_cfs_throttle_work(struct task_struct *p)
5747 {
5748 	init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
5749 	/* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
5750 	p->sched_throttle_work.next = &p->sched_throttle_work;
5751 	INIT_LIST_HEAD(&p->throttle_node);
5752 }
5753 
5754 /*
5755  * Task is throttled and someone wants to dequeue it again:
5756  * it could be sched/core when core needs to do things like
5757  * task affinity change, task group change, task sched class
5758  * change etc. and in these cases, DEQUEUE_SLEEP is not set;
5759  * or the task is blocked after throttled due to freezer etc.
5760  * and in these cases, DEQUEUE_SLEEP is set.
5761  */
5762 static void detach_task_cfs_rq(struct task_struct *p);
5763 static void dequeue_throttled_task(struct task_struct *p, int flags)
5764 {
5765 	WARN_ON_ONCE(p->se.on_rq);
5766 	list_del_init(&p->throttle_node);
5767 
5768 	/* task blocked after throttled */
5769 	if (flags & DEQUEUE_SLEEP) {
5770 		p->throttled = false;
5771 		return;
5772 	}
5773 
5774 	/*
5775 	 * task is migrating off its old cfs_rq, detach
5776 	 * the task's load from its old cfs_rq.
5777 	 */
5778 	if (task_on_rq_migrating(p))
5779 		detach_task_cfs_rq(p);
5780 }
5781 
5782 static bool enqueue_throttled_task(struct task_struct *p)
5783 {
5784 	struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
5785 
5786 	/* @p should have gone through dequeue_throttled_task() first */
5787 	WARN_ON_ONCE(!list_empty(&p->throttle_node));
5788 
5789 	/*
5790 	 * If the throttled task @p is enqueued to a throttled cfs_rq,
5791 	 * take the fast path by directly putting the task on the
5792 	 * target cfs_rq's limbo list.
5793 	 *
5794 	 * Do not do that when @p is current because the following race can
5795 	 * cause @p's group_node to be incorectly re-insterted in its rq's
5796 	 * cfs_tasks list, despite being throttled:
5797 	 *
5798 	 *     cpuX                       cpuY
5799 	 *   p ret2user
5800 	 *  throttle_cfs_rq_work()  sched_move_task(p)
5801 	 *  LOCK task_rq_lock
5802 	 *  dequeue_task_fair(p)
5803 	 *  UNLOCK task_rq_lock
5804 	 *                          LOCK task_rq_lock
5805 	 *                          task_current_donor(p) == true
5806 	 *                          task_on_rq_queued(p) == true
5807 	 *                          dequeue_task(p)
5808 	 *                          put_prev_task(p)
5809 	 *                          sched_change_group()
5810 	 *                          enqueue_task(p) -> p's new cfs_rq
5811 	 *                                             is throttled, go
5812 	 *                                             fast path and skip
5813 	 *                                             actual enqueue
5814 	 *                          set_next_task(p)
5815 	 *                    list_move(&se->group_node, &rq->cfs_tasks); // bug
5816 	 *  schedule()
5817 	 *
5818 	 * In the above race case, @p current cfs_rq is in the same rq as
5819 	 * its previous cfs_rq because sched_move_task() only moves a task
5820 	 * to a different group from the same rq, so we can use its current
5821 	 * cfs_rq to derive rq and test if the task is current.
5822 	 */
5823 	if (throttled_hierarchy(cfs_rq) &&
5824 	    !task_current_donor(rq_of(cfs_rq), p)) {
5825 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5826 		return true;
5827 	}
5828 
5829 	/* we can't take the fast path, do an actual enqueue*/
5830 	p->throttled = false;
5831 	return false;
5832 }
5833 
5834 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
5835 static int tg_unthrottle_up(struct task_group *tg, void *data)
5836 {
5837 	struct rq *rq = data;
5838 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5839 	struct task_struct *p, *tmp;
5840 
5841 	if (--cfs_rq->throttle_count)
5842 		return 0;
5843 
5844 	if (cfs_rq->pelt_clock_throttled) {
5845 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5846 					     cfs_rq->throttled_clock_pelt;
5847 		cfs_rq->pelt_clock_throttled = 0;
5848 	}
5849 
5850 	if (cfs_rq->throttled_clock_self) {
5851 		u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5852 
5853 		cfs_rq->throttled_clock_self = 0;
5854 
5855 		if (WARN_ON_ONCE((s64)delta < 0))
5856 			delta = 0;
5857 
5858 		cfs_rq->throttled_clock_self_time += delta;
5859 	}
5860 
5861 	/* Re-enqueue the tasks that have been throttled at this level. */
5862 	list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) {
5863 		list_del_init(&p->throttle_node);
5864 		p->throttled = false;
5865 		enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP);
5866 	}
5867 
5868 	/* Add cfs_rq with load or one or more already running entities to the list */
5869 	if (!cfs_rq_is_decayed(cfs_rq))
5870 		list_add_leaf_cfs_rq(cfs_rq);
5871 
5872 	return 0;
5873 }
5874 
5875 static inline bool task_has_throttle_work(struct task_struct *p)
5876 {
5877 	return p->sched_throttle_work.next != &p->sched_throttle_work;
5878 }
5879 
5880 static inline void task_throttle_setup_work(struct task_struct *p)
5881 {
5882 	if (task_has_throttle_work(p))
5883 		return;
5884 
5885 	/*
5886 	 * Kthreads and exiting tasks don't return to userspace, so adding the
5887 	 * work is pointless
5888 	 */
5889 	if ((p->flags & (PF_EXITING | PF_KTHREAD)))
5890 		return;
5891 
5892 	task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
5893 }
5894 
5895 static void record_throttle_clock(struct cfs_rq *cfs_rq)
5896 {
5897 	struct rq *rq = rq_of(cfs_rq);
5898 
5899 	if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5900 		cfs_rq->throttled_clock = rq_clock(rq);
5901 
5902 	if (!cfs_rq->throttled_clock_self)
5903 		cfs_rq->throttled_clock_self = rq_clock(rq);
5904 }
5905 
5906 static int tg_throttle_down(struct task_group *tg, void *data)
5907 {
5908 	struct rq *rq = data;
5909 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5910 
5911 	if (cfs_rq->throttle_count++)
5912 		return 0;
5913 
5914 	/*
5915 	 * For cfs_rqs that still have entities enqueued, PELT clock
5916 	 * stop happens at dequeue time when all entities are dequeued.
5917 	 */
5918 	if (!cfs_rq->nr_queued) {
5919 		list_del_leaf_cfs_rq(cfs_rq);
5920 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5921 		cfs_rq->pelt_clock_throttled = 1;
5922 	}
5923 
5924 	WARN_ON_ONCE(cfs_rq->throttled_clock_self);
5925 	WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
5926 	return 0;
5927 }
5928 
5929 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5930 {
5931 	struct rq *rq = rq_of(cfs_rq);
5932 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5933 	int dequeue = 1;
5934 
5935 	raw_spin_lock(&cfs_b->lock);
5936 	/* This will start the period timer if necessary */
5937 	if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5938 		/*
5939 		 * We have raced with bandwidth becoming available, and if we
5940 		 * actually throttled the timer might not unthrottle us for an
5941 		 * entire period. We additionally needed to make sure that any
5942 		 * subsequent check_cfs_rq_runtime calls agree not to throttle
5943 		 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5944 		 * for 1ns of runtime rather than just check cfs_b.
5945 		 */
5946 		dequeue = 0;
5947 	} else {
5948 		list_add_tail_rcu(&cfs_rq->throttled_list,
5949 				  &cfs_b->throttled_cfs_rq);
5950 	}
5951 	raw_spin_unlock(&cfs_b->lock);
5952 
5953 	if (!dequeue)
5954 		return false;  /* Throttle no longer required. */
5955 
5956 	/* freeze hierarchy runnable averages while throttled */
5957 	rcu_read_lock();
5958 	walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5959 	rcu_read_unlock();
5960 
5961 	/*
5962 	 * Note: distribution will already see us throttled via the
5963 	 * throttled-list.  rq->lock protects completion.
5964 	 */
5965 	cfs_rq->throttled = 1;
5966 	WARN_ON_ONCE(cfs_rq->throttled_clock);
5967 	return true;
5968 }
5969 
5970 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5971 {
5972 	struct rq *rq = rq_of(cfs_rq);
5973 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5974 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
5975 
5976 	/*
5977 	 * It's possible we are called with runtime_remaining < 0 due to things
5978 	 * like async unthrottled us with a positive runtime_remaining but other
5979 	 * still running entities consumed those runtime before we reached here.
5980 	 *
5981 	 * We can't unthrottle this cfs_rq without any runtime remaining because
5982 	 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
5983 	 * which is not supposed to happen on unthrottle path.
5984 	 */
5985 	if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
5986 		return;
5987 
5988 	cfs_rq->throttled = 0;
5989 
5990 	update_rq_clock(rq);
5991 
5992 	raw_spin_lock(&cfs_b->lock);
5993 	if (cfs_rq->throttled_clock) {
5994 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5995 		cfs_rq->throttled_clock = 0;
5996 	}
5997 	list_del_rcu(&cfs_rq->throttled_list);
5998 	raw_spin_unlock(&cfs_b->lock);
5999 
6000 	/* update hierarchical throttle state */
6001 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6002 
6003 	if (!cfs_rq->load.weight) {
6004 		if (!cfs_rq->on_list)
6005 			return;
6006 		/*
6007 		 * Nothing to run but something to decay (on_list)?
6008 		 * Complete the branch.
6009 		 */
6010 		for_each_sched_entity(se) {
6011 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6012 				break;
6013 		}
6014 	}
6015 
6016 	assert_list_leaf_cfs_rq(rq);
6017 
6018 	/* Determine whether we need to wake up potentially idle CPU: */
6019 	if (rq->curr == rq->idle && rq->cfs.nr_queued)
6020 		resched_curr(rq);
6021 }
6022 
6023 static void __cfsb_csd_unthrottle(void *arg)
6024 {
6025 	struct cfs_rq *cursor, *tmp;
6026 	struct rq *rq = arg;
6027 	struct rq_flags rf;
6028 
6029 	rq_lock(rq, &rf);
6030 
6031 	/*
6032 	 * Iterating over the list can trigger several call to
6033 	 * update_rq_clock() in unthrottle_cfs_rq().
6034 	 * Do it once and skip the potential next ones.
6035 	 */
6036 	update_rq_clock(rq);
6037 	rq_clock_start_loop_update(rq);
6038 
6039 	/*
6040 	 * Since we hold rq lock we're safe from concurrent manipulation of
6041 	 * the CSD list. However, this RCU critical section annotates the
6042 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
6043 	 * race with group being freed in the window between removing it
6044 	 * from the list and advancing to the next entry in the list.
6045 	 */
6046 	rcu_read_lock();
6047 
6048 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6049 				 throttled_csd_list) {
6050 		list_del_init(&cursor->throttled_csd_list);
6051 
6052 		if (cfs_rq_throttled(cursor))
6053 			unthrottle_cfs_rq(cursor);
6054 	}
6055 
6056 	rcu_read_unlock();
6057 
6058 	rq_clock_stop_loop_update(rq);
6059 	rq_unlock(rq, &rf);
6060 }
6061 
6062 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6063 {
6064 	struct rq *rq = rq_of(cfs_rq);
6065 	bool first;
6066 
6067 	if (rq == this_rq()) {
6068 		unthrottle_cfs_rq(cfs_rq);
6069 		return;
6070 	}
6071 
6072 	/* Already enqueued */
6073 	if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
6074 		return;
6075 
6076 	first = list_empty(&rq->cfsb_csd_list);
6077 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6078 	if (first)
6079 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6080 }
6081 
6082 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6083 {
6084 	lockdep_assert_rq_held(rq_of(cfs_rq));
6085 
6086 	if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
6087 	    cfs_rq->runtime_remaining <= 0))
6088 		return;
6089 
6090 	__unthrottle_cfs_rq_async(cfs_rq);
6091 }
6092 
6093 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6094 {
6095 	int this_cpu = smp_processor_id();
6096 	u64 runtime, remaining = 1;
6097 	bool throttled = false;
6098 	struct cfs_rq *cfs_rq, *tmp;
6099 	struct rq_flags rf;
6100 	struct rq *rq;
6101 	LIST_HEAD(local_unthrottle);
6102 
6103 	rcu_read_lock();
6104 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6105 				throttled_list) {
6106 		rq = rq_of(cfs_rq);
6107 
6108 		if (!remaining) {
6109 			throttled = true;
6110 			break;
6111 		}
6112 
6113 		rq_lock_irqsave(rq, &rf);
6114 		if (!cfs_rq_throttled(cfs_rq))
6115 			goto next;
6116 
6117 		/* Already queued for async unthrottle */
6118 		if (!list_empty(&cfs_rq->throttled_csd_list))
6119 			goto next;
6120 
6121 		/* By the above checks, this should never be true */
6122 		WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
6123 
6124 		raw_spin_lock(&cfs_b->lock);
6125 		runtime = -cfs_rq->runtime_remaining + 1;
6126 		if (runtime > cfs_b->runtime)
6127 			runtime = cfs_b->runtime;
6128 		cfs_b->runtime -= runtime;
6129 		remaining = cfs_b->runtime;
6130 		raw_spin_unlock(&cfs_b->lock);
6131 
6132 		cfs_rq->runtime_remaining += runtime;
6133 
6134 		/* we check whether we're throttled above */
6135 		if (cfs_rq->runtime_remaining > 0) {
6136 			if (cpu_of(rq) != this_cpu) {
6137 				unthrottle_cfs_rq_async(cfs_rq);
6138 			} else {
6139 				/*
6140 				 * We currently only expect to be unthrottling
6141 				 * a single cfs_rq locally.
6142 				 */
6143 				WARN_ON_ONCE(!list_empty(&local_unthrottle));
6144 				list_add_tail(&cfs_rq->throttled_csd_list,
6145 					      &local_unthrottle);
6146 			}
6147 		} else {
6148 			throttled = true;
6149 		}
6150 
6151 next:
6152 		rq_unlock_irqrestore(rq, &rf);
6153 	}
6154 
6155 	list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6156 				 throttled_csd_list) {
6157 		struct rq *rq = rq_of(cfs_rq);
6158 
6159 		rq_lock_irqsave(rq, &rf);
6160 
6161 		list_del_init(&cfs_rq->throttled_csd_list);
6162 
6163 		if (cfs_rq_throttled(cfs_rq))
6164 			unthrottle_cfs_rq(cfs_rq);
6165 
6166 		rq_unlock_irqrestore(rq, &rf);
6167 	}
6168 	WARN_ON_ONCE(!list_empty(&local_unthrottle));
6169 
6170 	rcu_read_unlock();
6171 
6172 	return throttled;
6173 }
6174 
6175 /*
6176  * Responsible for refilling a task_group's bandwidth and unthrottling its
6177  * cfs_rqs as appropriate. If there has been no activity within the last
6178  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6179  * used to track this state.
6180  */
6181 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6182 {
6183 	int throttled;
6184 
6185 	/* no need to continue the timer with no bandwidth constraint */
6186 	if (cfs_b->quota == RUNTIME_INF)
6187 		goto out_deactivate;
6188 
6189 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6190 	cfs_b->nr_periods += overrun;
6191 
6192 	/* Refill extra burst quota even if cfs_b->idle */
6193 	__refill_cfs_bandwidth_runtime(cfs_b);
6194 
6195 	/*
6196 	 * idle depends on !throttled (for the case of a large deficit), and if
6197 	 * we're going inactive then everything else can be deferred
6198 	 */
6199 	if (cfs_b->idle && !throttled)
6200 		goto out_deactivate;
6201 
6202 	if (!throttled) {
6203 		/* mark as potentially idle for the upcoming period */
6204 		cfs_b->idle = 1;
6205 		return 0;
6206 	}
6207 
6208 	/* account preceding periods in which throttling occurred */
6209 	cfs_b->nr_throttled += overrun;
6210 
6211 	/*
6212 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
6213 	 */
6214 	while (throttled && cfs_b->runtime > 0) {
6215 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6216 		/* we can't nest cfs_b->lock while distributing bandwidth */
6217 		throttled = distribute_cfs_runtime(cfs_b);
6218 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
6219 	}
6220 
6221 	/*
6222 	 * While we are ensured activity in the period following an
6223 	 * unthrottle, this also covers the case in which the new bandwidth is
6224 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
6225 	 * timer to remain active while there are any throttled entities.)
6226 	 */
6227 	cfs_b->idle = 0;
6228 
6229 	return 0;
6230 
6231 out_deactivate:
6232 	return 1;
6233 }
6234 
6235 /* a cfs_rq won't donate quota below this amount */
6236 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6237 /* minimum remaining period time to redistribute slack quota */
6238 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6239 /* how long we wait to gather additional slack before distributing */
6240 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6241 
6242 /*
6243  * Are we near the end of the current quota period?
6244  *
6245  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6246  * hrtimer base being cleared by hrtimer_start. In the case of
6247  * migrate_hrtimers, base is never cleared, so we are fine.
6248  */
6249 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6250 {
6251 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
6252 	s64 remaining;
6253 
6254 	/* if the call-back is running a quota refresh is already occurring */
6255 	if (hrtimer_callback_running(refresh_timer))
6256 		return 1;
6257 
6258 	/* is a quota refresh about to occur? */
6259 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6260 	if (remaining < (s64)min_expire)
6261 		return 1;
6262 
6263 	return 0;
6264 }
6265 
6266 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6267 {
6268 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6269 
6270 	/* if there's a quota refresh soon don't bother with slack */
6271 	if (runtime_refresh_within(cfs_b, min_left))
6272 		return;
6273 
6274 	/* don't push forwards an existing deferred unthrottle */
6275 	if (cfs_b->slack_started)
6276 		return;
6277 	cfs_b->slack_started = true;
6278 
6279 	hrtimer_start(&cfs_b->slack_timer,
6280 			ns_to_ktime(cfs_bandwidth_slack_period),
6281 			HRTIMER_MODE_REL);
6282 }
6283 
6284 /* we know any runtime found here is valid as update_curr() precedes return */
6285 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6286 {
6287 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6288 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6289 
6290 	if (slack_runtime <= 0)
6291 		return;
6292 
6293 	raw_spin_lock(&cfs_b->lock);
6294 	if (cfs_b->quota != RUNTIME_INF) {
6295 		cfs_b->runtime += slack_runtime;
6296 
6297 		/* we are under rq->lock, defer unthrottling using a timer */
6298 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6299 		    !list_empty(&cfs_b->throttled_cfs_rq))
6300 			start_cfs_slack_bandwidth(cfs_b);
6301 	}
6302 	raw_spin_unlock(&cfs_b->lock);
6303 
6304 	/* even if it's not valid for return we don't want to try again */
6305 	cfs_rq->runtime_remaining -= slack_runtime;
6306 }
6307 
6308 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6309 {
6310 	if (!cfs_bandwidth_used())
6311 		return;
6312 
6313 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6314 		return;
6315 
6316 	__return_cfs_rq_runtime(cfs_rq);
6317 }
6318 
6319 /*
6320  * This is done with a timer (instead of inline with bandwidth return) since
6321  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6322  */
6323 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6324 {
6325 	u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6326 	unsigned long flags;
6327 
6328 	/* confirm we're still not at a refresh boundary */
6329 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6330 	cfs_b->slack_started = false;
6331 
6332 	if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6333 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6334 		return;
6335 	}
6336 
6337 	if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6338 		runtime = cfs_b->runtime;
6339 
6340 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6341 
6342 	if (!runtime)
6343 		return;
6344 
6345 	distribute_cfs_runtime(cfs_b);
6346 }
6347 
6348 /*
6349  * When a group wakes up we want to make sure that its quota is not already
6350  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6351  * runtime as update_curr() throttling can not trigger until it's on-rq.
6352  */
6353 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6354 {
6355 	if (!cfs_bandwidth_used())
6356 		return;
6357 
6358 	/* an active group must be handled by the update_curr()->put() path */
6359 	if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6360 		return;
6361 
6362 	/* ensure the group is not already throttled */
6363 	if (cfs_rq_throttled(cfs_rq))
6364 		return;
6365 
6366 	/* update runtime allocation */
6367 	account_cfs_rq_runtime(cfs_rq, 0);
6368 	if (cfs_rq->runtime_remaining <= 0)
6369 		throttle_cfs_rq(cfs_rq);
6370 }
6371 
6372 static void sync_throttle(struct task_group *tg, int cpu)
6373 {
6374 	struct cfs_rq *pcfs_rq, *cfs_rq;
6375 
6376 	if (!cfs_bandwidth_used())
6377 		return;
6378 
6379 	if (!tg->parent)
6380 		return;
6381 
6382 	cfs_rq = tg->cfs_rq[cpu];
6383 	pcfs_rq = tg->parent->cfs_rq[cpu];
6384 
6385 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
6386 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6387 
6388 	/*
6389 	 * It is not enough to sync the "pelt_clock_throttled" indicator
6390 	 * with the parent cfs_rq when the hierarchy is not queued.
6391 	 * Always join a throttled hierarchy with PELT clock throttled
6392 	 * and leaf it to the first enqueue, or distribution to
6393 	 * unthrottle the PELT clock.
6394 	 */
6395 	if (cfs_rq->throttle_count)
6396 		cfs_rq->pelt_clock_throttled = 1;
6397 }
6398 
6399 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6400 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6401 {
6402 	if (!cfs_bandwidth_used())
6403 		return false;
6404 
6405 	if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6406 		return false;
6407 
6408 	/*
6409 	 * it's possible for a throttled entity to be forced into a running
6410 	 * state (e.g. set_curr_task), in this case we're finished.
6411 	 */
6412 	if (cfs_rq_throttled(cfs_rq))
6413 		return true;
6414 
6415 	return throttle_cfs_rq(cfs_rq);
6416 }
6417 
6418 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6419 {
6420 	struct cfs_bandwidth *cfs_b =
6421 		container_of(timer, struct cfs_bandwidth, slack_timer);
6422 
6423 	do_sched_cfs_slack_timer(cfs_b);
6424 
6425 	return HRTIMER_NORESTART;
6426 }
6427 
6428 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6429 {
6430 	struct cfs_bandwidth *cfs_b =
6431 		container_of(timer, struct cfs_bandwidth, period_timer);
6432 	unsigned long flags;
6433 	int overrun;
6434 	int idle = 0;
6435 	int count = 0;
6436 
6437 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6438 	for (;;) {
6439 		overrun = hrtimer_forward_now(timer, cfs_b->period);
6440 		if (!overrun)
6441 			break;
6442 
6443 		idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6444 
6445 		if (++count > 3) {
6446 			u64 new, old = ktime_to_ns(cfs_b->period);
6447 
6448 			/*
6449 			 * Grow period by a factor of 2 to avoid losing precision.
6450 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6451 			 * to fail.
6452 			 */
6453 			new = old * 2;
6454 			if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
6455 				cfs_b->period = ns_to_ktime(new);
6456 				cfs_b->quota *= 2;
6457 				cfs_b->burst *= 2;
6458 
6459 				pr_warn_ratelimited(
6460 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6461 					smp_processor_id(),
6462 					div_u64(new, NSEC_PER_USEC),
6463 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6464 			} else {
6465 				pr_warn_ratelimited(
6466 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6467 					smp_processor_id(),
6468 					div_u64(old, NSEC_PER_USEC),
6469 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6470 			}
6471 
6472 			/* reset count so we don't come right back in here */
6473 			count = 0;
6474 		}
6475 	}
6476 	if (idle)
6477 		cfs_b->period_active = 0;
6478 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6479 
6480 	return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6481 }
6482 
6483 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6484 {
6485 	raw_spin_lock_init(&cfs_b->lock);
6486 	cfs_b->runtime = 0;
6487 	cfs_b->quota = RUNTIME_INF;
6488 	cfs_b->period = us_to_ktime(default_bw_period_us());
6489 	cfs_b->burst = 0;
6490 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6491 
6492 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6493 	hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
6494 		      HRTIMER_MODE_ABS_PINNED);
6495 
6496 	/* Add a random offset so that timers interleave */
6497 	hrtimer_set_expires(&cfs_b->period_timer,
6498 			    get_random_u32_below(cfs_b->period));
6499 	hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
6500 		      HRTIMER_MODE_REL);
6501 	cfs_b->slack_started = false;
6502 }
6503 
6504 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6505 {
6506 	cfs_rq->runtime_enabled = 0;
6507 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
6508 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6509 	INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
6510 }
6511 
6512 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6513 {
6514 	lockdep_assert_held(&cfs_b->lock);
6515 
6516 	if (cfs_b->period_active)
6517 		return;
6518 
6519 	cfs_b->period_active = 1;
6520 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6521 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6522 }
6523 
6524 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6525 {
6526 	int __maybe_unused i;
6527 
6528 	/* init_cfs_bandwidth() was not called */
6529 	if (!cfs_b->throttled_cfs_rq.next)
6530 		return;
6531 
6532 	hrtimer_cancel(&cfs_b->period_timer);
6533 	hrtimer_cancel(&cfs_b->slack_timer);
6534 
6535 	/*
6536 	 * It is possible that we still have some cfs_rq's pending on a CSD
6537 	 * list, though this race is very rare. In order for this to occur, we
6538 	 * must have raced with the last task leaving the group while there
6539 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
6540 	 * CSD item but the remote cpu has not yet processed it. To handle this,
6541 	 * we can simply flush all pending CSD work inline here. We're
6542 	 * guaranteed at this point that no additional cfs_rq of this group can
6543 	 * join a CSD list.
6544 	 */
6545 	for_each_possible_cpu(i) {
6546 		struct rq *rq = cpu_rq(i);
6547 		unsigned long flags;
6548 
6549 		if (list_empty(&rq->cfsb_csd_list))
6550 			continue;
6551 
6552 		local_irq_save(flags);
6553 		__cfsb_csd_unthrottle(rq);
6554 		local_irq_restore(flags);
6555 	}
6556 }
6557 
6558 /*
6559  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6560  *
6561  * The race is harmless, since modifying bandwidth settings of unhooked group
6562  * bits doesn't do much.
6563  */
6564 
6565 /* cpu online callback */
6566 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6567 {
6568 	struct task_group *tg;
6569 
6570 	lockdep_assert_rq_held(rq);
6571 
6572 	rcu_read_lock();
6573 	list_for_each_entry_rcu(tg, &task_groups, list) {
6574 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6575 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6576 
6577 		raw_spin_lock(&cfs_b->lock);
6578 		cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6579 		raw_spin_unlock(&cfs_b->lock);
6580 	}
6581 	rcu_read_unlock();
6582 }
6583 
6584 /* cpu offline callback */
6585 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6586 {
6587 	struct task_group *tg;
6588 
6589 	lockdep_assert_rq_held(rq);
6590 
6591 	// Do not unthrottle for an active CPU
6592 	if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6593 		return;
6594 
6595 	/*
6596 	 * The rq clock has already been updated in the
6597 	 * set_rq_offline(), so we should skip updating
6598 	 * the rq clock again in unthrottle_cfs_rq().
6599 	 */
6600 	rq_clock_start_loop_update(rq);
6601 
6602 	rcu_read_lock();
6603 	list_for_each_entry_rcu(tg, &task_groups, list) {
6604 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6605 
6606 		if (!cfs_rq->runtime_enabled)
6607 			continue;
6608 
6609 		/*
6610 		 * Offline rq is schedulable till CPU is completely disabled
6611 		 * in take_cpu_down(), so we prevent new cfs throttling here.
6612 		 */
6613 		cfs_rq->runtime_enabled = 0;
6614 
6615 		if (!cfs_rq_throttled(cfs_rq))
6616 			continue;
6617 
6618 		/*
6619 		 * clock_task is not advancing so we just need to make sure
6620 		 * there's some valid quota amount
6621 		 */
6622 		cfs_rq->runtime_remaining = 1;
6623 		unthrottle_cfs_rq(cfs_rq);
6624 	}
6625 	rcu_read_unlock();
6626 
6627 	rq_clock_stop_loop_update(rq);
6628 }
6629 
6630 bool cfs_task_bw_constrained(struct task_struct *p)
6631 {
6632 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
6633 
6634 	if (!cfs_bandwidth_used())
6635 		return false;
6636 
6637 	if (cfs_rq->runtime_enabled ||
6638 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6639 		return true;
6640 
6641 	return false;
6642 }
6643 
6644 #ifdef CONFIG_NO_HZ_FULL
6645 /* called from pick_next_task_fair() */
6646 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6647 {
6648 	int cpu = cpu_of(rq);
6649 
6650 	if (!cfs_bandwidth_used())
6651 		return;
6652 
6653 	if (!tick_nohz_full_cpu(cpu))
6654 		return;
6655 
6656 	if (rq->nr_running != 1)
6657 		return;
6658 
6659 	/*
6660 	 *  We know there is only one task runnable and we've just picked it. The
6661 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6662 	 *  be otherwise able to stop the tick. Just need to check if we are using
6663 	 *  bandwidth control.
6664 	 */
6665 	if (cfs_task_bw_constrained(p))
6666 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6667 }
6668 #endif /* CONFIG_NO_HZ_FULL */
6669 
6670 #else /* !CONFIG_CFS_BANDWIDTH: */
6671 
6672 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6673 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6674 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6675 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6676 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6677 static void task_throttle_setup_work(struct task_struct *p) {}
6678 static bool task_is_throttled(struct task_struct *p) { return false; }
6679 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
6680 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
6681 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
6682 
6683 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6684 {
6685 	return 0;
6686 }
6687 
6688 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6689 {
6690 	return false;
6691 }
6692 
6693 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6694 {
6695 	return 0;
6696 }
6697 
6698 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6699 {
6700 	return 0;
6701 }
6702 
6703 #ifdef CONFIG_FAIR_GROUP_SCHED
6704 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6705 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6706 #endif
6707 
6708 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6709 {
6710 	return NULL;
6711 }
6712 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6713 static inline void update_runtime_enabled(struct rq *rq) {}
6714 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6715 #ifdef CONFIG_CGROUP_SCHED
6716 bool cfs_task_bw_constrained(struct task_struct *p)
6717 {
6718 	return false;
6719 }
6720 #endif
6721 #endif /* !CONFIG_CFS_BANDWIDTH */
6722 
6723 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6724 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6725 #endif
6726 
6727 /**************************************************
6728  * CFS operations on tasks:
6729  */
6730 
6731 #ifdef CONFIG_SCHED_HRTICK
6732 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6733 {
6734 	struct sched_entity *se = &p->se;
6735 
6736 	WARN_ON_ONCE(task_rq(p) != rq);
6737 
6738 	if (rq->cfs.h_nr_queued > 1) {
6739 		u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6740 		u64 slice = se->slice;
6741 		s64 delta = slice - ran;
6742 
6743 		if (delta < 0) {
6744 			if (task_current_donor(rq, p))
6745 				resched_curr(rq);
6746 			return;
6747 		}
6748 		hrtick_start(rq, delta);
6749 	}
6750 }
6751 
6752 /*
6753  * called from enqueue/dequeue and updates the hrtick when the
6754  * current task is from our class and nr_running is low enough
6755  * to matter.
6756  */
6757 static void hrtick_update(struct rq *rq)
6758 {
6759 	struct task_struct *donor = rq->donor;
6760 
6761 	if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
6762 		return;
6763 
6764 	hrtick_start_fair(rq, donor);
6765 }
6766 #else /* !CONFIG_SCHED_HRTICK: */
6767 static inline void
6768 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6769 {
6770 }
6771 
6772 static inline void hrtick_update(struct rq *rq)
6773 {
6774 }
6775 #endif /* !CONFIG_SCHED_HRTICK */
6776 
6777 static inline bool cpu_overutilized(int cpu)
6778 {
6779 	unsigned long  rq_util_min, rq_util_max;
6780 
6781 	if (!sched_energy_enabled())
6782 		return false;
6783 
6784 	rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6785 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6786 
6787 	/* Return true only if the utilization doesn't fit CPU's capacity */
6788 	return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6789 }
6790 
6791 /*
6792  * overutilized value make sense only if EAS is enabled
6793  */
6794 static inline bool is_rd_overutilized(struct root_domain *rd)
6795 {
6796 	return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
6797 }
6798 
6799 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
6800 {
6801 	if (!sched_energy_enabled())
6802 		return;
6803 
6804 	WRITE_ONCE(rd->overutilized, flag);
6805 	trace_sched_overutilized_tp(rd, flag);
6806 }
6807 
6808 static inline void check_update_overutilized_status(struct rq *rq)
6809 {
6810 	/*
6811 	 * overutilized field is used for load balancing decisions only
6812 	 * if energy aware scheduler is being used
6813 	 */
6814 
6815 	if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
6816 		set_rd_overutilized(rq->rd, 1);
6817 }
6818 
6819 /* Runqueue only has SCHED_IDLE tasks enqueued */
6820 static int sched_idle_rq(struct rq *rq)
6821 {
6822 	return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
6823 			rq->nr_running);
6824 }
6825 
6826 static int sched_idle_cpu(int cpu)
6827 {
6828 	return sched_idle_rq(cpu_rq(cpu));
6829 }
6830 
6831 static void
6832 requeue_delayed_entity(struct sched_entity *se)
6833 {
6834 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6835 
6836 	/*
6837 	 * se->sched_delayed should imply: se->on_rq == 1.
6838 	 * Because a delayed entity is one that is still on
6839 	 * the runqueue competing until elegibility.
6840 	 */
6841 	WARN_ON_ONCE(!se->sched_delayed);
6842 	WARN_ON_ONCE(!se->on_rq);
6843 
6844 	if (sched_feat(DELAY_ZERO)) {
6845 		update_entity_lag(cfs_rq, se);
6846 		if (se->vlag > 0) {
6847 			cfs_rq->nr_queued--;
6848 			if (se != cfs_rq->curr)
6849 				__dequeue_entity(cfs_rq, se);
6850 			se->vlag = 0;
6851 			place_entity(cfs_rq, se, 0);
6852 			if (se != cfs_rq->curr)
6853 				__enqueue_entity(cfs_rq, se);
6854 			cfs_rq->nr_queued++;
6855 		}
6856 	}
6857 
6858 	update_load_avg(cfs_rq, se, 0);
6859 	clear_delayed(se);
6860 }
6861 
6862 /*
6863  * The enqueue_task method is called before nr_running is
6864  * increased. Here we update the fair scheduling stats and
6865  * then put the task into the rbtree:
6866  */
6867 static void
6868 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6869 {
6870 	struct cfs_rq *cfs_rq;
6871 	struct sched_entity *se = &p->se;
6872 	int h_nr_idle = task_has_idle_policy(p);
6873 	int h_nr_runnable = 1;
6874 	int task_new = !(flags & ENQUEUE_WAKEUP);
6875 	int rq_h_nr_queued = rq->cfs.h_nr_queued;
6876 	u64 slice = 0;
6877 
6878 	if (task_is_throttled(p) && enqueue_throttled_task(p))
6879 		return;
6880 
6881 	/*
6882 	 * The code below (indirectly) updates schedutil which looks at
6883 	 * the cfs_rq utilization to select a frequency.
6884 	 * Let's add the task's estimated utilization to the cfs_rq's
6885 	 * estimated utilization, before we update schedutil.
6886 	 */
6887 	if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
6888 		util_est_enqueue(&rq->cfs, p);
6889 
6890 	if (flags & ENQUEUE_DELAYED) {
6891 		requeue_delayed_entity(se);
6892 		return;
6893 	}
6894 
6895 	/*
6896 	 * If in_iowait is set, the code below may not trigger any cpufreq
6897 	 * utilization updates, so do it here explicitly with the IOWAIT flag
6898 	 * passed.
6899 	 */
6900 	if (p->in_iowait)
6901 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6902 
6903 	if (task_new && se->sched_delayed)
6904 		h_nr_runnable = 0;
6905 
6906 	for_each_sched_entity(se) {
6907 		if (se->on_rq) {
6908 			if (se->sched_delayed)
6909 				requeue_delayed_entity(se);
6910 			break;
6911 		}
6912 		cfs_rq = cfs_rq_of(se);
6913 
6914 		/*
6915 		 * Basically set the slice of group entries to the min_slice of
6916 		 * their respective cfs_rq. This ensures the group can service
6917 		 * its entities in the desired time-frame.
6918 		 */
6919 		if (slice) {
6920 			se->slice = slice;
6921 			se->custom_slice = 1;
6922 		}
6923 		enqueue_entity(cfs_rq, se, flags);
6924 		slice = cfs_rq_min_slice(cfs_rq);
6925 
6926 		cfs_rq->h_nr_runnable += h_nr_runnable;
6927 		cfs_rq->h_nr_queued++;
6928 		cfs_rq->h_nr_idle += h_nr_idle;
6929 
6930 		if (cfs_rq_is_idle(cfs_rq))
6931 			h_nr_idle = 1;
6932 
6933 		flags = ENQUEUE_WAKEUP;
6934 	}
6935 
6936 	for_each_sched_entity(se) {
6937 		cfs_rq = cfs_rq_of(se);
6938 
6939 		update_load_avg(cfs_rq, se, UPDATE_TG);
6940 		se_update_runnable(se);
6941 		update_cfs_group(se);
6942 
6943 		se->slice = slice;
6944 		if (se != cfs_rq->curr)
6945 			min_vruntime_cb_propagate(&se->run_node, NULL);
6946 		slice = cfs_rq_min_slice(cfs_rq);
6947 
6948 		cfs_rq->h_nr_runnable += h_nr_runnable;
6949 		cfs_rq->h_nr_queued++;
6950 		cfs_rq->h_nr_idle += h_nr_idle;
6951 
6952 		if (cfs_rq_is_idle(cfs_rq))
6953 			h_nr_idle = 1;
6954 	}
6955 
6956 	if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
6957 		dl_server_start(&rq->fair_server);
6958 
6959 	/* At this point se is NULL and we are at root level*/
6960 	add_nr_running(rq, 1);
6961 
6962 	/*
6963 	 * Since new tasks are assigned an initial util_avg equal to
6964 	 * half of the spare capacity of their CPU, tiny tasks have the
6965 	 * ability to cross the overutilized threshold, which will
6966 	 * result in the load balancer ruining all the task placement
6967 	 * done by EAS. As a way to mitigate that effect, do not account
6968 	 * for the first enqueue operation of new tasks during the
6969 	 * overutilized flag detection.
6970 	 *
6971 	 * A better way of solving this problem would be to wait for
6972 	 * the PELT signals of tasks to converge before taking them
6973 	 * into account, but that is not straightforward to implement,
6974 	 * and the following generally works well enough in practice.
6975 	 */
6976 	if (!task_new)
6977 		check_update_overutilized_status(rq);
6978 
6979 	assert_list_leaf_cfs_rq(rq);
6980 
6981 	hrtick_update(rq);
6982 }
6983 
6984 /*
6985  * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
6986  * failing half-way through and resume the dequeue later.
6987  *
6988  * Returns:
6989  * -1 - dequeue delayed
6990  *  0 - dequeue throttled
6991  *  1 - dequeue complete
6992  */
6993 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
6994 {
6995 	bool was_sched_idle = sched_idle_rq(rq);
6996 	bool task_sleep = flags & DEQUEUE_SLEEP;
6997 	bool task_delayed = flags & DEQUEUE_DELAYED;
6998 	bool task_throttled = flags & DEQUEUE_THROTTLE;
6999 	struct task_struct *p = NULL;
7000 	int h_nr_idle = 0;
7001 	int h_nr_queued = 0;
7002 	int h_nr_runnable = 0;
7003 	struct cfs_rq *cfs_rq;
7004 	u64 slice = 0;
7005 
7006 	if (entity_is_task(se)) {
7007 		p = task_of(se);
7008 		h_nr_queued = 1;
7009 		h_nr_idle = task_has_idle_policy(p);
7010 		if (task_sleep || task_delayed || !se->sched_delayed)
7011 			h_nr_runnable = 1;
7012 	}
7013 
7014 	for_each_sched_entity(se) {
7015 		cfs_rq = cfs_rq_of(se);
7016 
7017 		if (!dequeue_entity(cfs_rq, se, flags)) {
7018 			if (p && &p->se == se)
7019 				return -1;
7020 
7021 			slice = cfs_rq_min_slice(cfs_rq);
7022 			break;
7023 		}
7024 
7025 		cfs_rq->h_nr_runnable -= h_nr_runnable;
7026 		cfs_rq->h_nr_queued -= h_nr_queued;
7027 		cfs_rq->h_nr_idle -= h_nr_idle;
7028 
7029 		if (cfs_rq_is_idle(cfs_rq))
7030 			h_nr_idle = h_nr_queued;
7031 
7032 		if (throttled_hierarchy(cfs_rq) && task_throttled)
7033 			record_throttle_clock(cfs_rq);
7034 
7035 		/* Don't dequeue parent if it has other entities besides us */
7036 		if (cfs_rq->load.weight) {
7037 			slice = cfs_rq_min_slice(cfs_rq);
7038 
7039 			/* Avoid re-evaluating load for this entity: */
7040 			se = parent_entity(se);
7041 			/*
7042 			 * Bias pick_next to pick a task from this cfs_rq, as
7043 			 * p is sleeping when it is within its sched_slice.
7044 			 */
7045 			if (task_sleep && se)
7046 				set_next_buddy(se);
7047 			break;
7048 		}
7049 		flags |= DEQUEUE_SLEEP;
7050 		flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7051 	}
7052 
7053 	for_each_sched_entity(se) {
7054 		cfs_rq = cfs_rq_of(se);
7055 
7056 		update_load_avg(cfs_rq, se, UPDATE_TG);
7057 		se_update_runnable(se);
7058 		update_cfs_group(se);
7059 
7060 		se->slice = slice;
7061 		if (se != cfs_rq->curr)
7062 			min_vruntime_cb_propagate(&se->run_node, NULL);
7063 		slice = cfs_rq_min_slice(cfs_rq);
7064 
7065 		cfs_rq->h_nr_runnable -= h_nr_runnable;
7066 		cfs_rq->h_nr_queued -= h_nr_queued;
7067 		cfs_rq->h_nr_idle -= h_nr_idle;
7068 
7069 		if (cfs_rq_is_idle(cfs_rq))
7070 			h_nr_idle = h_nr_queued;
7071 
7072 		if (throttled_hierarchy(cfs_rq) && task_throttled)
7073 			record_throttle_clock(cfs_rq);
7074 	}
7075 
7076 	sub_nr_running(rq, h_nr_queued);
7077 
7078 	/* balance early to pull high priority tasks */
7079 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7080 		rq->next_balance = jiffies;
7081 
7082 	if (p && task_delayed) {
7083 		WARN_ON_ONCE(!task_sleep);
7084 		WARN_ON_ONCE(p->on_rq != 1);
7085 
7086 		/* Fix-up what dequeue_task_fair() skipped */
7087 		hrtick_update(rq);
7088 
7089 		/*
7090 		 * Fix-up what block_task() skipped.
7091 		 *
7092 		 * Must be last, @p might not be valid after this.
7093 		 */
7094 		__block_task(rq, p);
7095 	}
7096 
7097 	return 1;
7098 }
7099 
7100 /*
7101  * The dequeue_task method is called before nr_running is
7102  * decreased. We remove the task from the rbtree and
7103  * update the fair scheduling stats:
7104  */
7105 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7106 {
7107 	if (task_is_throttled(p)) {
7108 		dequeue_throttled_task(p, flags);
7109 		return true;
7110 	}
7111 
7112 	if (!p->se.sched_delayed)
7113 		util_est_dequeue(&rq->cfs, p);
7114 
7115 	util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7116 	if (dequeue_entities(rq, &p->se, flags) < 0)
7117 		return false;
7118 
7119 	/*
7120 	 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7121 	 */
7122 
7123 	hrtick_update(rq);
7124 	return true;
7125 }
7126 
7127 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
7128 {
7129 	return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
7130 }
7131 
7132 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7133 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7134 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7135 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7136 
7137 #ifdef CONFIG_NO_HZ_COMMON
7138 
7139 static struct {
7140 	cpumask_var_t idle_cpus_mask;
7141 	int has_blocked_load;		/* Idle CPUS has blocked load */
7142 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
7143 	unsigned long next_balance;     /* in jiffy units */
7144 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
7145 } nohz ____cacheline_aligned;
7146 
7147 #endif /* CONFIG_NO_HZ_COMMON */
7148 
7149 static unsigned long cpu_load(struct rq *rq)
7150 {
7151 	return cfs_rq_load_avg(&rq->cfs);
7152 }
7153 
7154 /*
7155  * cpu_load_without - compute CPU load without any contributions from *p
7156  * @cpu: the CPU which load is requested
7157  * @p: the task which load should be discounted
7158  *
7159  * The load of a CPU is defined by the load of tasks currently enqueued on that
7160  * CPU as well as tasks which are currently sleeping after an execution on that
7161  * CPU.
7162  *
7163  * This method returns the load of the specified CPU by discounting the load of
7164  * the specified task, whenever the task is currently contributing to the CPU
7165  * load.
7166  */
7167 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7168 {
7169 	struct cfs_rq *cfs_rq;
7170 	unsigned int load;
7171 
7172 	/* Task has no contribution or is new */
7173 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7174 		return cpu_load(rq);
7175 
7176 	cfs_rq = &rq->cfs;
7177 	load = READ_ONCE(cfs_rq->avg.load_avg);
7178 
7179 	/* Discount task's util from CPU's util */
7180 	lsub_positive(&load, task_h_load(p));
7181 
7182 	return load;
7183 }
7184 
7185 static unsigned long cpu_runnable(struct rq *rq)
7186 {
7187 	return cfs_rq_runnable_avg(&rq->cfs);
7188 }
7189 
7190 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7191 {
7192 	struct cfs_rq *cfs_rq;
7193 	unsigned int runnable;
7194 
7195 	/* Task has no contribution or is new */
7196 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7197 		return cpu_runnable(rq);
7198 
7199 	cfs_rq = &rq->cfs;
7200 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7201 
7202 	/* Discount task's runnable from CPU's runnable */
7203 	lsub_positive(&runnable, p->se.avg.runnable_avg);
7204 
7205 	return runnable;
7206 }
7207 
7208 static unsigned long capacity_of(int cpu)
7209 {
7210 	return cpu_rq(cpu)->cpu_capacity;
7211 }
7212 
7213 static void record_wakee(struct task_struct *p)
7214 {
7215 	/*
7216 	 * Only decay a single time; tasks that have less then 1 wakeup per
7217 	 * jiffy will not have built up many flips.
7218 	 */
7219 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7220 		current->wakee_flips >>= 1;
7221 		current->wakee_flip_decay_ts = jiffies;
7222 	}
7223 
7224 	if (current->last_wakee != p) {
7225 		current->last_wakee = p;
7226 		current->wakee_flips++;
7227 	}
7228 }
7229 
7230 /*
7231  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7232  *
7233  * A waker of many should wake a different task than the one last awakened
7234  * at a frequency roughly N times higher than one of its wakees.
7235  *
7236  * In order to determine whether we should let the load spread vs consolidating
7237  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7238  * partner, and a factor of lls_size higher frequency in the other.
7239  *
7240  * With both conditions met, we can be relatively sure that the relationship is
7241  * non-monogamous, with partner count exceeding socket size.
7242  *
7243  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7244  * whatever is irrelevant, spread criteria is apparent partner count exceeds
7245  * socket size.
7246  */
7247 static int wake_wide(struct task_struct *p)
7248 {
7249 	unsigned int master = current->wakee_flips;
7250 	unsigned int slave = p->wakee_flips;
7251 	int factor = __this_cpu_read(sd_llc_size);
7252 
7253 	if (master < slave)
7254 		swap(master, slave);
7255 	if (slave < factor || master < slave * factor)
7256 		return 0;
7257 	return 1;
7258 }
7259 
7260 /*
7261  * The purpose of wake_affine() is to quickly determine on which CPU we can run
7262  * soonest. For the purpose of speed we only consider the waking and previous
7263  * CPU.
7264  *
7265  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7266  *			cache-affine and is (or	will be) idle.
7267  *
7268  * wake_affine_weight() - considers the weight to reflect the average
7269  *			  scheduling latency of the CPUs. This seems to work
7270  *			  for the overloaded case.
7271  */
7272 static int
7273 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7274 {
7275 	/*
7276 	 * If this_cpu is idle, it implies the wakeup is from interrupt
7277 	 * context. Only allow the move if cache is shared. Otherwise an
7278 	 * interrupt intensive workload could force all tasks onto one
7279 	 * node depending on the IO topology or IRQ affinity settings.
7280 	 *
7281 	 * If the prev_cpu is idle and cache affine then avoid a migration.
7282 	 * There is no guarantee that the cache hot data from an interrupt
7283 	 * is more important than cache hot data on the prev_cpu and from
7284 	 * a cpufreq perspective, it's better to have higher utilisation
7285 	 * on one CPU.
7286 	 */
7287 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7288 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7289 
7290 	if (sync) {
7291 		struct rq *rq = cpu_rq(this_cpu);
7292 
7293 		if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
7294 			return this_cpu;
7295 	}
7296 
7297 	if (available_idle_cpu(prev_cpu))
7298 		return prev_cpu;
7299 
7300 	return nr_cpumask_bits;
7301 }
7302 
7303 static int
7304 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7305 		   int this_cpu, int prev_cpu, int sync)
7306 {
7307 	s64 this_eff_load, prev_eff_load;
7308 	unsigned long task_load;
7309 
7310 	this_eff_load = cpu_load(cpu_rq(this_cpu));
7311 
7312 	if (sync) {
7313 		unsigned long current_load = task_h_load(current);
7314 
7315 		if (current_load > this_eff_load)
7316 			return this_cpu;
7317 
7318 		this_eff_load -= current_load;
7319 	}
7320 
7321 	task_load = task_h_load(p);
7322 
7323 	this_eff_load += task_load;
7324 	if (sched_feat(WA_BIAS))
7325 		this_eff_load *= 100;
7326 	this_eff_load *= capacity_of(prev_cpu);
7327 
7328 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7329 	prev_eff_load -= task_load;
7330 	if (sched_feat(WA_BIAS))
7331 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7332 	prev_eff_load *= capacity_of(this_cpu);
7333 
7334 	/*
7335 	 * If sync, adjust the weight of prev_eff_load such that if
7336 	 * prev_eff == this_eff that select_idle_sibling() will consider
7337 	 * stacking the wakee on top of the waker if no other CPU is
7338 	 * idle.
7339 	 */
7340 	if (sync)
7341 		prev_eff_load += 1;
7342 
7343 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7344 }
7345 
7346 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7347 		       int this_cpu, int prev_cpu, int sync)
7348 {
7349 	int target = nr_cpumask_bits;
7350 
7351 	if (sched_feat(WA_IDLE))
7352 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
7353 
7354 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7355 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7356 
7357 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7358 	if (target != this_cpu)
7359 		return prev_cpu;
7360 
7361 	schedstat_inc(sd->ttwu_move_affine);
7362 	schedstat_inc(p->stats.nr_wakeups_affine);
7363 	return target;
7364 }
7365 
7366 static struct sched_group *
7367 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7368 
7369 /*
7370  * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7371  */
7372 static int
7373 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7374 {
7375 	unsigned long load, min_load = ULONG_MAX;
7376 	unsigned int min_exit_latency = UINT_MAX;
7377 	u64 latest_idle_timestamp = 0;
7378 	int least_loaded_cpu = this_cpu;
7379 	int shallowest_idle_cpu = -1;
7380 	int i;
7381 
7382 	/* Check if we have any choice: */
7383 	if (group->group_weight == 1)
7384 		return cpumask_first(sched_group_span(group));
7385 
7386 	/* Traverse only the allowed CPUs */
7387 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7388 		struct rq *rq = cpu_rq(i);
7389 
7390 		if (!sched_core_cookie_match(rq, p))
7391 			continue;
7392 
7393 		if (sched_idle_cpu(i))
7394 			return i;
7395 
7396 		if (available_idle_cpu(i)) {
7397 			struct cpuidle_state *idle = idle_get_state(rq);
7398 			if (idle && idle->exit_latency < min_exit_latency) {
7399 				/*
7400 				 * We give priority to a CPU whose idle state
7401 				 * has the smallest exit latency irrespective
7402 				 * of any idle timestamp.
7403 				 */
7404 				min_exit_latency = idle->exit_latency;
7405 				latest_idle_timestamp = rq->idle_stamp;
7406 				shallowest_idle_cpu = i;
7407 			} else if ((!idle || idle->exit_latency == min_exit_latency) &&
7408 				   rq->idle_stamp > latest_idle_timestamp) {
7409 				/*
7410 				 * If equal or no active idle state, then
7411 				 * the most recently idled CPU might have
7412 				 * a warmer cache.
7413 				 */
7414 				latest_idle_timestamp = rq->idle_stamp;
7415 				shallowest_idle_cpu = i;
7416 			}
7417 		} else if (shallowest_idle_cpu == -1) {
7418 			load = cpu_load(cpu_rq(i));
7419 			if (load < min_load) {
7420 				min_load = load;
7421 				least_loaded_cpu = i;
7422 			}
7423 		}
7424 	}
7425 
7426 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7427 }
7428 
7429 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7430 				  int cpu, int prev_cpu, int sd_flag)
7431 {
7432 	int new_cpu = cpu;
7433 
7434 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7435 		return prev_cpu;
7436 
7437 	/*
7438 	 * We need task's util for cpu_util_without, sync it up to
7439 	 * prev_cpu's last_update_time.
7440 	 */
7441 	if (!(sd_flag & SD_BALANCE_FORK))
7442 		sync_entity_load_avg(&p->se);
7443 
7444 	while (sd) {
7445 		struct sched_group *group;
7446 		struct sched_domain *tmp;
7447 		int weight;
7448 
7449 		if (!(sd->flags & sd_flag)) {
7450 			sd = sd->child;
7451 			continue;
7452 		}
7453 
7454 		group = sched_balance_find_dst_group(sd, p, cpu);
7455 		if (!group) {
7456 			sd = sd->child;
7457 			continue;
7458 		}
7459 
7460 		new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7461 		if (new_cpu == cpu) {
7462 			/* Now try balancing at a lower domain level of 'cpu': */
7463 			sd = sd->child;
7464 			continue;
7465 		}
7466 
7467 		/* Now try balancing at a lower domain level of 'new_cpu': */
7468 		cpu = new_cpu;
7469 		weight = sd->span_weight;
7470 		sd = NULL;
7471 		for_each_domain(cpu, tmp) {
7472 			if (weight <= tmp->span_weight)
7473 				break;
7474 			if (tmp->flags & sd_flag)
7475 				sd = tmp;
7476 		}
7477 	}
7478 
7479 	return new_cpu;
7480 }
7481 
7482 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7483 {
7484 	if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7485 	    sched_cpu_cookie_match(cpu_rq(cpu), p))
7486 		return cpu;
7487 
7488 	return -1;
7489 }
7490 
7491 #ifdef CONFIG_SCHED_SMT
7492 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7493 EXPORT_SYMBOL_GPL(sched_smt_present);
7494 
7495 static inline void set_idle_cores(int cpu, int val)
7496 {
7497 	struct sched_domain_shared *sds;
7498 
7499 	sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
7500 	if (sds)
7501 		WRITE_ONCE(sds->has_idle_cores, val);
7502 }
7503 
7504 static inline bool test_idle_cores(int cpu)
7505 {
7506 	struct sched_domain_shared *sds;
7507 
7508 	sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
7509 	if (sds)
7510 		return READ_ONCE(sds->has_idle_cores);
7511 
7512 	return false;
7513 }
7514 
7515 /*
7516  * Scans the local SMT mask to see if the entire core is idle, and records this
7517  * information in sd_llc_shared->has_idle_cores.
7518  *
7519  * Since SMT siblings share all cache levels, inspecting this limited remote
7520  * state should be fairly cheap.
7521  */
7522 void __update_idle_core(struct rq *rq)
7523 {
7524 	int core = cpu_of(rq);
7525 	int cpu;
7526 
7527 	rcu_read_lock();
7528 	if (test_idle_cores(core))
7529 		goto unlock;
7530 
7531 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7532 		if (cpu == core)
7533 			continue;
7534 
7535 		if (!available_idle_cpu(cpu))
7536 			goto unlock;
7537 	}
7538 
7539 	set_idle_cores(core, 1);
7540 unlock:
7541 	rcu_read_unlock();
7542 }
7543 
7544 /*
7545  * Scan the entire LLC domain for idle cores; this dynamically switches off if
7546  * there are no idle cores left in the system; tracked through
7547  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7548  */
7549 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7550 {
7551 	bool idle = true;
7552 	int cpu;
7553 
7554 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7555 		if (!available_idle_cpu(cpu)) {
7556 			idle = false;
7557 			if (*idle_cpu == -1) {
7558 				if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7559 					*idle_cpu = cpu;
7560 					break;
7561 				}
7562 				continue;
7563 			}
7564 			break;
7565 		}
7566 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7567 			*idle_cpu = cpu;
7568 	}
7569 
7570 	if (idle)
7571 		return core;
7572 
7573 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7574 	return -1;
7575 }
7576 
7577 /*
7578  * Scan the local SMT mask for idle CPUs.
7579  */
7580 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7581 {
7582 	int cpu;
7583 
7584 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7585 		if (cpu == target)
7586 			continue;
7587 		/*
7588 		 * Check if the CPU is in the LLC scheduling domain of @target.
7589 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7590 		 */
7591 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7592 			continue;
7593 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7594 			return cpu;
7595 	}
7596 
7597 	return -1;
7598 }
7599 
7600 #else /* !CONFIG_SCHED_SMT: */
7601 
7602 static inline void set_idle_cores(int cpu, int val)
7603 {
7604 }
7605 
7606 static inline bool test_idle_cores(int cpu)
7607 {
7608 	return false;
7609 }
7610 
7611 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7612 {
7613 	return __select_idle_cpu(core, p);
7614 }
7615 
7616 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7617 {
7618 	return -1;
7619 }
7620 
7621 #endif /* !CONFIG_SCHED_SMT */
7622 
7623 /*
7624  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7625  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7626  * average idle time for this rq (as found in rq->avg_idle).
7627  */
7628 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7629 {
7630 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7631 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
7632 	struct sched_domain_shared *sd_share;
7633 
7634 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7635 
7636 	if (sched_feat(SIS_UTIL)) {
7637 		sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, target));
7638 		if (sd_share) {
7639 			/* because !--nr is the condition to stop scan */
7640 			nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7641 			/* overloaded LLC is unlikely to have idle cpu/core */
7642 			if (nr == 1)
7643 				return -1;
7644 		}
7645 	}
7646 
7647 	if (static_branch_unlikely(&sched_cluster_active)) {
7648 		struct sched_group *sg = sd->groups;
7649 
7650 		if (sg->flags & SD_CLUSTER) {
7651 			for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7652 				if (!cpumask_test_cpu(cpu, cpus))
7653 					continue;
7654 
7655 				if (has_idle_core) {
7656 					i = select_idle_core(p, cpu, cpus, &idle_cpu);
7657 					if ((unsigned int)i < nr_cpumask_bits)
7658 						return i;
7659 				} else {
7660 					if (--nr <= 0)
7661 						return -1;
7662 					idle_cpu = __select_idle_cpu(cpu, p);
7663 					if ((unsigned int)idle_cpu < nr_cpumask_bits)
7664 						return idle_cpu;
7665 				}
7666 			}
7667 			cpumask_andnot(cpus, cpus, sched_group_span(sg));
7668 		}
7669 	}
7670 
7671 	for_each_cpu_wrap(cpu, cpus, target + 1) {
7672 		if (has_idle_core) {
7673 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
7674 			if ((unsigned int)i < nr_cpumask_bits)
7675 				return i;
7676 
7677 		} else {
7678 			if (--nr <= 0)
7679 				return -1;
7680 			idle_cpu = __select_idle_cpu(cpu, p);
7681 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
7682 				break;
7683 		}
7684 	}
7685 
7686 	if (has_idle_core)
7687 		set_idle_cores(target, false);
7688 
7689 	return idle_cpu;
7690 }
7691 
7692 /*
7693  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7694  * the task fits. If no CPU is big enough, but there are idle ones, try to
7695  * maximize capacity.
7696  */
7697 static int
7698 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7699 {
7700 	unsigned long task_util, util_min, util_max, best_cap = 0;
7701 	int fits, best_fits = 0;
7702 	int cpu, best_cpu = -1;
7703 	struct cpumask *cpus;
7704 
7705 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7706 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7707 
7708 	task_util = task_util_est(p);
7709 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
7710 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
7711 
7712 	for_each_cpu_wrap(cpu, cpus, target) {
7713 		unsigned long cpu_cap = capacity_of(cpu);
7714 
7715 		if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7716 			continue;
7717 
7718 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7719 
7720 		/* This CPU fits with all requirements */
7721 		if (fits > 0)
7722 			return cpu;
7723 		/*
7724 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7725 		 * Look for the CPU with best capacity.
7726 		 */
7727 		else if (fits < 0)
7728 			cpu_cap = get_actual_cpu_capacity(cpu);
7729 
7730 		/*
7731 		 * First, select CPU which fits better (-1 being better than 0).
7732 		 * Then, select the one with best capacity at same level.
7733 		 */
7734 		if ((fits < best_fits) ||
7735 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
7736 			best_cap = cpu_cap;
7737 			best_cpu = cpu;
7738 			best_fits = fits;
7739 		}
7740 	}
7741 
7742 	return best_cpu;
7743 }
7744 
7745 static inline bool asym_fits_cpu(unsigned long util,
7746 				 unsigned long util_min,
7747 				 unsigned long util_max,
7748 				 int cpu)
7749 {
7750 	if (sched_asym_cpucap_active())
7751 		/*
7752 		 * Return true only if the cpu fully fits the task requirements
7753 		 * which include the utilization and the performance hints.
7754 		 */
7755 		return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7756 
7757 	return true;
7758 }
7759 
7760 /*
7761  * Try and locate an idle core/thread in the LLC cache domain.
7762  */
7763 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7764 {
7765 	bool has_idle_core = false;
7766 	struct sched_domain *sd;
7767 	unsigned long task_util, util_min, util_max;
7768 	int i, recent_used_cpu, prev_aff = -1;
7769 
7770 	/*
7771 	 * On asymmetric system, update task utilization because we will check
7772 	 * that the task fits with CPU's capacity.
7773 	 */
7774 	if (sched_asym_cpucap_active()) {
7775 		sync_entity_load_avg(&p->se);
7776 		task_util = task_util_est(p);
7777 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
7778 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
7779 	}
7780 
7781 	/*
7782 	 * per-cpu select_rq_mask usage
7783 	 */
7784 	lockdep_assert_irqs_disabled();
7785 
7786 	if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7787 	    asym_fits_cpu(task_util, util_min, util_max, target))
7788 		return target;
7789 
7790 	/*
7791 	 * If the previous CPU is cache affine and idle, don't be stupid:
7792 	 */
7793 	if (prev != target && cpus_share_cache(prev, target) &&
7794 	    (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7795 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
7796 
7797 		if (!static_branch_unlikely(&sched_cluster_active) ||
7798 		    cpus_share_resources(prev, target))
7799 			return prev;
7800 
7801 		prev_aff = prev;
7802 	}
7803 
7804 	/*
7805 	 * Allow a per-cpu kthread to stack with the wakee if the
7806 	 * kworker thread and the tasks previous CPUs are the same.
7807 	 * The assumption is that the wakee queued work for the
7808 	 * per-cpu kthread that is now complete and the wakeup is
7809 	 * essentially a sync wakeup. An obvious example of this
7810 	 * pattern is IO completions.
7811 	 */
7812 	if (is_per_cpu_kthread(current) &&
7813 	    in_task() &&
7814 	    prev == smp_processor_id() &&
7815 	    this_rq()->nr_running <= 1 &&
7816 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
7817 		return prev;
7818 	}
7819 
7820 	/* Check a recently used CPU as a potential idle candidate: */
7821 	recent_used_cpu = p->recent_used_cpu;
7822 	p->recent_used_cpu = prev;
7823 	if (recent_used_cpu != prev &&
7824 	    recent_used_cpu != target &&
7825 	    cpus_share_cache(recent_used_cpu, target) &&
7826 	    (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7827 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7828 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7829 
7830 		if (!static_branch_unlikely(&sched_cluster_active) ||
7831 		    cpus_share_resources(recent_used_cpu, target))
7832 			return recent_used_cpu;
7833 
7834 	} else {
7835 		recent_used_cpu = -1;
7836 	}
7837 
7838 	/*
7839 	 * For asymmetric CPU capacity systems, our domain of interest is
7840 	 * sd_asym_cpucapacity rather than sd_llc.
7841 	 */
7842 	if (sched_asym_cpucap_active()) {
7843 		sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target));
7844 		/*
7845 		 * On an asymmetric CPU capacity system where an exclusive
7846 		 * cpuset defines a symmetric island (i.e. one unique
7847 		 * capacity_orig value through the cpuset), the key will be set
7848 		 * but the CPUs within that cpuset will not have a domain with
7849 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7850 		 * capacity path.
7851 		 */
7852 		if (sd) {
7853 			i = select_idle_capacity(p, sd, target);
7854 			return ((unsigned)i < nr_cpumask_bits) ? i : target;
7855 		}
7856 	}
7857 
7858 	sd = rcu_dereference_all(per_cpu(sd_llc, target));
7859 	if (!sd)
7860 		return target;
7861 
7862 	if (sched_smt_active()) {
7863 		has_idle_core = test_idle_cores(target);
7864 
7865 		if (!has_idle_core && cpus_share_cache(prev, target)) {
7866 			i = select_idle_smt(p, sd, prev);
7867 			if ((unsigned int)i < nr_cpumask_bits)
7868 				return i;
7869 		}
7870 	}
7871 
7872 	i = select_idle_cpu(p, sd, has_idle_core, target);
7873 	if ((unsigned)i < nr_cpumask_bits)
7874 		return i;
7875 
7876 	/*
7877 	 * For cluster machines which have lower sharing cache like L2 or
7878 	 * LLC Tag, we tend to find an idle CPU in the target's cluster
7879 	 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7880 	 * use them if possible when no idle CPU found in select_idle_cpu().
7881 	 */
7882 	if ((unsigned int)prev_aff < nr_cpumask_bits)
7883 		return prev_aff;
7884 	if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7885 		return recent_used_cpu;
7886 
7887 	return target;
7888 }
7889 
7890 /**
7891  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7892  * @cpu: the CPU to get the utilization for
7893  * @p: task for which the CPU utilization should be predicted or NULL
7894  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7895  * @boost: 1 to enable boosting, otherwise 0
7896  *
7897  * The unit of the return value must be the same as the one of CPU capacity
7898  * so that CPU utilization can be compared with CPU capacity.
7899  *
7900  * CPU utilization is the sum of running time of runnable tasks plus the
7901  * recent utilization of currently non-runnable tasks on that CPU.
7902  * It represents the amount of CPU capacity currently used by CFS tasks in
7903  * the range [0..max CPU capacity] with max CPU capacity being the CPU
7904  * capacity at f_max.
7905  *
7906  * The estimated CPU utilization is defined as the maximum between CPU
7907  * utilization and sum of the estimated utilization of the currently
7908  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7909  * previously-executed tasks, which helps better deduce how busy a CPU will
7910  * be when a long-sleeping task wakes up. The contribution to CPU utilization
7911  * of such a task would be significantly decayed at this point of time.
7912  *
7913  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7914  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7915  * utilization. Boosting is implemented in cpu_util() so that internal
7916  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7917  * latter via cpu_util_cfs_boost().
7918  *
7919  * CPU utilization can be higher than the current CPU capacity
7920  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7921  * of rounding errors as well as task migrations or wakeups of new tasks.
7922  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7923  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7924  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7925  * capacity. CPU utilization is allowed to overshoot current CPU capacity
7926  * though since this is useful for predicting the CPU capacity required
7927  * after task migrations (scheduler-driven DVFS).
7928  *
7929  * Return: (Boosted) (estimated) utilization for the specified CPU.
7930  */
7931 static unsigned long
7932 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7933 {
7934 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7935 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7936 	unsigned long runnable;
7937 
7938 	if (boost) {
7939 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7940 		util = max(util, runnable);
7941 	}
7942 
7943 	/*
7944 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7945 	 * contribution. If @p migrates from another CPU to @cpu add its
7946 	 * contribution. In all the other cases @cpu is not impacted by the
7947 	 * migration so its util_avg is already correct.
7948 	 */
7949 	if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7950 		lsub_positive(&util, task_util(p));
7951 	else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7952 		util += task_util(p);
7953 
7954 	if (sched_feat(UTIL_EST)) {
7955 		unsigned long util_est;
7956 
7957 		util_est = READ_ONCE(cfs_rq->avg.util_est);
7958 
7959 		/*
7960 		 * During wake-up @p isn't enqueued yet and doesn't contribute
7961 		 * to any cpu_rq(cpu)->cfs.avg.util_est.
7962 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7963 		 * has been enqueued.
7964 		 *
7965 		 * During exec (@dst_cpu = -1) @p is enqueued and does
7966 		 * contribute to cpu_rq(cpu)->cfs.util_est.
7967 		 * Remove it to "simulate" cpu_util without @p's contribution.
7968 		 *
7969 		 * Despite the task_on_rq_queued(@p) check there is still a
7970 		 * small window for a possible race when an exec
7971 		 * select_task_rq_fair() races with LB's detach_task().
7972 		 *
7973 		 *   detach_task()
7974 		 *     deactivate_task()
7975 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
7976 		 *       -------------------------------- A
7977 		 *       dequeue_task()                    \
7978 		 *         dequeue_task_fair()              + Race Time
7979 		 *           util_est_dequeue()            /
7980 		 *       -------------------------------- B
7981 		 *
7982 		 * The additional check "current == p" is required to further
7983 		 * reduce the race window.
7984 		 */
7985 		if (dst_cpu == cpu)
7986 			util_est += _task_util_est(p);
7987 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
7988 			lsub_positive(&util_est, _task_util_est(p));
7989 
7990 		util = max(util, util_est);
7991 	}
7992 
7993 	return min(util, arch_scale_cpu_capacity(cpu));
7994 }
7995 
7996 unsigned long cpu_util_cfs(int cpu)
7997 {
7998 	return cpu_util(cpu, NULL, -1, 0);
7999 }
8000 
8001 unsigned long cpu_util_cfs_boost(int cpu)
8002 {
8003 	return cpu_util(cpu, NULL, -1, 1);
8004 }
8005 
8006 /*
8007  * cpu_util_without: compute cpu utilization without any contributions from *p
8008  * @cpu: the CPU which utilization is requested
8009  * @p: the task which utilization should be discounted
8010  *
8011  * The utilization of a CPU is defined by the utilization of tasks currently
8012  * enqueued on that CPU as well as tasks which are currently sleeping after an
8013  * execution on that CPU.
8014  *
8015  * This method returns the utilization of the specified CPU by discounting the
8016  * utilization of the specified task, whenever the task is currently
8017  * contributing to the CPU utilization.
8018  */
8019 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8020 {
8021 	/* Task has no contribution or is new */
8022 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8023 		p = NULL;
8024 
8025 	return cpu_util(cpu, p, -1, 0);
8026 }
8027 
8028 /*
8029  * This function computes an effective utilization for the given CPU, to be
8030  * used for frequency selection given the linear relation: f = u * f_max.
8031  *
8032  * The scheduler tracks the following metrics:
8033  *
8034  *   cpu_util_{cfs,rt,dl,irq}()
8035  *   cpu_bw_dl()
8036  *
8037  * Where the cfs,rt and dl util numbers are tracked with the same metric and
8038  * synchronized windows and are thus directly comparable.
8039  *
8040  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8041  * which excludes things like IRQ and steal-time. These latter are then accrued
8042  * in the IRQ utilization.
8043  *
8044  * The DL bandwidth number OTOH is not a measured metric but a value computed
8045  * based on the task model parameters and gives the minimal utilization
8046  * required to meet deadlines.
8047  */
8048 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8049 				 unsigned long *min,
8050 				 unsigned long *max)
8051 {
8052 	unsigned long util, irq, scale;
8053 	struct rq *rq = cpu_rq(cpu);
8054 
8055 	scale = arch_scale_cpu_capacity(cpu);
8056 
8057 	/*
8058 	 * Early check to see if IRQ/steal time saturates the CPU, can be
8059 	 * because of inaccuracies in how we track these -- see
8060 	 * update_irq_load_avg().
8061 	 */
8062 	irq = cpu_util_irq(rq);
8063 	if (unlikely(irq >= scale)) {
8064 		if (min)
8065 			*min = scale;
8066 		if (max)
8067 			*max = scale;
8068 		return scale;
8069 	}
8070 
8071 	if (min) {
8072 		/*
8073 		 * The minimum utilization returns the highest level between:
8074 		 * - the computed DL bandwidth needed with the IRQ pressure which
8075 		 *   steals time to the deadline task.
8076 		 * - The minimum performance requirement for CFS and/or RT.
8077 		 */
8078 		*min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8079 
8080 		/*
8081 		 * When an RT task is runnable and uclamp is not used, we must
8082 		 * ensure that the task will run at maximum compute capacity.
8083 		 */
8084 		if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8085 			*min = max(*min, scale);
8086 	}
8087 
8088 	/*
8089 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8090 	 * CFS tasks and we use the same metric to track the effective
8091 	 * utilization (PELT windows are synchronized) we can directly add them
8092 	 * to obtain the CPU's actual utilization.
8093 	 */
8094 	util = util_cfs + cpu_util_rt(rq);
8095 	util += cpu_util_dl(rq);
8096 
8097 	/*
8098 	 * The maximum hint is a soft bandwidth requirement, which can be lower
8099 	 * than the actual utilization because of uclamp_max requirements.
8100 	 */
8101 	if (max)
8102 		*max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8103 
8104 	if (util >= scale)
8105 		return scale;
8106 
8107 	/*
8108 	 * There is still idle time; further improve the number by using the
8109 	 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8110 	 * need to scale the task numbers:
8111 	 *
8112 	 *              max - irq
8113 	 *   U' = irq + --------- * U
8114 	 *                 max
8115 	 */
8116 	util = scale_irq_capacity(util, irq, scale);
8117 	util += irq;
8118 
8119 	return min(scale, util);
8120 }
8121 
8122 unsigned long sched_cpu_util(int cpu)
8123 {
8124 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8125 }
8126 
8127 /*
8128  * energy_env - Utilization landscape for energy estimation.
8129  * @task_busy_time: Utilization contribution by the task for which we test the
8130  *                  placement. Given by eenv_task_busy_time().
8131  * @pd_busy_time:   Utilization of the whole perf domain without the task
8132  *                  contribution. Given by eenv_pd_busy_time().
8133  * @cpu_cap:        Maximum CPU capacity for the perf domain.
8134  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8135  */
8136 struct energy_env {
8137 	unsigned long task_busy_time;
8138 	unsigned long pd_busy_time;
8139 	unsigned long cpu_cap;
8140 	unsigned long pd_cap;
8141 };
8142 
8143 /*
8144  * Compute the task busy time for compute_energy(). This time cannot be
8145  * injected directly into effective_cpu_util() because of the IRQ scaling.
8146  * The latter only makes sense with the most recent CPUs where the task has
8147  * run.
8148  */
8149 static inline void eenv_task_busy_time(struct energy_env *eenv,
8150 				       struct task_struct *p, int prev_cpu)
8151 {
8152 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8153 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8154 
8155 	if (unlikely(irq >= max_cap))
8156 		busy_time = max_cap;
8157 	else
8158 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8159 
8160 	eenv->task_busy_time = busy_time;
8161 }
8162 
8163 /*
8164  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8165  * utilization for each @pd_cpus, it however doesn't take into account
8166  * clamping since the ratio (utilization / cpu_capacity) is already enough to
8167  * scale the EM reported power consumption at the (eventually clamped)
8168  * cpu_capacity.
8169  *
8170  * The contribution of the task @p for which we want to estimate the
8171  * energy cost is removed (by cpu_util()) and must be calculated
8172  * separately (see eenv_task_busy_time). This ensures:
8173  *
8174  *   - A stable PD utilization, no matter which CPU of that PD we want to place
8175  *     the task on.
8176  *
8177  *   - A fair comparison between CPUs as the task contribution (task_util())
8178  *     will always be the same no matter which CPU utilization we rely on
8179  *     (util_avg or util_est).
8180  *
8181  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8182  * exceed @eenv->pd_cap.
8183  */
8184 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8185 				     struct cpumask *pd_cpus,
8186 				     struct task_struct *p)
8187 {
8188 	unsigned long busy_time = 0;
8189 	int cpu;
8190 
8191 	for_each_cpu(cpu, pd_cpus) {
8192 		unsigned long util = cpu_util(cpu, p, -1, 0);
8193 
8194 		busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8195 	}
8196 
8197 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8198 }
8199 
8200 /*
8201  * Compute the maximum utilization for compute_energy() when the task @p
8202  * is placed on the cpu @dst_cpu.
8203  *
8204  * Returns the maximum utilization among @eenv->cpus. This utilization can't
8205  * exceed @eenv->cpu_cap.
8206  */
8207 static inline unsigned long
8208 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8209 		 struct task_struct *p, int dst_cpu)
8210 {
8211 	unsigned long max_util = 0;
8212 	int cpu;
8213 
8214 	for_each_cpu(cpu, pd_cpus) {
8215 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8216 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8217 		unsigned long eff_util, min, max;
8218 
8219 		/*
8220 		 * Performance domain frequency: utilization clamping
8221 		 * must be considered since it affects the selection
8222 		 * of the performance domain frequency.
8223 		 * NOTE: in case RT tasks are running, by default the min
8224 		 * utilization can be max OPP.
8225 		 */
8226 		eff_util = effective_cpu_util(cpu, util, &min, &max);
8227 
8228 		/* Task's uclamp can modify min and max value */
8229 		if (tsk && uclamp_is_used()) {
8230 			min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8231 
8232 			/*
8233 			 * If there is no active max uclamp constraint,
8234 			 * directly use task's one, otherwise keep max.
8235 			 */
8236 			if (uclamp_rq_is_idle(cpu_rq(cpu)))
8237 				max = uclamp_eff_value(p, UCLAMP_MAX);
8238 			else
8239 				max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8240 		}
8241 
8242 		eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8243 		max_util = max(max_util, eff_util);
8244 	}
8245 
8246 	return min(max_util, eenv->cpu_cap);
8247 }
8248 
8249 /*
8250  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8251  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8252  * contribution is ignored.
8253  */
8254 static inline unsigned long
8255 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8256 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8257 {
8258 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8259 	unsigned long busy_time = eenv->pd_busy_time;
8260 	unsigned long energy;
8261 
8262 	if (dst_cpu >= 0)
8263 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8264 
8265 	energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8266 
8267 	trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8268 
8269 	return energy;
8270 }
8271 
8272 /*
8273  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8274  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8275  * spare capacity in each performance domain and uses it as a potential
8276  * candidate to execute the task. Then, it uses the Energy Model to figure
8277  * out which of the CPU candidates is the most energy-efficient.
8278  *
8279  * The rationale for this heuristic is as follows. In a performance domain,
8280  * all the most energy efficient CPU candidates (according to the Energy
8281  * Model) are those for which we'll request a low frequency. When there are
8282  * several CPUs for which the frequency request will be the same, we don't
8283  * have enough data to break the tie between them, because the Energy Model
8284  * only includes active power costs. With this model, if we assume that
8285  * frequency requests follow utilization (e.g. using schedutil), the CPU with
8286  * the maximum spare capacity in a performance domain is guaranteed to be among
8287  * the best candidates of the performance domain.
8288  *
8289  * In practice, it could be preferable from an energy standpoint to pack
8290  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8291  * but that could also hurt our chances to go cluster idle, and we have no
8292  * ways to tell with the current Energy Model if this is actually a good
8293  * idea or not. So, find_energy_efficient_cpu() basically favors
8294  * cluster-packing, and spreading inside a cluster. That should at least be
8295  * a good thing for latency, and this is consistent with the idea that most
8296  * of the energy savings of EAS come from the asymmetry of the system, and
8297  * not so much from breaking the tie between identical CPUs. That's also the
8298  * reason why EAS is enabled in the topology code only for systems where
8299  * SD_ASYM_CPUCAPACITY is set.
8300  *
8301  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8302  * they don't have any useful utilization data yet and it's not possible to
8303  * forecast their impact on energy consumption. Consequently, they will be
8304  * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8305  * to be energy-inefficient in some use-cases. The alternative would be to
8306  * bias new tasks towards specific types of CPUs first, or to try to infer
8307  * their util_avg from the parent task, but those heuristics could hurt
8308  * other use-cases too. So, until someone finds a better way to solve this,
8309  * let's keep things simple by re-using the existing slow path.
8310  */
8311 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8312 {
8313 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8314 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8315 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8316 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8317 	struct root_domain *rd = this_rq()->rd;
8318 	int cpu, best_energy_cpu, target = -1;
8319 	int prev_fits = -1, best_fits = -1;
8320 	unsigned long best_actual_cap = 0;
8321 	unsigned long prev_actual_cap = 0;
8322 	struct sched_domain *sd;
8323 	struct perf_domain *pd;
8324 	struct energy_env eenv;
8325 
8326 	rcu_read_lock();
8327 	pd = rcu_dereference_all(rd->pd);
8328 	if (!pd)
8329 		goto unlock;
8330 
8331 	/*
8332 	 * Energy-aware wake-up happens on the lowest sched_domain starting
8333 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8334 	 */
8335 	sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity));
8336 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8337 		sd = sd->parent;
8338 	if (!sd)
8339 		goto unlock;
8340 
8341 	target = prev_cpu;
8342 
8343 	sync_entity_load_avg(&p->se);
8344 	if (!task_util_est(p) && p_util_min == 0)
8345 		goto unlock;
8346 
8347 	eenv_task_busy_time(&eenv, p, prev_cpu);
8348 
8349 	for (; pd; pd = pd->next) {
8350 		unsigned long util_min = p_util_min, util_max = p_util_max;
8351 		unsigned long cpu_cap, cpu_actual_cap, util;
8352 		long prev_spare_cap = -1, max_spare_cap = -1;
8353 		unsigned long rq_util_min, rq_util_max;
8354 		unsigned long cur_delta, base_energy;
8355 		int max_spare_cap_cpu = -1;
8356 		int fits, max_fits = -1;
8357 
8358 		if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask))
8359 			continue;
8360 
8361 		/* Account external pressure for the energy estimation */
8362 		cpu = cpumask_first(cpus);
8363 		cpu_actual_cap = get_actual_cpu_capacity(cpu);
8364 
8365 		eenv.cpu_cap = cpu_actual_cap;
8366 		eenv.pd_cap = 0;
8367 
8368 		for_each_cpu(cpu, cpus) {
8369 			struct rq *rq = cpu_rq(cpu);
8370 
8371 			eenv.pd_cap += cpu_actual_cap;
8372 
8373 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8374 				continue;
8375 
8376 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8377 				continue;
8378 
8379 			util = cpu_util(cpu, p, cpu, 0);
8380 			cpu_cap = capacity_of(cpu);
8381 
8382 			/*
8383 			 * Skip CPUs that cannot satisfy the capacity request.
8384 			 * IOW, placing the task there would make the CPU
8385 			 * overutilized. Take uclamp into account to see how
8386 			 * much capacity we can get out of the CPU; this is
8387 			 * aligned with sched_cpu_util().
8388 			 */
8389 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8390 				/*
8391 				 * Open code uclamp_rq_util_with() except for
8392 				 * the clamp() part. I.e.: apply max aggregation
8393 				 * only. util_fits_cpu() logic requires to
8394 				 * operate on non clamped util but must use the
8395 				 * max-aggregated uclamp_{min, max}.
8396 				 */
8397 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8398 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8399 
8400 				util_min = max(rq_util_min, p_util_min);
8401 				util_max = max(rq_util_max, p_util_max);
8402 			}
8403 
8404 			fits = util_fits_cpu(util, util_min, util_max, cpu);
8405 			if (!fits)
8406 				continue;
8407 
8408 			lsub_positive(&cpu_cap, util);
8409 
8410 			if (cpu == prev_cpu) {
8411 				/* Always use prev_cpu as a candidate. */
8412 				prev_spare_cap = cpu_cap;
8413 				prev_fits = fits;
8414 			} else if ((fits > max_fits) ||
8415 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8416 				/*
8417 				 * Find the CPU with the maximum spare capacity
8418 				 * among the remaining CPUs in the performance
8419 				 * domain.
8420 				 */
8421 				max_spare_cap = cpu_cap;
8422 				max_spare_cap_cpu = cpu;
8423 				max_fits = fits;
8424 			}
8425 		}
8426 
8427 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8428 			continue;
8429 
8430 		eenv_pd_busy_time(&eenv, cpus, p);
8431 		/* Compute the 'base' energy of the pd, without @p */
8432 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8433 
8434 		/* Evaluate the energy impact of using prev_cpu. */
8435 		if (prev_spare_cap > -1) {
8436 			prev_delta = compute_energy(&eenv, pd, cpus, p,
8437 						    prev_cpu);
8438 			/* CPU utilization has changed */
8439 			if (prev_delta < base_energy)
8440 				goto unlock;
8441 			prev_delta -= base_energy;
8442 			prev_actual_cap = cpu_actual_cap;
8443 			best_delta = min(best_delta, prev_delta);
8444 		}
8445 
8446 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
8447 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8448 			/* Current best energy cpu fits better */
8449 			if (max_fits < best_fits)
8450 				continue;
8451 
8452 			/*
8453 			 * Both don't fit performance hint (i.e. uclamp_min)
8454 			 * but best energy cpu has better capacity.
8455 			 */
8456 			if ((max_fits < 0) &&
8457 			    (cpu_actual_cap <= best_actual_cap))
8458 				continue;
8459 
8460 			cur_delta = compute_energy(&eenv, pd, cpus, p,
8461 						   max_spare_cap_cpu);
8462 			/* CPU utilization has changed */
8463 			if (cur_delta < base_energy)
8464 				goto unlock;
8465 			cur_delta -= base_energy;
8466 
8467 			/*
8468 			 * Both fit for the task but best energy cpu has lower
8469 			 * energy impact.
8470 			 */
8471 			if ((max_fits > 0) && (best_fits > 0) &&
8472 			    (cur_delta >= best_delta))
8473 				continue;
8474 
8475 			best_delta = cur_delta;
8476 			best_energy_cpu = max_spare_cap_cpu;
8477 			best_fits = max_fits;
8478 			best_actual_cap = cpu_actual_cap;
8479 		}
8480 	}
8481 	rcu_read_unlock();
8482 
8483 	if ((best_fits > prev_fits) ||
8484 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
8485 	    ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8486 		target = best_energy_cpu;
8487 
8488 	return target;
8489 
8490 unlock:
8491 	rcu_read_unlock();
8492 
8493 	return target;
8494 }
8495 
8496 /*
8497  * select_task_rq_fair: Select target runqueue for the waking task in domains
8498  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8499  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8500  *
8501  * Balances load by selecting the idlest CPU in the idlest group, or under
8502  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8503  *
8504  * Returns the target CPU number.
8505  */
8506 static int
8507 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8508 {
8509 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8510 	struct sched_domain *tmp, *sd = NULL;
8511 	int cpu = smp_processor_id();
8512 	int new_cpu = prev_cpu;
8513 	int want_affine = 0;
8514 	/* SD_flags and WF_flags share the first nibble */
8515 	int sd_flag = wake_flags & 0xF;
8516 
8517 	/*
8518 	 * required for stable ->cpus_allowed
8519 	 */
8520 	lockdep_assert_held(&p->pi_lock);
8521 	if (wake_flags & WF_TTWU) {
8522 		record_wakee(p);
8523 
8524 		if ((wake_flags & WF_CURRENT_CPU) &&
8525 		    cpumask_test_cpu(cpu, p->cpus_ptr))
8526 			return cpu;
8527 
8528 		if (!is_rd_overutilized(this_rq()->rd)) {
8529 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8530 			if (new_cpu >= 0)
8531 				return new_cpu;
8532 			new_cpu = prev_cpu;
8533 		}
8534 
8535 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8536 	}
8537 
8538 	rcu_read_lock();
8539 	for_each_domain(cpu, tmp) {
8540 		/*
8541 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
8542 		 * cpu is a valid SD_WAKE_AFFINE target.
8543 		 */
8544 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8545 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8546 			if (cpu != prev_cpu)
8547 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8548 
8549 			sd = NULL; /* Prefer wake_affine over balance flags */
8550 			break;
8551 		}
8552 
8553 		/*
8554 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8555 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8556 		 * will usually go to the fast path.
8557 		 */
8558 		if (tmp->flags & sd_flag)
8559 			sd = tmp;
8560 		else if (!want_affine)
8561 			break;
8562 	}
8563 
8564 	if (unlikely(sd)) {
8565 		/* Slow path */
8566 		new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8567 	} else if (wake_flags & WF_TTWU) { /* XXX always ? */
8568 		/* Fast path */
8569 		new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8570 	}
8571 	rcu_read_unlock();
8572 
8573 	return new_cpu;
8574 }
8575 
8576 /*
8577  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8578  * cfs_rq_of(p) references at time of call are still valid and identify the
8579  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8580  */
8581 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8582 {
8583 	struct sched_entity *se = &p->se;
8584 
8585 	if (!task_on_rq_migrating(p)) {
8586 		remove_entity_load_avg(se);
8587 
8588 		/*
8589 		 * Here, the task's PELT values have been updated according to
8590 		 * the current rq's clock. But if that clock hasn't been
8591 		 * updated in a while, a substantial idle time will be missed,
8592 		 * leading to an inflation after wake-up on the new rq.
8593 		 *
8594 		 * Estimate the missing time from the cfs_rq last_update_time
8595 		 * and update sched_avg to improve the PELT continuity after
8596 		 * migration.
8597 		 */
8598 		migrate_se_pelt_lag(se);
8599 	}
8600 
8601 	/* Tell new CPU we are migrated */
8602 	se->avg.last_update_time = 0;
8603 
8604 	update_scan_period(p, new_cpu);
8605 }
8606 
8607 static void task_dead_fair(struct task_struct *p)
8608 {
8609 	struct sched_entity *se = &p->se;
8610 
8611 	if (se->sched_delayed) {
8612 		struct rq_flags rf;
8613 		struct rq *rq;
8614 
8615 		rq = task_rq_lock(p, &rf);
8616 		if (se->sched_delayed) {
8617 			update_rq_clock(rq);
8618 			dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8619 		}
8620 		task_rq_unlock(rq, p, &rf);
8621 	}
8622 
8623 	remove_entity_load_avg(se);
8624 }
8625 
8626 /*
8627  * Set the max capacity the task is allowed to run at for misfit detection.
8628  */
8629 static void set_task_max_allowed_capacity(struct task_struct *p)
8630 {
8631 	struct asym_cap_data *entry;
8632 
8633 	if (!sched_asym_cpucap_active())
8634 		return;
8635 
8636 	rcu_read_lock();
8637 	list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8638 		cpumask_t *cpumask;
8639 
8640 		cpumask = cpu_capacity_span(entry);
8641 		if (!cpumask_intersects(p->cpus_ptr, cpumask))
8642 			continue;
8643 
8644 		p->max_allowed_capacity = entry->capacity;
8645 		break;
8646 	}
8647 	rcu_read_unlock();
8648 }
8649 
8650 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8651 {
8652 	set_cpus_allowed_common(p, ctx);
8653 	set_task_max_allowed_capacity(p);
8654 }
8655 
8656 static void set_next_buddy(struct sched_entity *se)
8657 {
8658 	for_each_sched_entity(se) {
8659 		if (WARN_ON_ONCE(!se->on_rq))
8660 			return;
8661 		if (se_is_idle(se))
8662 			return;
8663 		cfs_rq_of(se)->next = se;
8664 	}
8665 }
8666 
8667 enum preempt_wakeup_action {
8668 	PREEMPT_WAKEUP_NONE,	/* No preemption. */
8669 	PREEMPT_WAKEUP_SHORT,	/* Ignore slice protection. */
8670 	PREEMPT_WAKEUP_PICK,	/* Let __pick_eevdf() decide. */
8671 	PREEMPT_WAKEUP_RESCHED,	/* Force reschedule. */
8672 };
8673 
8674 static inline bool
8675 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags,
8676 		  struct sched_entity *pse, struct sched_entity *se)
8677 {
8678 	/*
8679 	 * Keep existing buddy if the deadline is sooner than pse.
8680 	 * The older buddy may be cache cold and completely unrelated
8681 	 * to the current wakeup but that is unpredictable where as
8682 	 * obeying the deadline is more in line with EEVDF objectives.
8683 	 */
8684 	if (cfs_rq->next && entity_before(cfs_rq->next, pse))
8685 		return false;
8686 
8687 	set_next_buddy(pse);
8688 	return true;
8689 }
8690 
8691 /*
8692  * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
8693  * strictly enforced because the hint is either misunderstood or
8694  * multiple tasks must be woken up.
8695  */
8696 static inline enum preempt_wakeup_action
8697 preempt_sync(struct rq *rq, int wake_flags,
8698 	     struct sched_entity *pse, struct sched_entity *se)
8699 {
8700 	u64 threshold, delta;
8701 
8702 	/*
8703 	 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
8704 	 * though it is likely harmless.
8705 	 */
8706 	WARN_ON_ONCE(!(wake_flags & WF_TTWU));
8707 
8708 	threshold = sysctl_sched_migration_cost;
8709 	delta = rq_clock_task(rq) - se->exec_start;
8710 	if ((s64)delta < 0)
8711 		delta = 0;
8712 
8713 	/*
8714 	 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
8715 	 * could run on other CPUs. Reduce the threshold before preemption is
8716 	 * allowed to an arbitrary lower value as it is more likely (but not
8717 	 * guaranteed) the waker requires the wakee to finish.
8718 	 */
8719 	if (wake_flags & WF_RQ_SELECTED)
8720 		threshold >>= 2;
8721 
8722 	/*
8723 	 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
8724 	 * wakeups to be issued.
8725 	 */
8726 	if (entity_before(pse, se) && delta >= threshold)
8727 		return PREEMPT_WAKEUP_RESCHED;
8728 
8729 	return PREEMPT_WAKEUP_NONE;
8730 }
8731 
8732 /*
8733  * Preempt the current task with a newly woken task if needed:
8734  */
8735 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8736 {
8737 	enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
8738 	struct task_struct *donor = rq->donor;
8739 	struct sched_entity *se = &donor->se, *pse = &p->se;
8740 	struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8741 	int cse_is_idle, pse_is_idle;
8742 
8743 	/*
8744 	 * XXX Getting preempted by higher class, try and find idle CPU?
8745 	 */
8746 	if (p->sched_class != &fair_sched_class)
8747 		return;
8748 
8749 	if (unlikely(se == pse))
8750 		return;
8751 
8752 	/*
8753 	 * This is possible from callers such as attach_tasks(), in which we
8754 	 * unconditionally wakeup_preempt() after an enqueue (which may have
8755 	 * lead to a throttle).  This both saves work and prevents false
8756 	 * next-buddy nomination below.
8757 	 */
8758 	if (task_is_throttled(p))
8759 		return;
8760 
8761 	/*
8762 	 * We can come here with TIF_NEED_RESCHED already set from new task
8763 	 * wake up path.
8764 	 *
8765 	 * Note: this also catches the edge-case of curr being in a throttled
8766 	 * group (e.g. via set_curr_task), since update_curr() (in the
8767 	 * enqueue of curr) will have resulted in resched being set.  This
8768 	 * prevents us from potentially nominating it as a false LAST_BUDDY
8769 	 * below.
8770 	 */
8771 	if (test_tsk_need_resched(rq->curr))
8772 		return;
8773 
8774 	if (!sched_feat(WAKEUP_PREEMPTION))
8775 		return;
8776 
8777 	find_matching_se(&se, &pse);
8778 	WARN_ON_ONCE(!pse);
8779 
8780 	cse_is_idle = se_is_idle(se);
8781 	pse_is_idle = se_is_idle(pse);
8782 
8783 	/*
8784 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8785 	 * in the inverse case).
8786 	 */
8787 	if (cse_is_idle && !pse_is_idle) {
8788 		/*
8789 		 * When non-idle entity preempt an idle entity,
8790 		 * don't give idle entity slice protection.
8791 		 */
8792 		preempt_action = PREEMPT_WAKEUP_SHORT;
8793 		goto preempt;
8794 	}
8795 
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(!normal_policy(p->policy)))
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 	if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
8812 		preempt_action = PREEMPT_WAKEUP_SHORT;
8813 		goto pick;
8814 	}
8815 
8816 	/*
8817 	 * Ignore wakee preemption on WF_FORK as it is less likely that
8818 	 * there is shared data as exec often follow fork. Do not
8819 	 * preempt for tasks that are sched_delayed as it would violate
8820 	 * EEVDF to forcibly queue an ineligible task.
8821 	 */
8822 	if ((wake_flags & WF_FORK) || pse->sched_delayed)
8823 		return;
8824 
8825 	/*
8826 	 * If @p potentially is completing work required by current then
8827 	 * consider preemption.
8828 	 *
8829 	 * Reschedule if waker is no longer eligible. */
8830 	if (in_task() && !entity_eligible(cfs_rq, se)) {
8831 		preempt_action = PREEMPT_WAKEUP_RESCHED;
8832 		goto preempt;
8833 	}
8834 
8835 	/* Prefer picking wakee soon if appropriate. */
8836 	if (sched_feat(NEXT_BUDDY) &&
8837 	    set_preempt_buddy(cfs_rq, wake_flags, pse, se)) {
8838 
8839 		/*
8840 		 * Decide whether to obey WF_SYNC hint for a new buddy. Old
8841 		 * buddies are ignored as they may not be relevant to the
8842 		 * waker and less likely to be cache hot.
8843 		 */
8844 		if (wake_flags & WF_SYNC)
8845 			preempt_action = preempt_sync(rq, wake_flags, pse, se);
8846 	}
8847 
8848 	switch (preempt_action) {
8849 	case PREEMPT_WAKEUP_NONE:
8850 		return;
8851 	case PREEMPT_WAKEUP_RESCHED:
8852 		goto preempt;
8853 	case PREEMPT_WAKEUP_SHORT:
8854 		fallthrough;
8855 	case PREEMPT_WAKEUP_PICK:
8856 		break;
8857 	}
8858 
8859 pick:
8860 	/*
8861 	 * If @p has become the most eligible task, force preemption.
8862 	 */
8863 	if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse)
8864 		goto preempt;
8865 
8866 	if (sched_feat(RUN_TO_PARITY))
8867 		update_protect_slice(cfs_rq, se);
8868 
8869 	return;
8870 
8871 preempt:
8872 	if (preempt_action == PREEMPT_WAKEUP_SHORT)
8873 		cancel_protect_slice(se);
8874 
8875 	resched_curr_lazy(rq);
8876 }
8877 
8878 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
8879 {
8880 	struct sched_entity *se;
8881 	struct cfs_rq *cfs_rq;
8882 	struct task_struct *p;
8883 	bool throttled;
8884 
8885 again:
8886 	cfs_rq = &rq->cfs;
8887 	if (!cfs_rq->nr_queued)
8888 		return NULL;
8889 
8890 	throttled = false;
8891 
8892 	do {
8893 		/* Might not have done put_prev_entity() */
8894 		if (cfs_rq->curr && cfs_rq->curr->on_rq)
8895 			update_curr(cfs_rq);
8896 
8897 		throttled |= check_cfs_rq_runtime(cfs_rq);
8898 
8899 		se = pick_next_entity(rq, cfs_rq);
8900 		if (!se)
8901 			goto again;
8902 		cfs_rq = group_cfs_rq(se);
8903 	} while (cfs_rq);
8904 
8905 	p = task_of(se);
8906 	if (unlikely(throttled))
8907 		task_throttle_setup_work(p);
8908 	return p;
8909 }
8910 
8911 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8912 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8913 
8914 struct task_struct *
8915 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8916 {
8917 	struct sched_entity *se;
8918 	struct task_struct *p;
8919 	int new_tasks;
8920 
8921 again:
8922 	p = pick_task_fair(rq, rf);
8923 	if (!p)
8924 		goto idle;
8925 	se = &p->se;
8926 
8927 #ifdef CONFIG_FAIR_GROUP_SCHED
8928 	if (prev->sched_class != &fair_sched_class)
8929 		goto simple;
8930 
8931 	__put_prev_set_next_dl_server(rq, prev, p);
8932 
8933 	/*
8934 	 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8935 	 * likely that a next task is from the same cgroup as the current.
8936 	 *
8937 	 * Therefore attempt to avoid putting and setting the entire cgroup
8938 	 * hierarchy, only change the part that actually changes.
8939 	 *
8940 	 * Since we haven't yet done put_prev_entity and if the selected task
8941 	 * is a different task than we started out with, try and touch the
8942 	 * least amount of cfs_rqs.
8943 	 */
8944 	if (prev != p) {
8945 		struct sched_entity *pse = &prev->se;
8946 		struct cfs_rq *cfs_rq;
8947 
8948 		while (!(cfs_rq = is_same_group(se, pse))) {
8949 			int se_depth = se->depth;
8950 			int pse_depth = pse->depth;
8951 
8952 			if (se_depth <= pse_depth) {
8953 				put_prev_entity(cfs_rq_of(pse), pse);
8954 				pse = parent_entity(pse);
8955 			}
8956 			if (se_depth >= pse_depth) {
8957 				set_next_entity(cfs_rq_of(se), se);
8958 				se = parent_entity(se);
8959 			}
8960 		}
8961 
8962 		put_prev_entity(cfs_rq, pse);
8963 		set_next_entity(cfs_rq, se);
8964 
8965 		__set_next_task_fair(rq, p, true);
8966 	}
8967 
8968 	return p;
8969 
8970 simple:
8971 #endif /* CONFIG_FAIR_GROUP_SCHED */
8972 	put_prev_set_next_task(rq, prev, p);
8973 	return p;
8974 
8975 idle:
8976 	if (rf) {
8977 		new_tasks = sched_balance_newidle(rq, rf);
8978 
8979 		/*
8980 		 * Because sched_balance_newidle() releases (and re-acquires)
8981 		 * rq->lock, it is possible for any higher priority task to
8982 		 * appear. In that case we must re-start the pick_next_entity()
8983 		 * loop.
8984 		 */
8985 		if (new_tasks < 0)
8986 			return RETRY_TASK;
8987 
8988 		if (new_tasks > 0)
8989 			goto again;
8990 	}
8991 
8992 	/*
8993 	 * rq is about to be idle, check if we need to update the
8994 	 * lost_idle_time of clock_pelt
8995 	 */
8996 	update_idle_rq_clock_pelt(rq);
8997 
8998 	return NULL;
8999 }
9000 
9001 static struct task_struct *
9002 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
9003 {
9004 	return pick_task_fair(dl_se->rq, rf);
9005 }
9006 
9007 void fair_server_init(struct rq *rq)
9008 {
9009 	struct sched_dl_entity *dl_se = &rq->fair_server;
9010 
9011 	init_dl_entity(dl_se);
9012 
9013 	dl_server_init(dl_se, rq, fair_server_pick_task);
9014 }
9015 
9016 /*
9017  * Account for a descheduled task:
9018  */
9019 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9020 {
9021 	struct sched_entity *se = &prev->se;
9022 	struct cfs_rq *cfs_rq;
9023 
9024 	for_each_sched_entity(se) {
9025 		cfs_rq = cfs_rq_of(se);
9026 		put_prev_entity(cfs_rq, se);
9027 	}
9028 }
9029 
9030 /*
9031  * sched_yield() is very simple
9032  */
9033 static void yield_task_fair(struct rq *rq)
9034 {
9035 	struct task_struct *curr = rq->donor;
9036 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9037 	struct sched_entity *se = &curr->se;
9038 
9039 	/*
9040 	 * Are we the only task in the tree?
9041 	 */
9042 	if (unlikely(rq->nr_running == 1))
9043 		return;
9044 
9045 	clear_buddies(cfs_rq, se);
9046 
9047 	update_rq_clock(rq);
9048 	/*
9049 	 * Update run-time statistics of the 'current'.
9050 	 */
9051 	update_curr(cfs_rq);
9052 	/*
9053 	 * Tell update_rq_clock() that we've just updated,
9054 	 * so we don't do microscopic update in schedule()
9055 	 * and double the fastpath cost.
9056 	 */
9057 	rq_clock_skip_update(rq);
9058 
9059 	/*
9060 	 * Forfeit the remaining vruntime, only if the entity is eligible. This
9061 	 * condition is necessary because in core scheduling we prefer to run
9062 	 * ineligible tasks rather than force idling. If this happens we may
9063 	 * end up in a loop where the core scheduler picks the yielding task,
9064 	 * which yields immediately again; without the condition the vruntime
9065 	 * ends up quickly running away.
9066 	 */
9067 	if (entity_eligible(cfs_rq, se)) {
9068 		se->vruntime = se->deadline;
9069 		se->deadline += calc_delta_fair(se->slice, se);
9070 	}
9071 }
9072 
9073 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9074 {
9075 	struct sched_entity *se = &p->se;
9076 
9077 	/* !se->on_rq also covers throttled task */
9078 	if (!se->on_rq)
9079 		return false;
9080 
9081 	/* Tell the scheduler that we'd really like se to run next. */
9082 	set_next_buddy(se);
9083 
9084 	yield_task_fair(rq);
9085 
9086 	return true;
9087 }
9088 
9089 /**************************************************
9090  * Fair scheduling class load-balancing methods.
9091  *
9092  * BASICS
9093  *
9094  * The purpose of load-balancing is to achieve the same basic fairness the
9095  * per-CPU scheduler provides, namely provide a proportional amount of compute
9096  * time to each task. This is expressed in the following equation:
9097  *
9098  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
9099  *
9100  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9101  * W_i,0 is defined as:
9102  *
9103  *   W_i,0 = \Sum_j w_i,j                                             (2)
9104  *
9105  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9106  * is derived from the nice value as per sched_prio_to_weight[].
9107  *
9108  * The weight average is an exponential decay average of the instantaneous
9109  * weight:
9110  *
9111  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
9112  *
9113  * C_i is the compute capacity of CPU i, typically it is the
9114  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9115  * can also include other factors [XXX].
9116  *
9117  * To achieve this balance we define a measure of imbalance which follows
9118  * directly from (1):
9119  *
9120  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
9121  *
9122  * We them move tasks around to minimize the imbalance. In the continuous
9123  * function space it is obvious this converges, in the discrete case we get
9124  * a few fun cases generally called infeasible weight scenarios.
9125  *
9126  * [XXX expand on:
9127  *     - infeasible weights;
9128  *     - local vs global optima in the discrete case. ]
9129  *
9130  *
9131  * SCHED DOMAINS
9132  *
9133  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9134  * for all i,j solution, we create a tree of CPUs that follows the hardware
9135  * topology where each level pairs two lower groups (or better). This results
9136  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9137  * tree to only the first of the previous level and we decrease the frequency
9138  * of load-balance at each level inversely proportional to the number of CPUs in
9139  * the groups.
9140  *
9141  * This yields:
9142  *
9143  *     log_2 n     1     n
9144  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
9145  *     i = 0      2^i   2^i
9146  *                               `- size of each group
9147  *         |         |     `- number of CPUs doing load-balance
9148  *         |         `- freq
9149  *         `- sum over all levels
9150  *
9151  * Coupled with a limit on how many tasks we can migrate every balance pass,
9152  * this makes (5) the runtime complexity of the balancer.
9153  *
9154  * An important property here is that each CPU is still (indirectly) connected
9155  * to every other CPU in at most O(log n) steps:
9156  *
9157  * The adjacency matrix of the resulting graph is given by:
9158  *
9159  *             log_2 n
9160  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
9161  *             k = 0
9162  *
9163  * And you'll find that:
9164  *
9165  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
9166  *
9167  * Showing there's indeed a path between every CPU in at most O(log n) steps.
9168  * The task movement gives a factor of O(m), giving a convergence complexity
9169  * of:
9170  *
9171  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
9172  *
9173  *
9174  * WORK CONSERVING
9175  *
9176  * In order to avoid CPUs going idle while there's still work to do, new idle
9177  * balancing is more aggressive and has the newly idle CPU iterate up the domain
9178  * tree itself instead of relying on other CPUs to bring it work.
9179  *
9180  * This adds some complexity to both (5) and (8) but it reduces the total idle
9181  * time.
9182  *
9183  * [XXX more?]
9184  *
9185  *
9186  * CGROUPS
9187  *
9188  * Cgroups make a horror show out of (2), instead of a simple sum we get:
9189  *
9190  *                                s_k,i
9191  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
9192  *                                 S_k
9193  *
9194  * Where
9195  *
9196  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
9197  *
9198  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9199  *
9200  * The big problem is S_k, its a global sum needed to compute a local (W_i)
9201  * property.
9202  *
9203  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9204  *      rewrite all of this once again.]
9205  */
9206 
9207 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9208 
9209 enum fbq_type { regular, remote, all };
9210 
9211 /*
9212  * 'group_type' describes the group of CPUs at the moment of load balancing.
9213  *
9214  * The enum is ordered by pulling priority, with the group with lowest priority
9215  * first so the group_type can simply be compared when selecting the busiest
9216  * group. See update_sd_pick_busiest().
9217  */
9218 enum group_type {
9219 	/* The group has spare capacity that can be used to run more tasks.  */
9220 	group_has_spare = 0,
9221 	/*
9222 	 * The group is fully used and the tasks don't compete for more CPU
9223 	 * cycles. Nevertheless, some tasks might wait before running.
9224 	 */
9225 	group_fully_busy,
9226 	/*
9227 	 * One task doesn't fit with CPU's capacity and must be migrated to a
9228 	 * more powerful CPU.
9229 	 */
9230 	group_misfit_task,
9231 	/*
9232 	 * Balance SMT group that's fully busy. Can benefit from migration
9233 	 * a task on SMT with busy sibling to another CPU on idle core.
9234 	 */
9235 	group_smt_balance,
9236 	/*
9237 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9238 	 * and the task should be migrated to it instead of running on the
9239 	 * current CPU.
9240 	 */
9241 	group_asym_packing,
9242 	/*
9243 	 * The tasks' affinity constraints previously prevented the scheduler
9244 	 * from balancing the load across the system.
9245 	 */
9246 	group_imbalanced,
9247 	/*
9248 	 * The CPU is overloaded and can't provide expected CPU cycles to all
9249 	 * tasks.
9250 	 */
9251 	group_overloaded
9252 };
9253 
9254 enum migration_type {
9255 	migrate_load = 0,
9256 	migrate_util,
9257 	migrate_task,
9258 	migrate_misfit
9259 };
9260 
9261 #define LBF_ALL_PINNED	0x01
9262 #define LBF_NEED_BREAK	0x02
9263 #define LBF_DST_PINNED  0x04
9264 #define LBF_SOME_PINNED	0x08
9265 #define LBF_ACTIVE_LB	0x10
9266 
9267 struct lb_env {
9268 	struct sched_domain	*sd;
9269 
9270 	struct rq		*src_rq;
9271 	int			src_cpu;
9272 
9273 	int			dst_cpu;
9274 	struct rq		*dst_rq;
9275 
9276 	struct cpumask		*dst_grpmask;
9277 	int			new_dst_cpu;
9278 	enum cpu_idle_type	idle;
9279 	long			imbalance;
9280 	/* The set of CPUs under consideration for load-balancing */
9281 	struct cpumask		*cpus;
9282 
9283 	unsigned int		flags;
9284 
9285 	unsigned int		loop;
9286 	unsigned int		loop_break;
9287 	unsigned int		loop_max;
9288 
9289 	enum fbq_type		fbq_type;
9290 	enum migration_type	migration_type;
9291 	struct list_head	tasks;
9292 };
9293 
9294 /*
9295  * Is this task likely cache-hot:
9296  */
9297 static int task_hot(struct task_struct *p, struct lb_env *env)
9298 {
9299 	s64 delta;
9300 
9301 	lockdep_assert_rq_held(env->src_rq);
9302 
9303 	if (p->sched_class != &fair_sched_class)
9304 		return 0;
9305 
9306 	if (unlikely(task_has_idle_policy(p)))
9307 		return 0;
9308 
9309 	/* SMT siblings share cache */
9310 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9311 		return 0;
9312 
9313 	/*
9314 	 * Buddy candidates are cache hot:
9315 	 */
9316 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9317 	    (&p->se == cfs_rq_of(&p->se)->next))
9318 		return 1;
9319 
9320 	if (sysctl_sched_migration_cost == -1)
9321 		return 1;
9322 
9323 	/*
9324 	 * Don't migrate task if the task's cookie does not match
9325 	 * with the destination CPU's core cookie.
9326 	 */
9327 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9328 		return 1;
9329 
9330 	if (sysctl_sched_migration_cost == 0)
9331 		return 0;
9332 
9333 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9334 
9335 	return delta < (s64)sysctl_sched_migration_cost;
9336 }
9337 
9338 #ifdef CONFIG_NUMA_BALANCING
9339 /*
9340  * Returns a positive value, if task migration degrades locality.
9341  * Returns 0, if task migration is not affected by locality.
9342  * Returns a negative value, if task migration improves locality i.e migration preferred.
9343  */
9344 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9345 {
9346 	struct numa_group *numa_group = rcu_dereference_all(p->numa_group);
9347 	unsigned long src_weight, dst_weight;
9348 	int src_nid, dst_nid, dist;
9349 
9350 	if (!static_branch_likely(&sched_numa_balancing))
9351 		return 0;
9352 
9353 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9354 		return 0;
9355 
9356 	src_nid = cpu_to_node(env->src_cpu);
9357 	dst_nid = cpu_to_node(env->dst_cpu);
9358 
9359 	if (src_nid == dst_nid)
9360 		return 0;
9361 
9362 	/* Migrating away from the preferred node is always bad. */
9363 	if (src_nid == p->numa_preferred_nid) {
9364 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9365 			return 1;
9366 		else
9367 			return 0;
9368 	}
9369 
9370 	/* Encourage migration to the preferred node. */
9371 	if (dst_nid == p->numa_preferred_nid)
9372 		return -1;
9373 
9374 	/* Leaving a core idle is often worse than degrading locality. */
9375 	if (env->idle == CPU_IDLE)
9376 		return 0;
9377 
9378 	dist = node_distance(src_nid, dst_nid);
9379 	if (numa_group) {
9380 		src_weight = group_weight(p, src_nid, dist);
9381 		dst_weight = group_weight(p, dst_nid, dist);
9382 	} else {
9383 		src_weight = task_weight(p, src_nid, dist);
9384 		dst_weight = task_weight(p, dst_nid, dist);
9385 	}
9386 
9387 	return src_weight - dst_weight;
9388 }
9389 
9390 #else /* !CONFIG_NUMA_BALANCING: */
9391 static inline long migrate_degrades_locality(struct task_struct *p,
9392 					     struct lb_env *env)
9393 {
9394 	return 0;
9395 }
9396 #endif /* !CONFIG_NUMA_BALANCING */
9397 
9398 /*
9399  * Check whether the task is ineligible on the destination cpu
9400  *
9401  * When the PLACE_LAG scheduling feature is enabled and
9402  * dst_cfs_rq->nr_queued is greater than 1, if the task
9403  * is ineligible, it will also be ineligible when
9404  * it is migrated to the destination cpu.
9405  */
9406 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9407 {
9408 	struct cfs_rq *dst_cfs_rq;
9409 
9410 #ifdef CONFIG_FAIR_GROUP_SCHED
9411 	dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9412 #else
9413 	dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9414 #endif
9415 	if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9416 	    !entity_eligible(task_cfs_rq(p), &p->se))
9417 		return 1;
9418 
9419 	return 0;
9420 }
9421 
9422 /*
9423  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9424  */
9425 static
9426 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9427 {
9428 	long degrades, hot;
9429 
9430 	lockdep_assert_rq_held(env->src_rq);
9431 	if (p->sched_task_hot)
9432 		p->sched_task_hot = 0;
9433 
9434 	/*
9435 	 * We do not migrate tasks that are:
9436 	 * 1) delayed dequeued unless we migrate load, or
9437 	 * 2) target cfs_rq is in throttled hierarchy, or
9438 	 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9439 	 * 4) running (obviously), or
9440 	 * 5) are cache-hot on their current CPU, or
9441 	 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9442 	 */
9443 	if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9444 		return 0;
9445 
9446 	if (lb_throttled_hierarchy(p, env->dst_cpu))
9447 		return 0;
9448 
9449 	/*
9450 	 * We want to prioritize the migration of eligible tasks.
9451 	 * For ineligible tasks we soft-limit them and only allow
9452 	 * them to migrate when nr_balance_failed is non-zero to
9453 	 * avoid load-balancing trying very hard to balance the load.
9454 	 */
9455 	if (!env->sd->nr_balance_failed &&
9456 	    task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9457 		return 0;
9458 
9459 	/* Disregard percpu kthreads; they are where they need to be. */
9460 	if (kthread_is_per_cpu(p))
9461 		return 0;
9462 
9463 	if (task_is_blocked(p))
9464 		return 0;
9465 
9466 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9467 		int cpu;
9468 
9469 		schedstat_inc(p->stats.nr_failed_migrations_affine);
9470 
9471 		env->flags |= LBF_SOME_PINNED;
9472 
9473 		/*
9474 		 * Remember if this task can be migrated to any other CPU in
9475 		 * our sched_group. We may want to revisit it if we couldn't
9476 		 * meet load balance goals by pulling other tasks on src_cpu.
9477 		 *
9478 		 * Avoid computing new_dst_cpu
9479 		 * - for NEWLY_IDLE
9480 		 * - if we have already computed one in current iteration
9481 		 * - if it's an active balance
9482 		 */
9483 		if (env->idle == CPU_NEWLY_IDLE ||
9484 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9485 			return 0;
9486 
9487 		/* Prevent to re-select dst_cpu via env's CPUs: */
9488 		cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
9489 
9490 		if (cpu < nr_cpu_ids) {
9491 			env->flags |= LBF_DST_PINNED;
9492 			env->new_dst_cpu = cpu;
9493 		}
9494 
9495 		return 0;
9496 	}
9497 
9498 	/* Record that we found at least one task that could run on dst_cpu */
9499 	env->flags &= ~LBF_ALL_PINNED;
9500 
9501 	if (task_on_cpu(env->src_rq, p) ||
9502 	    task_current_donor(env->src_rq, p)) {
9503 		schedstat_inc(p->stats.nr_failed_migrations_running);
9504 		return 0;
9505 	}
9506 
9507 	/*
9508 	 * Aggressive migration if:
9509 	 * 1) active balance
9510 	 * 2) destination numa is preferred
9511 	 * 3) task is cache cold, or
9512 	 * 4) too many balance attempts have failed.
9513 	 */
9514 	if (env->flags & LBF_ACTIVE_LB)
9515 		return 1;
9516 
9517 	degrades = migrate_degrades_locality(p, env);
9518 	if (!degrades)
9519 		hot = task_hot(p, env);
9520 	else
9521 		hot = degrades > 0;
9522 
9523 	if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9524 		if (hot)
9525 			p->sched_task_hot = 1;
9526 		return 1;
9527 	}
9528 
9529 	schedstat_inc(p->stats.nr_failed_migrations_hot);
9530 	return 0;
9531 }
9532 
9533 /*
9534  * detach_task() -- detach the task for the migration specified in env
9535  */
9536 static void detach_task(struct task_struct *p, struct lb_env *env)
9537 {
9538 	lockdep_assert_rq_held(env->src_rq);
9539 
9540 	if (p->sched_task_hot) {
9541 		p->sched_task_hot = 0;
9542 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9543 		schedstat_inc(p->stats.nr_forced_migrations);
9544 	}
9545 
9546 	WARN_ON(task_current(env->src_rq, p));
9547 	WARN_ON(task_current_donor(env->src_rq, p));
9548 
9549 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9550 	set_task_cpu(p, env->dst_cpu);
9551 }
9552 
9553 /*
9554  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9555  * part of active balancing operations within "domain".
9556  *
9557  * Returns a task if successful and NULL otherwise.
9558  */
9559 static struct task_struct *detach_one_task(struct lb_env *env)
9560 {
9561 	struct task_struct *p;
9562 
9563 	lockdep_assert_rq_held(env->src_rq);
9564 
9565 	list_for_each_entry_reverse(p,
9566 			&env->src_rq->cfs_tasks, se.group_node) {
9567 		if (!can_migrate_task(p, env))
9568 			continue;
9569 
9570 		detach_task(p, env);
9571 
9572 		/*
9573 		 * Right now, this is only the second place where
9574 		 * lb_gained[env->idle] is updated (other is detach_tasks)
9575 		 * so we can safely collect stats here rather than
9576 		 * inside detach_tasks().
9577 		 */
9578 		schedstat_inc(env->sd->lb_gained[env->idle]);
9579 		return p;
9580 	}
9581 	return NULL;
9582 }
9583 
9584 /*
9585  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9586  * busiest_rq, as part of a balancing operation within domain "sd".
9587  *
9588  * Returns number of detached tasks if successful and 0 otherwise.
9589  */
9590 static int detach_tasks(struct lb_env *env)
9591 {
9592 	struct list_head *tasks = &env->src_rq->cfs_tasks;
9593 	unsigned long util, load;
9594 	struct task_struct *p;
9595 	int detached = 0;
9596 
9597 	lockdep_assert_rq_held(env->src_rq);
9598 
9599 	/*
9600 	 * Source run queue has been emptied by another CPU, clear
9601 	 * LBF_ALL_PINNED flag as we will not test any task.
9602 	 */
9603 	if (env->src_rq->nr_running <= 1) {
9604 		env->flags &= ~LBF_ALL_PINNED;
9605 		return 0;
9606 	}
9607 
9608 	if (env->imbalance <= 0)
9609 		return 0;
9610 
9611 	while (!list_empty(tasks)) {
9612 		/*
9613 		 * We don't want to steal all, otherwise we may be treated likewise,
9614 		 * which could at worst lead to a livelock crash.
9615 		 */
9616 		if (env->idle && env->src_rq->nr_running <= 1)
9617 			break;
9618 
9619 		env->loop++;
9620 		/* We've more or less seen every task there is, call it quits */
9621 		if (env->loop > env->loop_max)
9622 			break;
9623 
9624 		/* take a breather every nr_migrate tasks */
9625 		if (env->loop > env->loop_break) {
9626 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
9627 			env->flags |= LBF_NEED_BREAK;
9628 			break;
9629 		}
9630 
9631 		p = list_last_entry(tasks, struct task_struct, se.group_node);
9632 
9633 		if (!can_migrate_task(p, env))
9634 			goto next;
9635 
9636 		switch (env->migration_type) {
9637 		case migrate_load:
9638 			/*
9639 			 * Depending of the number of CPUs and tasks and the
9640 			 * cgroup hierarchy, task_h_load() can return a null
9641 			 * value. Make sure that env->imbalance decreases
9642 			 * otherwise detach_tasks() will stop only after
9643 			 * detaching up to loop_max tasks.
9644 			 */
9645 			load = max_t(unsigned long, task_h_load(p), 1);
9646 
9647 			if (sched_feat(LB_MIN) &&
9648 			    load < 16 && !env->sd->nr_balance_failed)
9649 				goto next;
9650 
9651 			/*
9652 			 * Make sure that we don't migrate too much load.
9653 			 * Nevertheless, let relax the constraint if
9654 			 * scheduler fails to find a good waiting task to
9655 			 * migrate.
9656 			 */
9657 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9658 				goto next;
9659 
9660 			env->imbalance -= load;
9661 			break;
9662 
9663 		case migrate_util:
9664 			util = task_util_est(p);
9665 
9666 			if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9667 				goto next;
9668 
9669 			env->imbalance -= util;
9670 			break;
9671 
9672 		case migrate_task:
9673 			env->imbalance--;
9674 			break;
9675 
9676 		case migrate_misfit:
9677 			/* This is not a misfit task */
9678 			if (task_fits_cpu(p, env->src_cpu))
9679 				goto next;
9680 
9681 			env->imbalance = 0;
9682 			break;
9683 		}
9684 
9685 		detach_task(p, env);
9686 		list_add(&p->se.group_node, &env->tasks);
9687 
9688 		detached++;
9689 
9690 #ifdef CONFIG_PREEMPTION
9691 		/*
9692 		 * NEWIDLE balancing is a source of latency, so preemptible
9693 		 * kernels will stop after the first task is detached to minimize
9694 		 * the critical section.
9695 		 */
9696 		if (env->idle == CPU_NEWLY_IDLE)
9697 			break;
9698 #endif
9699 
9700 		/*
9701 		 * We only want to steal up to the prescribed amount of
9702 		 * load/util/tasks.
9703 		 */
9704 		if (env->imbalance <= 0)
9705 			break;
9706 
9707 		continue;
9708 next:
9709 		if (p->sched_task_hot)
9710 			schedstat_inc(p->stats.nr_failed_migrations_hot);
9711 
9712 		list_move(&p->se.group_node, tasks);
9713 	}
9714 
9715 	/*
9716 	 * Right now, this is one of only two places we collect this stat
9717 	 * so we can safely collect detach_one_task() stats here rather
9718 	 * than inside detach_one_task().
9719 	 */
9720 	schedstat_add(env->sd->lb_gained[env->idle], detached);
9721 
9722 	return detached;
9723 }
9724 
9725 /*
9726  * attach_task() -- attach the task detached by detach_task() to its new rq.
9727  */
9728 static void attach_task(struct rq *rq, struct task_struct *p)
9729 {
9730 	lockdep_assert_rq_held(rq);
9731 
9732 	WARN_ON_ONCE(task_rq(p) != rq);
9733 	activate_task(rq, p, ENQUEUE_NOCLOCK);
9734 	wakeup_preempt(rq, p, 0);
9735 }
9736 
9737 /*
9738  * attach_one_task() -- attaches the task returned from detach_one_task() to
9739  * its new rq.
9740  */
9741 static void attach_one_task(struct rq *rq, struct task_struct *p)
9742 {
9743 	struct rq_flags rf;
9744 
9745 	rq_lock(rq, &rf);
9746 	update_rq_clock(rq);
9747 	attach_task(rq, p);
9748 	rq_unlock(rq, &rf);
9749 }
9750 
9751 /*
9752  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9753  * new rq.
9754  */
9755 static void attach_tasks(struct lb_env *env)
9756 {
9757 	struct list_head *tasks = &env->tasks;
9758 	struct task_struct *p;
9759 	struct rq_flags rf;
9760 
9761 	rq_lock(env->dst_rq, &rf);
9762 	update_rq_clock(env->dst_rq);
9763 
9764 	while (!list_empty(tasks)) {
9765 		p = list_first_entry(tasks, struct task_struct, se.group_node);
9766 		list_del_init(&p->se.group_node);
9767 
9768 		attach_task(env->dst_rq, p);
9769 	}
9770 
9771 	rq_unlock(env->dst_rq, &rf);
9772 }
9773 
9774 #ifdef CONFIG_NO_HZ_COMMON
9775 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq)
9776 {
9777 	if (cfs_rq->avg.load_avg)
9778 		return true;
9779 
9780 	if (cfs_rq->avg.util_avg)
9781 		return true;
9782 
9783 	return false;
9784 }
9785 
9786 static inline bool others_have_blocked(struct rq *rq)
9787 {
9788 	if (cpu_util_rt(rq))
9789 		return true;
9790 
9791 	if (cpu_util_dl(rq))
9792 		return true;
9793 
9794 	if (hw_load_avg(rq))
9795 		return true;
9796 
9797 	if (cpu_util_irq(rq))
9798 		return true;
9799 
9800 	return false;
9801 }
9802 
9803 static inline void update_blocked_load_tick(struct rq *rq)
9804 {
9805 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9806 }
9807 
9808 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load)
9809 {
9810 	if (!has_blocked_load)
9811 		rq->has_blocked_load = 0;
9812 }
9813 #else /* !CONFIG_NO_HZ_COMMON: */
9814 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; }
9815 static inline bool others_have_blocked(struct rq *rq) { return false; }
9816 static inline void update_blocked_load_tick(struct rq *rq) {}
9817 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {}
9818 #endif /* !CONFIG_NO_HZ_COMMON */
9819 
9820 static bool __update_blocked_others(struct rq *rq, bool *done)
9821 {
9822 	bool updated;
9823 
9824 	/*
9825 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9826 	 * DL and IRQ signals have been updated before updating CFS.
9827 	 */
9828 	updated = update_other_load_avgs(rq);
9829 
9830 	if (others_have_blocked(rq))
9831 		*done = false;
9832 
9833 	return updated;
9834 }
9835 
9836 #ifdef CONFIG_FAIR_GROUP_SCHED
9837 
9838 static bool __update_blocked_fair(struct rq *rq, bool *done)
9839 {
9840 	struct cfs_rq *cfs_rq, *pos;
9841 	bool decayed = false;
9842 	int cpu = cpu_of(rq);
9843 
9844 	/*
9845 	 * Iterates the task_group tree in a bottom up fashion, see
9846 	 * list_add_leaf_cfs_rq() for details.
9847 	 */
9848 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9849 		struct sched_entity *se;
9850 
9851 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9852 			update_tg_load_avg(cfs_rq);
9853 
9854 			if (cfs_rq->nr_queued == 0)
9855 				update_idle_cfs_rq_clock_pelt(cfs_rq);
9856 
9857 			if (cfs_rq == &rq->cfs)
9858 				decayed = true;
9859 		}
9860 
9861 		/* Propagate pending load changes to the parent, if any: */
9862 		se = cfs_rq->tg->se[cpu];
9863 		if (se && !skip_blocked_update(se))
9864 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9865 
9866 		/*
9867 		 * There can be a lot of idle CPU cgroups.  Don't let fully
9868 		 * decayed cfs_rqs linger on the list.
9869 		 */
9870 		if (cfs_rq_is_decayed(cfs_rq))
9871 			list_del_leaf_cfs_rq(cfs_rq);
9872 
9873 		/* Don't need periodic decay once load/util_avg are null */
9874 		if (cfs_rq_has_blocked_load(cfs_rq))
9875 			*done = false;
9876 	}
9877 
9878 	return decayed;
9879 }
9880 
9881 /*
9882  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9883  * This needs to be done in a top-down fashion because the load of a child
9884  * group is a fraction of its parents load.
9885  */
9886 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9887 {
9888 	struct rq *rq = rq_of(cfs_rq);
9889 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9890 	unsigned long now = jiffies;
9891 	unsigned long load;
9892 
9893 	if (cfs_rq->last_h_load_update == now)
9894 		return;
9895 
9896 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
9897 	for_each_sched_entity(se) {
9898 		cfs_rq = cfs_rq_of(se);
9899 		WRITE_ONCE(cfs_rq->h_load_next, se);
9900 		if (cfs_rq->last_h_load_update == now)
9901 			break;
9902 	}
9903 
9904 	if (!se) {
9905 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9906 		cfs_rq->last_h_load_update = now;
9907 	}
9908 
9909 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9910 		load = cfs_rq->h_load;
9911 		load = div64_ul(load * se->avg.load_avg,
9912 			cfs_rq_load_avg(cfs_rq) + 1);
9913 		cfs_rq = group_cfs_rq(se);
9914 		cfs_rq->h_load = load;
9915 		cfs_rq->last_h_load_update = now;
9916 	}
9917 }
9918 
9919 static unsigned long task_h_load(struct task_struct *p)
9920 {
9921 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
9922 
9923 	update_cfs_rq_h_load(cfs_rq);
9924 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9925 			cfs_rq_load_avg(cfs_rq) + 1);
9926 }
9927 #else /* !CONFIG_FAIR_GROUP_SCHED: */
9928 static bool __update_blocked_fair(struct rq *rq, bool *done)
9929 {
9930 	struct cfs_rq *cfs_rq = &rq->cfs;
9931 	bool decayed;
9932 
9933 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9934 	if (cfs_rq_has_blocked_load(cfs_rq))
9935 		*done = false;
9936 
9937 	return decayed;
9938 }
9939 
9940 static unsigned long task_h_load(struct task_struct *p)
9941 {
9942 	return p->se.avg.load_avg;
9943 }
9944 #endif /* !CONFIG_FAIR_GROUP_SCHED */
9945 
9946 static void __sched_balance_update_blocked_averages(struct rq *rq)
9947 {
9948 	bool decayed = false, done = true;
9949 
9950 	update_blocked_load_tick(rq);
9951 
9952 	decayed |= __update_blocked_others(rq, &done);
9953 	decayed |= __update_blocked_fair(rq, &done);
9954 
9955 	update_has_blocked_load_status(rq, !done);
9956 	if (decayed)
9957 		cpufreq_update_util(rq, 0);
9958 }
9959 
9960 static void sched_balance_update_blocked_averages(int cpu)
9961 {
9962 	struct rq *rq = cpu_rq(cpu);
9963 
9964 	guard(rq_lock_irqsave)(rq);
9965 	update_rq_clock(rq);
9966 	__sched_balance_update_blocked_averages(rq);
9967 }
9968 
9969 /********** Helpers for sched_balance_find_src_group ************************/
9970 
9971 /*
9972  * sg_lb_stats - stats of a sched_group required for load-balancing:
9973  */
9974 struct sg_lb_stats {
9975 	unsigned long avg_load;			/* Avg load            over the CPUs of the group */
9976 	unsigned long group_load;		/* Total load          over the CPUs of the group */
9977 	unsigned long group_capacity;		/* Capacity            over the CPUs of the group */
9978 	unsigned long group_util;		/* Total utilization   over the CPUs of the group */
9979 	unsigned long group_runnable;		/* Total runnable time over the CPUs of the group */
9980 	unsigned int sum_nr_running;		/* Nr of all tasks running in the group */
9981 	unsigned int sum_h_nr_running;		/* Nr of CFS tasks running in the group */
9982 	unsigned int idle_cpus;                 /* Nr of idle CPUs         in the group */
9983 	unsigned int group_weight;
9984 	enum group_type group_type;
9985 	unsigned int group_asym_packing;	/* Tasks should be moved to preferred CPU */
9986 	unsigned int group_smt_balance;		/* Task on busy SMT be moved */
9987 	unsigned long group_misfit_task_load;	/* A CPU has a task too big for its capacity */
9988 #ifdef CONFIG_NUMA_BALANCING
9989 	unsigned int nr_numa_running;
9990 	unsigned int nr_preferred_running;
9991 #endif
9992 };
9993 
9994 /*
9995  * sd_lb_stats - stats of a sched_domain required for load-balancing:
9996  */
9997 struct sd_lb_stats {
9998 	struct sched_group *busiest;		/* Busiest group in this sd */
9999 	struct sched_group *local;		/* Local group in this sd */
10000 	unsigned long total_load;		/* Total load of all groups in sd */
10001 	unsigned long total_capacity;		/* Total capacity of all groups in sd */
10002 	unsigned long avg_load;			/* Average load across all groups in sd */
10003 	unsigned int prefer_sibling;		/* Tasks should go to sibling first */
10004 
10005 	struct sg_lb_stats busiest_stat;	/* Statistics of the busiest group */
10006 	struct sg_lb_stats local_stat;		/* Statistics of the local group */
10007 };
10008 
10009 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
10010 {
10011 	/*
10012 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
10013 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10014 	 * We must however set busiest_stat::group_type and
10015 	 * busiest_stat::idle_cpus to the worst busiest group because
10016 	 * update_sd_pick_busiest() reads these before assignment.
10017 	 */
10018 	*sds = (struct sd_lb_stats){
10019 		.busiest = NULL,
10020 		.local = NULL,
10021 		.total_load = 0UL,
10022 		.total_capacity = 0UL,
10023 		.busiest_stat = {
10024 			.idle_cpus = UINT_MAX,
10025 			.group_type = group_has_spare,
10026 		},
10027 	};
10028 }
10029 
10030 static unsigned long scale_rt_capacity(int cpu)
10031 {
10032 	unsigned long max = get_actual_cpu_capacity(cpu);
10033 	struct rq *rq = cpu_rq(cpu);
10034 	unsigned long used, free;
10035 	unsigned long irq;
10036 
10037 	irq = cpu_util_irq(rq);
10038 
10039 	if (unlikely(irq >= max))
10040 		return 1;
10041 
10042 	/*
10043 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10044 	 * (running and not running) with weights 0 and 1024 respectively.
10045 	 */
10046 	used = cpu_util_rt(rq);
10047 	used += cpu_util_dl(rq);
10048 
10049 	if (unlikely(used >= max))
10050 		return 1;
10051 
10052 	free = max - used;
10053 
10054 	return scale_irq_capacity(free, irq, max);
10055 }
10056 
10057 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10058 {
10059 	unsigned long capacity = scale_rt_capacity(cpu);
10060 	struct sched_group *sdg = sd->groups;
10061 
10062 	if (!capacity)
10063 		capacity = 1;
10064 
10065 	cpu_rq(cpu)->cpu_capacity = capacity;
10066 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10067 
10068 	sdg->sgc->capacity = capacity;
10069 	sdg->sgc->min_capacity = capacity;
10070 	sdg->sgc->max_capacity = capacity;
10071 }
10072 
10073 void update_group_capacity(struct sched_domain *sd, int cpu)
10074 {
10075 	struct sched_domain *child = sd->child;
10076 	struct sched_group *group, *sdg = sd->groups;
10077 	unsigned long capacity, min_capacity, max_capacity;
10078 	unsigned long interval;
10079 
10080 	interval = msecs_to_jiffies(sd->balance_interval);
10081 	interval = clamp(interval, 1UL, max_load_balance_interval);
10082 	sdg->sgc->next_update = jiffies + interval;
10083 
10084 	if (!child) {
10085 		update_cpu_capacity(sd, cpu);
10086 		return;
10087 	}
10088 
10089 	capacity = 0;
10090 	min_capacity = ULONG_MAX;
10091 	max_capacity = 0;
10092 
10093 	if (child->flags & SD_NUMA) {
10094 		/*
10095 		 * SD_NUMA domains cannot assume that child groups
10096 		 * span the current group.
10097 		 */
10098 
10099 		for_each_cpu(cpu, sched_group_span(sdg)) {
10100 			unsigned long cpu_cap = capacity_of(cpu);
10101 
10102 			capacity += cpu_cap;
10103 			min_capacity = min(cpu_cap, min_capacity);
10104 			max_capacity = max(cpu_cap, max_capacity);
10105 		}
10106 	} else  {
10107 		/*
10108 		 * !SD_NUMA domains can assume that child groups
10109 		 * span the current group.
10110 		 */
10111 
10112 		group = child->groups;
10113 		do {
10114 			struct sched_group_capacity *sgc = group->sgc;
10115 
10116 			capacity += sgc->capacity;
10117 			min_capacity = min(sgc->min_capacity, min_capacity);
10118 			max_capacity = max(sgc->max_capacity, max_capacity);
10119 			group = group->next;
10120 		} while (group != child->groups);
10121 	}
10122 
10123 	sdg->sgc->capacity = capacity;
10124 	sdg->sgc->min_capacity = min_capacity;
10125 	sdg->sgc->max_capacity = max_capacity;
10126 }
10127 
10128 /*
10129  * Check whether the capacity of the rq has been noticeably reduced by side
10130  * activity. The imbalance_pct is used for the threshold.
10131  * Return true is the capacity is reduced
10132  */
10133 static inline int
10134 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10135 {
10136 	return ((rq->cpu_capacity * sd->imbalance_pct) <
10137 				(arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10138 }
10139 
10140 /* Check if the rq has a misfit task */
10141 static inline bool check_misfit_status(struct rq *rq)
10142 {
10143 	return rq->misfit_task_load;
10144 }
10145 
10146 /*
10147  * Group imbalance indicates (and tries to solve) the problem where balancing
10148  * groups is inadequate due to ->cpus_ptr constraints.
10149  *
10150  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10151  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10152  * Something like:
10153  *
10154  *	{ 0 1 2 3 } { 4 5 6 7 }
10155  *	        *     * * *
10156  *
10157  * If we were to balance group-wise we'd place two tasks in the first group and
10158  * two tasks in the second group. Clearly this is undesired as it will overload
10159  * cpu 3 and leave one of the CPUs in the second group unused.
10160  *
10161  * The current solution to this issue is detecting the skew in the first group
10162  * by noticing the lower domain failed to reach balance and had difficulty
10163  * moving tasks due to affinity constraints.
10164  *
10165  * When this is so detected; this group becomes a candidate for busiest; see
10166  * update_sd_pick_busiest(). And calculate_imbalance() and
10167  * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10168  * to create an effective group imbalance.
10169  *
10170  * This is a somewhat tricky proposition since the next run might not find the
10171  * group imbalance and decide the groups need to be balanced again. A most
10172  * subtle and fragile situation.
10173  */
10174 
10175 static inline int sg_imbalanced(struct sched_group *group)
10176 {
10177 	return group->sgc->imbalance;
10178 }
10179 
10180 /*
10181  * group_has_capacity returns true if the group has spare capacity that could
10182  * be used by some tasks.
10183  * We consider that a group has spare capacity if the number of task is
10184  * smaller than the number of CPUs or if the utilization is lower than the
10185  * available capacity for CFS tasks.
10186  * For the latter, we use a threshold to stabilize the state, to take into
10187  * account the variance of the tasks' load and to return true if the available
10188  * capacity in meaningful for the load balancer.
10189  * As an example, an available capacity of 1% can appear but it doesn't make
10190  * any benefit for the load balance.
10191  */
10192 static inline bool
10193 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10194 {
10195 	if (sgs->sum_nr_running < sgs->group_weight)
10196 		return true;
10197 
10198 	if ((sgs->group_capacity * imbalance_pct) <
10199 			(sgs->group_runnable * 100))
10200 		return false;
10201 
10202 	if ((sgs->group_capacity * 100) >
10203 			(sgs->group_util * imbalance_pct))
10204 		return true;
10205 
10206 	return false;
10207 }
10208 
10209 /*
10210  *  group_is_overloaded returns true if the group has more tasks than it can
10211  *  handle.
10212  *  group_is_overloaded is not equals to !group_has_capacity because a group
10213  *  with the exact right number of tasks, has no more spare capacity but is not
10214  *  overloaded so both group_has_capacity and group_is_overloaded return
10215  *  false.
10216  */
10217 static inline bool
10218 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10219 {
10220 	if (sgs->sum_nr_running <= sgs->group_weight)
10221 		return false;
10222 
10223 	if ((sgs->group_capacity * 100) <
10224 			(sgs->group_util * imbalance_pct))
10225 		return true;
10226 
10227 	if ((sgs->group_capacity * imbalance_pct) <
10228 			(sgs->group_runnable * 100))
10229 		return true;
10230 
10231 	return false;
10232 }
10233 
10234 static inline enum
10235 group_type group_classify(unsigned int imbalance_pct,
10236 			  struct sched_group *group,
10237 			  struct sg_lb_stats *sgs)
10238 {
10239 	if (group_is_overloaded(imbalance_pct, sgs))
10240 		return group_overloaded;
10241 
10242 	if (sg_imbalanced(group))
10243 		return group_imbalanced;
10244 
10245 	if (sgs->group_asym_packing)
10246 		return group_asym_packing;
10247 
10248 	if (sgs->group_smt_balance)
10249 		return group_smt_balance;
10250 
10251 	if (sgs->group_misfit_task_load)
10252 		return group_misfit_task;
10253 
10254 	if (!group_has_capacity(imbalance_pct, sgs))
10255 		return group_fully_busy;
10256 
10257 	return group_has_spare;
10258 }
10259 
10260 /**
10261  * sched_use_asym_prio - Check whether asym_packing priority must be used
10262  * @sd:		The scheduling domain of the load balancing
10263  * @cpu:	A CPU
10264  *
10265  * Always use CPU priority when balancing load between SMT siblings. When
10266  * balancing load between cores, it is not sufficient that @cpu is idle. Only
10267  * use CPU priority if the whole core is idle.
10268  *
10269  * Returns: True if the priority of @cpu must be followed. False otherwise.
10270  */
10271 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10272 {
10273 	if (!(sd->flags & SD_ASYM_PACKING))
10274 		return false;
10275 
10276 	if (!sched_smt_active())
10277 		return true;
10278 
10279 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10280 }
10281 
10282 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10283 {
10284 	/*
10285 	 * First check if @dst_cpu can do asym_packing load balance. Only do it
10286 	 * if it has higher priority than @src_cpu.
10287 	 */
10288 	return sched_use_asym_prio(sd, dst_cpu) &&
10289 		sched_asym_prefer(dst_cpu, src_cpu);
10290 }
10291 
10292 /**
10293  * sched_group_asym - Check if the destination CPU can do asym_packing balance
10294  * @env:	The load balancing environment
10295  * @sgs:	Load-balancing statistics of the candidate busiest group
10296  * @group:	The candidate busiest group
10297  *
10298  * @env::dst_cpu can do asym_packing if it has higher priority than the
10299  * preferred CPU of @group.
10300  *
10301  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10302  * otherwise.
10303  */
10304 static inline bool
10305 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10306 {
10307 	/*
10308 	 * CPU priorities do not make sense for SMT cores with more than one
10309 	 * busy sibling.
10310 	 */
10311 	if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10312 	    (sgs->group_weight - sgs->idle_cpus != 1))
10313 		return false;
10314 
10315 	return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
10316 }
10317 
10318 /* One group has more than one SMT CPU while the other group does not */
10319 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10320 				    struct sched_group *sg2)
10321 {
10322 	if (!sg1 || !sg2)
10323 		return false;
10324 
10325 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10326 		(sg2->flags & SD_SHARE_CPUCAPACITY);
10327 }
10328 
10329 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10330 			       struct sched_group *group)
10331 {
10332 	if (!env->idle)
10333 		return false;
10334 
10335 	/*
10336 	 * For SMT source group, it is better to move a task
10337 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10338 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10339 	 * will not be on.
10340 	 */
10341 	if (group->flags & SD_SHARE_CPUCAPACITY &&
10342 	    sgs->sum_h_nr_running > 1)
10343 		return true;
10344 
10345 	return false;
10346 }
10347 
10348 static inline long sibling_imbalance(struct lb_env *env,
10349 				    struct sd_lb_stats *sds,
10350 				    struct sg_lb_stats *busiest,
10351 				    struct sg_lb_stats *local)
10352 {
10353 	int ncores_busiest, ncores_local;
10354 	long imbalance;
10355 
10356 	if (!env->idle || !busiest->sum_nr_running)
10357 		return 0;
10358 
10359 	ncores_busiest = sds->busiest->cores;
10360 	ncores_local = sds->local->cores;
10361 
10362 	if (ncores_busiest == ncores_local) {
10363 		imbalance = busiest->sum_nr_running;
10364 		lsub_positive(&imbalance, local->sum_nr_running);
10365 		return imbalance;
10366 	}
10367 
10368 	/* Balance such that nr_running/ncores ratio are same on both groups */
10369 	imbalance = ncores_local * busiest->sum_nr_running;
10370 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10371 	/* Normalize imbalance and do rounding on normalization */
10372 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10373 	imbalance /= ncores_local + ncores_busiest;
10374 
10375 	/* Take advantage of resource in an empty sched group */
10376 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
10377 	    busiest->sum_nr_running > 1)
10378 		imbalance = 2;
10379 
10380 	return imbalance;
10381 }
10382 
10383 static inline bool
10384 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10385 {
10386 	/*
10387 	 * When there is more than 1 task, the group_overloaded case already
10388 	 * takes care of cpu with reduced capacity
10389 	 */
10390 	if (rq->cfs.h_nr_runnable != 1)
10391 		return false;
10392 
10393 	return check_cpu_capacity(rq, sd);
10394 }
10395 
10396 /**
10397  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10398  * @env: The load balancing environment.
10399  * @sds: Load-balancing data with statistics of the local group.
10400  * @group: sched_group whose statistics are to be updated.
10401  * @sgs: variable to hold the statistics for this group.
10402  * @sg_overloaded: sched_group is overloaded
10403  * @sg_overutilized: sched_group is overutilized
10404  */
10405 static inline void update_sg_lb_stats(struct lb_env *env,
10406 				      struct sd_lb_stats *sds,
10407 				      struct sched_group *group,
10408 				      struct sg_lb_stats *sgs,
10409 				      bool *sg_overloaded,
10410 				      bool *sg_overutilized)
10411 {
10412 	int i, nr_running, local_group, sd_flags = env->sd->flags;
10413 	bool balancing_at_rd = !env->sd->parent;
10414 
10415 	memset(sgs, 0, sizeof(*sgs));
10416 
10417 	local_group = group == sds->local;
10418 
10419 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10420 		struct rq *rq = cpu_rq(i);
10421 		unsigned long load = cpu_load(rq);
10422 
10423 		sgs->group_load += load;
10424 		sgs->group_util += cpu_util_cfs(i);
10425 		sgs->group_runnable += cpu_runnable(rq);
10426 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10427 
10428 		nr_running = rq->nr_running;
10429 		sgs->sum_nr_running += nr_running;
10430 
10431 		if (cpu_overutilized(i))
10432 			*sg_overutilized = 1;
10433 
10434 		/*
10435 		 * No need to call idle_cpu() if nr_running is not 0
10436 		 */
10437 		if (!nr_running && idle_cpu(i)) {
10438 			sgs->idle_cpus++;
10439 			/* Idle cpu can't have misfit task */
10440 			continue;
10441 		}
10442 
10443 		/* Overload indicator is only updated at root domain */
10444 		if (balancing_at_rd && nr_running > 1)
10445 			*sg_overloaded = 1;
10446 
10447 #ifdef CONFIG_NUMA_BALANCING
10448 		/* Only fbq_classify_group() uses this to classify NUMA groups */
10449 		if (sd_flags & SD_NUMA) {
10450 			sgs->nr_numa_running += rq->nr_numa_running;
10451 			sgs->nr_preferred_running += rq->nr_preferred_running;
10452 		}
10453 #endif
10454 		if (local_group)
10455 			continue;
10456 
10457 		if (sd_flags & SD_ASYM_CPUCAPACITY) {
10458 			/* Check for a misfit task on the cpu */
10459 			if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10460 				sgs->group_misfit_task_load = rq->misfit_task_load;
10461 				*sg_overloaded = 1;
10462 			}
10463 		} else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10464 			/* Check for a task running on a CPU with reduced capacity */
10465 			if (sgs->group_misfit_task_load < load)
10466 				sgs->group_misfit_task_load = load;
10467 		}
10468 	}
10469 
10470 	sgs->group_capacity = group->sgc->capacity;
10471 
10472 	sgs->group_weight = group->group_weight;
10473 
10474 	/* Check if dst CPU is idle and preferred to this group */
10475 	if (!local_group && env->idle && sgs->sum_h_nr_running &&
10476 	    sched_group_asym(env, sgs, group))
10477 		sgs->group_asym_packing = 1;
10478 
10479 	/* Check for loaded SMT group to be balanced to dst CPU */
10480 	if (!local_group && smt_balance(env, sgs, group))
10481 		sgs->group_smt_balance = 1;
10482 
10483 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10484 
10485 	/* Computing avg_load makes sense only when group is overloaded */
10486 	if (sgs->group_type == group_overloaded)
10487 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10488 				sgs->group_capacity;
10489 }
10490 
10491 /**
10492  * update_sd_pick_busiest - return 1 on busiest group
10493  * @env: The load balancing environment.
10494  * @sds: sched_domain statistics
10495  * @sg: sched_group candidate to be checked for being the busiest
10496  * @sgs: sched_group statistics
10497  *
10498  * Determine if @sg is a busier group than the previously selected
10499  * busiest group.
10500  *
10501  * Return: %true if @sg is a busier group than the previously selected
10502  * busiest group. %false otherwise.
10503  */
10504 static bool update_sd_pick_busiest(struct lb_env *env,
10505 				   struct sd_lb_stats *sds,
10506 				   struct sched_group *sg,
10507 				   struct sg_lb_stats *sgs)
10508 {
10509 	struct sg_lb_stats *busiest = &sds->busiest_stat;
10510 
10511 	/* Make sure that there is at least one task to pull */
10512 	if (!sgs->sum_h_nr_running)
10513 		return false;
10514 
10515 	/*
10516 	 * Don't try to pull misfit tasks we can't help.
10517 	 * We can use max_capacity here as reduction in capacity on some
10518 	 * CPUs in the group should either be possible to resolve
10519 	 * internally or be covered by avg_load imbalance (eventually).
10520 	 */
10521 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10522 	    (sgs->group_type == group_misfit_task) &&
10523 	    (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10524 	     sds->local_stat.group_type != group_has_spare))
10525 		return false;
10526 
10527 	if (sgs->group_type > busiest->group_type)
10528 		return true;
10529 
10530 	if (sgs->group_type < busiest->group_type)
10531 		return false;
10532 
10533 	/*
10534 	 * The candidate and the current busiest group are the same type of
10535 	 * group. Let check which one is the busiest according to the type.
10536 	 */
10537 
10538 	switch (sgs->group_type) {
10539 	case group_overloaded:
10540 		/* Select the overloaded group with highest avg_load. */
10541 		return sgs->avg_load > busiest->avg_load;
10542 
10543 	case group_imbalanced:
10544 		/*
10545 		 * Select the 1st imbalanced group as we don't have any way to
10546 		 * choose one more than another.
10547 		 */
10548 		return false;
10549 
10550 	case group_asym_packing:
10551 		/* Prefer to move from lowest priority CPU's work */
10552 		return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
10553 					 READ_ONCE(sg->asym_prefer_cpu));
10554 
10555 	case group_misfit_task:
10556 		/*
10557 		 * If we have more than one misfit sg go with the biggest
10558 		 * misfit.
10559 		 */
10560 		return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10561 
10562 	case group_smt_balance:
10563 		/*
10564 		 * Check if we have spare CPUs on either SMT group to
10565 		 * choose has spare or fully busy handling.
10566 		 */
10567 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10568 			goto has_spare;
10569 
10570 		fallthrough;
10571 
10572 	case group_fully_busy:
10573 		/*
10574 		 * Select the fully busy group with highest avg_load. In
10575 		 * theory, there is no need to pull task from such kind of
10576 		 * group because tasks have all compute capacity that they need
10577 		 * but we can still improve the overall throughput by reducing
10578 		 * contention when accessing shared HW resources.
10579 		 *
10580 		 * XXX for now avg_load is not computed and always 0 so we
10581 		 * select the 1st one, except if @sg is composed of SMT
10582 		 * siblings.
10583 		 */
10584 
10585 		if (sgs->avg_load < busiest->avg_load)
10586 			return false;
10587 
10588 		if (sgs->avg_load == busiest->avg_load) {
10589 			/*
10590 			 * SMT sched groups need more help than non-SMT groups.
10591 			 * If @sg happens to also be SMT, either choice is good.
10592 			 */
10593 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10594 				return false;
10595 		}
10596 
10597 		break;
10598 
10599 	case group_has_spare:
10600 		/*
10601 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10602 		 * as we do not want to pull task off SMT core with one task
10603 		 * and make the core idle.
10604 		 */
10605 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10606 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10607 				return false;
10608 			else
10609 				return true;
10610 		}
10611 has_spare:
10612 
10613 		/*
10614 		 * Select not overloaded group with lowest number of idle CPUs
10615 		 * and highest number of running tasks. We could also compare
10616 		 * the spare capacity which is more stable but it can end up
10617 		 * that the group has less spare capacity but finally more idle
10618 		 * CPUs which means less opportunity to pull tasks.
10619 		 */
10620 		if (sgs->idle_cpus > busiest->idle_cpus)
10621 			return false;
10622 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10623 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
10624 			return false;
10625 
10626 		break;
10627 	}
10628 
10629 	/*
10630 	 * Candidate sg has no more than one task per CPU and has higher
10631 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10632 	 * throughput. Maximize throughput, power/energy consequences are not
10633 	 * considered.
10634 	 */
10635 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10636 	    (sgs->group_type <= group_fully_busy) &&
10637 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10638 		return false;
10639 
10640 	return true;
10641 }
10642 
10643 #ifdef CONFIG_NUMA_BALANCING
10644 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10645 {
10646 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10647 		return regular;
10648 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10649 		return remote;
10650 	return all;
10651 }
10652 
10653 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10654 {
10655 	if (rq->nr_running > rq->nr_numa_running)
10656 		return regular;
10657 	if (rq->nr_running > rq->nr_preferred_running)
10658 		return remote;
10659 	return all;
10660 }
10661 #else /* !CONFIG_NUMA_BALANCING: */
10662 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10663 {
10664 	return all;
10665 }
10666 
10667 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10668 {
10669 	return regular;
10670 }
10671 #endif /* !CONFIG_NUMA_BALANCING */
10672 
10673 
10674 struct sg_lb_stats;
10675 
10676 /*
10677  * task_running_on_cpu - return 1 if @p is running on @cpu.
10678  */
10679 
10680 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10681 {
10682 	/* Task has no contribution or is new */
10683 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10684 		return 0;
10685 
10686 	if (task_on_rq_queued(p))
10687 		return 1;
10688 
10689 	return 0;
10690 }
10691 
10692 /**
10693  * idle_cpu_without - would a given CPU be idle without p ?
10694  * @cpu: the processor on which idleness is tested.
10695  * @p: task which should be ignored.
10696  *
10697  * Return: 1 if the CPU would be idle. 0 otherwise.
10698  */
10699 static int idle_cpu_without(int cpu, struct task_struct *p)
10700 {
10701 	struct rq *rq = cpu_rq(cpu);
10702 
10703 	if (rq->curr != rq->idle && rq->curr != p)
10704 		return 0;
10705 
10706 	/*
10707 	 * rq->nr_running can't be used but an updated version without the
10708 	 * impact of p on cpu must be used instead. The updated nr_running
10709 	 * be computed and tested before calling idle_cpu_without().
10710 	 */
10711 
10712 	if (rq->ttwu_pending)
10713 		return 0;
10714 
10715 	return 1;
10716 }
10717 
10718 /*
10719  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10720  * @sd: The sched_domain level to look for idlest group.
10721  * @group: sched_group whose statistics are to be updated.
10722  * @sgs: variable to hold the statistics for this group.
10723  * @p: The task for which we look for the idlest group/CPU.
10724  */
10725 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10726 					  struct sched_group *group,
10727 					  struct sg_lb_stats *sgs,
10728 					  struct task_struct *p)
10729 {
10730 	int i, nr_running;
10731 
10732 	memset(sgs, 0, sizeof(*sgs));
10733 
10734 	/* Assume that task can't fit any CPU of the group */
10735 	if (sd->flags & SD_ASYM_CPUCAPACITY)
10736 		sgs->group_misfit_task_load = 1;
10737 
10738 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
10739 		struct rq *rq = cpu_rq(i);
10740 		unsigned int local;
10741 
10742 		sgs->group_load += cpu_load_without(rq, p);
10743 		sgs->group_util += cpu_util_without(i, p);
10744 		sgs->group_runnable += cpu_runnable_without(rq, p);
10745 		local = task_running_on_cpu(i, p);
10746 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
10747 
10748 		nr_running = rq->nr_running - local;
10749 		sgs->sum_nr_running += nr_running;
10750 
10751 		/*
10752 		 * No need to call idle_cpu_without() if nr_running is not 0
10753 		 */
10754 		if (!nr_running && idle_cpu_without(i, p))
10755 			sgs->idle_cpus++;
10756 
10757 		/* Check if task fits in the CPU */
10758 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
10759 		    sgs->group_misfit_task_load &&
10760 		    task_fits_cpu(p, i))
10761 			sgs->group_misfit_task_load = 0;
10762 
10763 	}
10764 
10765 	sgs->group_capacity = group->sgc->capacity;
10766 
10767 	sgs->group_weight = group->group_weight;
10768 
10769 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10770 
10771 	/*
10772 	 * Computing avg_load makes sense only when group is fully busy or
10773 	 * overloaded
10774 	 */
10775 	if (sgs->group_type == group_fully_busy ||
10776 		sgs->group_type == group_overloaded)
10777 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10778 				sgs->group_capacity;
10779 }
10780 
10781 static bool update_pick_idlest(struct sched_group *idlest,
10782 			       struct sg_lb_stats *idlest_sgs,
10783 			       struct sched_group *group,
10784 			       struct sg_lb_stats *sgs)
10785 {
10786 	if (sgs->group_type < idlest_sgs->group_type)
10787 		return true;
10788 
10789 	if (sgs->group_type > idlest_sgs->group_type)
10790 		return false;
10791 
10792 	/*
10793 	 * The candidate and the current idlest group are the same type of
10794 	 * group. Let check which one is the idlest according to the type.
10795 	 */
10796 
10797 	switch (sgs->group_type) {
10798 	case group_overloaded:
10799 	case group_fully_busy:
10800 		/* Select the group with lowest avg_load. */
10801 		if (idlest_sgs->avg_load <= sgs->avg_load)
10802 			return false;
10803 		break;
10804 
10805 	case group_imbalanced:
10806 	case group_asym_packing:
10807 	case group_smt_balance:
10808 		/* Those types are not used in the slow wakeup path */
10809 		return false;
10810 
10811 	case group_misfit_task:
10812 		/* Select group with the highest max capacity */
10813 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10814 			return false;
10815 		break;
10816 
10817 	case group_has_spare:
10818 		/* Select group with most idle CPUs */
10819 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10820 			return false;
10821 
10822 		/* Select group with lowest group_util */
10823 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10824 			idlest_sgs->group_util <= sgs->group_util)
10825 			return false;
10826 
10827 		break;
10828 	}
10829 
10830 	return true;
10831 }
10832 
10833 /*
10834  * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
10835  * domain.
10836  *
10837  * Assumes p is allowed on at least one CPU in sd.
10838  */
10839 static struct sched_group *
10840 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10841 {
10842 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10843 	struct sg_lb_stats local_sgs, tmp_sgs;
10844 	struct sg_lb_stats *sgs;
10845 	unsigned long imbalance;
10846 	struct sg_lb_stats idlest_sgs = {
10847 			.avg_load = UINT_MAX,
10848 			.group_type = group_overloaded,
10849 	};
10850 
10851 	do {
10852 		int local_group;
10853 
10854 		/* Skip over this group if it has no CPUs allowed */
10855 		if (!cpumask_intersects(sched_group_span(group),
10856 					p->cpus_ptr))
10857 			continue;
10858 
10859 		/* Skip over this group if no cookie matched */
10860 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10861 			continue;
10862 
10863 		local_group = cpumask_test_cpu(this_cpu,
10864 					       sched_group_span(group));
10865 
10866 		if (local_group) {
10867 			sgs = &local_sgs;
10868 			local = group;
10869 		} else {
10870 			sgs = &tmp_sgs;
10871 		}
10872 
10873 		update_sg_wakeup_stats(sd, group, sgs, p);
10874 
10875 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10876 			idlest = group;
10877 			idlest_sgs = *sgs;
10878 		}
10879 
10880 	} while (group = group->next, group != sd->groups);
10881 
10882 
10883 	/* There is no idlest group to push tasks to */
10884 	if (!idlest)
10885 		return NULL;
10886 
10887 	/* The local group has been skipped because of CPU affinity */
10888 	if (!local)
10889 		return idlest;
10890 
10891 	/*
10892 	 * If the local group is idler than the selected idlest group
10893 	 * don't try and push the task.
10894 	 */
10895 	if (local_sgs.group_type < idlest_sgs.group_type)
10896 		return NULL;
10897 
10898 	/*
10899 	 * If the local group is busier than the selected idlest group
10900 	 * try and push the task.
10901 	 */
10902 	if (local_sgs.group_type > idlest_sgs.group_type)
10903 		return idlest;
10904 
10905 	switch (local_sgs.group_type) {
10906 	case group_overloaded:
10907 	case group_fully_busy:
10908 
10909 		/* Calculate allowed imbalance based on load */
10910 		imbalance = scale_load_down(NICE_0_LOAD) *
10911 				(sd->imbalance_pct-100) / 100;
10912 
10913 		/*
10914 		 * When comparing groups across NUMA domains, it's possible for
10915 		 * the local domain to be very lightly loaded relative to the
10916 		 * remote domains but "imbalance" skews the comparison making
10917 		 * remote CPUs look much more favourable. When considering
10918 		 * cross-domain, add imbalance to the load on the remote node
10919 		 * and consider staying local.
10920 		 */
10921 
10922 		if ((sd->flags & SD_NUMA) &&
10923 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10924 			return NULL;
10925 
10926 		/*
10927 		 * If the local group is less loaded than the selected
10928 		 * idlest group don't try and push any tasks.
10929 		 */
10930 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10931 			return NULL;
10932 
10933 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10934 			return NULL;
10935 		break;
10936 
10937 	case group_imbalanced:
10938 	case group_asym_packing:
10939 	case group_smt_balance:
10940 		/* Those type are not used in the slow wakeup path */
10941 		return NULL;
10942 
10943 	case group_misfit_task:
10944 		/* Select group with the highest max capacity */
10945 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10946 			return NULL;
10947 		break;
10948 
10949 	case group_has_spare:
10950 #ifdef CONFIG_NUMA
10951 		if (sd->flags & SD_NUMA) {
10952 			int imb_numa_nr = sd->imb_numa_nr;
10953 #ifdef CONFIG_NUMA_BALANCING
10954 			int idlest_cpu;
10955 			/*
10956 			 * If there is spare capacity at NUMA, try to select
10957 			 * the preferred node
10958 			 */
10959 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10960 				return NULL;
10961 
10962 			idlest_cpu = cpumask_first(sched_group_span(idlest));
10963 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10964 				return idlest;
10965 #endif /* CONFIG_NUMA_BALANCING */
10966 			/*
10967 			 * Otherwise, keep the task close to the wakeup source
10968 			 * and improve locality if the number of running tasks
10969 			 * would remain below threshold where an imbalance is
10970 			 * allowed while accounting for the possibility the
10971 			 * task is pinned to a subset of CPUs. If there is a
10972 			 * real need of migration, periodic load balance will
10973 			 * take care of it.
10974 			 */
10975 			if (p->nr_cpus_allowed != NR_CPUS) {
10976 				unsigned int w = cpumask_weight_and(p->cpus_ptr,
10977 								sched_group_span(local));
10978 				imb_numa_nr = min(w, sd->imb_numa_nr);
10979 			}
10980 
10981 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10982 			if (!adjust_numa_imbalance(imbalance,
10983 						   local_sgs.sum_nr_running + 1,
10984 						   imb_numa_nr)) {
10985 				return NULL;
10986 			}
10987 		}
10988 #endif /* CONFIG_NUMA */
10989 
10990 		/*
10991 		 * Select group with highest number of idle CPUs. We could also
10992 		 * compare the utilization which is more stable but it can end
10993 		 * up that the group has less spare capacity but finally more
10994 		 * idle CPUs which means more opportunity to run task.
10995 		 */
10996 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10997 			return NULL;
10998 		break;
10999 	}
11000 
11001 	return idlest;
11002 }
11003 
11004 static void update_idle_cpu_scan(struct lb_env *env,
11005 				 unsigned long sum_util)
11006 {
11007 	struct sched_domain_shared *sd_share;
11008 	int llc_weight, pct;
11009 	u64 x, y, tmp;
11010 	/*
11011 	 * Update the number of CPUs to scan in LLC domain, which could
11012 	 * be used as a hint in select_idle_cpu(). The update of sd_share
11013 	 * could be expensive because it is within a shared cache line.
11014 	 * So the write of this hint only occurs during periodic load
11015 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11016 	 * can fire way more frequently than the former.
11017 	 */
11018 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11019 		return;
11020 
11021 	llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
11022 	if (env->sd->span_weight != llc_weight)
11023 		return;
11024 
11025 	sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, env->dst_cpu));
11026 	if (!sd_share)
11027 		return;
11028 
11029 	/*
11030 	 * The number of CPUs to search drops as sum_util increases, when
11031 	 * sum_util hits 85% or above, the scan stops.
11032 	 * The reason to choose 85% as the threshold is because this is the
11033 	 * imbalance_pct(117) when a LLC sched group is overloaded.
11034 	 *
11035 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
11036 	 * and y'= y / SCHED_CAPACITY_SCALE
11037 	 *
11038 	 * x is the ratio of sum_util compared to the CPU capacity:
11039 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11040 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
11041 	 * and the number of CPUs to scan is calculated by:
11042 	 *
11043 	 * nr_scan = llc_weight * y'                                    [2]
11044 	 *
11045 	 * When x hits the threshold of overloaded, AKA, when
11046 	 * x = 100 / pct, y drops to 0. According to [1],
11047 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11048 	 *
11049 	 * Scale x by SCHED_CAPACITY_SCALE:
11050 	 * x' = sum_util / llc_weight;                                  [3]
11051 	 *
11052 	 * and finally [1] becomes:
11053 	 * y = SCHED_CAPACITY_SCALE -
11054 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
11055 	 *
11056 	 */
11057 	/* equation [3] */
11058 	x = sum_util;
11059 	do_div(x, llc_weight);
11060 
11061 	/* equation [4] */
11062 	pct = env->sd->imbalance_pct;
11063 	tmp = x * x * pct * pct;
11064 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11065 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11066 	y = SCHED_CAPACITY_SCALE - tmp;
11067 
11068 	/* equation [2] */
11069 	y *= llc_weight;
11070 	do_div(y, SCHED_CAPACITY_SCALE);
11071 	if ((int)y != sd_share->nr_idle_scan)
11072 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11073 }
11074 
11075 /**
11076  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11077  * @env: The load balancing environment.
11078  * @sds: variable to hold the statistics for this sched_domain.
11079  */
11080 
11081 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11082 {
11083 	struct sched_group *sg = env->sd->groups;
11084 	struct sg_lb_stats *local = &sds->local_stat;
11085 	struct sg_lb_stats tmp_sgs;
11086 	unsigned long sum_util = 0;
11087 	bool sg_overloaded = 0, sg_overutilized = 0;
11088 
11089 	do {
11090 		struct sg_lb_stats *sgs = &tmp_sgs;
11091 		int local_group;
11092 
11093 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11094 		if (local_group) {
11095 			sds->local = sg;
11096 			sgs = local;
11097 
11098 			if (env->idle != CPU_NEWLY_IDLE ||
11099 			    time_after_eq(jiffies, sg->sgc->next_update))
11100 				update_group_capacity(env->sd, env->dst_cpu);
11101 		}
11102 
11103 		update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11104 
11105 		if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11106 			sds->busiest = sg;
11107 			sds->busiest_stat = *sgs;
11108 		}
11109 
11110 		/* Now, start updating sd_lb_stats */
11111 		sds->total_load += sgs->group_load;
11112 		sds->total_capacity += sgs->group_capacity;
11113 
11114 		sum_util += sgs->group_util;
11115 		sg = sg->next;
11116 	} while (sg != env->sd->groups);
11117 
11118 	/*
11119 	 * Indicate that the child domain of the busiest group prefers tasks
11120 	 * go to a child's sibling domains first. NB the flags of a sched group
11121 	 * are those of the child domain.
11122 	 */
11123 	if (sds->busiest)
11124 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11125 
11126 
11127 	if (env->sd->flags & SD_NUMA)
11128 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11129 
11130 	if (!env->sd->parent) {
11131 		/* update overload indicator if we are at root domain */
11132 		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11133 
11134 		/* Update over-utilization (tipping point, U >= 0) indicator */
11135 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11136 	} else if (sg_overutilized) {
11137 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11138 	}
11139 
11140 	update_idle_cpu_scan(env, sum_util);
11141 }
11142 
11143 /**
11144  * calculate_imbalance - Calculate the amount of imbalance present within the
11145  *			 groups of a given sched_domain during load balance.
11146  * @env: load balance environment
11147  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11148  */
11149 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11150 {
11151 	struct sg_lb_stats *local, *busiest;
11152 
11153 	local = &sds->local_stat;
11154 	busiest = &sds->busiest_stat;
11155 
11156 	if (busiest->group_type == group_misfit_task) {
11157 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11158 			/* Set imbalance to allow misfit tasks to be balanced. */
11159 			env->migration_type = migrate_misfit;
11160 			env->imbalance = 1;
11161 		} else {
11162 			/*
11163 			 * Set load imbalance to allow moving task from cpu
11164 			 * with reduced capacity.
11165 			 */
11166 			env->migration_type = migrate_load;
11167 			env->imbalance = busiest->group_misfit_task_load;
11168 		}
11169 		return;
11170 	}
11171 
11172 	if (busiest->group_type == group_asym_packing) {
11173 		/*
11174 		 * In case of asym capacity, we will try to migrate all load to
11175 		 * the preferred CPU.
11176 		 */
11177 		env->migration_type = migrate_task;
11178 		env->imbalance = busiest->sum_h_nr_running;
11179 		return;
11180 	}
11181 
11182 	if (busiest->group_type == group_smt_balance) {
11183 		/* Reduce number of tasks sharing CPU capacity */
11184 		env->migration_type = migrate_task;
11185 		env->imbalance = 1;
11186 		return;
11187 	}
11188 
11189 	if (busiest->group_type == group_imbalanced) {
11190 		/*
11191 		 * In the group_imb case we cannot rely on group-wide averages
11192 		 * to ensure CPU-load equilibrium, try to move any task to fix
11193 		 * the imbalance. The next load balance will take care of
11194 		 * balancing back the system.
11195 		 */
11196 		env->migration_type = migrate_task;
11197 		env->imbalance = 1;
11198 		return;
11199 	}
11200 
11201 	/*
11202 	 * Try to use spare capacity of local group without overloading it or
11203 	 * emptying busiest.
11204 	 */
11205 	if (local->group_type == group_has_spare) {
11206 		if ((busiest->group_type > group_fully_busy) &&
11207 		    !(env->sd->flags & SD_SHARE_LLC)) {
11208 			/*
11209 			 * If busiest is overloaded, try to fill spare
11210 			 * capacity. This might end up creating spare capacity
11211 			 * in busiest or busiest still being overloaded but
11212 			 * there is no simple way to directly compute the
11213 			 * amount of load to migrate in order to balance the
11214 			 * system.
11215 			 */
11216 			env->migration_type = migrate_util;
11217 			env->imbalance = max(local->group_capacity, local->group_util) -
11218 					 local->group_util;
11219 
11220 			/*
11221 			 * In some cases, the group's utilization is max or even
11222 			 * higher than capacity because of migrations but the
11223 			 * local CPU is (newly) idle. There is at least one
11224 			 * waiting task in this overloaded busiest group. Let's
11225 			 * try to pull it.
11226 			 */
11227 			if (env->idle && env->imbalance == 0) {
11228 				env->migration_type = migrate_task;
11229 				env->imbalance = 1;
11230 			}
11231 
11232 			return;
11233 		}
11234 
11235 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
11236 			/*
11237 			 * When prefer sibling, evenly spread running tasks on
11238 			 * groups.
11239 			 */
11240 			env->migration_type = migrate_task;
11241 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
11242 		} else {
11243 
11244 			/*
11245 			 * If there is no overload, we just want to even the number of
11246 			 * idle CPUs.
11247 			 */
11248 			env->migration_type = migrate_task;
11249 			env->imbalance = max_t(long, 0,
11250 					       (local->idle_cpus - busiest->idle_cpus));
11251 		}
11252 
11253 #ifdef CONFIG_NUMA
11254 		/* Consider allowing a small imbalance between NUMA groups */
11255 		if (env->sd->flags & SD_NUMA) {
11256 			env->imbalance = adjust_numa_imbalance(env->imbalance,
11257 							       local->sum_nr_running + 1,
11258 							       env->sd->imb_numa_nr);
11259 		}
11260 #endif
11261 
11262 		/* Number of tasks to move to restore balance */
11263 		env->imbalance >>= 1;
11264 
11265 		return;
11266 	}
11267 
11268 	/*
11269 	 * Local is fully busy but has to take more load to relieve the
11270 	 * busiest group
11271 	 */
11272 	if (local->group_type < group_overloaded) {
11273 		/*
11274 		 * Local will become overloaded so the avg_load metrics are
11275 		 * finally needed.
11276 		 */
11277 
11278 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11279 				  local->group_capacity;
11280 
11281 		/*
11282 		 * If the local group is more loaded than the selected
11283 		 * busiest group don't try to pull any tasks.
11284 		 */
11285 		if (local->avg_load >= busiest->avg_load) {
11286 			env->imbalance = 0;
11287 			return;
11288 		}
11289 
11290 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11291 				sds->total_capacity;
11292 
11293 		/*
11294 		 * If the local group is more loaded than the average system
11295 		 * load, don't try to pull any tasks.
11296 		 */
11297 		if (local->avg_load >= sds->avg_load) {
11298 			env->imbalance = 0;
11299 			return;
11300 		}
11301 
11302 	}
11303 
11304 	/*
11305 	 * Both group are or will become overloaded and we're trying to get all
11306 	 * the CPUs to the average_load, so we don't want to push ourselves
11307 	 * above the average load, nor do we wish to reduce the max loaded CPU
11308 	 * below the average load. At the same time, we also don't want to
11309 	 * reduce the group load below the group capacity. Thus we look for
11310 	 * the minimum possible imbalance.
11311 	 */
11312 	env->migration_type = migrate_load;
11313 	env->imbalance = min(
11314 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11315 		(sds->avg_load - local->avg_load) * local->group_capacity
11316 	) / SCHED_CAPACITY_SCALE;
11317 }
11318 
11319 /******* sched_balance_find_src_group() helpers end here *********************/
11320 
11321 /*
11322  * Decision matrix according to the local and busiest group type:
11323  *
11324  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11325  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
11326  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
11327  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
11328  * asym_packing     force     force      N/A    N/A  force      force
11329  * imbalanced       force     force      N/A    N/A  force      force
11330  * overloaded       force     force      N/A    N/A  force      avg_load
11331  *
11332  * N/A :      Not Applicable because already filtered while updating
11333  *            statistics.
11334  * balanced : The system is balanced for these 2 groups.
11335  * force :    Calculate the imbalance as load migration is probably needed.
11336  * avg_load : Only if imbalance is significant enough.
11337  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
11338  *            different in groups.
11339  */
11340 
11341 /**
11342  * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11343  * if there is an imbalance.
11344  * @env: The load balancing environment.
11345  *
11346  * Also calculates the amount of runnable load which should be moved
11347  * to restore balance.
11348  *
11349  * Return:	- The busiest group if imbalance exists.
11350  */
11351 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11352 {
11353 	struct sg_lb_stats *local, *busiest;
11354 	struct sd_lb_stats sds;
11355 
11356 	init_sd_lb_stats(&sds);
11357 
11358 	/*
11359 	 * Compute the various statistics relevant for load balancing at
11360 	 * this level.
11361 	 */
11362 	update_sd_lb_stats(env, &sds);
11363 
11364 	/* There is no busy sibling group to pull tasks from */
11365 	if (!sds.busiest)
11366 		goto out_balanced;
11367 
11368 	busiest = &sds.busiest_stat;
11369 
11370 	/* Misfit tasks should be dealt with regardless of the avg load */
11371 	if (busiest->group_type == group_misfit_task)
11372 		goto force_balance;
11373 
11374 	if (!is_rd_overutilized(env->dst_rq->rd) &&
11375 	    rcu_dereference_all(env->dst_rq->rd->pd))
11376 		goto out_balanced;
11377 
11378 	/* ASYM feature bypasses nice load balance check */
11379 	if (busiest->group_type == group_asym_packing)
11380 		goto force_balance;
11381 
11382 	/*
11383 	 * If the busiest group is imbalanced the below checks don't
11384 	 * work because they assume all things are equal, which typically
11385 	 * isn't true due to cpus_ptr constraints and the like.
11386 	 */
11387 	if (busiest->group_type == group_imbalanced)
11388 		goto force_balance;
11389 
11390 	local = &sds.local_stat;
11391 	/*
11392 	 * If the local group is busier than the selected busiest group
11393 	 * don't try and pull any tasks.
11394 	 */
11395 	if (local->group_type > busiest->group_type)
11396 		goto out_balanced;
11397 
11398 	/*
11399 	 * When groups are overloaded, use the avg_load to ensure fairness
11400 	 * between tasks.
11401 	 */
11402 	if (local->group_type == group_overloaded) {
11403 		/*
11404 		 * If the local group is more loaded than the selected
11405 		 * busiest group don't try to pull any tasks.
11406 		 */
11407 		if (local->avg_load >= busiest->avg_load)
11408 			goto out_balanced;
11409 
11410 		/* XXX broken for overlapping NUMA groups */
11411 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11412 				sds.total_capacity;
11413 
11414 		/*
11415 		 * Don't pull any tasks if this group is already above the
11416 		 * domain average load.
11417 		 */
11418 		if (local->avg_load >= sds.avg_load)
11419 			goto out_balanced;
11420 
11421 		/*
11422 		 * If the busiest group is more loaded, use imbalance_pct to be
11423 		 * conservative.
11424 		 */
11425 		if (100 * busiest->avg_load <=
11426 				env->sd->imbalance_pct * local->avg_load)
11427 			goto out_balanced;
11428 	}
11429 
11430 	/*
11431 	 * Try to move all excess tasks to a sibling domain of the busiest
11432 	 * group's child domain.
11433 	 */
11434 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
11435 	    sibling_imbalance(env, &sds, busiest, local) > 1)
11436 		goto force_balance;
11437 
11438 	if (busiest->group_type != group_overloaded) {
11439 		if (!env->idle) {
11440 			/*
11441 			 * If the busiest group is not overloaded (and as a
11442 			 * result the local one too) but this CPU is already
11443 			 * busy, let another idle CPU try to pull task.
11444 			 */
11445 			goto out_balanced;
11446 		}
11447 
11448 		if (busiest->group_type == group_smt_balance &&
11449 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11450 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
11451 			goto force_balance;
11452 		}
11453 
11454 		if (busiest->group_weight > 1 &&
11455 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
11456 			/*
11457 			 * If the busiest group is not overloaded
11458 			 * and there is no imbalance between this and busiest
11459 			 * group wrt idle CPUs, it is balanced. The imbalance
11460 			 * becomes significant if the diff is greater than 1
11461 			 * otherwise we might end up to just move the imbalance
11462 			 * on another group. Of course this applies only if
11463 			 * there is more than 1 CPU per group.
11464 			 */
11465 			goto out_balanced;
11466 		}
11467 
11468 		if (busiest->sum_h_nr_running == 1) {
11469 			/*
11470 			 * busiest doesn't have any tasks waiting to run
11471 			 */
11472 			goto out_balanced;
11473 		}
11474 	}
11475 
11476 force_balance:
11477 	/* Looks like there is an imbalance. Compute it */
11478 	calculate_imbalance(env, &sds);
11479 	return env->imbalance ? sds.busiest : NULL;
11480 
11481 out_balanced:
11482 	env->imbalance = 0;
11483 	return NULL;
11484 }
11485 
11486 /*
11487  * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11488  */
11489 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11490 				     struct sched_group *group)
11491 {
11492 	struct rq *busiest = NULL, *rq;
11493 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11494 	unsigned int busiest_nr = 0;
11495 	int i;
11496 
11497 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11498 		unsigned long capacity, load, util;
11499 		unsigned int nr_running;
11500 		enum fbq_type rt;
11501 
11502 		rq = cpu_rq(i);
11503 		rt = fbq_classify_rq(rq);
11504 
11505 		/*
11506 		 * We classify groups/runqueues into three groups:
11507 		 *  - regular: there are !numa tasks
11508 		 *  - remote:  there are numa tasks that run on the 'wrong' node
11509 		 *  - all:     there is no distinction
11510 		 *
11511 		 * In order to avoid migrating ideally placed numa tasks,
11512 		 * ignore those when there's better options.
11513 		 *
11514 		 * If we ignore the actual busiest queue to migrate another
11515 		 * task, the next balance pass can still reduce the busiest
11516 		 * queue by moving tasks around inside the node.
11517 		 *
11518 		 * If we cannot move enough load due to this classification
11519 		 * the next pass will adjust the group classification and
11520 		 * allow migration of more tasks.
11521 		 *
11522 		 * Both cases only affect the total convergence complexity.
11523 		 */
11524 		if (rt > env->fbq_type)
11525 			continue;
11526 
11527 		nr_running = rq->cfs.h_nr_runnable;
11528 		if (!nr_running)
11529 			continue;
11530 
11531 		capacity = capacity_of(i);
11532 
11533 		/*
11534 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11535 		 * eventually lead to active_balancing high->low capacity.
11536 		 * Higher per-CPU capacity is considered better than balancing
11537 		 * average load.
11538 		 */
11539 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11540 		    !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11541 		    nr_running == 1)
11542 			continue;
11543 
11544 		/*
11545 		 * Make sure we only pull tasks from a CPU of lower priority
11546 		 * when balancing between SMT siblings.
11547 		 *
11548 		 * If balancing between cores, let lower priority CPUs help
11549 		 * SMT cores with more than one busy sibling.
11550 		 */
11551 		if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11552 			continue;
11553 
11554 		switch (env->migration_type) {
11555 		case migrate_load:
11556 			/*
11557 			 * When comparing with load imbalance, use cpu_load()
11558 			 * which is not scaled with the CPU capacity.
11559 			 */
11560 			load = cpu_load(rq);
11561 
11562 			if (nr_running == 1 && load > env->imbalance &&
11563 			    !check_cpu_capacity(rq, env->sd))
11564 				break;
11565 
11566 			/*
11567 			 * For the load comparisons with the other CPUs,
11568 			 * consider the cpu_load() scaled with the CPU
11569 			 * capacity, so that the load can be moved away
11570 			 * from the CPU that is potentially running at a
11571 			 * lower capacity.
11572 			 *
11573 			 * Thus we're looking for max(load_i / capacity_i),
11574 			 * crosswise multiplication to rid ourselves of the
11575 			 * division works out to:
11576 			 * load_i * capacity_j > load_j * capacity_i;
11577 			 * where j is our previous maximum.
11578 			 */
11579 			if (load * busiest_capacity > busiest_load * capacity) {
11580 				busiest_load = load;
11581 				busiest_capacity = capacity;
11582 				busiest = rq;
11583 			}
11584 			break;
11585 
11586 		case migrate_util:
11587 			util = cpu_util_cfs_boost(i);
11588 
11589 			/*
11590 			 * Don't try to pull utilization from a CPU with one
11591 			 * running task. Whatever its utilization, we will fail
11592 			 * detach the task.
11593 			 */
11594 			if (nr_running <= 1)
11595 				continue;
11596 
11597 			if (busiest_util < util) {
11598 				busiest_util = util;
11599 				busiest = rq;
11600 			}
11601 			break;
11602 
11603 		case migrate_task:
11604 			if (busiest_nr < nr_running) {
11605 				busiest_nr = nr_running;
11606 				busiest = rq;
11607 			}
11608 			break;
11609 
11610 		case migrate_misfit:
11611 			/*
11612 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
11613 			 * simply seek the "biggest" misfit task.
11614 			 */
11615 			if (rq->misfit_task_load > busiest_load) {
11616 				busiest_load = rq->misfit_task_load;
11617 				busiest = rq;
11618 			}
11619 
11620 			break;
11621 
11622 		}
11623 	}
11624 
11625 	return busiest;
11626 }
11627 
11628 /*
11629  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11630  * so long as it is large enough.
11631  */
11632 #define MAX_PINNED_INTERVAL	512
11633 
11634 static inline bool
11635 asym_active_balance(struct lb_env *env)
11636 {
11637 	/*
11638 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
11639 	 * priority CPUs in order to pack all tasks in the highest priority
11640 	 * CPUs. When done between cores, do it only if the whole core if the
11641 	 * whole core is idle.
11642 	 *
11643 	 * If @env::src_cpu is an SMT core with busy siblings, let
11644 	 * the lower priority @env::dst_cpu help it. Do not follow
11645 	 * CPU priority.
11646 	 */
11647 	return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11648 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11649 		!sched_use_asym_prio(env->sd, env->src_cpu));
11650 }
11651 
11652 static inline bool
11653 imbalanced_active_balance(struct lb_env *env)
11654 {
11655 	struct sched_domain *sd = env->sd;
11656 
11657 	/*
11658 	 * The imbalanced case includes the case of pinned tasks preventing a fair
11659 	 * distribution of the load on the system but also the even distribution of the
11660 	 * threads on a system with spare capacity
11661 	 */
11662 	if ((env->migration_type == migrate_task) &&
11663 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
11664 		return 1;
11665 
11666 	return 0;
11667 }
11668 
11669 static int need_active_balance(struct lb_env *env)
11670 {
11671 	struct sched_domain *sd = env->sd;
11672 
11673 	if (asym_active_balance(env))
11674 		return 1;
11675 
11676 	if (imbalanced_active_balance(env))
11677 		return 1;
11678 
11679 	/*
11680 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11681 	 * It's worth migrating the task if the src_cpu's capacity is reduced
11682 	 * because of other sched_class or IRQs if more capacity stays
11683 	 * available on dst_cpu.
11684 	 */
11685 	if (env->idle &&
11686 	    (env->src_rq->cfs.h_nr_runnable == 1)) {
11687 		if ((check_cpu_capacity(env->src_rq, sd)) &&
11688 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11689 			return 1;
11690 	}
11691 
11692 	if (env->migration_type == migrate_misfit)
11693 		return 1;
11694 
11695 	return 0;
11696 }
11697 
11698 static int active_load_balance_cpu_stop(void *data);
11699 
11700 static int should_we_balance(struct lb_env *env)
11701 {
11702 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11703 	struct sched_group *sg = env->sd->groups;
11704 	int cpu, idle_smt = -1;
11705 
11706 	/*
11707 	 * Ensure the balancing environment is consistent; can happen
11708 	 * when the softirq triggers 'during' hotplug.
11709 	 */
11710 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11711 		return 0;
11712 
11713 	/*
11714 	 * In the newly idle case, we will allow all the CPUs
11715 	 * to do the newly idle load balance.
11716 	 *
11717 	 * However, we bail out if we already have tasks or a wakeup pending,
11718 	 * to optimize wakeup latency.
11719 	 */
11720 	if (env->idle == CPU_NEWLY_IDLE) {
11721 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11722 			return 0;
11723 		return 1;
11724 	}
11725 
11726 	cpumask_copy(swb_cpus, group_balance_mask(sg));
11727 	/* Try to find first idle CPU */
11728 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11729 		if (!idle_cpu(cpu))
11730 			continue;
11731 
11732 		/*
11733 		 * Don't balance to idle SMT in busy core right away when
11734 		 * balancing cores, but remember the first idle SMT CPU for
11735 		 * later consideration.  Find CPU on an idle core first.
11736 		 */
11737 		if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11738 			if (idle_smt == -1)
11739 				idle_smt = cpu;
11740 			/*
11741 			 * If the core is not idle, and first SMT sibling which is
11742 			 * idle has been found, then its not needed to check other
11743 			 * SMT siblings for idleness:
11744 			 */
11745 #ifdef CONFIG_SCHED_SMT
11746 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11747 #endif
11748 			continue;
11749 		}
11750 
11751 		/*
11752 		 * Are we the first idle core in a non-SMT domain or higher,
11753 		 * or the first idle CPU in a SMT domain?
11754 		 */
11755 		return cpu == env->dst_cpu;
11756 	}
11757 
11758 	/* Are we the first idle CPU with busy siblings? */
11759 	if (idle_smt != -1)
11760 		return idle_smt == env->dst_cpu;
11761 
11762 	/* Are we the first CPU of this group ? */
11763 	return group_balance_cpu(sg) == env->dst_cpu;
11764 }
11765 
11766 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
11767 				     enum cpu_idle_type idle)
11768 {
11769 	if (!schedstat_enabled())
11770 		return;
11771 
11772 	switch (env->migration_type) {
11773 	case migrate_load:
11774 		__schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
11775 		break;
11776 	case migrate_util:
11777 		__schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
11778 		break;
11779 	case migrate_task:
11780 		__schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
11781 		break;
11782 	case migrate_misfit:
11783 		__schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
11784 		break;
11785 	}
11786 }
11787 
11788 /*
11789  * This flag serializes load-balancing passes over large domains
11790  * (above the NODE topology level) - only one load-balancing instance
11791  * may run at a time, to reduce overhead on very large systems with
11792  * lots of CPUs and large NUMA distances.
11793  *
11794  * - Note that load-balancing passes triggered while another one
11795  *   is executing are skipped and not re-tried.
11796  *
11797  * - Also note that this does not serialize rebalance_domains()
11798  *   execution, as non-SD_SERIALIZE domains will still be
11799  *   load-balanced in parallel.
11800  */
11801 static atomic_t sched_balance_running = ATOMIC_INIT(0);
11802 
11803 /*
11804  * Check this_cpu to ensure it is balanced within domain. Attempt to move
11805  * tasks if there is an imbalance.
11806  */
11807 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11808 			struct sched_domain *sd, enum cpu_idle_type idle,
11809 			int *continue_balancing)
11810 {
11811 	int ld_moved, cur_ld_moved, active_balance = 0;
11812 	struct sched_domain *sd_parent = sd->parent;
11813 	struct sched_group *group;
11814 	struct rq *busiest;
11815 	struct rq_flags rf;
11816 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11817 	struct lb_env env = {
11818 		.sd		= sd,
11819 		.dst_cpu	= this_cpu,
11820 		.dst_rq		= this_rq,
11821 		.dst_grpmask    = group_balance_mask(sd->groups),
11822 		.idle		= idle,
11823 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
11824 		.cpus		= cpus,
11825 		.fbq_type	= all,
11826 		.tasks		= LIST_HEAD_INIT(env.tasks),
11827 	};
11828 	bool need_unlock = false;
11829 
11830 	cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11831 
11832 	schedstat_inc(sd->lb_count[idle]);
11833 
11834 redo:
11835 	if (!should_we_balance(&env)) {
11836 		*continue_balancing = 0;
11837 		goto out_balanced;
11838 	}
11839 
11840 	if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
11841 		int zero = 0;
11842 		if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
11843 			goto out_balanced;
11844 
11845 		need_unlock = true;
11846 	}
11847 
11848 	group = sched_balance_find_src_group(&env);
11849 	if (!group) {
11850 		schedstat_inc(sd->lb_nobusyg[idle]);
11851 		goto out_balanced;
11852 	}
11853 
11854 	busiest = sched_balance_find_src_rq(&env, group);
11855 	if (!busiest) {
11856 		schedstat_inc(sd->lb_nobusyq[idle]);
11857 		goto out_balanced;
11858 	}
11859 
11860 	WARN_ON_ONCE(busiest == env.dst_rq);
11861 
11862 	update_lb_imbalance_stat(&env, sd, idle);
11863 
11864 	env.src_cpu = busiest->cpu;
11865 	env.src_rq = busiest;
11866 
11867 	ld_moved = 0;
11868 	/* Clear this flag as soon as we find a pullable task */
11869 	env.flags |= LBF_ALL_PINNED;
11870 	if (busiest->nr_running > 1) {
11871 		/*
11872 		 * Attempt to move tasks. If sched_balance_find_src_group has found
11873 		 * an imbalance but busiest->nr_running <= 1, the group is
11874 		 * still unbalanced. ld_moved simply stays zero, so it is
11875 		 * correctly treated as an imbalance.
11876 		 */
11877 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
11878 
11879 more_balance:
11880 		rq_lock_irqsave(busiest, &rf);
11881 		update_rq_clock(busiest);
11882 
11883 		/*
11884 		 * cur_ld_moved - load moved in current iteration
11885 		 * ld_moved     - cumulative load moved across iterations
11886 		 */
11887 		cur_ld_moved = detach_tasks(&env);
11888 
11889 		/*
11890 		 * We've detached some tasks from busiest_rq. Every
11891 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11892 		 * unlock busiest->lock, and we are able to be sure
11893 		 * that nobody can manipulate the tasks in parallel.
11894 		 * See task_rq_lock() family for the details.
11895 		 */
11896 
11897 		rq_unlock(busiest, &rf);
11898 
11899 		if (cur_ld_moved) {
11900 			attach_tasks(&env);
11901 			ld_moved += cur_ld_moved;
11902 		}
11903 
11904 		local_irq_restore(rf.flags);
11905 
11906 		if (env.flags & LBF_NEED_BREAK) {
11907 			env.flags &= ~LBF_NEED_BREAK;
11908 			goto more_balance;
11909 		}
11910 
11911 		/*
11912 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11913 		 * us and move them to an alternate dst_cpu in our sched_group
11914 		 * where they can run. The upper limit on how many times we
11915 		 * iterate on same src_cpu is dependent on number of CPUs in our
11916 		 * sched_group.
11917 		 *
11918 		 * This changes load balance semantics a bit on who can move
11919 		 * load to a given_cpu. In addition to the given_cpu itself
11920 		 * (or a ilb_cpu acting on its behalf where given_cpu is
11921 		 * nohz-idle), we now have balance_cpu in a position to move
11922 		 * load to given_cpu. In rare situations, this may cause
11923 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11924 		 * _independently_ and at _same_ time to move some load to
11925 		 * given_cpu) causing excess load to be moved to given_cpu.
11926 		 * This however should not happen so much in practice and
11927 		 * moreover subsequent load balance cycles should correct the
11928 		 * excess load moved.
11929 		 */
11930 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11931 
11932 			/* Prevent to re-select dst_cpu via env's CPUs */
11933 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
11934 
11935 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
11936 			env.dst_cpu	 = env.new_dst_cpu;
11937 			env.flags	&= ~LBF_DST_PINNED;
11938 			env.loop	 = 0;
11939 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
11940 
11941 			/*
11942 			 * Go back to "more_balance" rather than "redo" since we
11943 			 * need to continue with same src_cpu.
11944 			 */
11945 			goto more_balance;
11946 		}
11947 
11948 		/*
11949 		 * We failed to reach balance because of affinity.
11950 		 */
11951 		if (sd_parent) {
11952 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11953 
11954 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11955 				*group_imbalance = 1;
11956 		}
11957 
11958 		/* All tasks on this runqueue were pinned by CPU affinity */
11959 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
11960 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
11961 			/*
11962 			 * Attempting to continue load balancing at the current
11963 			 * sched_domain level only makes sense if there are
11964 			 * active CPUs remaining as possible busiest CPUs to
11965 			 * pull load from which are not contained within the
11966 			 * destination group that is receiving any migrated
11967 			 * load.
11968 			 */
11969 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
11970 				env.loop = 0;
11971 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
11972 				goto redo;
11973 			}
11974 			goto out_all_pinned;
11975 		}
11976 	}
11977 
11978 	if (!ld_moved) {
11979 		schedstat_inc(sd->lb_failed[idle]);
11980 		/*
11981 		 * Increment the failure counter only on periodic balance.
11982 		 * We do not want newidle balance, which can be very
11983 		 * frequent, pollute the failure counter causing
11984 		 * excessive cache_hot migrations and active balances.
11985 		 *
11986 		 * Similarly for migration_misfit which is not related to
11987 		 * load/util migration, don't pollute nr_balance_failed.
11988 		 */
11989 		if (idle != CPU_NEWLY_IDLE &&
11990 		    env.migration_type != migrate_misfit)
11991 			sd->nr_balance_failed++;
11992 
11993 		if (need_active_balance(&env)) {
11994 			unsigned long flags;
11995 
11996 			raw_spin_rq_lock_irqsave(busiest, flags);
11997 
11998 			/*
11999 			 * Don't kick the active_load_balance_cpu_stop,
12000 			 * if the curr task on busiest CPU can't be
12001 			 * moved to this_cpu:
12002 			 */
12003 			if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
12004 				raw_spin_rq_unlock_irqrestore(busiest, flags);
12005 				goto out_one_pinned;
12006 			}
12007 
12008 			/* Record that we found at least one task that could run on this_cpu */
12009 			env.flags &= ~LBF_ALL_PINNED;
12010 
12011 			/*
12012 			 * ->active_balance synchronizes accesses to
12013 			 * ->active_balance_work.  Once set, it's cleared
12014 			 * only after active load balance is finished.
12015 			 */
12016 			if (!busiest->active_balance) {
12017 				busiest->active_balance = 1;
12018 				busiest->push_cpu = this_cpu;
12019 				active_balance = 1;
12020 			}
12021 
12022 			preempt_disable();
12023 			raw_spin_rq_unlock_irqrestore(busiest, flags);
12024 			if (active_balance) {
12025 				stop_one_cpu_nowait(cpu_of(busiest),
12026 					active_load_balance_cpu_stop, busiest,
12027 					&busiest->active_balance_work);
12028 			}
12029 			preempt_enable();
12030 		}
12031 	} else {
12032 		sd->nr_balance_failed = 0;
12033 	}
12034 
12035 	if (likely(!active_balance) || need_active_balance(&env)) {
12036 		/* We were unbalanced, so reset the balancing interval */
12037 		sd->balance_interval = sd->min_interval;
12038 	}
12039 
12040 	goto out;
12041 
12042 out_balanced:
12043 	/*
12044 	 * We reach balance although we may have faced some affinity
12045 	 * constraints. Clear the imbalance flag only if other tasks got
12046 	 * a chance to move and fix the imbalance.
12047 	 */
12048 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12049 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12050 
12051 		if (*group_imbalance)
12052 			*group_imbalance = 0;
12053 	}
12054 
12055 out_all_pinned:
12056 	/*
12057 	 * We reach balance because all tasks are pinned at this level so
12058 	 * we can't migrate them. Let the imbalance flag set so parent level
12059 	 * can try to migrate them.
12060 	 */
12061 	schedstat_inc(sd->lb_balanced[idle]);
12062 
12063 	sd->nr_balance_failed = 0;
12064 
12065 out_one_pinned:
12066 	ld_moved = 0;
12067 
12068 	/*
12069 	 * sched_balance_newidle() disregards balance intervals, so we could
12070 	 * repeatedly reach this code, which would lead to balance_interval
12071 	 * skyrocketing in a short amount of time. Skip the balance_interval
12072 	 * increase logic to avoid that.
12073 	 *
12074 	 * Similarly misfit migration which is not necessarily an indication of
12075 	 * the system being busy and requires lb to backoff to let it settle
12076 	 * down.
12077 	 */
12078 	if (env.idle == CPU_NEWLY_IDLE ||
12079 	    env.migration_type == migrate_misfit)
12080 		goto out;
12081 
12082 	/* tune up the balancing interval */
12083 	if ((env.flags & LBF_ALL_PINNED &&
12084 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
12085 	    sd->balance_interval < sd->max_interval)
12086 		sd->balance_interval *= 2;
12087 out:
12088 	if (need_unlock)
12089 		atomic_set_release(&sched_balance_running, 0);
12090 
12091 	return ld_moved;
12092 }
12093 
12094 static inline unsigned long
12095 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12096 {
12097 	unsigned long interval = sd->balance_interval;
12098 
12099 	if (cpu_busy)
12100 		interval *= sd->busy_factor;
12101 
12102 	/* scale ms to jiffies */
12103 	interval = msecs_to_jiffies(interval);
12104 
12105 	/*
12106 	 * Reduce likelihood of busy balancing at higher domains racing with
12107 	 * balancing at lower domains by preventing their balancing periods
12108 	 * from being multiples of each other.
12109 	 */
12110 	if (cpu_busy)
12111 		interval -= 1;
12112 
12113 	interval = clamp(interval, 1UL, max_load_balance_interval);
12114 
12115 	return interval;
12116 }
12117 
12118 static inline void
12119 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12120 {
12121 	unsigned long interval, next;
12122 
12123 	/* used by idle balance, so cpu_busy = 0 */
12124 	interval = get_sd_balance_interval(sd, 0);
12125 	next = sd->last_balance + interval;
12126 
12127 	if (time_after(*next_balance, next))
12128 		*next_balance = next;
12129 }
12130 
12131 /*
12132  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12133  * running tasks off the busiest CPU onto idle CPUs. It requires at
12134  * least 1 task to be running on each physical CPU where possible, and
12135  * avoids physical / logical imbalances.
12136  */
12137 static int active_load_balance_cpu_stop(void *data)
12138 {
12139 	struct rq *busiest_rq = data;
12140 	int busiest_cpu = cpu_of(busiest_rq);
12141 	int target_cpu = busiest_rq->push_cpu;
12142 	struct rq *target_rq = cpu_rq(target_cpu);
12143 	struct sched_domain *sd;
12144 	struct task_struct *p = NULL;
12145 	struct rq_flags rf;
12146 
12147 	rq_lock_irq(busiest_rq, &rf);
12148 	/*
12149 	 * Between queueing the stop-work and running it is a hole in which
12150 	 * CPUs can become inactive. We should not move tasks from or to
12151 	 * inactive CPUs.
12152 	 */
12153 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12154 		goto out_unlock;
12155 
12156 	/* Make sure the requested CPU hasn't gone down in the meantime: */
12157 	if (unlikely(busiest_cpu != smp_processor_id() ||
12158 		     !busiest_rq->active_balance))
12159 		goto out_unlock;
12160 
12161 	/* Is there any task to move? */
12162 	if (busiest_rq->nr_running <= 1)
12163 		goto out_unlock;
12164 
12165 	/*
12166 	 * This condition is "impossible", if it occurs
12167 	 * we need to fix it. Originally reported by
12168 	 * Bjorn Helgaas on a 128-CPU setup.
12169 	 */
12170 	WARN_ON_ONCE(busiest_rq == target_rq);
12171 
12172 	/* Search for an sd spanning us and the target CPU. */
12173 	rcu_read_lock();
12174 	for_each_domain(target_cpu, sd) {
12175 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12176 			break;
12177 	}
12178 
12179 	if (likely(sd)) {
12180 		struct lb_env env = {
12181 			.sd		= sd,
12182 			.dst_cpu	= target_cpu,
12183 			.dst_rq		= target_rq,
12184 			.src_cpu	= busiest_rq->cpu,
12185 			.src_rq		= busiest_rq,
12186 			.idle		= CPU_IDLE,
12187 			.flags		= LBF_ACTIVE_LB,
12188 		};
12189 
12190 		schedstat_inc(sd->alb_count);
12191 		update_rq_clock(busiest_rq);
12192 
12193 		p = detach_one_task(&env);
12194 		if (p) {
12195 			schedstat_inc(sd->alb_pushed);
12196 			/* Active balancing done, reset the failure counter. */
12197 			sd->nr_balance_failed = 0;
12198 		} else {
12199 			schedstat_inc(sd->alb_failed);
12200 		}
12201 	}
12202 	rcu_read_unlock();
12203 out_unlock:
12204 	busiest_rq->active_balance = 0;
12205 	rq_unlock(busiest_rq, &rf);
12206 
12207 	if (p)
12208 		attach_one_task(target_rq, p);
12209 
12210 	local_irq_enable();
12211 
12212 	return 0;
12213 }
12214 
12215 /*
12216  * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12217  * This trades load-balance latency on larger machines for less cross talk.
12218  */
12219 void update_max_interval(void)
12220 {
12221 	max_load_balance_interval = HZ*num_online_cpus()/10;
12222 }
12223 
12224 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
12225 {
12226 	sd->newidle_call++;
12227 	sd->newidle_success += success;
12228 
12229 	if (sd->newidle_call >= 1024) {
12230 		sd->newidle_ratio = sd->newidle_success;
12231 		sd->newidle_call /= 2;
12232 		sd->newidle_success /= 2;
12233 	}
12234 }
12235 
12236 static inline bool
12237 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
12238 {
12239 	unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
12240 	unsigned long now = jiffies;
12241 
12242 	if (cost)
12243 		update_newidle_stats(sd, success);
12244 
12245 	if (cost > sd->max_newidle_lb_cost) {
12246 		/*
12247 		 * Track max cost of a domain to make sure to not delay the
12248 		 * next wakeup on the CPU.
12249 		 */
12250 		sd->max_newidle_lb_cost = cost;
12251 		sd->last_decay_max_lb_cost = now;
12252 
12253 	} else if (time_after(now, next_decay)) {
12254 		/*
12255 		 * Decay the newidle max times by ~1% per second to ensure that
12256 		 * it is not outdated and the current max cost is actually
12257 		 * shorter.
12258 		 */
12259 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12260 		sd->last_decay_max_lb_cost = now;
12261 		return true;
12262 	}
12263 
12264 	return false;
12265 }
12266 
12267 /*
12268  * It checks each scheduling domain to see if it is due to be balanced,
12269  * and initiates a balancing operation if so.
12270  *
12271  * Balancing parameters are set up in init_sched_domains.
12272  */
12273 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12274 {
12275 	int continue_balancing = 1;
12276 	int cpu = rq->cpu;
12277 	int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12278 	unsigned long interval;
12279 	struct sched_domain *sd;
12280 	/* Earliest time when we have to do rebalance again */
12281 	unsigned long next_balance = jiffies + 60*HZ;
12282 	int update_next_balance = 0;
12283 	int need_decay = 0;
12284 	u64 max_cost = 0;
12285 
12286 	rcu_read_lock();
12287 	for_each_domain(cpu, sd) {
12288 		/*
12289 		 * Decay the newidle max times here because this is a regular
12290 		 * visit to all the domains.
12291 		 */
12292 		need_decay = update_newidle_cost(sd, 0, 0);
12293 		max_cost += sd->max_newidle_lb_cost;
12294 
12295 		/*
12296 		 * Stop the load balance at this level. There is another
12297 		 * CPU in our sched group which is doing load balancing more
12298 		 * actively.
12299 		 */
12300 		if (!continue_balancing) {
12301 			if (need_decay)
12302 				continue;
12303 			break;
12304 		}
12305 
12306 		interval = get_sd_balance_interval(sd, busy);
12307 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
12308 			if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12309 				/*
12310 				 * The LBF_DST_PINNED logic could have changed
12311 				 * env->dst_cpu, so we can't know our idle
12312 				 * state even if we migrated tasks. Update it.
12313 				 */
12314 				idle = idle_cpu(cpu);
12315 				busy = !idle && !sched_idle_cpu(cpu);
12316 			}
12317 			sd->last_balance = jiffies;
12318 			interval = get_sd_balance_interval(sd, busy);
12319 		}
12320 		if (time_after(next_balance, sd->last_balance + interval)) {
12321 			next_balance = sd->last_balance + interval;
12322 			update_next_balance = 1;
12323 		}
12324 	}
12325 	if (need_decay) {
12326 		/*
12327 		 * Ensure the rq-wide value also decays but keep it at a
12328 		 * reasonable floor to avoid funnies with rq->avg_idle.
12329 		 */
12330 		rq->max_idle_balance_cost =
12331 			max((u64)sysctl_sched_migration_cost, max_cost);
12332 	}
12333 	rcu_read_unlock();
12334 
12335 	/*
12336 	 * next_balance will be updated only when there is a need.
12337 	 * When the cpu is attached to null domain for ex, it will not be
12338 	 * updated.
12339 	 */
12340 	if (likely(update_next_balance))
12341 		rq->next_balance = next_balance;
12342 
12343 }
12344 
12345 static inline int on_null_domain(struct rq *rq)
12346 {
12347 	return unlikely(!rcu_dereference_sched(rq->sd));
12348 }
12349 
12350 #ifdef CONFIG_NO_HZ_COMMON
12351 /*
12352  * NOHZ idle load balancing (ILB) details:
12353  *
12354  * - When one of the busy CPUs notices that there may be an idle rebalancing
12355  *   needed, they will kick the idle load balancer, which then does idle
12356  *   load balancing for all the idle CPUs.
12357  */
12358 static inline int find_new_ilb(void)
12359 {
12360 	const struct cpumask *hk_mask;
12361 	int ilb_cpu;
12362 
12363 	hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12364 
12365 	for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12366 
12367 		if (ilb_cpu == smp_processor_id())
12368 			continue;
12369 
12370 		if (idle_cpu(ilb_cpu))
12371 			return ilb_cpu;
12372 	}
12373 
12374 	return -1;
12375 }
12376 
12377 /*
12378  * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12379  * SMP function call (IPI).
12380  *
12381  * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12382  * (if there is one).
12383  */
12384 static void kick_ilb(unsigned int flags)
12385 {
12386 	int ilb_cpu;
12387 
12388 	/*
12389 	 * Increase nohz.next_balance only when if full ilb is triggered but
12390 	 * not if we only update stats.
12391 	 */
12392 	if (flags & NOHZ_BALANCE_KICK)
12393 		nohz.next_balance = jiffies+1;
12394 
12395 	ilb_cpu = find_new_ilb();
12396 	if (ilb_cpu < 0)
12397 		return;
12398 
12399 	/*
12400 	 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12401 	 * i.e. all bits in flags are already set in ilb_cpu.
12402 	 */
12403 	if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12404 		return;
12405 
12406 	/*
12407 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12408 	 * the first flag owns it; cleared by nohz_csd_func().
12409 	 */
12410 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12411 	if (flags & NOHZ_KICK_MASK)
12412 		return;
12413 
12414 	/*
12415 	 * This way we generate an IPI on the target CPU which
12416 	 * is idle, and the softirq performing NOHZ idle load balancing
12417 	 * will be run before returning from the IPI.
12418 	 */
12419 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12420 }
12421 
12422 /*
12423  * Current decision point for kicking the idle load balancer in the presence
12424  * of idle CPUs in the system.
12425  */
12426 static void nohz_balancer_kick(struct rq *rq)
12427 {
12428 	unsigned long now = jiffies;
12429 	struct sched_domain_shared *sds;
12430 	struct sched_domain *sd;
12431 	int nr_busy, i, cpu = rq->cpu;
12432 	unsigned int flags = 0;
12433 
12434 	if (unlikely(rq->idle_balance))
12435 		return;
12436 
12437 	/*
12438 	 * We may be recently in ticked or tickless idle mode. At the first
12439 	 * busy tick after returning from idle, we will update the busy stats.
12440 	 */
12441 	nohz_balance_exit_idle(rq);
12442 
12443 	if (READ_ONCE(nohz.has_blocked_load) &&
12444 	    time_after(now, READ_ONCE(nohz.next_blocked)))
12445 		flags = NOHZ_STATS_KICK;
12446 
12447 	/*
12448 	 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0
12449 	 * Skip the read if time is not due.
12450 	 *
12451 	 * If none are in tickless mode, there maybe a narrow window
12452 	 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called.
12453 	 * But idle load balancing is not done as find_new_ilb fails.
12454 	 * That's very rare. So read nohz.nr_cpus only if time is due.
12455 	 */
12456 	if (time_before(now, nohz.next_balance))
12457 		goto out;
12458 
12459 	/*
12460 	 * None are in tickless mode and hence no need for NOHZ idle load
12461 	 * balancing
12462 	 */
12463 	if (unlikely(cpumask_empty(nohz.idle_cpus_mask)))
12464 		return;
12465 
12466 	if (rq->nr_running >= 2) {
12467 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12468 		goto out;
12469 	}
12470 
12471 	rcu_read_lock();
12472 
12473 	sd = rcu_dereference_all(rq->sd);
12474 	if (sd) {
12475 		/*
12476 		 * If there's a runnable CFS task and the current CPU has reduced
12477 		 * capacity, kick the ILB to see if there's a better CPU to run on:
12478 		 */
12479 		if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12480 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12481 			goto unlock;
12482 		}
12483 	}
12484 
12485 	sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu));
12486 	if (sd) {
12487 		/*
12488 		 * When ASYM_PACKING; see if there's a more preferred CPU
12489 		 * currently idle; in which case, kick the ILB to move tasks
12490 		 * around.
12491 		 *
12492 		 * When balancing between cores, all the SMT siblings of the
12493 		 * preferred CPU must be idle.
12494 		 */
12495 		for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12496 			if (sched_asym(sd, i, cpu)) {
12497 				flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12498 				goto unlock;
12499 			}
12500 		}
12501 	}
12502 
12503 	sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu));
12504 	if (sd) {
12505 		/*
12506 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12507 		 * to run the misfit task on.
12508 		 */
12509 		if (check_misfit_status(rq)) {
12510 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12511 			goto unlock;
12512 		}
12513 
12514 		/*
12515 		 * For asymmetric systems, we do not want to nicely balance
12516 		 * cache use, instead we want to embrace asymmetry and only
12517 		 * ensure tasks have enough CPU capacity.
12518 		 *
12519 		 * Skip the LLC logic because it's not relevant in that case.
12520 		 */
12521 		goto unlock;
12522 	}
12523 
12524 	sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
12525 	if (sds) {
12526 		/*
12527 		 * If there is an imbalance between LLC domains (IOW we could
12528 		 * increase the overall cache utilization), we need a less-loaded LLC
12529 		 * domain to pull some load from. Likewise, we may need to spread
12530 		 * load within the current LLC domain (e.g. packed SMT cores but
12531 		 * other CPUs are idle). We can't really know from here how busy
12532 		 * the others are - so just get a NOHZ balance going if it looks
12533 		 * like this LLC domain has tasks we could move.
12534 		 */
12535 		nr_busy = atomic_read(&sds->nr_busy_cpus);
12536 		if (nr_busy > 1) {
12537 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12538 			goto unlock;
12539 		}
12540 	}
12541 unlock:
12542 	rcu_read_unlock();
12543 out:
12544 	if (READ_ONCE(nohz.needs_update))
12545 		flags |= NOHZ_NEXT_KICK;
12546 
12547 	if (flags)
12548 		kick_ilb(flags);
12549 }
12550 
12551 static void set_cpu_sd_state_busy(int cpu)
12552 {
12553 	struct sched_domain *sd;
12554 
12555 	rcu_read_lock();
12556 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
12557 
12558 	if (!sd || !sd->nohz_idle)
12559 		goto unlock;
12560 	sd->nohz_idle = 0;
12561 
12562 	atomic_inc(&sd->shared->nr_busy_cpus);
12563 unlock:
12564 	rcu_read_unlock();
12565 }
12566 
12567 void nohz_balance_exit_idle(struct rq *rq)
12568 {
12569 	WARN_ON_ONCE(rq != this_rq());
12570 
12571 	if (likely(!rq->nohz_tick_stopped))
12572 		return;
12573 
12574 	rq->nohz_tick_stopped = 0;
12575 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12576 
12577 	set_cpu_sd_state_busy(rq->cpu);
12578 }
12579 
12580 static void set_cpu_sd_state_idle(int cpu)
12581 {
12582 	struct sched_domain *sd;
12583 
12584 	rcu_read_lock();
12585 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
12586 
12587 	if (!sd || sd->nohz_idle)
12588 		goto unlock;
12589 	sd->nohz_idle = 1;
12590 
12591 	atomic_dec(&sd->shared->nr_busy_cpus);
12592 unlock:
12593 	rcu_read_unlock();
12594 }
12595 
12596 /*
12597  * This routine will record that the CPU is going idle with tick stopped.
12598  * This info will be used in performing idle load balancing in the future.
12599  */
12600 void nohz_balance_enter_idle(int cpu)
12601 {
12602 	struct rq *rq = cpu_rq(cpu);
12603 
12604 	WARN_ON_ONCE(cpu != smp_processor_id());
12605 
12606 	/* If this CPU is going down, then nothing needs to be done: */
12607 	if (!cpu_active(cpu))
12608 		return;
12609 
12610 	/*
12611 	 * Can be set safely without rq->lock held
12612 	 * If a clear happens, it will have evaluated last additions because
12613 	 * rq->lock is held during the check and the clear
12614 	 */
12615 	rq->has_blocked_load = 1;
12616 
12617 	/*
12618 	 * The tick is still stopped but load could have been added in the
12619 	 * meantime. We set the nohz.has_blocked_load flag to trig a check of the
12620 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12621 	 * of nohz.has_blocked_load can only happen after checking the new load
12622 	 */
12623 	if (rq->nohz_tick_stopped)
12624 		goto out;
12625 
12626 	/* If we're a completely isolated CPU, we don't play: */
12627 	if (on_null_domain(rq))
12628 		return;
12629 
12630 	rq->nohz_tick_stopped = 1;
12631 
12632 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12633 
12634 	/*
12635 	 * Ensures that if nohz_idle_balance() fails to observe our
12636 	 * @idle_cpus_mask store, it must observe the @has_blocked_load
12637 	 * and @needs_update stores.
12638 	 */
12639 	smp_mb__after_atomic();
12640 
12641 	set_cpu_sd_state_idle(cpu);
12642 
12643 	WRITE_ONCE(nohz.needs_update, 1);
12644 out:
12645 	/*
12646 	 * Each time a cpu enter idle, we assume that it has blocked load and
12647 	 * enable the periodic update of the load of idle CPUs
12648 	 */
12649 	WRITE_ONCE(nohz.has_blocked_load, 1);
12650 }
12651 
12652 static bool update_nohz_stats(struct rq *rq)
12653 {
12654 	unsigned int cpu = rq->cpu;
12655 
12656 	if (!rq->has_blocked_load)
12657 		return false;
12658 
12659 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12660 		return false;
12661 
12662 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12663 		return true;
12664 
12665 	sched_balance_update_blocked_averages(cpu);
12666 
12667 	return rq->has_blocked_load;
12668 }
12669 
12670 /*
12671  * Internal function that runs load balance for all idle CPUs. The load balance
12672  * can be a simple update of blocked load or a complete load balance with
12673  * tasks movement depending of flags.
12674  */
12675 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12676 {
12677 	/* Earliest time when we have to do rebalance again */
12678 	unsigned long now = jiffies;
12679 	unsigned long next_balance = now + 60*HZ;
12680 	bool has_blocked_load = false;
12681 	int update_next_balance = 0;
12682 	int this_cpu = this_rq->cpu;
12683 	int balance_cpu;
12684 	struct rq *rq;
12685 
12686 	WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12687 
12688 	/*
12689 	 * We assume there will be no idle load after this update and clear
12690 	 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will
12691 	 * set the has_blocked_load flag and trigger another update of idle load.
12692 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12693 	 * setting the flag, we are sure to not clear the state and not
12694 	 * check the load of an idle cpu.
12695 	 *
12696 	 * Same applies to idle_cpus_mask vs needs_update.
12697 	 */
12698 	if (flags & NOHZ_STATS_KICK)
12699 		WRITE_ONCE(nohz.has_blocked_load, 0);
12700 	if (flags & NOHZ_NEXT_KICK)
12701 		WRITE_ONCE(nohz.needs_update, 0);
12702 
12703 	/*
12704 	 * Ensures that if we miss the CPU, we must see the has_blocked_load
12705 	 * store from nohz_balance_enter_idle().
12706 	 */
12707 	smp_mb();
12708 
12709 	/*
12710 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12711 	 * chance for other idle cpu to pull load.
12712 	 */
12713 	for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
12714 		if (!idle_cpu(balance_cpu))
12715 			continue;
12716 
12717 		/*
12718 		 * If this CPU gets work to do, stop the load balancing
12719 		 * work being done for other CPUs. Next load
12720 		 * balancing owner will pick it up.
12721 		 */
12722 		if (!idle_cpu(this_cpu) && need_resched()) {
12723 			if (flags & NOHZ_STATS_KICK)
12724 				has_blocked_load = true;
12725 			if (flags & NOHZ_NEXT_KICK)
12726 				WRITE_ONCE(nohz.needs_update, 1);
12727 			goto abort;
12728 		}
12729 
12730 		rq = cpu_rq(balance_cpu);
12731 
12732 		if (flags & NOHZ_STATS_KICK)
12733 			has_blocked_load |= update_nohz_stats(rq);
12734 
12735 		/*
12736 		 * If time for next balance is due,
12737 		 * do the balance.
12738 		 */
12739 		if (time_after_eq(jiffies, rq->next_balance)) {
12740 			struct rq_flags rf;
12741 
12742 			rq_lock_irqsave(rq, &rf);
12743 			update_rq_clock(rq);
12744 			rq_unlock_irqrestore(rq, &rf);
12745 
12746 			if (flags & NOHZ_BALANCE_KICK)
12747 				sched_balance_domains(rq, CPU_IDLE);
12748 		}
12749 
12750 		if (time_after(next_balance, rq->next_balance)) {
12751 			next_balance = rq->next_balance;
12752 			update_next_balance = 1;
12753 		}
12754 	}
12755 
12756 	/*
12757 	 * next_balance will be updated only when there is a need.
12758 	 * When the CPU is attached to null domain for ex, it will not be
12759 	 * updated.
12760 	 */
12761 	if (likely(update_next_balance))
12762 		nohz.next_balance = next_balance;
12763 
12764 	if (flags & NOHZ_STATS_KICK)
12765 		WRITE_ONCE(nohz.next_blocked,
12766 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12767 
12768 abort:
12769 	/* There is still blocked load, enable periodic update */
12770 	if (has_blocked_load)
12771 		WRITE_ONCE(nohz.has_blocked_load, 1);
12772 }
12773 
12774 /*
12775  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12776  * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12777  */
12778 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12779 {
12780 	unsigned int flags = this_rq->nohz_idle_balance;
12781 
12782 	if (!flags)
12783 		return false;
12784 
12785 	this_rq->nohz_idle_balance = 0;
12786 
12787 	if (idle != CPU_IDLE)
12788 		return false;
12789 
12790 	_nohz_idle_balance(this_rq, flags);
12791 
12792 	return true;
12793 }
12794 
12795 /*
12796  * Check if we need to directly run the ILB for updating blocked load before
12797  * entering idle state. Here we run ILB directly without issuing IPIs.
12798  *
12799  * Note that when this function is called, the tick may not yet be stopped on
12800  * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12801  * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12802  * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12803  * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12804  * called from this function on (this) CPU that's not yet in the mask. That's
12805  * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12806  * updating the blocked load of already idle CPUs without waking up one of
12807  * those idle CPUs and outside the preempt disable / IRQ off phase of the local
12808  * cpu about to enter idle, because it can take a long time.
12809  */
12810 void nohz_run_idle_balance(int cpu)
12811 {
12812 	unsigned int flags;
12813 
12814 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12815 
12816 	/*
12817 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12818 	 * (i.e. NOHZ_STATS_KICK set) and will do the same.
12819 	 */
12820 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12821 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12822 }
12823 
12824 static void nohz_newidle_balance(struct rq *this_rq)
12825 {
12826 	int this_cpu = this_rq->cpu;
12827 
12828 	/* Will wake up very soon. No time for doing anything else*/
12829 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
12830 		return;
12831 
12832 	/* Don't need to update blocked load of idle CPUs*/
12833 	if (!READ_ONCE(nohz.has_blocked_load) ||
12834 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12835 		return;
12836 
12837 	/*
12838 	 * Set the need to trigger ILB in order to update blocked load
12839 	 * before entering idle state.
12840 	 */
12841 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12842 }
12843 
12844 #else /* !CONFIG_NO_HZ_COMMON: */
12845 static inline void nohz_balancer_kick(struct rq *rq) { }
12846 
12847 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12848 {
12849 	return false;
12850 }
12851 
12852 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12853 #endif /* !CONFIG_NO_HZ_COMMON */
12854 
12855 /*
12856  * sched_balance_newidle is called by schedule() if this_cpu is about to become
12857  * idle. Attempts to pull tasks from other CPUs.
12858  *
12859  * Returns:
12860  *   < 0 - we released the lock and there are !fair tasks present
12861  *     0 - failed, no new tasks
12862  *   > 0 - success, new (fair) tasks present
12863  */
12864 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
12865 {
12866 	unsigned long next_balance = jiffies + HZ;
12867 	int this_cpu = this_rq->cpu;
12868 	int continue_balancing = 1;
12869 	u64 t0, t1, curr_cost = 0;
12870 	struct sched_domain *sd;
12871 	int pulled_task = 0;
12872 
12873 	update_misfit_status(NULL, this_rq);
12874 
12875 	/*
12876 	 * There is a task waiting to run. No need to search for one.
12877 	 * Return 0; the task will be enqueued when switching to idle.
12878 	 */
12879 	if (this_rq->ttwu_pending)
12880 		return 0;
12881 
12882 	/*
12883 	 * We must set idle_stamp _before_ calling sched_balance_rq()
12884 	 * for CPU_NEWLY_IDLE, such that we measure the this duration
12885 	 * as idle time.
12886 	 */
12887 	this_rq->idle_stamp = rq_clock(this_rq);
12888 
12889 	/*
12890 	 * Do not pull tasks towards !active CPUs...
12891 	 */
12892 	if (!cpu_active(this_cpu))
12893 		return 0;
12894 
12895 	/*
12896 	 * This is OK, because current is on_cpu, which avoids it being picked
12897 	 * for load-balance and preemption/IRQs are still disabled avoiding
12898 	 * further scheduler activity on it and we're being very careful to
12899 	 * re-start the picking loop.
12900 	 */
12901 	rq_unpin_lock(this_rq, rf);
12902 
12903 	sd = rcu_dereference_sched_domain(this_rq->sd);
12904 	if (!sd)
12905 		goto out;
12906 
12907 	if (!get_rd_overloaded(this_rq->rd) ||
12908 	    this_rq->avg_idle < sd->max_newidle_lb_cost) {
12909 
12910 		update_next_balance(sd, &next_balance);
12911 		goto out;
12912 	}
12913 
12914 	/*
12915 	 * Include sched_balance_update_blocked_averages() in the cost
12916 	 * calculation because it can be quite costly -- this ensures we skip
12917 	 * it when avg_idle gets to be very low.
12918 	 */
12919 	t0 = sched_clock_cpu(this_cpu);
12920 	__sched_balance_update_blocked_averages(this_rq);
12921 
12922 	this_rq->next_class = &fair_sched_class;
12923 	raw_spin_rq_unlock(this_rq);
12924 
12925 	for_each_domain(this_cpu, sd) {
12926 		u64 domain_cost;
12927 
12928 		update_next_balance(sd, &next_balance);
12929 
12930 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12931 			break;
12932 
12933 		if (sd->flags & SD_BALANCE_NEWIDLE) {
12934 			unsigned int weight = 1;
12935 
12936 			if (sched_feat(NI_RANDOM)) {
12937 				/*
12938 				 * Throw a 1k sided dice; and only run
12939 				 * newidle_balance according to the success
12940 				 * rate.
12941 				 */
12942 				u32 d1k = sched_rng() % 1024;
12943 				weight = 1 + sd->newidle_ratio;
12944 				if (d1k > weight) {
12945 					update_newidle_stats(sd, 0);
12946 					continue;
12947 				}
12948 				weight = (1024 + weight/2) / weight;
12949 			}
12950 
12951 			pulled_task = sched_balance_rq(this_cpu, this_rq,
12952 						   sd, CPU_NEWLY_IDLE,
12953 						   &continue_balancing);
12954 
12955 			t1 = sched_clock_cpu(this_cpu);
12956 			domain_cost = t1 - t0;
12957 			curr_cost += domain_cost;
12958 			t0 = t1;
12959 
12960 			/*
12961 			 * Track max cost of a domain to make sure to not delay the
12962 			 * next wakeup on the CPU.
12963 			 */
12964 			update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
12965 		}
12966 
12967 		/*
12968 		 * Stop searching for tasks to pull if there are
12969 		 * now runnable tasks on this rq.
12970 		 */
12971 		if (pulled_task || !continue_balancing)
12972 			break;
12973 	}
12974 
12975 	raw_spin_rq_lock(this_rq);
12976 
12977 	if (curr_cost > this_rq->max_idle_balance_cost)
12978 		this_rq->max_idle_balance_cost = curr_cost;
12979 
12980 	/*
12981 	 * While browsing the domains, we released the rq lock, a task could
12982 	 * have been enqueued in the meantime. Since we're not going idle,
12983 	 * pretend we pulled a task.
12984 	 */
12985 	if (this_rq->cfs.h_nr_queued && !pulled_task)
12986 		pulled_task = 1;
12987 
12988 	/* If a higher prio class was modified, restart the pick */
12989 	if (sched_class_above(this_rq->next_class, &fair_sched_class))
12990 		pulled_task = -1;
12991 
12992 out:
12993 	/* Move the next balance forward */
12994 	if (time_after(this_rq->next_balance, next_balance))
12995 		this_rq->next_balance = next_balance;
12996 
12997 	if (pulled_task)
12998 		this_rq->idle_stamp = 0;
12999 	else
13000 		nohz_newidle_balance(this_rq);
13001 
13002 	rq_repin_lock(this_rq, rf);
13003 
13004 	return pulled_task;
13005 }
13006 
13007 /*
13008  * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
13009  *
13010  * - directly from the local sched_tick() for periodic load balancing
13011  *
13012  * - indirectly from a remote sched_tick() for NOHZ idle balancing
13013  *   through the SMP cross-call nohz_csd_func()
13014  */
13015 static __latent_entropy void sched_balance_softirq(void)
13016 {
13017 	struct rq *this_rq = this_rq();
13018 	enum cpu_idle_type idle = this_rq->idle_balance;
13019 	/*
13020 	 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13021 	 * balancing on behalf of the other idle CPUs whose ticks are
13022 	 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13023 	 * give the idle CPUs a chance to load balance. Else we may
13024 	 * load balance only within the local sched_domain hierarchy
13025 	 * and abort nohz_idle_balance altogether if we pull some load.
13026 	 */
13027 	if (nohz_idle_balance(this_rq, idle))
13028 		return;
13029 
13030 	/* normal load balance */
13031 	sched_balance_update_blocked_averages(this_rq->cpu);
13032 	sched_balance_domains(this_rq, idle);
13033 }
13034 
13035 /*
13036  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13037  */
13038 void sched_balance_trigger(struct rq *rq)
13039 {
13040 	/*
13041 	 * Don't need to rebalance while attached to NULL domain or
13042 	 * runqueue CPU is not active
13043 	 */
13044 	if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13045 		return;
13046 
13047 	if (time_after_eq(jiffies, rq->next_balance))
13048 		raise_softirq(SCHED_SOFTIRQ);
13049 
13050 	nohz_balancer_kick(rq);
13051 }
13052 
13053 static void rq_online_fair(struct rq *rq)
13054 {
13055 	update_sysctl();
13056 
13057 	update_runtime_enabled(rq);
13058 }
13059 
13060 static void rq_offline_fair(struct rq *rq)
13061 {
13062 	update_sysctl();
13063 
13064 	/* Ensure any throttled groups are reachable by pick_next_task */
13065 	unthrottle_offline_cfs_rqs(rq);
13066 
13067 	/* Ensure that we remove rq contribution to group share: */
13068 	clear_tg_offline_cfs_rqs(rq);
13069 }
13070 
13071 #ifdef CONFIG_SCHED_CORE
13072 static inline bool
13073 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13074 {
13075 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13076 	u64 slice = se->slice;
13077 
13078 	return (rtime * min_nr_tasks > slice);
13079 }
13080 
13081 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
13082 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13083 {
13084 	if (!sched_core_enabled(rq))
13085 		return;
13086 
13087 	/*
13088 	 * If runqueue has only one task which used up its slice and
13089 	 * if the sibling is forced idle, then trigger schedule to
13090 	 * give forced idle task a chance.
13091 	 *
13092 	 * sched_slice() considers only this active rq and it gets the
13093 	 * whole slice. But during force idle, we have siblings acting
13094 	 * like a single runqueue and hence we need to consider runnable
13095 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
13096 	 * go through the forced idle rq, but that would be a perf hit.
13097 	 * We can assume that the forced idle CPU has at least
13098 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13099 	 * if we need to give up the CPU.
13100 	 */
13101 	if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
13102 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13103 		resched_curr(rq);
13104 }
13105 
13106 /*
13107  * Consider any infeasible weight scenario. Take for instance two tasks,
13108  * each bound to their respective sibling, one with weight 1 and one with
13109  * weight 2. Then the lower weight task will run ahead of the higher weight
13110  * task without bound.
13111  *
13112  * This utterly destroys the concept of a shared time base.
13113  *
13114  * Remember; all this is about a proportionally fair scheduling, where each
13115  * tasks receives:
13116  *
13117  *              w_i
13118  *   dt_i = ---------- dt                                     (1)
13119  *          \Sum_j w_j
13120  *
13121  * which we do by tracking a virtual time, s_i:
13122  *
13123  *          1
13124  *   s_i = --- d[t]_i                                         (2)
13125  *         w_i
13126  *
13127  * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
13128  * The immediate corollary is that the ideal schedule S, where (2) to use
13129  * an infinitesimal delta, is:
13130  *
13131  *           1
13132  *   S = ---------- dt                                        (3)
13133  *       \Sum_i w_i
13134  *
13135  * From which we can define the lag, or deviation from the ideal, as:
13136  *
13137  *   lag(i) = S - s_i                                         (4)
13138  *
13139  * And since the one and only purpose is to approximate S, we get that:
13140  *
13141  *   \Sum_i w_i lag(i) := 0                                   (5)
13142  *
13143  * If this were not so, we no longer converge to S, and we can no longer
13144  * claim our scheduler has any of the properties we derive from S. This is
13145  * exactly what you did above, you broke it!
13146  *
13147  *
13148  * Let's continue for a while though; to see if there is anything useful to
13149  * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
13150  *
13151  *       \Sum_i w_i s_i
13152  *   S = --------------                                       (6)
13153  *         \Sum_i w_i
13154  *
13155  * Which gives us a way to compute S, given our s_i. Now, if you've read
13156  * our code, you know that we do not in fact do this, the reason for this
13157  * is two-fold. Firstly, computing S in that way requires a 64bit division
13158  * for every time we'd use it (see 12), and secondly, this only describes
13159  * the steady-state, it doesn't handle dynamics.
13160  *
13161  * Anyway, in (6):  s_i -> x + (s_i - x), to get:
13162  *
13163  *           \Sum_i w_i (s_i - x)
13164  *   S - x = --------------------                             (7)
13165  *              \Sum_i w_i
13166  *
13167  * Which shows that S and s_i transform alike (which makes perfect sense
13168  * given that S is basically the (weighted) average of s_i).
13169  *
13170  * So the thing to remember is that the above is strictly UP. It is
13171  * possible to generalize to multiple runqueues -- however it gets really
13172  * yuck when you have to add affinity support, as illustrated by our very
13173  * first counter-example.
13174  *
13175  * Luckily I think we can avoid needing a full multi-queue variant for
13176  * core-scheduling (or load-balancing). The crucial observation is that we
13177  * only actually need this comparison in the presence of forced-idle; only
13178  * then do we need to tell if the stalled rq has higher priority over the
13179  * other.
13180  *
13181  * [XXX assumes SMT2; better consider the more general case, I suspect
13182  * it'll work out because our comparison is always between 2 rqs and the
13183  * answer is only interesting if one of them is forced-idle]
13184  *
13185  * And (under assumption of SMT2) when there is forced-idle, there is only
13186  * a single queue, so everything works like normal.
13187  *
13188  * Let, for our runqueue 'k':
13189  *
13190  *   T_k = \Sum_i w_i s_i
13191  *   W_k = \Sum_i w_i      ; for all i of k                  (8)
13192  *
13193  * Then we can write (6) like:
13194  *
13195  *         T_k
13196  *   S_k = ---                                               (9)
13197  *         W_k
13198  *
13199  * From which immediately follows that:
13200  *
13201  *           T_k + T_l
13202  *   S_k+l = ---------                                       (10)
13203  *           W_k + W_l
13204  *
13205  * On which we can define a combined lag:
13206  *
13207  *   lag_k+l(i) := S_k+l - s_i                               (11)
13208  *
13209  * And that gives us the tools to compare tasks across a combined runqueue.
13210  *
13211  *
13212  * Combined this gives the following:
13213  *
13214  *  a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
13215  *     using (7); this only requires storing single 'time'-stamps.
13216  *
13217  *  b) when comparing tasks between 2 runqueues of which one is forced-idle,
13218  *     compare the combined lag, per (11).
13219  *
13220  * Now, of course cgroups (I so hate them) make this more interesting in
13221  * that a) seems to suggest we need to iterate all cgroup on a CPU at such
13222  * boundaries, but I think we can avoid that. The force-idle is for the
13223  * whole CPU, all it's rqs. So we can mark it in the root and lazily
13224  * propagate downward on demand.
13225  */
13226 
13227 /*
13228  * So this sync is basically a relative reset of S to 0.
13229  *
13230  * So with 2 queues, when one goes idle, we drop them both to 0 and one
13231  * then increases due to not being idle, and the idle one builds up lag to
13232  * get re-elected. So far so simple, right?
13233  *
13234  * When there's 3, we can have the situation where 2 run and one is idle,
13235  * we sync to 0 and let the idle one build up lag to get re-election. Now
13236  * suppose another one also drops idle. At this point dropping all to 0
13237  * again would destroy the built-up lag from the queue that was already
13238  * idle, not good.
13239  *
13240  * So instead of syncing everything, we can:
13241  *
13242  *   less := !((s64)(s_a - s_b) <= 0)
13243  *
13244  *   (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
13245  *                             == v_a - (v_b - S_a + S_b)
13246  *
13247  * IOW, we can recast the (lag) comparison to a one-sided difference.
13248  * So if then, instead of syncing the whole queue, sync the idle queue
13249  * against the active queue with S_a + S_b at the point where we sync.
13250  *
13251  * (XXX consider the implication of living in a cyclic group: N / 2^n N)
13252  *
13253  * This gives us means of syncing single queues against the active queue,
13254  * and for already idle queues to preserve their build-up lag.
13255  *
13256  * Of course, then we get the situation where there's 2 active and one
13257  * going idle, who do we pick to sync against? Theory would have us sync
13258  * against the combined S, but as we've already demonstrated, there is no
13259  * such thing in infeasible weight scenarios.
13260  *
13261  * One thing I've considered; and this is where that core_active rudiment
13262  * came from, is having active queues sync up between themselves after
13263  * every tick. This limits the observed divergence due to the work
13264  * conservancy.
13265  *
13266  * On top of that, we can improve upon things by employing (10) here.
13267  */
13268 
13269 /*
13270  * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
13271  */
13272 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13273 			 bool forceidle)
13274 {
13275 	for_each_sched_entity(se) {
13276 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13277 
13278 		if (forceidle) {
13279 			if (cfs_rq->forceidle_seq == fi_seq)
13280 				break;
13281 			cfs_rq->forceidle_seq = fi_seq;
13282 		}
13283 
13284 		cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
13285 	}
13286 }
13287 
13288 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13289 {
13290 	struct sched_entity *se = &p->se;
13291 
13292 	if (p->sched_class != &fair_sched_class)
13293 		return;
13294 
13295 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13296 }
13297 
13298 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13299 			bool in_fi)
13300 {
13301 	struct rq *rq = task_rq(a);
13302 	const struct sched_entity *sea = &a->se;
13303 	const struct sched_entity *seb = &b->se;
13304 	struct cfs_rq *cfs_rqa;
13305 	struct cfs_rq *cfs_rqb;
13306 	s64 delta;
13307 
13308 	WARN_ON_ONCE(task_rq(b)->core != rq->core);
13309 
13310 #ifdef CONFIG_FAIR_GROUP_SCHED
13311 	/*
13312 	 * Find an se in the hierarchy for tasks a and b, such that the se's
13313 	 * are immediate siblings.
13314 	 */
13315 	while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13316 		int sea_depth = sea->depth;
13317 		int seb_depth = seb->depth;
13318 
13319 		if (sea_depth >= seb_depth)
13320 			sea = parent_entity(sea);
13321 		if (sea_depth <= seb_depth)
13322 			seb = parent_entity(seb);
13323 	}
13324 
13325 	se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13326 	se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13327 
13328 	cfs_rqa = sea->cfs_rq;
13329 	cfs_rqb = seb->cfs_rq;
13330 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13331 	cfs_rqa = &task_rq(a)->cfs;
13332 	cfs_rqb = &task_rq(b)->cfs;
13333 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13334 
13335 	/*
13336 	 * Find delta after normalizing se's vruntime with its cfs_rq's
13337 	 * zero_vruntime_fi, which would have been updated in prior calls
13338 	 * to se_fi_update().
13339 	 */
13340 	delta = vruntime_op(sea->vruntime, "-", seb->vruntime) +
13341 		vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi);
13342 
13343 	return delta > 0;
13344 }
13345 
13346 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13347 {
13348 	struct cfs_rq *cfs_rq;
13349 
13350 #ifdef CONFIG_FAIR_GROUP_SCHED
13351 	cfs_rq = task_group(p)->cfs_rq[cpu];
13352 #else
13353 	cfs_rq = &cpu_rq(cpu)->cfs;
13354 #endif
13355 	return throttled_hierarchy(cfs_rq);
13356 }
13357 #else /* !CONFIG_SCHED_CORE: */
13358 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13359 #endif /* !CONFIG_SCHED_CORE */
13360 
13361 /*
13362  * scheduler tick hitting a task of our scheduling class.
13363  *
13364  * NOTE: This function can be called remotely by the tick offload that
13365  * goes along full dynticks. Therefore no local assumption can be made
13366  * and everything must be accessed through the @rq and @curr passed in
13367  * parameters.
13368  */
13369 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13370 {
13371 	struct cfs_rq *cfs_rq;
13372 	struct sched_entity *se = &curr->se;
13373 
13374 	for_each_sched_entity(se) {
13375 		cfs_rq = cfs_rq_of(se);
13376 		entity_tick(cfs_rq, se, queued);
13377 	}
13378 
13379 	if (queued) {
13380 		if (!need_resched())
13381 			hrtick_start_fair(rq, curr);
13382 		return;
13383 	}
13384 
13385 	if (static_branch_unlikely(&sched_numa_balancing))
13386 		task_tick_numa(rq, curr);
13387 
13388 	update_misfit_status(curr, rq);
13389 	check_update_overutilized_status(task_rq(curr));
13390 
13391 	task_tick_core(rq, curr);
13392 }
13393 
13394 /*
13395  * called on fork with the child task as argument from the parent's context
13396  *  - child not yet on the tasklist
13397  *  - preemption disabled
13398  */
13399 static void task_fork_fair(struct task_struct *p)
13400 {
13401 	set_task_max_allowed_capacity(p);
13402 }
13403 
13404 /*
13405  * Priority of the task has changed. Check to see if we preempt
13406  * the current task.
13407  */
13408 static void
13409 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
13410 {
13411 	if (!task_on_rq_queued(p))
13412 		return;
13413 
13414 	if (p->prio == oldprio)
13415 		return;
13416 
13417 	if (rq->cfs.nr_queued == 1)
13418 		return;
13419 
13420 	/*
13421 	 * Reschedule if we are currently running on this runqueue and
13422 	 * our priority decreased, or if we are not currently running on
13423 	 * this runqueue and our priority is higher than the current's
13424 	 */
13425 	if (task_current_donor(rq, p)) {
13426 		if (p->prio > oldprio)
13427 			resched_curr(rq);
13428 	} else {
13429 		wakeup_preempt(rq, p, 0);
13430 	}
13431 }
13432 
13433 #ifdef CONFIG_FAIR_GROUP_SCHED
13434 /*
13435  * Propagate the changes of the sched_entity across the tg tree to make it
13436  * visible to the root
13437  */
13438 static void propagate_entity_cfs_rq(struct sched_entity *se)
13439 {
13440 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13441 
13442 	/*
13443 	 * If a task gets attached to this cfs_rq and before being queued,
13444 	 * it gets migrated to another CPU due to reasons like affinity
13445 	 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
13446 	 * that removed load decayed or it can cause faireness problem.
13447 	 */
13448 	if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13449 		list_add_leaf_cfs_rq(cfs_rq);
13450 
13451 	/* Start to propagate at parent */
13452 	se = se->parent;
13453 
13454 	for_each_sched_entity(se) {
13455 		cfs_rq = cfs_rq_of(se);
13456 
13457 		update_load_avg(cfs_rq, se, UPDATE_TG);
13458 
13459 		if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13460 			list_add_leaf_cfs_rq(cfs_rq);
13461 	}
13462 
13463 	assert_list_leaf_cfs_rq(rq_of(cfs_rq));
13464 }
13465 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13466 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13467 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13468 
13469 static void detach_entity_cfs_rq(struct sched_entity *se)
13470 {
13471 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13472 
13473 	/*
13474 	 * In case the task sched_avg hasn't been attached:
13475 	 * - A forked task which hasn't been woken up by wake_up_new_task().
13476 	 * - A task which has been woken up by try_to_wake_up() but is
13477 	 *   waiting for actually being woken up by sched_ttwu_pending().
13478 	 */
13479 	if (!se->avg.last_update_time)
13480 		return;
13481 
13482 	/* Catch up with the cfs_rq and remove our load when we leave */
13483 	update_load_avg(cfs_rq, se, 0);
13484 	detach_entity_load_avg(cfs_rq, se);
13485 	update_tg_load_avg(cfs_rq);
13486 	propagate_entity_cfs_rq(se);
13487 }
13488 
13489 static void attach_entity_cfs_rq(struct sched_entity *se)
13490 {
13491 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13492 
13493 	/* Synchronize entity with its cfs_rq */
13494 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13495 	attach_entity_load_avg(cfs_rq, se);
13496 	update_tg_load_avg(cfs_rq);
13497 	propagate_entity_cfs_rq(se);
13498 }
13499 
13500 static void detach_task_cfs_rq(struct task_struct *p)
13501 {
13502 	struct sched_entity *se = &p->se;
13503 
13504 	detach_entity_cfs_rq(se);
13505 }
13506 
13507 static void attach_task_cfs_rq(struct task_struct *p)
13508 {
13509 	struct sched_entity *se = &p->se;
13510 
13511 	attach_entity_cfs_rq(se);
13512 }
13513 
13514 static void switching_from_fair(struct rq *rq, struct task_struct *p)
13515 {
13516 	if (p->se.sched_delayed)
13517 		dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
13518 }
13519 
13520 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13521 {
13522 	detach_task_cfs_rq(p);
13523 }
13524 
13525 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13526 {
13527 	WARN_ON_ONCE(p->se.sched_delayed);
13528 
13529 	attach_task_cfs_rq(p);
13530 
13531 	set_task_max_allowed_capacity(p);
13532 
13533 	if (task_on_rq_queued(p)) {
13534 		/*
13535 		 * We were most likely switched from sched_rt, so
13536 		 * kick off the schedule if running, otherwise just see
13537 		 * if we can still preempt the current task.
13538 		 */
13539 		if (task_current_donor(rq, p))
13540 			resched_curr(rq);
13541 		else
13542 			wakeup_preempt(rq, p, 0);
13543 	}
13544 }
13545 
13546 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13547 {
13548 	struct sched_entity *se = &p->se;
13549 
13550 	if (task_on_rq_queued(p)) {
13551 		/*
13552 		 * Move the next running task to the front of the list, so our
13553 		 * cfs_tasks list becomes MRU one.
13554 		 */
13555 		list_move(&se->group_node, &rq->cfs_tasks);
13556 	}
13557 	if (!first)
13558 		return;
13559 
13560 	WARN_ON_ONCE(se->sched_delayed);
13561 
13562 	if (hrtick_enabled_fair(rq))
13563 		hrtick_start_fair(rq, p);
13564 
13565 	update_misfit_status(p, rq);
13566 	sched_fair_update_stop_tick(rq, p);
13567 }
13568 
13569 /*
13570  * Account for a task changing its policy or group.
13571  *
13572  * This routine is mostly called to set cfs_rq->curr field when a task
13573  * migrates between groups/classes.
13574  */
13575 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13576 {
13577 	struct sched_entity *se = &p->se;
13578 
13579 	for_each_sched_entity(se) {
13580 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13581 
13582 		set_next_entity(cfs_rq, se);
13583 		/* ensure bandwidth has been allocated on our new cfs_rq */
13584 		account_cfs_rq_runtime(cfs_rq, 0);
13585 	}
13586 
13587 	__set_next_task_fair(rq, p, first);
13588 }
13589 
13590 void init_cfs_rq(struct cfs_rq *cfs_rq)
13591 {
13592 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13593 	cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
13594 	raw_spin_lock_init(&cfs_rq->removed.lock);
13595 }
13596 
13597 #ifdef CONFIG_FAIR_GROUP_SCHED
13598 static void task_change_group_fair(struct task_struct *p)
13599 {
13600 	/*
13601 	 * We couldn't detach or attach a forked task which
13602 	 * hasn't been woken up by wake_up_new_task().
13603 	 */
13604 	if (READ_ONCE(p->__state) == TASK_NEW)
13605 		return;
13606 
13607 	detach_task_cfs_rq(p);
13608 
13609 	/* Tell se's cfs_rq has been changed -- migrated */
13610 	p->se.avg.last_update_time = 0;
13611 	set_task_rq(p, task_cpu(p));
13612 	attach_task_cfs_rq(p);
13613 }
13614 
13615 void free_fair_sched_group(struct task_group *tg)
13616 {
13617 	int i;
13618 
13619 	for_each_possible_cpu(i) {
13620 		if (tg->cfs_rq)
13621 			kfree(tg->cfs_rq[i]);
13622 		if (tg->se)
13623 			kfree(tg->se[i]);
13624 	}
13625 
13626 	kfree(tg->cfs_rq);
13627 	kfree(tg->se);
13628 }
13629 
13630 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13631 {
13632 	struct sched_entity *se;
13633 	struct cfs_rq *cfs_rq;
13634 	int i;
13635 
13636 	tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13637 	if (!tg->cfs_rq)
13638 		goto err;
13639 	tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13640 	if (!tg->se)
13641 		goto err;
13642 
13643 	tg->shares = NICE_0_LOAD;
13644 
13645 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13646 
13647 	for_each_possible_cpu(i) {
13648 		cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13649 				      GFP_KERNEL, cpu_to_node(i));
13650 		if (!cfs_rq)
13651 			goto err;
13652 
13653 		se = kzalloc_node(sizeof(struct sched_entity_stats),
13654 				  GFP_KERNEL, cpu_to_node(i));
13655 		if (!se)
13656 			goto err_free_rq;
13657 
13658 		init_cfs_rq(cfs_rq);
13659 		init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13660 		init_entity_runnable_average(se);
13661 	}
13662 
13663 	return 1;
13664 
13665 err_free_rq:
13666 	kfree(cfs_rq);
13667 err:
13668 	return 0;
13669 }
13670 
13671 void online_fair_sched_group(struct task_group *tg)
13672 {
13673 	struct sched_entity *se;
13674 	struct rq_flags rf;
13675 	struct rq *rq;
13676 	int i;
13677 
13678 	for_each_possible_cpu(i) {
13679 		rq = cpu_rq(i);
13680 		se = tg->se[i];
13681 		rq_lock_irq(rq, &rf);
13682 		update_rq_clock(rq);
13683 		attach_entity_cfs_rq(se);
13684 		sync_throttle(tg, i);
13685 		rq_unlock_irq(rq, &rf);
13686 	}
13687 }
13688 
13689 void unregister_fair_sched_group(struct task_group *tg)
13690 {
13691 	int cpu;
13692 
13693 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13694 
13695 	for_each_possible_cpu(cpu) {
13696 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13697 		struct sched_entity *se = tg->se[cpu];
13698 		struct rq *rq = cpu_rq(cpu);
13699 
13700 		if (se) {
13701 			if (se->sched_delayed) {
13702 				guard(rq_lock_irqsave)(rq);
13703 				if (se->sched_delayed) {
13704 					update_rq_clock(rq);
13705 					dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13706 				}
13707 				list_del_leaf_cfs_rq(cfs_rq);
13708 			}
13709 			remove_entity_load_avg(se);
13710 		}
13711 
13712 		/*
13713 		 * Only empty task groups can be destroyed; so we can speculatively
13714 		 * check on_list without danger of it being re-added.
13715 		 */
13716 		if (cfs_rq->on_list) {
13717 			guard(rq_lock_irqsave)(rq);
13718 			list_del_leaf_cfs_rq(cfs_rq);
13719 		}
13720 	}
13721 }
13722 
13723 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13724 			struct sched_entity *se, int cpu,
13725 			struct sched_entity *parent)
13726 {
13727 	struct rq *rq = cpu_rq(cpu);
13728 
13729 	cfs_rq->tg = tg;
13730 	cfs_rq->rq = rq;
13731 	init_cfs_rq_runtime(cfs_rq);
13732 
13733 	tg->cfs_rq[cpu] = cfs_rq;
13734 	tg->se[cpu] = se;
13735 
13736 	/* se could be NULL for root_task_group */
13737 	if (!se)
13738 		return;
13739 
13740 	if (!parent) {
13741 		se->cfs_rq = &rq->cfs;
13742 		se->depth = 0;
13743 	} else {
13744 		se->cfs_rq = parent->my_q;
13745 		se->depth = parent->depth + 1;
13746 	}
13747 
13748 	se->my_q = cfs_rq;
13749 	/* guarantee group entities always have weight */
13750 	update_load_set(&se->load, NICE_0_LOAD);
13751 	se->parent = parent;
13752 }
13753 
13754 static DEFINE_MUTEX(shares_mutex);
13755 
13756 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13757 {
13758 	int i;
13759 
13760 	lockdep_assert_held(&shares_mutex);
13761 
13762 	/*
13763 	 * We can't change the weight of the root cgroup.
13764 	 */
13765 	if (!tg->se[0])
13766 		return -EINVAL;
13767 
13768 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13769 
13770 	if (tg->shares == shares)
13771 		return 0;
13772 
13773 	tg->shares = shares;
13774 	for_each_possible_cpu(i) {
13775 		struct rq *rq = cpu_rq(i);
13776 		struct sched_entity *se = tg->se[i];
13777 		struct rq_flags rf;
13778 
13779 		/* Propagate contribution to hierarchy */
13780 		rq_lock_irqsave(rq, &rf);
13781 		update_rq_clock(rq);
13782 		for_each_sched_entity(se) {
13783 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13784 			update_cfs_group(se);
13785 		}
13786 		rq_unlock_irqrestore(rq, &rf);
13787 	}
13788 
13789 	return 0;
13790 }
13791 
13792 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13793 {
13794 	int ret;
13795 
13796 	mutex_lock(&shares_mutex);
13797 	if (tg_is_idle(tg))
13798 		ret = -EINVAL;
13799 	else
13800 		ret = __sched_group_set_shares(tg, shares);
13801 	mutex_unlock(&shares_mutex);
13802 
13803 	return ret;
13804 }
13805 
13806 int sched_group_set_idle(struct task_group *tg, long idle)
13807 {
13808 	int i;
13809 
13810 	if (tg == &root_task_group)
13811 		return -EINVAL;
13812 
13813 	if (idle < 0 || idle > 1)
13814 		return -EINVAL;
13815 
13816 	mutex_lock(&shares_mutex);
13817 
13818 	if (tg->idle == idle) {
13819 		mutex_unlock(&shares_mutex);
13820 		return 0;
13821 	}
13822 
13823 	tg->idle = idle;
13824 
13825 	for_each_possible_cpu(i) {
13826 		struct rq *rq = cpu_rq(i);
13827 		struct sched_entity *se = tg->se[i];
13828 		struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
13829 		bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13830 		long idle_task_delta;
13831 		struct rq_flags rf;
13832 
13833 		rq_lock_irqsave(rq, &rf);
13834 
13835 		grp_cfs_rq->idle = idle;
13836 		if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13837 			goto next_cpu;
13838 
13839 		idle_task_delta = grp_cfs_rq->h_nr_queued -
13840 				  grp_cfs_rq->h_nr_idle;
13841 		if (!cfs_rq_is_idle(grp_cfs_rq))
13842 			idle_task_delta *= -1;
13843 
13844 		for_each_sched_entity(se) {
13845 			struct cfs_rq *cfs_rq = cfs_rq_of(se);
13846 
13847 			if (!se->on_rq)
13848 				break;
13849 
13850 			cfs_rq->h_nr_idle += idle_task_delta;
13851 
13852 			/* Already accounted at parent level and above. */
13853 			if (cfs_rq_is_idle(cfs_rq))
13854 				break;
13855 		}
13856 
13857 next_cpu:
13858 		rq_unlock_irqrestore(rq, &rf);
13859 	}
13860 
13861 	/* Idle groups have minimum weight. */
13862 	if (tg_is_idle(tg))
13863 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13864 	else
13865 		__sched_group_set_shares(tg, NICE_0_LOAD);
13866 
13867 	mutex_unlock(&shares_mutex);
13868 	return 0;
13869 }
13870 
13871 #endif /* CONFIG_FAIR_GROUP_SCHED */
13872 
13873 
13874 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13875 {
13876 	struct sched_entity *se = &task->se;
13877 	unsigned int rr_interval = 0;
13878 
13879 	/*
13880 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13881 	 * idle runqueue:
13882 	 */
13883 	if (rq->cfs.load.weight)
13884 		rr_interval = NS_TO_JIFFIES(se->slice);
13885 
13886 	return rr_interval;
13887 }
13888 
13889 /*
13890  * All the scheduling class methods:
13891  */
13892 DEFINE_SCHED_CLASS(fair) = {
13893 	.enqueue_task		= enqueue_task_fair,
13894 	.dequeue_task		= dequeue_task_fair,
13895 	.yield_task		= yield_task_fair,
13896 	.yield_to_task		= yield_to_task_fair,
13897 
13898 	.wakeup_preempt		= wakeup_preempt_fair,
13899 
13900 	.pick_task		= pick_task_fair,
13901 	.pick_next_task		= pick_next_task_fair,
13902 	.put_prev_task		= put_prev_task_fair,
13903 	.set_next_task          = set_next_task_fair,
13904 
13905 	.select_task_rq		= select_task_rq_fair,
13906 	.migrate_task_rq	= migrate_task_rq_fair,
13907 
13908 	.rq_online		= rq_online_fair,
13909 	.rq_offline		= rq_offline_fair,
13910 
13911 	.task_dead		= task_dead_fair,
13912 	.set_cpus_allowed	= set_cpus_allowed_fair,
13913 
13914 	.task_tick		= task_tick_fair,
13915 	.task_fork		= task_fork_fair,
13916 
13917 	.reweight_task		= reweight_task_fair,
13918 	.prio_changed		= prio_changed_fair,
13919 	.switching_from		= switching_from_fair,
13920 	.switched_from		= switched_from_fair,
13921 	.switched_to		= switched_to_fair,
13922 
13923 	.get_rr_interval	= get_rr_interval_fair,
13924 
13925 	.update_curr		= update_curr_fair,
13926 
13927 #ifdef CONFIG_FAIR_GROUP_SCHED
13928 	.task_change_group	= task_change_group_fair,
13929 #endif
13930 
13931 #ifdef CONFIG_SCHED_CORE
13932 	.task_is_throttled	= task_is_throttled_fair,
13933 #endif
13934 
13935 #ifdef CONFIG_UCLAMP_TASK
13936 	.uclamp_enabled		= 1,
13937 #endif
13938 };
13939 
13940 void print_cfs_stats(struct seq_file *m, int cpu)
13941 {
13942 	struct cfs_rq *cfs_rq, *pos;
13943 
13944 	rcu_read_lock();
13945 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13946 		print_cfs_rq(m, cpu, cfs_rq);
13947 	rcu_read_unlock();
13948 }
13949 
13950 #ifdef CONFIG_NUMA_BALANCING
13951 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13952 {
13953 	int node;
13954 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13955 	struct numa_group *ng;
13956 
13957 	rcu_read_lock();
13958 	ng = rcu_dereference_all(p->numa_group);
13959 	for_each_online_node(node) {
13960 		if (p->numa_faults) {
13961 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13962 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13963 		}
13964 		if (ng) {
13965 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13966 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13967 		}
13968 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13969 	}
13970 	rcu_read_unlock();
13971 }
13972 #endif /* CONFIG_NUMA_BALANCING */
13973 
13974 __init void init_sched_fair_class(void)
13975 {
13976 	int i;
13977 
13978 	for_each_possible_cpu(i) {
13979 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13980 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
13981 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13982 					GFP_KERNEL, cpu_to_node(i));
13983 
13984 #ifdef CONFIG_CFS_BANDWIDTH
13985 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13986 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13987 #endif
13988 	}
13989 
13990 	open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
13991 
13992 #ifdef CONFIG_NO_HZ_COMMON
13993 	nohz.next_balance = jiffies;
13994 	nohz.next_blocked = jiffies;
13995 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13996 #endif
13997 }
13998