xref: /linux/kernel/sched/fair.c (revision 342fe98c34311969950fa58a840fd0b95a16c9dd)
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, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
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/jiffies.h>
26 #include <linux/math.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/hrtimer.h>
30 #include <linux/hrtimer_bases.h>
31 #include <linux/spinlock_api.h>
32 #include <linux/cpumask_api.h>
33 #include <linux/lockdep_api.h>
34 #include <linux/softirq.h>
35 #include <linux/refcount_api.h>
36 #include <linux/topology.h>
37 #include <linux/sched/clock.h>
38 #include <linux/sched/cond_resched.h>
39 #include <linux/sched/cputime.h>
40 #include <linux/sched/isolation.h>
41 #include <linux/sched/nohz.h>
42 #include <linux/sched/prio.h>
43 #include <linux/static_call.h>
44 
45 #include <linux/cpuidle.h>
46 #include <linux/interrupt.h>
47 #include <linux/memory-tiers.h>
48 #include <linux/mempolicy.h>
49 #include <linux/mutex_api.h>
50 #include <linux/profile.h>
51 #include <linux/psi.h>
52 #include <linux/ratelimit.h>
53 #include <linux/task_work.h>
54 #include <linux/rbtree_augmented.h>
55 
56 #include <asm/switch_to.h>
57 
58 #include <uapi/linux/sched/types.h>
59 
60 #include "sched.h"
61 #include "stats.h"
62 #include "autogroup.h"
63 
64 /*
65  * The initial- and re-scaling of tunables is configurable
66  *
67  * Options are:
68  *
69  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
70  *   SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
71  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
72  *
73  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
74  */
75 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
76 
77 /*
78  * Default base time slice (request size r_i) for SCHED_NORMAL/SCHED_BATCH:
79  *
80  * Under EEVDF this is the request size used to compute the virtual
81  * deadline; see update_deadline().
82  *
83  * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
84  */
85 unsigned int sysctl_sched_base_slice			= 700000ULL;
86 static unsigned int normalized_sysctl_sched_base_slice	= 700000ULL;
87 
88 __read_mostly unsigned int sysctl_sched_migration_cost	= 500000UL;
89 
90 static int __init setup_sched_thermal_decay_shift(char *str)
91 {
92 	pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
93 	return 1;
94 }
95 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
96 
97 /*
98  * For asym packing, by default the lower numbered CPU has higher priority.
99  */
100 int __weak arch_asym_cpu_priority(int cpu)
101 {
102 	return -cpu;
103 }
104 
105 /*
106  * The margin used when comparing utilization with CPU capacity.
107  *
108  * (default: ~20%)
109  */
110 #define fits_capacity(cap, max)	((cap) * 1280 < (max) * 1024)
111 
112 /*
113  * The margin used when comparing CPU capacities.
114  * is 'cap1' noticeably greater than 'cap2'
115  *
116  * (default: ~5%)
117  */
118 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
119 
120 #ifdef CONFIG_CFS_BANDWIDTH
121 /*
122  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
123  * each time a cfs_rq requests quota.
124  *
125  * Note: in the case that the slice exceeds the runtime remaining (either due
126  * to consumption or the quota being specified to be smaller than the slice)
127  * we will always only issue the remaining available time.
128  *
129  * (default: 5 msec, units: microseconds)
130  */
131 static unsigned int sysctl_sched_cfs_bandwidth_slice		= 5000UL;
132 #endif
133 
134 #ifdef CONFIG_NUMA_BALANCING
135 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
136 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
137 #endif
138 
139 #ifdef CONFIG_SYSCTL
140 static const struct ctl_table sched_fair_sysctls[] = {
141 #ifdef CONFIG_CFS_BANDWIDTH
142 	{
143 		.procname       = "sched_cfs_bandwidth_slice_us",
144 		.data           = &sysctl_sched_cfs_bandwidth_slice,
145 		.maxlen         = sizeof(unsigned int),
146 		.mode           = 0644,
147 		.proc_handler   = proc_dointvec_minmax,
148 		.extra1         = SYSCTL_ONE,
149 	},
150 #endif
151 #ifdef CONFIG_NUMA_BALANCING
152 	{
153 		.procname	= "numa_balancing_promote_rate_limit_MBps",
154 		.data		= &sysctl_numa_balancing_promote_rate_limit,
155 		.maxlen		= sizeof(unsigned int),
156 		.mode		= 0644,
157 		.proc_handler	= proc_dointvec_minmax,
158 		.extra1		= SYSCTL_ZERO,
159 	},
160 #endif /* CONFIG_NUMA_BALANCING */
161 };
162 
163 static int __init sched_fair_sysctl_init(void)
164 {
165 	register_sysctl_init("kernel", sched_fair_sysctls);
166 	return 0;
167 }
168 late_initcall(sched_fair_sysctl_init);
169 #endif /* CONFIG_SYSCTL */
170 
171 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
172 {
173 	lw->weight += inc;
174 	lw->inv_weight = 0;
175 }
176 
177 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
178 {
179 	lw->weight -= dec;
180 	lw->inv_weight = 0;
181 }
182 
183 static inline void update_load_set(struct load_weight *lw, unsigned long w)
184 {
185 	lw->weight = w;
186 	lw->inv_weight = 0;
187 }
188 
189 /*
190  * Increase the granularity value when there are more CPUs,
191  * because with more CPUs the 'effective latency' as visible
192  * to users decreases. But the relationship is not linear,
193  * so pick a second-best guess by going with the log2 of the
194  * number of CPUs.
195  *
196  * This idea comes from the SD scheduler of Con Kolivas:
197  */
198 static unsigned int get_update_sysctl_factor(void)
199 {
200 	unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
201 	unsigned int factor;
202 
203 	switch (sysctl_sched_tunable_scaling) {
204 	case SCHED_TUNABLESCALING_NONE:
205 		factor = 1;
206 		break;
207 	case SCHED_TUNABLESCALING_LINEAR:
208 		factor = cpus;
209 		break;
210 	case SCHED_TUNABLESCALING_LOG:
211 	default:
212 		factor = 1 + ilog2(cpus);
213 		break;
214 	}
215 
216 	return factor;
217 }
218 
219 static void update_sysctl(void)
220 {
221 	unsigned int factor = get_update_sysctl_factor();
222 
223 #define SET_SYSCTL(name) \
224 	(sysctl_##name = (factor) * normalized_sysctl_##name)
225 	SET_SYSCTL(sched_base_slice);
226 #undef SET_SYSCTL
227 }
228 
229 void __init sched_init_granularity(void)
230 {
231 	update_sysctl();
232 }
233 
234 #ifndef CONFIG_64BIT
235 #define WMULT_CONST	(~0U)
236 #define WMULT_SHIFT	32
237 
238 static void __update_inv_weight(struct load_weight *lw)
239 {
240 	unsigned long w;
241 
242 	if (likely(lw->inv_weight))
243 		return;
244 
245 	w = scale_load_down(lw->weight);
246 
247 	if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
248 		lw->inv_weight = 1;
249 	else if (unlikely(!w))
250 		lw->inv_weight = WMULT_CONST;
251 	else
252 		lw->inv_weight = WMULT_CONST / w;
253 }
254 
255 /*
256  * delta_exec * weight / lw.weight
257  *   OR
258  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
259  *
260  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
261  * we're guaranteed shift stays positive because inv_weight is guaranteed to
262  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
263  *
264  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
265  * weight/lw.weight <= 1, and therefore our shift will also be positive.
266  */
267 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
268 {
269 	u64 fact = scale_load_down(weight);
270 	u32 fact_hi = (u32)(fact >> 32);
271 	int shift = WMULT_SHIFT;
272 	int fs;
273 
274 	__update_inv_weight(lw);
275 
276 	if (unlikely(fact_hi)) {
277 		fs = fls(fact_hi);
278 		shift -= fs;
279 		fact >>= fs;
280 	}
281 
282 	fact = mul_u32_u32(fact, lw->inv_weight);
283 
284 	fact_hi = (u32)(fact >> 32);
285 	if (fact_hi) {
286 		fs = fls(fact_hi);
287 		shift -= fs;
288 		fact >>= fs;
289 	}
290 
291 	return mul_u64_u32_shr(delta_exec, fact, shift);
292 }
293 #else
294 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
295 {
296 	return (delta_exec * weight) / lw->weight;
297 }
298 #endif
299 
300 /*
301  * delta /= w
302  */
303 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
304 {
305 	if (se->h_load.weight != NICE_0_LOAD)
306 		delta = __calc_delta(delta, NICE_0_LOAD, &se->h_load);
307 
308 	return delta;
309 }
310 
311 const struct sched_class fair_sched_class;
312 
313 /**************************************************************
314  * CFS operations on generic schedulable entities:
315  */
316 
317 #ifdef CONFIG_FAIR_GROUP_SCHED
318 
319 /* Walk up scheduling entities hierarchy */
320 #define for_each_sched_entity(se) \
321 		for (; se; se = se->parent)
322 
323 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
324 {
325 	struct rq *rq = rq_of(cfs_rq);
326 	int cpu = cpu_of(rq);
327 
328 	if (cfs_rq->on_list)
329 		return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
330 
331 	cfs_rq->on_list = 1;
332 
333 	/*
334 	 * Ensure we either appear before our parent (if already
335 	 * enqueued) or force our parent to appear after us when it is
336 	 * enqueued. The fact that we always enqueue bottom-up
337 	 * reduces this to two cases and a special case for the root
338 	 * cfs_rq. Furthermore, it also means that we will always reset
339 	 * tmp_alone_branch either when the branch is connected
340 	 * to a tree or when we reach the top of the tree
341 	 */
342 	if (cfs_rq->tg->parent &&
343 	    tg_cfs_rq(cfs_rq->tg->parent, cpu)->on_list) {
344 		/*
345 		 * If parent is already on the list, we add the child
346 		 * just before. Thanks to circular linked property of
347 		 * the list, this means to put the child at the tail
348 		 * of the list that starts by parent.
349 		 */
350 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
351 			&(tg_cfs_rq(cfs_rq->tg->parent, cpu)->leaf_cfs_rq_list));
352 		/*
353 		 * The branch is now connected to its tree so we can
354 		 * reset tmp_alone_branch to the beginning of the
355 		 * list.
356 		 */
357 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
358 		return true;
359 	}
360 
361 	if (!cfs_rq->tg->parent) {
362 		/*
363 		 * cfs rq without parent should be put
364 		 * at the tail of the list.
365 		 */
366 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
367 			&rq->leaf_cfs_rq_list);
368 		/*
369 		 * We have reach the top of a tree so we can reset
370 		 * tmp_alone_branch to the beginning of the list.
371 		 */
372 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
373 		return true;
374 	}
375 
376 	/*
377 	 * The parent has not already been added so we want to
378 	 * make sure that it will be put after us.
379 	 * tmp_alone_branch points to the begin of the branch
380 	 * where we will add parent.
381 	 */
382 	list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
383 	/*
384 	 * update tmp_alone_branch to points to the new begin
385 	 * of the branch
386 	 */
387 	rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
388 	return false;
389 }
390 
391 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
392 {
393 	if (cfs_rq->on_list) {
394 		struct rq *rq = rq_of(cfs_rq);
395 
396 		/*
397 		 * With cfs_rq being unthrottled/throttled during an enqueue,
398 		 * it can happen the tmp_alone_branch points to the leaf that
399 		 * we finally want to delete. In this case, tmp_alone_branch moves
400 		 * to the prev element but it will point to rq->leaf_cfs_rq_list
401 		 * at the end of the enqueue.
402 		 */
403 		if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
404 			rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
405 
406 		list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
407 		cfs_rq->on_list = 0;
408 	}
409 }
410 
411 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
412 {
413 	WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
414 }
415 
416 /* Iterate through all leaf cfs_rq's on a runqueue */
417 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)			\
418 	list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,	\
419 				 leaf_cfs_rq_list)
420 
421 /* Do the two (enqueued) entities belong to the same group ? */
422 static inline struct cfs_rq *
423 is_same_group(struct sched_entity *se, struct sched_entity *pse)
424 {
425 	if (se->cfs_rq == pse->cfs_rq)
426 		return se->cfs_rq;
427 
428 	return NULL;
429 }
430 
431 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
432 {
433 	return se->parent;
434 }
435 
436 static int tg_is_idle(struct task_group *tg)
437 {
438 	return tg->idle > 0;
439 }
440 
441 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
442 {
443 	return cfs_rq->idle > 0;
444 }
445 
446 static int se_is_idle(struct sched_entity *se)
447 {
448 	if (entity_is_task(se)) {
449 		return task_has_idle_policy(task_of(se)) ||
450 			cfs_rq_is_idle(cfs_rq_of(se));
451 	}
452 	return cfs_rq_is_idle(group_cfs_rq(se));
453 }
454 
455 #else /* !CONFIG_FAIR_GROUP_SCHED: */
456 
457 #define for_each_sched_entity(se) \
458 		for (; se; se = NULL)
459 
460 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
461 {
462 	return true;
463 }
464 
465 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
466 {
467 }
468 
469 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
470 {
471 }
472 
473 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
474 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
475 
476 static inline struct sched_entity *parent_entity(struct sched_entity *se)
477 {
478 	return NULL;
479 }
480 
481 static inline int tg_is_idle(struct task_group *tg)
482 {
483 	return 0;
484 }
485 
486 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
487 {
488 	return 0;
489 }
490 
491 static int se_is_idle(struct sched_entity *se)
492 {
493 	return task_has_idle_policy(task_of(se));
494 }
495 
496 #endif /* !CONFIG_FAIR_GROUP_SCHED */
497 
498 static __always_inline
499 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
500 
501 /**************************************************************
502  * Scheduling class tree data structure manipulation methods:
503  */
504 
505 extern void __BUILD_BUG_vruntime_cmp(void);
506 
507 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */
508 
509 #define vruntime_cmp(A, CMP_STR, B) ({				\
510 	int __res = 0;						\
511 								\
512 	if (!__builtin_strcmp(CMP_STR, "<")) {			\
513 		__res = ((s64)((A)-(B)) < 0);			\
514 	} else if (!__builtin_strcmp(CMP_STR, "<=")) {		\
515 		__res = ((s64)((A)-(B)) <= 0);			\
516 	} else if (!__builtin_strcmp(CMP_STR, ">")) {		\
517 		__res = ((s64)((A)-(B)) > 0);			\
518 	} else if (!__builtin_strcmp(CMP_STR, ">=")) {		\
519 		__res = ((s64)((A)-(B)) >= 0);			\
520 	} else {						\
521 		/* Unknown operator throws linker error: */	\
522 		__BUILD_BUG_vruntime_cmp();			\
523 	}							\
524 								\
525 	__res;							\
526 })
527 
528 extern void __BUILD_BUG_vruntime_op(void);
529 
530 #define vruntime_op(A, OP_STR, B) ({				\
531 	s64 __res = 0;						\
532 								\
533 	if (!__builtin_strcmp(OP_STR, "-")) {			\
534 		__res = (s64)((A)-(B));				\
535 	} else {						\
536 		/* Unknown operator throws linker error: */	\
537 		__BUILD_BUG_vruntime_op();			\
538 	}							\
539 								\
540 	__res;						\
541 })
542 
543 
544 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
545 {
546 	if (vruntime_cmp(vruntime, ">", max_vruntime))
547 		max_vruntime = vruntime;
548 
549 	return max_vruntime;
550 }
551 
552 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
553 {
554 	if (vruntime_cmp(vruntime, "<", min_vruntime))
555 		min_vruntime = vruntime;
556 
557 	return min_vruntime;
558 }
559 
560 static inline bool entity_before(const struct sched_entity *a,
561 				 const struct sched_entity *b)
562 {
563 	/*
564 	 * Tiebreak on vruntime seems unnecessary since it can
565 	 * hardly happen.
566 	 */
567 	return vruntime_cmp(a->deadline, "<", b->deadline);
568 }
569 
570 /*
571  * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale
572  * and this value should be no more than two lag bounds. Which puts it in the
573  * general order of:
574  *
575  *	(slice + TICK_NSEC) << NICE_0_LOAD_SHIFT
576  *
577  * which is around 44 bits in size (on 64bit); that is 20 for
578  * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for
579  * however many msec the actual slice+tick ends up begin.
580  *
581  * (disregarding the actual divide-by-weight part makes for the worst case
582  * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually
583  * being the zero-lag point).
584  */
585 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
586 {
587 	return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime);
588 }
589 
590 #define __node_2_se(node) \
591 	rb_entry((node), struct sched_entity, run_node)
592 
593 /*
594  * Compute virtual time from the per-task service numbers:
595  *
596  * Fair schedulers conserve lag:
597  *
598  *   \Sum lag_i = 0
599  *
600  * Where lag_i is given by:
601  *
602  *   lag_i = S - s_i = w_i * (V - v_i)
603  *
604  * Where S is the ideal service time and V is it's virtual time counterpart.
605  * Therefore:
606  *
607  *   \Sum lag_i = 0
608  *   \Sum w_i * (V - v_i) = 0
609  *   \Sum (w_i * V - w_i * v_i) = 0
610  *
611  * From which we can solve an expression for V in v_i (which we have in
612  * se->vruntime):
613  *
614  *       \Sum v_i * w_i   \Sum v_i * w_i
615  *   V = -------------- = --------------
616  *          \Sum w_i            W
617  *
618  * Specifically, this is the weighted average of all entity virtual runtimes.
619  *
620  * [[ NOTE: this is only equal to the ideal scheduler under the condition
621  *          that join/leave operations happen at lag_i = 0, otherwise the
622  *          virtual time has non-contiguous motion equivalent to:
623  *
624  *	      V +-= lag_i / W
625  *
626  *	    Also see the comment in place_entity() that deals with this. ]]
627  *
628  * However, since v_i is u64, and the multiplication could easily overflow
629  * transform it into a relative form that uses smaller quantities:
630  *
631  * Substitute: v_i == (v_i - v0) + v0
632  *
633  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
634  * V = ---------------------------- = --------------------- + v0
635  *                  W                            W
636  *
637  * Which we track using:
638  *
639  *                    v0 := cfs_rq->zero_vruntime
640  * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime
641  *              \Sum w_i := cfs_rq->sum_weight
642  *
643  * Since zero_vruntime closely tracks the per-task service, these
644  * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag
645  * induced in the system due to quantisation.
646  */
647 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w)
648 {
649 #ifdef CONFIG_64BIT
650 	if (cfs_rq->sum_shift)
651 		w = max(2UL, w >> cfs_rq->sum_shift);
652 #endif
653 	return w;
654 }
655 
656 static inline void
657 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
658 {
659 	unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
660 	s64 w_vruntime, key = entity_key(cfs_rq, se);
661 
662 	w_vruntime = key * weight;
663 	WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62));
664 
665 	cfs_rq->sum_w_vruntime += w_vruntime;
666 	cfs_rq->sum_weight += weight;
667 }
668 
669 static void
670 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se)
671 {
672 	unsigned long weight;
673 	s64 key, tmp;
674 
675 again:
676 	weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
677 	key = entity_key(cfs_rq, se);
678 
679 	if (check_mul_overflow(key, weight, &key))
680 		goto overflow;
681 
682 	if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp))
683 		goto overflow;
684 
685 	cfs_rq->sum_w_vruntime = tmp;
686 	cfs_rq->sum_weight += weight;
687 	return;
688 
689 overflow:
690 	/*
691 	 * There's gotta be a limit -- if we're still failing at this point
692 	 * there's really nothing much to be done about things.
693 	 */
694 	BUG_ON(cfs_rq->sum_shift >= 10);
695 	cfs_rq->sum_shift++;
696 
697 	/*
698 	 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1
699 	 */
700 	cfs_rq->sum_w_vruntime = 0;
701 	cfs_rq->sum_weight = 0;
702 
703 	for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost;
704 	     node; node = rb_next(node))
705 		__sum_w_vruntime_add(cfs_rq, __node_2_se(node));
706 
707 	goto again;
708 }
709 
710 static void
711 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
712 {
713 	if (sched_feat(PARANOID_AVG))
714 		return sum_w_vruntime_add_paranoid(cfs_rq, se);
715 
716 	__sum_w_vruntime_add(cfs_rq, se);
717 }
718 
719 static void
720 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
721 {
722 	unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
723 	s64 key = entity_key(cfs_rq, se);
724 
725 	cfs_rq->sum_w_vruntime -= key * weight;
726 	cfs_rq->sum_weight -= weight;
727 }
728 
729 static inline
730 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta)
731 {
732 	/*
733 	 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight
734 	 */
735 	cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta;
736 	cfs_rq->zero_vruntime += delta;
737 }
738 
739 /*
740  * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true
741  * For this to be so, the result of this function must have a left bias.
742  *
743  * Called in:
744  *  - place_entity()      -- before enqueue
745  *  - update_entity_lag() -- before dequeue
746  *  - update_deadline()   -- slice expiration
747  *
748  * This means it is one entry 'behind' but that puts it close enough to where
749  * the bound on entity_key() is at most two lag bounds.
750  */
751 u64 avg_vruntime(struct cfs_rq *cfs_rq)
752 {
753 	struct sched_entity *curr = cfs_rq->curr;
754 	long weight = cfs_rq->sum_weight;
755 	s64 delta = 0;
756 
757 	if (curr && !curr->on_rq)
758 		curr = NULL;
759 
760 	if (weight) {
761 		s64 runtime = cfs_rq->sum_w_vruntime;
762 
763 		if (curr) {
764 			unsigned long w = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
765 
766 			runtime += entity_key(cfs_rq, curr) * w;
767 			weight += w;
768 		}
769 
770 		/* sign flips effective floor / ceiling */
771 		if (runtime < 0)
772 			runtime -= (weight - 1);
773 
774 		delta = div64_long(runtime, weight);
775 	} else if (curr) {
776 		/*
777 		 * When there is but one element, it is the average.
778 		 */
779 		delta = curr->vruntime - cfs_rq->zero_vruntime;
780 	}
781 
782 	update_zero_vruntime(cfs_rq, delta);
783 
784 	return cfs_rq->zero_vruntime;
785 }
786 
787 /*
788  *     \Sum (v_i - v0)*w_i
789  * V = ------------------- + v0
790  *          \Sum w_i
791  *
792  * Let W = \Sum w_i, and move v_j such that 'v_j == V', thus:
793  *
794  * V = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0
795  *
796  * v_j = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0
797  *
798  * v_j = 1/W * (v_j - v0)*w_j + 1/W * \Sum_i!=j (v_i - v0)*w_i + v0
799  *
800  * v_j - 1/W * (v_j - v0)*w_j = 1/W * \Sum_i!=j (v_i - v0)*w_i + v0
801  *
802  * v_j*W - (v_j - v0)*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
803  *
804  * v_j*(W - w_j) + v0*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
805  *
806  * v_j*(W - w_j) = \Sum_i!=j (v_i - v0)*w_i + v0*(W - w_j)
807  *
808  *       \Sum_i!=j (v_i - v0)*w_i
809  * v_j = ------------------------ + v0
810  *               W - w_j
811  *
812  * When v_j happens to be curr, then '\Sum_i!=j (v_i - v0)*w_i'
813  * is cfs_rq->sum_w_runtime, and 'W - w_j' is cfs_rq->sum_weight, since curr
814  * is not included in the sum.
815  */
816 static u64 ineligible_vruntime(struct cfs_rq *cfs_rq)
817 {
818 	struct sched_entity *curr = cfs_rq->curr;
819 	long weight = cfs_rq->sum_weight;
820 	s64 delta = 0;
821 
822 	if (curr && !curr->on_rq)
823 		curr = NULL;
824 
825 	if (weight) {
826 		s64 runtime = cfs_rq->sum_w_vruntime;
827 
828 		/*
829 		 * Do not add @curr to obtain the effective '- w_j' terms.
830 		 */
831 
832 		/* sign flips effective floor / ceiling */
833 		if (runtime < 0)
834 			runtime -= (weight - 1);
835 
836 		delta = div64_long(runtime, weight);
837 	}
838 
839 	return cfs_rq->zero_vruntime + delta + 1;
840 }
841 
842 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq);
843 
844 /*
845  * lag_i = S - s_i = w_i * (V - v_i)
846  *
847  * However, since V is approximated by the weighted average of all entities it
848  * is possible -- by addition/removal/reweight to the tree -- to move V around
849  * and end up with a larger lag than we started with.
850  *
851  * Limit this to either double the slice length with a minimum of TICK_NSEC
852  * since that is the timing granularity.
853  *
854  * EEVDF gives the following limit for a steady state system:
855  *
856  *   -r_max < lag < max(r_max, q)
857  */
858 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime)
859 {
860 	u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC;
861 	s64 vlag, limit;
862 
863 	vlag = avruntime - se->vruntime;
864 	limit = calc_delta_fair(max_slice, se);
865 
866 	return clamp(vlag, -limit, limit);
867 }
868 
869 /*
870  * Delayed dequeue aims to reduce the negative lag of a dequeued task. While
871  * updating the lag of an entity, check that negative lag didn't increase
872  * during the delayed dequeue period which would be unfair.
873  * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO
874  * is set.
875  *
876  * Return true if the vlag has been modified. Specifically:
877  *
878  *   se->vlag != avg_vruntime() - se->vruntime
879  *
880  * This can be due to clamping in entity_lag() or clamping due to
881  * sched_delayed. Either way, when vlag is modified and the entity is
882  * retained, the tree needs to be adjusted.
883  */
884 static __always_inline
885 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
886 {
887 	u64 avruntime = avg_vruntime(cfs_rq);
888 	s64 vlag = entity_lag(cfs_rq, se, avruntime);
889 
890 	if (se->sched_delayed) {
891 		/* previous vlag < 0 otherwise se would not be delayed */
892 		vlag = max(vlag, se->vlag);
893 		if (sched_feat(DELAY_ZERO))
894 			vlag = min(vlag, 0);
895 	}
896 	se->vlag = vlag;
897 
898 	return avruntime - vlag != se->vruntime;
899 }
900 
901 /*
902  * Entity is eligible once it received less service than it ought to have,
903  * eg. lag >= 0.
904  *
905  * lag_i = S - s_i = w_i*(V - v_i)
906  *
907  * lag_i >= 0 -> V >= v_i
908  *
909  *     \Sum (v_i - v0)*w_i
910  * V = ------------------- + v0
911  *          \Sum w_i
912  *
913  * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i)
914  *
915  * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
916  *       to the loss in precision caused by the division.
917  */
918 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
919 {
920 	struct sched_entity *curr = cfs_rq->curr;
921 	s64 key, avg = cfs_rq->sum_w_vruntime;
922 	long load = cfs_rq->sum_weight;
923 
924 	if (curr && curr->on_rq) {
925 		unsigned long weight = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
926 
927 		avg += entity_key(cfs_rq, curr) * weight;
928 		load += weight;
929 	}
930 
931 	key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime);
932 
933 	/*
934 	 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD'
935 	 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24
936 	 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise.
937 	 *
938 	 * This gives that on 64bit the product will be at least 64bit which
939 	 * overflows s64, while on 32bit it will only be 44bits and should fit
940 	 * comfortably.
941 	 */
942 #ifdef CONFIG_64BIT
943 #ifdef CONFIG_ARCH_SUPPORTS_INT128
944 	/* This often results in simpler code than __builtin_mul_overflow(). */
945 	return avg >= (__int128)key * load;
946 #else
947 	s64 rhs;
948 	/*
949 	 * On overflow, the sign of key tells us the correct answer: a large
950 	 * positive key means vruntime >> V, so not eligible; a large negative
951 	 * key means vruntime << V, so eligible.
952 	 */
953 	if (check_mul_overflow(key, load, &rhs))
954 		return key <= 0;
955 
956 	return avg >= rhs;
957 #endif
958 #else /* 32bit */
959 	return avg >= key * load;
960 #endif
961 }
962 
963 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
964 {
965 	return vruntime_eligible(cfs_rq, se->vruntime);
966 }
967 
968 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
969 {
970 	struct sched_entity *root = __pick_root_entity(cfs_rq);
971 	struct sched_entity *curr = cfs_rq->curr;
972 	u64 min_slice = ~0ULL;
973 
974 	if (curr && curr->on_rq)
975 		min_slice = curr->slice;
976 
977 	if (root)
978 		min_slice = min(min_slice, root->min_slice);
979 
980 	return min_slice;
981 }
982 
983 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq)
984 {
985 	struct sched_entity *root = __pick_root_entity(cfs_rq);
986 	struct sched_entity *curr = cfs_rq->curr;
987 	u64 max_slice = 0ULL;
988 
989 	if (curr && curr->on_rq)
990 		max_slice = curr->slice;
991 
992 	if (root)
993 		max_slice = max(max_slice, root->max_slice);
994 
995 	return max_slice;
996 }
997 
998 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
999 {
1000 	return entity_before(__node_2_se(a), __node_2_se(b));
1001 }
1002 
1003 /* min() for wrapping vruntimes */
1004 static inline u64 __min_vruntime(u64 a, u64 b)
1005 {
1006 	return vruntime_cmp(a, "<", b) ? a : b;
1007 }
1008 
1009 RB_DECLARE_CALLBACKS(static, min_vruntime_cb,
1010 		     struct sched_entity, run_node,
1011 		     RB_AUG(vruntime, min_vruntime, __min_vruntime),
1012 		     RB_AUG(slice, min_slice, min),
1013 		     RB_AUG(slice, max_slice, max));
1014 
1015 /*
1016  * Enqueue an entity into the rb-tree:
1017  */
1018 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1019 {
1020 	WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1021 	WARN_ON_ONCE(!entity_is_task(se));
1022 
1023 	sum_w_vruntime_add(cfs_rq, se);
1024 	se->min_vruntime = se->vruntime;
1025 	se->min_slice = se->slice;
1026 	se->max_slice = se->slice;
1027 
1028 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1029 				__entity_less, &min_vruntime_cb);
1030 }
1031 
1032 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1033 {
1034 	WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1035 	WARN_ON_ONCE(!entity_is_task(se));
1036 
1037 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1038 				  &min_vruntime_cb);
1039 	sum_w_vruntime_sub(cfs_rq, se);
1040 }
1041 
1042 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
1043 {
1044 	struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
1045 
1046 	if (!root)
1047 		return NULL;
1048 
1049 	return __node_2_se(root);
1050 }
1051 
1052 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
1053 {
1054 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
1055 
1056 	if (!left)
1057 		return NULL;
1058 
1059 	return __node_2_se(left);
1060 }
1061 
1062 /*
1063  * Set the vruntime up to which an entity can run before looking
1064  * for another entity to pick.
1065  * In case of run to parity, we use the shortest slice of the enqueued
1066  * entities to set the protected period.
1067  * When run to parity is disabled, we give a minimum quantum to the running
1068  * entity to ensure progress.
1069  */
1070 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1071 {
1072 	u64 slice = normalized_sysctl_sched_base_slice;
1073 	u64 vprot = se->deadline;
1074 
1075 	if (sched_feat(RUN_TO_PARITY))
1076 		slice = cfs_rq_min_slice(cfs_rq);
1077 
1078 	slice = min(slice, se->slice);
1079 
1080 	/* If there are shorter slices than se's one */
1081 	if (slice != se->slice) {
1082 		vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
1083 		if (sched_feat(PREEMPT_SHORT))
1084 			vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq));
1085 	}
1086 
1087 	se->vprot = vprot;
1088 }
1089 
1090 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1091 {
1092 	u64 vruntime = min_vruntime(se->vruntime, avg_vruntime(cfs_rq));
1093 	u64 slice = cfs_rq_min_slice(cfs_rq);
1094 	u64 vprot = min_vruntime(se->vprot, vruntime + calc_delta_fair(slice, se));
1095 
1096 	if (sched_feat(PREEMPT_SHORT) && slice != se->slice)
1097 		vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq));
1098 
1099 	se->vprot = vprot;
1100 }
1101 
1102 static inline bool protect_slice(struct sched_entity *se)
1103 {
1104 	return vruntime_cmp(se->vruntime, "<", se->vprot);
1105 }
1106 
1107 static inline void cancel_protect_slice(struct sched_entity *se)
1108 {
1109 	if (protect_slice(se))
1110 		se->vprot = se->vruntime;
1111 }
1112 
1113 /*
1114  * Earliest Eligible Virtual Deadline First
1115  *
1116  * In order to provide latency guarantees for different request sizes
1117  * EEVDF selects the best runnable task from two criteria:
1118  *
1119  *  1) the task must be eligible (must be owed service)
1120  *
1121  *  2) from those tasks that meet 1), we select the one
1122  *     with the earliest virtual deadline.
1123  *
1124  * We can do this in O(log n) time due to an augmented RB-tree. The
1125  * tree keeps the entries sorted on deadline, but also functions as a
1126  * heap based on the vruntime by keeping:
1127  *
1128  *  se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
1129  *
1130  * Which allows tree pruning through eligibility.
1131  */
1132 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
1133 {
1134 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
1135 	struct sched_entity *se = __pick_first_entity(cfs_rq);
1136 	struct sched_entity *curr = cfs_rq->curr;
1137 	struct sched_entity *best = NULL;
1138 
1139 	/*
1140 	 * We can safely skip eligibility check if there is only one entity
1141 	 * in this cfs_rq, saving some cycles.
1142 	 */
1143 	if (cfs_rq->h_nr_queued == 1)
1144 		return curr && curr->on_rq ? curr : se;
1145 
1146 	/*
1147 	 * Picking the ->next buddy will affect latency but not fairness.
1148 	 */
1149 	if (sched_feat(PICK_BUDDY) && protect &&
1150 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
1151 		/* ->next will never be delayed */
1152 		WARN_ON_ONCE(cfs_rq->next->sched_delayed);
1153 		return cfs_rq->next;
1154 	}
1155 
1156 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
1157 		curr = NULL;
1158 
1159 	if (curr && protect && protect_slice(curr))
1160 		return curr;
1161 
1162 	/* Pick the leftmost entity if it's eligible */
1163 	if (se && entity_eligible(cfs_rq, se)) {
1164 		best = se;
1165 		goto found;
1166 	}
1167 
1168 	/* Heap search for the EEVD entity */
1169 	while (node) {
1170 		struct rb_node *left = node->rb_left;
1171 
1172 		/*
1173 		 * Eligible entities in left subtree are always better
1174 		 * choices, since they have earlier deadlines.
1175 		 */
1176 		if (left && vruntime_eligible(cfs_rq,
1177 					__node_2_se(left)->min_vruntime)) {
1178 			node = left;
1179 			continue;
1180 		}
1181 
1182 		se = __node_2_se(node);
1183 
1184 		/*
1185 		 * The left subtree either is empty or has no eligible
1186 		 * entity, so check the current node since it is the one
1187 		 * with earliest deadline that might be eligible.
1188 		 */
1189 		if (entity_eligible(cfs_rq, se)) {
1190 			best = se;
1191 			break;
1192 		}
1193 
1194 		node = node->rb_right;
1195 	}
1196 found:
1197 	if (!best || (curr && entity_before(curr, best)))
1198 		best = curr;
1199 
1200 	return best;
1201 }
1202 
1203 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1204 {
1205 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1206 
1207 	if (!last)
1208 		return NULL;
1209 
1210 	return __node_2_se(last);
1211 }
1212 
1213 /**************************************************************
1214  * Scheduling class statistics methods:
1215  */
1216 int sched_update_scaling(void)
1217 {
1218 	unsigned int factor = get_update_sysctl_factor();
1219 
1220 #define WRT_SYSCTL(name) \
1221 	(normalized_sysctl_##name = sysctl_##name / (factor))
1222 	WRT_SYSCTL(sched_base_slice);
1223 #undef WRT_SYSCTL
1224 
1225 	return 0;
1226 }
1227 
1228 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1229 
1230 /*
1231  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1232  * this is probably good enough.
1233  */
1234 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1235 {
1236 	if (vruntime_cmp(se->vruntime, "<", se->deadline))
1237 		return false;
1238 
1239 	/*
1240 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1241 	 * nice) while the request time r_i is determined by
1242 	 * sysctl_sched_base_slice.
1243 	 */
1244 	if (!se->custom_slice)
1245 		se->slice = sysctl_sched_base_slice;
1246 
1247 	/*
1248 	 * EEVDF: vd_i = ve_i + r_i / w_i
1249 	 */
1250 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1251 	avg_vruntime(cfs_rq);
1252 
1253 	/*
1254 	 * The task has consumed its request, reschedule.
1255 	 */
1256 	return true;
1257 }
1258 
1259 #include "pelt.h"
1260 
1261 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1262 static unsigned long task_h_load(struct task_struct *p);
1263 static unsigned long capacity_of(int cpu);
1264 
1265 /* Give new sched_entity start runnable values to heavy its load in infant time */
1266 void init_entity_runnable_average(struct sched_entity *se)
1267 {
1268 	struct sched_avg *sa = &se->avg;
1269 
1270 	memset(sa, 0, sizeof(*sa));
1271 
1272 	/*
1273 	 * Tasks are initialized with full load to be seen as heavy tasks until
1274 	 * they get a chance to stabilize to their real load level.
1275 	 * Group entities are initialized with zero load to reflect the fact that
1276 	 * nothing has been attached to the task group yet.
1277 	 */
1278 	if (entity_is_task(se))
1279 		sa->load_avg = scale_load_down(se->load.weight);
1280 
1281 	/* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1282 }
1283 
1284 /*
1285  * With new tasks being created, their initial util_avgs are extrapolated
1286  * based on the cfs_rq's current util_avg:
1287  *
1288  *   util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1289  *		* se_weight(se)
1290  *
1291  * However, in many cases, the above util_avg does not give a desired
1292  * value. Moreover, the sum of the util_avgs may be divergent, such
1293  * as when the series is a harmonic series.
1294  *
1295  * To solve this problem, we also cap the util_avg of successive tasks to
1296  * only 1/2 of the left utilization budget:
1297  *
1298  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1299  *
1300  * where n denotes the nth task and cpu_scale the CPU capacity.
1301  *
1302  * For example, for a CPU with 1024 of capacity, a simplest series from
1303  * the beginning would be like:
1304  *
1305  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1306  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1307  *
1308  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1309  * if util_avg > util_avg_cap.
1310  */
1311 void post_init_entity_util_avg(struct task_struct *p)
1312 {
1313 	struct sched_entity *se = &p->se;
1314 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1315 	struct sched_avg *sa = &se->avg;
1316 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1317 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1318 
1319 	if (p->sched_class != &fair_sched_class) {
1320 		/*
1321 		 * For !fair tasks do:
1322 		 *
1323 		update_cfs_rq_load_avg(now, cfs_rq);
1324 		attach_entity_load_avg(cfs_rq, se);
1325 		switched_from_fair(rq, p);
1326 		 *
1327 		 * such that the next switched_to_fair() has the
1328 		 * expected state.
1329 		 */
1330 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1331 		return;
1332 	}
1333 
1334 	if (cap > 0) {
1335 		if (cfs_rq->avg.util_avg != 0) {
1336 			sa->util_avg  = cfs_rq->avg.util_avg * se_weight(se);
1337 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1338 
1339 			if (sa->util_avg > cap)
1340 				sa->util_avg = cap;
1341 		} else {
1342 			sa->util_avg = cap;
1343 		}
1344 	}
1345 
1346 	sa->runnable_avg = sa->util_avg;
1347 }
1348 
1349 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec);
1350 
1351 static s64 update_se(struct rq *rq, struct sched_entity *se)
1352 {
1353 	u64 now = rq_clock_task(rq);
1354 	s64 delta_exec;
1355 
1356 	delta_exec = now - se->exec_start;
1357 	if (unlikely(delta_exec <= 0))
1358 		return delta_exec;
1359 
1360 	se->exec_start = now;
1361 	if (entity_is_task(se)) {
1362 		struct task_struct *running = rq->curr;
1363 		/*
1364 		 * If se is a task, we account the time against the running
1365 		 * task, as w/ proxy-exec they may not be the same.
1366 		 */
1367 		running->se.exec_start = now;
1368 		running->se.sum_exec_runtime += delta_exec;
1369 
1370 		trace_sched_stat_runtime(running, delta_exec);
1371 		account_group_exec_runtime(running, delta_exec);
1372 		account_mm_sched(rq, running, delta_exec);
1373 
1374 		cgroup_account_cputime(running, delta_exec);
1375 	} else {
1376 		/* If not task, account the time against donor se  */
1377 		se->sum_exec_runtime += delta_exec;
1378 	}
1379 
1380 	if (schedstat_enabled()) {
1381 		struct sched_statistics *stats;
1382 
1383 		stats = __schedstats_from_se(se);
1384 		__schedstat_set(stats->exec_max,
1385 				max(delta_exec, stats->exec_max));
1386 	}
1387 
1388 	return delta_exec;
1389 }
1390 
1391 #ifdef CONFIG_SCHED_CACHE
1392 
1393 /*
1394  * XXX numbers come from a place the sun don't shine -- probably wants to be SD
1395  * tunable or so.
1396  */
1397 #define EPOCH_PERIOD	(HZ / 100)	/* 10 ms */
1398 #define EPOCH_LLC_AFFINITY_TIMEOUT	5	/* 50 ms */
1399 __read_mostly unsigned int llc_aggr_tolerance	= 1;
1400 __read_mostly unsigned int llc_epoch_period	= EPOCH_PERIOD;
1401 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT;
1402 __read_mostly unsigned int llc_imb_pct		= 20;
1403 __read_mostly unsigned int llc_overaggr_pct	= 50;
1404 
1405 static int llc_id(int cpu)
1406 {
1407 	if (cpu < 0)
1408 		return -1;
1409 
1410 	return per_cpu(sd_llc_id, cpu);
1411 }
1412 
1413 static inline int get_sched_cache_scale(int mul)
1414 {
1415 	unsigned int tol = READ_ONCE(llc_aggr_tolerance);
1416 
1417 	if (!tol)
1418 		return 0;
1419 
1420 	if (tol >= 100)
1421 		return INT_MAX;
1422 
1423 	return (1 + (tol - 1) * mul);
1424 }
1425 
1426 static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu)
1427 {
1428 #ifdef CONFIG_NUMA_BALANCING
1429 	unsigned long llc, footprint;
1430 	struct sched_domain *sd;
1431 	int scale;
1432 
1433 	guard(rcu)();
1434 
1435 	sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd);
1436 	if (!sd)
1437 		return true;
1438 
1439 	if (static_branch_likely(&sched_numa_balancing)) {
1440 		/*
1441 		 * TBD: RDT exclusive LLC ways reserved should be
1442 		 * excluded.
1443 		 */
1444 		llc = sd->llc_bytes;
1445 		footprint = READ_ONCE(grp->footprint);
1446 
1447 		/*
1448 		 * Scale the LLC size by 256*llc_aggr_tolerance
1449 		 * and compare it to the task's footprint.
1450 		 *
1451 		 * Suppose the L3 size is 32MB. If the
1452 		 * llc_aggr_tolerance is 1:
1453 		 * When the footprint is larger than 32MB, the
1454 		 * process is regarded as exceeding the LLC
1455 		 * capacity. If the llc_aggr_tolerance is 99:
1456 		 * When the footprint is larger than 784GB, the
1457 		 * process is regarded as exceeding the LLC
1458 		 * capacity:
1459 		 * 784GB = (1 + (99 - 1) * 256) * 32MB
1460 		 * If the llc_aggr_tolerance is 100:
1461 		 * ignore the footprint and do the aggregation
1462 		 * anyway.
1463 		 */
1464 		scale = get_sched_cache_scale(256);
1465 		if (scale == INT_MAX)
1466 			return false;
1467 
1468 		return ((llc * (u64)scale) < (footprint * PAGE_SIZE));
1469 	}
1470 #endif
1471 	return false;
1472 }
1473 
1474 /* Are the running threads (in SMT siblings) below ~80% of the LLC's CPUs? */
1475 static inline bool fits_llc_nr(u64 nr_threads, unsigned int nr_cpus)
1476 {
1477 	return nr_threads * 5 < (u64)nr_cpus * 4;
1478 }
1479 
1480 static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p,
1481 			   int cpu)
1482 {
1483 	int scale;
1484 
1485 	if (get_nr_threads(p) <= 1)
1486 		return true;
1487 
1488 	/*
1489 	 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance
1490 	 * and compare it to the task's active threads.
1491 	 */
1492 	scale = get_sched_cache_scale(1);
1493 	if (scale == INT_MAX)
1494 		return false;
1495 
1496 	return !fits_llc_nr(READ_ONCE(grp->nr_running_avg) * cpu_smt_num_threads,
1497 			    scale * per_cpu(sd_llc_size, cpu));
1498 }
1499 
1500 /*
1501  * A task counts in nr_pref_llc_running while it is queued on its preferred
1502  * LLC (pref_llc_queued) and runnable (!sched_delayed), keeping the counter in
1503  * the runnable domain so alb_break_llc() can compare it with h_nr_runnable.
1504  */
1505 static bool task_pref_llc_runnable(struct task_struct *p)
1506 {
1507 	return p->pref_llc_queued && !p->se.sched_delayed;
1508 }
1509 
1510 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p)
1511 {
1512 	if (task_pref_llc_runnable(p))
1513 		rq->nr_pref_llc_running++;
1514 }
1515 
1516 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p)
1517 {
1518 	if (task_pref_llc_runnable(p))
1519 		rq->nr_pref_llc_running--;
1520 }
1521 
1522 static void account_llc_enqueue(struct rq *rq, struct task_struct *p)
1523 {
1524 	int pref_llc, pref_llc_queued;
1525 	struct sched_domain *sd;
1526 
1527 	pref_llc = p->preferred_llc;
1528 	if (pref_llc < 0)
1529 		return;
1530 
1531 	pref_llc_queued = (pref_llc == task_llc(p));
1532 	rq->nr_llc_running++;
1533 
1534 	/*
1535 	 * Record whether p is enqueued on its preferred
1536 	 * LLC, in order to pair with account_llc_dequeue()
1537 	 * to maintain a consistent nr_pref_llc_running per
1538 	 * runqueue.
1539 	 * This is necessary because a race condition exists:
1540 	 * after a task is enqueued on a runqueue, task_llc(p)
1541 	 * may change due to CPU hotplug. Therefore, checking
1542 	 * task_llc(p) to determine whether the task is being
1543 	 * dequeued from its preferred LLC is unreliable and
1544 	 * can cause inconsistent values - checking the
1545 	 * p->pref_llc_queued in account_llc_dequeue() would
1546 	 * be reliable.
1547 	 */
1548 	p->pref_llc_queued = pref_llc_queued;
1549 
1550 	/* Skipped while delayed; clear_delayed() adds it back on wake. */
1551 	pref_llc_running_inc(rq, p);
1552 
1553 	sd = rcu_dereference_all(rq->sd);
1554 	if (sd && (unsigned int)pref_llc < sd->llc_max)
1555 		sd->llc_counts[pref_llc]++;
1556 }
1557 
1558 static void account_llc_dequeue(struct rq *rq, struct task_struct *p)
1559 {
1560 	struct sched_domain *sd;
1561 	int pref_llc;
1562 
1563 	pref_llc = p->preferred_llc;
1564 	if (pref_llc < 0)
1565 		return;
1566 
1567 	rq->nr_llc_running--;
1568 	if (p->pref_llc_queued) {
1569 		/*
1570 		 * Skipped if still delayed (set_delayed() already removed it);
1571 		 * clearing pref_llc_queued below also stops clear_delayed()
1572 		 * from re-adding it.
1573 		 */
1574 		pref_llc_running_dec(rq, p);
1575 		/*
1576 		 * Update the status in case
1577 		 * other logic might query
1578 		 * this.
1579 		 */
1580 		p->pref_llc_queued = 0;
1581 	}
1582 
1583 	sd = rcu_dereference_all(rq->sd);
1584 	if (sd && (unsigned int)pref_llc < sd->llc_max) {
1585 		/*
1586 		 * There is a race condition between dequeue
1587 		 * and CPU hotplug. After a task has been enqueued
1588 		 * on CPUx, a CPU hotplug event occurs, and all online
1589 		 * CPUs (including CPUx) rebuild their sched_domains
1590 		 * and reset statistics to zero(including sd->llc_counts).
1591 		 * This can cause temporary undercount and we have to
1592 		 * check for such underflow in sd->llc_counts.
1593 		 *
1594 		 * This undercount is temporary and accurate accounting
1595 		 * will resume once the rq has a chance to be idle.
1596 		 */
1597 		if (sd->llc_counts[pref_llc])
1598 			sd->llc_counts[pref_llc]--;
1599 	}
1600 }
1601 
1602 int mm_init_sched(struct mm_struct *mm,
1603 		  struct sched_cache_time __percpu *_pcpu_sched)
1604 {
1605 	struct sched_cache_group *grp;
1606 	unsigned long epoch = 0;
1607 	int i;
1608 
1609 	grp = kzalloc_obj(*grp);
1610 	if (!grp) {
1611 		free_percpu(_pcpu_sched);
1612 		mm->sched_cache_grp = NULL;
1613 		return -ENOMEM;
1614 	}
1615 
1616 	for_each_possible_cpu(i) {
1617 		struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i);
1618 		struct rq *rq = cpu_rq(i);
1619 
1620 		pcpu_sched->runtime = 0;
1621 		/* a slightly stale cpu epoch is acceptible */
1622 		pcpu_sched->epoch = rq->cpu_epoch;
1623 		epoch = rq->cpu_epoch;
1624 	}
1625 
1626 	raw_spin_lock_init(&grp->lock);
1627 	grp->epoch = epoch;
1628 	grp->cpu = -1;
1629 	grp->next_scan = jiffies;
1630 	grp->nr_running_avg = 0;
1631 	grp->footprint = 0;
1632 	refcount_set(&grp->refcnt, 1);
1633 	/*
1634 	 * The update to grp->pcpu_sched should not be reordered
1635 	 * before initialization to grp's other fields, in case
1636 	 * the readers may get invalid mm_sched_epoch, etc.
1637 	 */
1638 	smp_store_release(&grp->pcpu_sched, _pcpu_sched);
1639 	/*
1640 	 * Publish the group last.  Not every reader qualifies it by
1641 	 * grp->pcpu_sched - can_migrate_llc_task() only checks that the
1642 	 * pointer is non-NULL before reading grp->footprint and
1643 	 * grp->nr_running_avg - so a reachable group must already be
1644 	 * fully initialized.
1645 	 */
1646 	smp_store_release(&mm->sched_cache_grp, grp);
1647 	return 0;
1648 }
1649 
1650 static void sched_cache_group_free_rcu(struct rcu_head *rcu)
1651 {
1652 	struct sched_cache_group *grp =
1653 		container_of(rcu, struct sched_cache_group, rcu);
1654 
1655 	free_percpu(grp->pcpu_sched);
1656 	kfree(grp);
1657 }
1658 
1659 static void sched_cache_group_put(struct sched_cache_group *grp)
1660 {
1661 	if (!grp || !refcount_dec_and_test(&grp->refcnt))
1662 		return;
1663 
1664 	call_rcu(&grp->rcu, sched_cache_group_free_rcu);
1665 }
1666 
1667 DEFINE_FREE(sched_cache_group_put, struct sched_cache_group *,
1668 	    sched_cache_group_put(_T));
1669 
1670 #define rcu_deref_sched_cache_grp(tsk) \
1671 	rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
1672 
1673 static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p,
1674 							 struct sched_cache_group *new)
1675 {
1676 	struct sched_cache_group *old;
1677 
1678 	old = rcu_deref_sched_cache_grp(p);
1679 	rcu_assign_pointer(p->sched_cache_grp, new);
1680 
1681 	return old;
1682 }
1683 
1684 struct sched_cache_group *sched_cache_group_get(struct sched_cache_group *grp)
1685 {
1686 	/*
1687 	 * refcount_inc_not_zero() is the acquire primitive for lockless
1688 	 * (RCU) lookups; plain refcount_inc() would scribble the count if
1689 	 * it already reached zero. Return NULL in that case.
1690 	 */
1691 	if (grp && !refcount_inc_not_zero(&grp->refcnt))
1692 		grp = NULL;
1693 
1694 	return grp;
1695 }
1696 
1697 struct sched_cache_group *task_cache_group_get(struct task_struct *p)
1698 {
1699 	guard(rcu)();
1700 	return sched_cache_group_get(rcu_dereference(p->sched_cache_grp));
1701 }
1702 
1703 void sched_cache_fork(struct task_struct *p)
1704 {
1705 	/*
1706 	 * The child takes its own reference on the mm's cache group, separate
1707 	 * from the reference held by the mm. @p is not yet visible to readers,
1708 	 * so a plain initializing store is enough.
1709 	 */
1710 	RCU_INIT_POINTER(p->sched_cache_grp,
1711 			 sched_cache_group_get(p->mm->sched_cache_grp));
1712 }
1713 
1714 void sched_cache_fork_cleanup(struct task_struct *p)
1715 {
1716 	/*
1717 	 * A fork that fails after sched_cache_fork() never reaches exit_mm(),
1718 	 * so drop the reference here. @p never became visible, so there are no
1719 	 * concurrent readers and the reference we hold keeps the group alive.
1720 	 */
1721 	sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp));
1722 	RCU_INIT_POINTER(p->sched_cache_grp, NULL);
1723 }
1724 
1725 void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
1726 {
1727 	struct sched_cache_group *old;
1728 
1729 	/*
1730 	 * Acquire the new reference before publishing the pointer, then drop
1731 	 * the old one. @p is current and the only writer of its own pointer.
1732 	 */
1733 	old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp));
1734 	sched_cache_group_put(old);
1735 }
1736 
1737 void sched_cache_exit_mm(struct task_struct *p)
1738 {
1739 	struct sched_cache_group *grp = sched_cache_replace_grp(p, NULL);
1740 
1741 #ifdef CONFIG_NUMA_BALANCING
1742 	/*
1743 	 * Subtract this task's footprint from the group before dropping the
1744 	 * reference, so the group footprint converges as its threads exit.
1745 	 * Unlocked for performance; clamp to avoid underflow.
1746 	 */
1747 	if (grp && p->total_numa_faults) {
1748 		unsigned long fp = READ_ONCE(grp->footprint);
1749 		unsigned long sub = min(fp, p->total_numa_faults);
1750 
1751 		WRITE_ONCE(grp->footprint, fp - sub);
1752 	}
1753 #endif
1754 	sched_cache_group_put(grp);
1755 }
1756 
1757 void mm_destroy_sched(struct mm_struct *mm)
1758 {
1759 	sched_cache_group_put(mm->sched_cache_grp);
1760 	mm->sched_cache_grp = NULL;
1761 }
1762 
1763 /* because why would C be fully specified */
1764 static __always_inline void __shr_u64(u64 *val, unsigned int n)
1765 {
1766 	if (n >= 64) {
1767 		*val = 0;
1768 		return;
1769 	}
1770 	*val >>= n;
1771 }
1772 
1773 static inline void __update_mm_sched(struct rq *rq,
1774 				     struct sched_cache_time *pcpu_sched)
1775 {
1776 	lockdep_assert_held(&rq->cpu_epoch_lock);
1777 
1778 	unsigned int period = max(READ_ONCE(llc_epoch_period), 1U);
1779 	unsigned long n, now = jiffies;
1780 	long delta = now - rq->cpu_epoch_next;
1781 
1782 	if (delta > 0) {
1783 		n = (delta + period - 1) / period;
1784 		rq->cpu_epoch += n;
1785 		rq->cpu_epoch_next += n * period;
1786 		__shr_u64(&rq->cpu_runtime, n);
1787 	}
1788 
1789 	n = rq->cpu_epoch - pcpu_sched->epoch;
1790 	if (n) {
1791 		pcpu_sched->epoch += n;
1792 		__shr_u64(&pcpu_sched->runtime, n);
1793 	}
1794 }
1795 
1796 static unsigned long fraction_mm_sched(struct rq *rq,
1797 				       struct sched_cache_time *pcpu_sched)
1798 {
1799 	guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock);
1800 
1801 	__update_mm_sched(rq, pcpu_sched);
1802 
1803 	/*
1804 	 * Runtime is a geometric series (r=0.5) and as such will sum to twice
1805 	 * the accumulation period, this means the multiplcation here should
1806 	 * not overflow.
1807 	 */
1808 	return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1);
1809 }
1810 
1811 static int get_pref_llc(struct task_struct *p, struct sched_cache_group *grp)
1812 {
1813 	int mm_sched_llc = -1, mm_sched_cpu;
1814 
1815 	if (!grp)
1816 		return -1;
1817 
1818 	mm_sched_cpu = READ_ONCE(grp->cpu);
1819 	if (mm_sched_cpu != -1) {
1820 		mm_sched_llc = llc_id(mm_sched_cpu);
1821 
1822 #ifdef CONFIG_NUMA_BALANCING
1823 		/*
1824 		 * Don't assign preferred LLC if it
1825 		 * conflicts with NUMA balancing.
1826 		 * This can happen when sched_setnuma() gets
1827 		 * called, however it is not much of an issue
1828 		 * because we expect account_mm_sched() to get
1829 		 * called fairly regularly -- at a higher rate
1830 		 * than sched_setnuma() at least -- and thus the
1831 		 * conflict only exists for a short period of time.
1832 		 */
1833 		if (static_branch_likely(&sched_numa_balancing) &&
1834 		    p->numa_preferred_nid >= 0 &&
1835 		    cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid)
1836 			mm_sched_llc = -1;
1837 #endif
1838 	}
1839 
1840 	return mm_sched_llc;
1841 }
1842 
1843 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p);
1844 
1845 static inline
1846 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
1847 {
1848 	struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp);
1849 	struct sched_cache_time *pcpu_sched;
1850 	int mm_sched_llc = -1;
1851 	unsigned long epoch;
1852 
1853 	if (!sched_cache_enabled())
1854 		return;
1855 
1856 	if (p->sched_class != &fair_sched_class)
1857 		return;
1858 	/*
1859 	 * init_task, kthreads and user thread created
1860 	 * by user_mode_thread() don't have a cache group.
1861 	 * In theory a kernel thread does not have any valid
1862 	 * cache group, because sched_cache_fork() is not
1863 	 * invoked for a kernel thread - !grp should gate the
1864 	 * kernel thread. Use the PF_KTHREAD check explicitly
1865 	 * here for safety reasons, to guard against future
1866 	 * modifications and to pair with task_tick_cache().
1867 	 */
1868 	if (p->flags & PF_KTHREAD || !grp || !grp->pcpu_sched)
1869 		return;
1870 
1871 	pcpu_sched = per_cpu_ptr(grp->pcpu_sched, cpu_of(rq));
1872 
1873 	scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) {
1874 		__update_mm_sched(rq, pcpu_sched);
1875 		pcpu_sched->runtime += delta_exec;
1876 		rq->cpu_runtime += delta_exec;
1877 		epoch = rq->cpu_epoch;
1878 	}
1879 
1880 	/*
1881 	 * If this process hasn't hit task_cache_work() for a while invalidate
1882 	 * its preferred state.
1883 	 */
1884 	if ((long)(epoch - READ_ONCE(grp->epoch)) > llc_epoch_affinity_timeout ||
1885 	    invalid_llc_nr(grp, p, cpu_of(rq)) ||
1886 	    exceed_llc_capacity(grp, cpu_of(rq))) {
1887 		if (READ_ONCE(grp->cpu) != -1)
1888 			WRITE_ONCE(grp->cpu, -1);
1889 	}
1890 
1891 	mm_sched_llc = get_pref_llc(p, grp);
1892 
1893 	/* task not on rq accounted later in account_entity_enqueue() */
1894 	if (task_running_on_cpu(rq->cpu, p) &&
1895 	    READ_ONCE(p->preferred_llc) != mm_sched_llc) {
1896 		account_llc_dequeue(rq, p);
1897 		WRITE_ONCE(p->preferred_llc, mm_sched_llc);
1898 		account_llc_enqueue(rq, p);
1899 	}
1900 }
1901 
1902 static void task_tick_cache(struct rq *rq, struct task_struct *p)
1903 {
1904 	struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp);
1905 	struct callback_head *work = &p->cache_work;
1906 	unsigned long epoch;
1907 
1908 	if (!sched_cache_enabled())
1909 		return;
1910 
1911 	if (!grp || p->flags & PF_KTHREAD ||
1912 	    !grp->pcpu_sched)
1913 		return;
1914 
1915 	epoch = rq->cpu_epoch;
1916 	/* avoid moving backwards */
1917 	if (time_after_eq(grp->epoch, epoch))
1918 		return;
1919 
1920 	guard(raw_spinlock)(&grp->lock);
1921 
1922 	if (work->next == work) {
1923 		task_work_add(p, work, TWA_RESUME);
1924 		WRITE_ONCE(grp->epoch, epoch);
1925 	}
1926 }
1927 
1928 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p,
1929 			      struct sched_cache_group *grp)
1930 {
1931 #ifdef CONFIG_NUMA_BALANCING
1932 	int cpu, curr_cpu, nid, pref_nid;
1933 
1934 	if (!static_branch_likely(&sched_numa_balancing))
1935 		goto out;
1936 
1937 	cpu = READ_ONCE(grp->cpu);
1938 	if (cpu != -1)
1939 		nid = cpu_to_node(cpu);
1940 	curr_cpu = task_cpu(p);
1941 
1942 	/*
1943 	 * Scanning in the preferred NUMA node is ideal. However, the NUMA
1944 	 * preferred node is per-task rather than per-process. It is possible
1945 	 * for different threads of the process to have distinct preferred
1946 	 * nodes; consequently, the process-wide preferred LLC may bounce
1947 	 * between different nodes. As a workaround, maintain the scan
1948 	 * CPU mask to also cover the process's current preferred LLC and the
1949 	 * current running node to mitigate the bouncing risk.
1950 	 * TBD: numa_group should be considered during task aggregation.
1951 	 */
1952 	pref_nid = p->numa_preferred_nid;
1953 	/* honor the task's preferred node */
1954 	if (pref_nid == NUMA_NO_NODE)
1955 		goto out;
1956 
1957 	cpumask_or(cpus, cpus, cpumask_of_node(pref_nid));
1958 
1959 	/* honor the task's preferred LLC CPU */
1960 	if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE)
1961 		cpumask_or(cpus, cpus, cpumask_of_node(nid));
1962 
1963 	/* make sure the task's current running node is included */
1964 	if (!cpumask_test_cpu(curr_cpu, cpus))
1965 		cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu)));
1966 
1967 	return;
1968 
1969 out:
1970 #endif
1971 	cpumask_copy(cpus, cpu_online_mask);
1972 }
1973 
1974 static inline void update_avg_scale(u64 *avg, u64 sample)
1975 {
1976 	int factor = per_cpu(sd_llc_size, raw_smp_processor_id());
1977 	s64 diff = sample - *avg;
1978 	u32 divisor;
1979 
1980 	/*
1981 	 * Scale the divisor based on the number of CPUs contained
1982 	 * in the LLC. This scaling ensures smaller LLC domains use
1983 	 * a smaller divisor to achieve more precise sensitivity to
1984 	 * changes in nr_running, while larger LLC domains are capped
1985 	 * at a maximum divisor of 8 which is the default smoothing
1986 	 * factor of EWMA in update_avg().
1987 	 */
1988 	divisor = clamp_t(u32, (factor >> 2), 2, 8);
1989 	*avg += div64_s64(diff, divisor);
1990 }
1991 
1992 static void task_cache_work(struct callback_head *work)
1993 {
1994 	struct sched_cache_group *grp __free(sched_cache_group_put) = NULL;
1995 	cpumask_var_t cpus __free(free_cpumask_var) = CPUMASK_VAR_NULL;
1996 	int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu;
1997 	unsigned long next_scan, now = jiffies;
1998 	struct task_struct *p = current, *cur;
1999 	unsigned long curr_m_a_occ = 0;
2000 	unsigned long m_a_occ = 0;
2001 
2002 	WARN_ON_ONCE(work != &p->cache_work);
2003 
2004 	work->next = work;
2005 
2006 	if (p->flags & PF_EXITING)
2007 		return;
2008 
2009 	/*
2010 	 * A reference makes sure grp is not released by others. The rcu
2011 	 * lock can not be held till after zalloc_cpumask_var() below,
2012 	 * because the latter might sleep.
2013 	 */
2014 	grp = task_cache_group_get(p);
2015 	if (!grp)
2016 		return;
2017 
2018 	next_scan = READ_ONCE(grp->next_scan);
2019 	if (time_before(now, next_scan))
2020 		return;
2021 
2022 	/* only 1 thread is allowed to scan */
2023 	if (!try_cmpxchg(&grp->next_scan, &next_scan,
2024 			 now + max_t(unsigned long,
2025 				     READ_ONCE(llc_epoch_period), 1)))
2026 		return;
2027 
2028 	curr_cpu = task_cpu(p);
2029 	if (invalid_llc_nr(grp, p, curr_cpu) ||
2030 	    exceed_llc_capacity(grp, curr_cpu)) {
2031 		if (READ_ONCE(grp->cpu) != -1)
2032 			WRITE_ONCE(grp->cpu, -1);
2033 
2034 		return;
2035 	}
2036 
2037 	if (!zalloc_cpumask_var(&cpus, GFP_KERNEL))
2038 		return;
2039 
2040 	scoped_guard (cpus_read_lock) {
2041 		guard(rcu)();
2042 
2043 		get_scan_cpumasks(cpus, p, grp);
2044 
2045 		for_each_cpu(cpu, cpus) {
2046 			/* XXX sched_cluster_active */
2047 			struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
2048 			unsigned long occ, m_occ = 0, a_occ = 0;
2049 			int m_cpu = -1, i;
2050 
2051 			if (!sd)
2052 				continue;
2053 
2054 			for_each_cpu(i, sched_domain_span(sd)) {
2055 				occ = fraction_mm_sched(cpu_rq(i),
2056 							per_cpu_ptr(grp->pcpu_sched, i));
2057 				a_occ += occ;
2058 				if (occ > m_occ) {
2059 					m_occ = occ;
2060 					m_cpu = i;
2061 				}
2062 
2063 				/*
2064 				 * rcu_access_pointer() is used because the
2065 				 * pointer is only compared, never dereferenced.
2066 				 */
2067 				cur = rcu_dereference_all(cpu_rq(i)->curr);
2068 				if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) &&
2069 				    rcu_access_pointer(cur->sched_cache_grp) == grp)
2070 					nr_running++;
2071 			}
2072 
2073 			/*
2074 			 * Compare the accumulated occupancy of each LLC. The
2075 			 * reason for using accumulated occupancy rather than average
2076 			 * per CPU occupancy is that it works better in asymmetric LLC
2077 			 * scenarios.
2078 			 * For example, if there are 2 threads in a 4CPU LLC and 3
2079 			 * threads in an 8CPU LLC, it might be better to choose the one
2080 			 * with 3 threads. However, this would not be the case if the
2081 			 * occupancy is divided by the number of CPUs in an LLC (i.e.,
2082 			 * if average per CPU occupancy is used).
2083 			 * Besides, NUMA balancing fault statistics behave similarly:
2084 			 * the total number of faults per node is compared rather than
2085 			 * the average number of faults per CPU. This strategy is also
2086 			 * followed here.
2087 			 */
2088 			if (a_occ > m_a_occ) {
2089 				m_a_occ = a_occ;
2090 				m_a_cpu = m_cpu;
2091 			}
2092 
2093 			if (llc_id(cpu) == llc_id(READ_ONCE(grp->cpu)))
2094 				curr_m_a_occ = a_occ;
2095 
2096 			cpumask_andnot(cpus, cpus, sched_domain_span(sd));
2097 		}
2098 	}
2099 
2100 	if (m_a_occ > (2 * curr_m_a_occ)) {
2101 		/*
2102 		 * Avoid switching sched_cache_grp->cpu too fast.
2103 		 * The reason to choose 2X is because:
2104 		 * 1. It is better to keep the preferred LLC stable,
2105 		 *    rather than changing it frequently and cause migrations
2106 		 * 2. 2X means the new preferred LLC has at least 1 more
2107 		 *    busy CPU than the old one(200% vs 100%, eg)
2108 		 * 3. 2X is chosen based on test results, as it delivers
2109 		 *    the optimal performance gain so far.
2110 		 */
2111 		WRITE_ONCE(grp->cpu, m_a_cpu);
2112 	}
2113 
2114 	update_avg_scale(&grp->nr_running_avg, nr_running);
2115 }
2116 
2117 void init_sched_mm(struct task_struct *p)
2118 {
2119 	struct callback_head *work = &p->cache_work;
2120 
2121 	init_task_work(work, task_cache_work);
2122 	work->next = work;
2123 	/*
2124 	 * dup_task_struct() copies the parent's task_struct, including its
2125 	 * sched_cache_grp, for which the child holds no reference.  Clear it
2126 	 * here - before copy_mm() runs - so the child never carries a
2127 	 * borrowed pointer that the fork error path would put.
2128 	 */
2129 	RCU_INIT_POINTER(p->sched_cache_grp, NULL);
2130 	/*
2131 	 * Reset new task's preference to avoid
2132 	 * polluting account_llc_enqueue().
2133 	 */
2134 	p->preferred_llc = -1;
2135 	p->pref_llc_queued = 0;
2136 }
2137 
2138 #else /* CONFIG_SCHED_CACHE */
2139 
2140 static inline void account_mm_sched(struct rq *rq, struct task_struct *p,
2141 				    s64 delta_exec) { }
2142 
2143 void init_sched_mm(struct task_struct *p) { }
2144 
2145 static void task_tick_cache(struct rq *rq, struct task_struct *p) { }
2146 
2147 static inline int get_pref_llc(struct task_struct *p,
2148 			       struct sched_cache_group *grp)
2149 {
2150 	return -1;
2151 }
2152 
2153 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {}
2154 
2155 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {}
2156 
2157 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p) {}
2158 
2159 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) {}
2160 
2161 #endif /* CONFIG_SCHED_CACHE */
2162 
2163 /*
2164  * Used by other classes to account runtime.
2165  */
2166 s64 update_curr_common(struct rq *rq)
2167 {
2168 	return update_se(rq, &rq->donor->se);
2169 }
2170 
2171 /*
2172  * Update the current task's runtime statistics.
2173  */
2174 static void update_curr(struct cfs_rq *cfs_rq)
2175 {
2176 	/*
2177 	 * Note: cfs_rq->curr corresponds to the task picked to
2178 	 * run (ie: rq->donor.se) which due to proxy-exec may
2179 	 * not necessarily be the actual task running
2180 	 * (rq->curr.se). This is easy to confuse!
2181 	 */
2182 	struct sched_entity *curr = cfs_rq->h_curr;
2183 	struct rq *rq = rq_of(cfs_rq);
2184 	s64 delta_exec;
2185 	bool resched;
2186 
2187 	if (unlikely(!curr))
2188 		return;
2189 
2190 	delta_exec = update_se(rq, curr);
2191 	if (unlikely(delta_exec <= 0))
2192 		return;
2193 
2194 	account_cfs_rq_runtime(cfs_rq, delta_exec);
2195 
2196 	if (!entity_is_task(curr))
2197 		return;
2198 
2199 	cfs_rq = &rq->cfs;
2200 
2201 	curr->vruntime += calc_delta_fair(delta_exec, curr);
2202 	resched = update_deadline(cfs_rq, curr);
2203 
2204 	/*
2205 	 * If the fair_server is active, we need to account for the
2206 	 * fair_server time whether or not the task is running on
2207 	 * behalf of fair_server or not:
2208 	 *  - If the task is running on behalf of fair_server, we need
2209 	 *    to limit its time based on the assigned runtime.
2210 	 *  - Fair task that runs outside of fair_server should account
2211 	 *    against fair_server such that it can account for this time
2212 	 *    and possibly avoid running this period.
2213 	 */
2214 	dl_server_update(&rq->fair_server, delta_exec);
2215 
2216 	if (cfs_rq->h_nr_queued == 1)
2217 		return;
2218 
2219 	if (resched || !protect_slice(curr)) {
2220 		resched_curr_lazy(rq);
2221 		clear_buddies(cfs_rq, curr);
2222 	}
2223 }
2224 
2225 static void update_curr_fair(struct rq *rq)
2226 {
2227 	struct sched_entity *se = &rq->donor->se;
2228 
2229 	for_each_sched_entity(se)
2230 		update_curr(cfs_rq_of(se));
2231 }
2232 
2233 static inline void
2234 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2235 {
2236 	struct sched_statistics *stats;
2237 	struct task_struct *p = NULL;
2238 
2239 	if (!schedstat_enabled())
2240 		return;
2241 
2242 	stats = __schedstats_from_se(se);
2243 
2244 	if (entity_is_task(se))
2245 		p = task_of(se);
2246 
2247 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
2248 }
2249 
2250 static inline void
2251 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2252 {
2253 	struct sched_statistics *stats;
2254 	struct task_struct *p = NULL;
2255 
2256 	if (!schedstat_enabled())
2257 		return;
2258 
2259 	stats = __schedstats_from_se(se);
2260 
2261 	/*
2262 	 * When the sched_schedstat changes from 0 to 1, some sched se
2263 	 * maybe already in the runqueue, the se->statistics.wait_start
2264 	 * will be 0.So it will let the delta wrong. We need to avoid this
2265 	 * scenario.
2266 	 */
2267 	if (unlikely(!schedstat_val(stats->wait_start)))
2268 		return;
2269 
2270 	if (entity_is_task(se))
2271 		p = task_of(se);
2272 
2273 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
2274 }
2275 
2276 static inline void
2277 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2278 {
2279 	struct sched_statistics *stats;
2280 	struct task_struct *tsk = NULL;
2281 
2282 	if (!schedstat_enabled())
2283 		return;
2284 
2285 	stats = __schedstats_from_se(se);
2286 
2287 	if (entity_is_task(se))
2288 		tsk = task_of(se);
2289 
2290 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
2291 }
2292 
2293 /*
2294  * Task is being enqueued - update stats:
2295  */
2296 static inline void
2297 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2298 {
2299 	if (!schedstat_enabled())
2300 		return;
2301 
2302 	/*
2303 	 * Are we enqueueing a waiting task? (for current tasks
2304 	 * a dequeue/enqueue event is a NOP)
2305 	 */
2306 	if (se != cfs_rq->h_curr)
2307 		update_stats_wait_start_fair(cfs_rq, se);
2308 
2309 	if (flags & ENQUEUE_WAKEUP)
2310 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
2311 }
2312 
2313 static inline void
2314 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2315 {
2316 
2317 	if (!schedstat_enabled())
2318 		return;
2319 
2320 	/*
2321 	 * Mark the end of the wait period if dequeueing a
2322 	 * waiting task:
2323 	 */
2324 	if (se != cfs_rq->h_curr)
2325 		update_stats_wait_end_fair(cfs_rq, se);
2326 
2327 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
2328 		struct task_struct *tsk = task_of(se);
2329 		unsigned int state;
2330 
2331 		/* XXX racy against TTWU */
2332 		state = READ_ONCE(tsk->__state);
2333 		if (state & TASK_INTERRUPTIBLE)
2334 			__schedstat_set(tsk->stats.sleep_start,
2335 				      rq_clock(rq_of(cfs_rq)));
2336 		if (state & TASK_UNINTERRUPTIBLE)
2337 			__schedstat_set(tsk->stats.block_start,
2338 				      rq_clock(rq_of(cfs_rq)));
2339 	}
2340 }
2341 
2342 /*
2343  * We are picking a new current task - update its stats:
2344  */
2345 static inline void
2346 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
2347 {
2348 	/*
2349 	 * We are starting a new run period:
2350 	 */
2351 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
2352 }
2353 
2354 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */
2355 static inline bool is_core_idle(int cpu)
2356 {
2357 	int sibling;
2358 
2359 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
2360 		if (cpu == sibling)
2361 			continue;
2362 
2363 		if (!idle_cpu(sibling))
2364 			return false;
2365 	}
2366 
2367 	return true;
2368 }
2369 
2370 #ifdef CONFIG_NUMA
2371 #define NUMA_IMBALANCE_MIN 2
2372 
2373 static inline long
2374 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
2375 {
2376 	/*
2377 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
2378 	 * threshold. Above this threshold, individual tasks may be contending
2379 	 * for both memory bandwidth and any shared HT resources.  This is an
2380 	 * approximation as the number of running tasks may not be related to
2381 	 * the number of busy CPUs due to sched_setaffinity.
2382 	 */
2383 	if (dst_running > imb_numa_nr)
2384 		return imbalance;
2385 
2386 	/*
2387 	 * Allow a small imbalance based on a simple pair of communicating
2388 	 * tasks that remain local when the destination is lightly loaded.
2389 	 */
2390 	if (imbalance <= NUMA_IMBALANCE_MIN)
2391 		return 0;
2392 
2393 	return imbalance;
2394 }
2395 #endif /* CONFIG_NUMA */
2396 
2397 #ifdef CONFIG_NUMA_BALANCING
2398 /*
2399  * Approximate time to scan a full NUMA task in ms. The task scan period is
2400  * calculated based on the tasks virtual memory size and
2401  * numa_balancing_scan_size.
2402  */
2403 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
2404 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
2405 
2406 /* Portion of address space to scan in MB */
2407 unsigned int sysctl_numa_balancing_scan_size = 256;
2408 
2409 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
2410 unsigned int sysctl_numa_balancing_scan_delay = 1000;
2411 
2412 /* The page with hint page fault latency < threshold in ms is considered hot */
2413 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
2414 
2415 struct numa_group {
2416 	refcount_t refcount;
2417 
2418 	spinlock_t lock; /* nr_tasks, tasks */
2419 	int nr_tasks;
2420 	pid_t gid;
2421 	int active_nodes;
2422 
2423 	struct rcu_head rcu;
2424 	unsigned long total_faults;
2425 	unsigned long max_faults_cpu;
2426 	/*
2427 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
2428 	 *
2429 	 * Faults_cpu is used to decide whether memory should move
2430 	 * towards the CPU. As a consequence, these stats are weighted
2431 	 * more by CPU use than by memory faults.
2432 	 */
2433 	unsigned long faults[];
2434 };
2435 
2436 /*
2437  * For functions that can be called in multiple contexts that permit reading
2438  * ->numa_group (see struct task_struct for locking rules).
2439  */
2440 static struct numa_group *deref_task_numa_group(struct task_struct *p)
2441 {
2442 	return rcu_dereference_check(p->numa_group, p == current ||
2443 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
2444 }
2445 
2446 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
2447 {
2448 	return rcu_dereference_protected(p->numa_group, p == current);
2449 }
2450 
2451 static inline unsigned long group_faults_priv(struct numa_group *ng);
2452 static inline unsigned long group_faults_shared(struct numa_group *ng);
2453 
2454 static unsigned int task_nr_scan_windows(struct task_struct *p)
2455 {
2456 	unsigned long rss = 0;
2457 	unsigned long nr_scan_pages;
2458 
2459 	/*
2460 	 * Calculations based on RSS as non-present and empty pages are skipped
2461 	 * by the PTE scanner and NUMA hinting faults should be trapped based
2462 	 * on resident pages
2463 	 */
2464 	nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
2465 	rss = get_mm_rss(p->mm);
2466 	if (!rss)
2467 		rss = nr_scan_pages;
2468 
2469 	rss = round_up(rss, nr_scan_pages);
2470 	return rss / nr_scan_pages;
2471 }
2472 
2473 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
2474 #define MAX_SCAN_WINDOW 2560
2475 
2476 static unsigned int task_scan_min(struct task_struct *p)
2477 {
2478 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
2479 	unsigned int scan, floor;
2480 	unsigned int windows = 1;
2481 
2482 	if (scan_size < MAX_SCAN_WINDOW)
2483 		windows = MAX_SCAN_WINDOW / scan_size;
2484 	floor = 1000 / windows;
2485 
2486 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
2487 	return max_t(unsigned int, floor, scan);
2488 }
2489 
2490 static unsigned int task_scan_start(struct task_struct *p)
2491 {
2492 	unsigned long smin = task_scan_min(p);
2493 	unsigned long period = smin;
2494 	struct numa_group *ng;
2495 
2496 	/* Scale the maximum scan period with the amount of shared memory. */
2497 	rcu_read_lock();
2498 	ng = rcu_dereference_all(p->numa_group);
2499 	if (ng) {
2500 		unsigned long shared = group_faults_shared(ng);
2501 		unsigned long private = group_faults_priv(ng);
2502 
2503 		period *= refcount_read(&ng->refcount);
2504 		period *= shared + 1;
2505 		period /= private + shared + 1;
2506 	}
2507 	rcu_read_unlock();
2508 
2509 	return max(smin, period);
2510 }
2511 
2512 static unsigned int task_scan_max(struct task_struct *p)
2513 {
2514 	unsigned long smin = task_scan_min(p);
2515 	unsigned long smax;
2516 	struct numa_group *ng;
2517 
2518 	/* Watch for min being lower than max due to floor calculations */
2519 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
2520 
2521 	/* Scale the maximum scan period with the amount of shared memory. */
2522 	ng = deref_curr_numa_group(p);
2523 	if (ng) {
2524 		unsigned long shared = group_faults_shared(ng);
2525 		unsigned long private = group_faults_priv(ng);
2526 		unsigned long period = smax;
2527 
2528 		period *= refcount_read(&ng->refcount);
2529 		period *= shared + 1;
2530 		period /= private + shared + 1;
2531 
2532 		smax = max(smax, period);
2533 	}
2534 
2535 	return max(smin, smax);
2536 }
2537 
2538 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2539 {
2540 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
2541 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
2542 }
2543 
2544 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2545 {
2546 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
2547 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
2548 }
2549 
2550 /* Shared or private faults. */
2551 #define NR_NUMA_HINT_FAULT_TYPES 2
2552 
2553 /* Memory and CPU locality */
2554 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
2555 
2556 /* Averaged statistics, and temporary buffers. */
2557 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
2558 
2559 pid_t task_numa_group_id(struct task_struct *p)
2560 {
2561 	struct numa_group *ng;
2562 	pid_t gid = 0;
2563 
2564 	rcu_read_lock();
2565 	ng = rcu_dereference_all(p->numa_group);
2566 	if (ng)
2567 		gid = ng->gid;
2568 	rcu_read_unlock();
2569 
2570 	return gid;
2571 }
2572 
2573 /*
2574  * The averaged statistics, shared & private, memory & CPU,
2575  * occupy the first half of the array. The second half of the
2576  * array is for current counters, which are averaged into the
2577  * first set by task_numa_placement.
2578  */
2579 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
2580 {
2581 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
2582 }
2583 
2584 static inline unsigned long task_faults(struct task_struct *p, int nid)
2585 {
2586 	if (!p->numa_faults)
2587 		return 0;
2588 
2589 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2590 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
2591 }
2592 
2593 static inline unsigned long group_faults(struct task_struct *p, int nid)
2594 {
2595 	struct numa_group *ng = deref_task_numa_group(p);
2596 
2597 	if (!ng)
2598 		return 0;
2599 
2600 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2601 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
2602 }
2603 
2604 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
2605 {
2606 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
2607 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
2608 }
2609 
2610 static inline unsigned long group_faults_priv(struct numa_group *ng)
2611 {
2612 	unsigned long faults = 0;
2613 	int node;
2614 
2615 	for_each_online_node(node) {
2616 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
2617 	}
2618 
2619 	return faults;
2620 }
2621 
2622 static inline unsigned long group_faults_shared(struct numa_group *ng)
2623 {
2624 	unsigned long faults = 0;
2625 	int node;
2626 
2627 	for_each_online_node(node) {
2628 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
2629 	}
2630 
2631 	return faults;
2632 }
2633 
2634 /*
2635  * A node triggering more than 1/3 as many NUMA faults as the maximum is
2636  * considered part of a numa group's pseudo-interleaving set. Migrations
2637  * between these nodes are slowed down, to allow things to settle down.
2638  */
2639 #define ACTIVE_NODE_FRACTION 3
2640 
2641 static bool numa_is_active_node(int nid, struct numa_group *ng)
2642 {
2643 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
2644 }
2645 
2646 /* Handle placement on systems where not all nodes are directly connected. */
2647 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
2648 					int lim_dist, bool task)
2649 {
2650 	unsigned long score = 0;
2651 	int node, max_dist;
2652 
2653 	/*
2654 	 * All nodes are directly connected, and the same distance
2655 	 * from each other. No need for fancy placement algorithms.
2656 	 */
2657 	if (sched_numa_topology_type == NUMA_DIRECT)
2658 		return 0;
2659 
2660 	/* sched_max_numa_distance may be changed in parallel. */
2661 	max_dist = READ_ONCE(sched_max_numa_distance);
2662 	/*
2663 	 * This code is called for each node, introducing N^2 complexity,
2664 	 * which should be OK given the number of nodes rarely exceeds 8.
2665 	 */
2666 	for_each_online_node(node) {
2667 		unsigned long faults;
2668 		int dist = node_distance(nid, node);
2669 
2670 		/*
2671 		 * The furthest away nodes in the system are not interesting
2672 		 * for placement; nid was already counted.
2673 		 */
2674 		if (dist >= max_dist || node == nid)
2675 			continue;
2676 
2677 		/*
2678 		 * On systems with a backplane NUMA topology, compare groups
2679 		 * of nodes, and move tasks towards the group with the most
2680 		 * memory accesses. When comparing two nodes at distance
2681 		 * "hoplimit", only nodes closer by than "hoplimit" are part
2682 		 * of each group. Skip other nodes.
2683 		 */
2684 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
2685 			continue;
2686 
2687 		/* Add up the faults from nearby nodes. */
2688 		if (task)
2689 			faults = task_faults(p, node);
2690 		else
2691 			faults = group_faults(p, node);
2692 
2693 		/*
2694 		 * On systems with a glueless mesh NUMA topology, there are
2695 		 * no fixed "groups of nodes". Instead, nodes that are not
2696 		 * directly connected bounce traffic through intermediate
2697 		 * nodes; a numa_group can occupy any set of nodes.
2698 		 * The further away a node is, the less the faults count.
2699 		 * This seems to result in good task placement.
2700 		 */
2701 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2702 			faults *= (max_dist - dist);
2703 			faults /= (max_dist - LOCAL_DISTANCE);
2704 		}
2705 
2706 		score += faults;
2707 	}
2708 
2709 	return score;
2710 }
2711 
2712 /*
2713  * These return the fraction of accesses done by a particular task, or
2714  * task group, on a particular numa node.  The group weight is given a
2715  * larger multiplier, in order to group tasks together that are almost
2716  * evenly spread out between numa nodes.
2717  */
2718 static inline unsigned long task_weight(struct task_struct *p, int nid,
2719 					int dist)
2720 {
2721 	unsigned long faults, total_faults;
2722 
2723 	if (!p->numa_faults)
2724 		return 0;
2725 
2726 	total_faults = p->total_numa_faults;
2727 
2728 	if (!total_faults)
2729 		return 0;
2730 
2731 	faults = task_faults(p, nid);
2732 	faults += score_nearby_nodes(p, nid, dist, true);
2733 
2734 	return 1000 * faults / total_faults;
2735 }
2736 
2737 static inline unsigned long group_weight(struct task_struct *p, int nid,
2738 					 int dist)
2739 {
2740 	struct numa_group *ng = deref_task_numa_group(p);
2741 	unsigned long faults, total_faults;
2742 
2743 	if (!ng)
2744 		return 0;
2745 
2746 	total_faults = ng->total_faults;
2747 
2748 	if (!total_faults)
2749 		return 0;
2750 
2751 	faults = group_faults(p, nid);
2752 	faults += score_nearby_nodes(p, nid, dist, false);
2753 
2754 	return 1000 * faults / total_faults;
2755 }
2756 
2757 /*
2758  * If memory tiering mode is enabled, cpupid of slow memory page is
2759  * used to record scan time instead of CPU and PID.  When tiering mode
2760  * is disabled at run time, the scan time (in cpupid) will be
2761  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
2762  * access out of array bound.
2763  */
2764 static inline bool cpupid_valid(int cpupid)
2765 {
2766 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
2767 }
2768 
2769 /*
2770  * For memory tiering mode, if there are enough free pages (more than
2771  * enough watermark defined here) in fast memory node, to take full
2772  * advantage of fast memory capacity, all recently accessed slow
2773  * memory pages will be migrated to fast memory node without
2774  * considering hot threshold.
2775  */
2776 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
2777 {
2778 	int z;
2779 	unsigned long enough_wmark;
2780 
2781 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
2782 			   pgdat->node_present_pages >> 4);
2783 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2784 		struct zone *zone = pgdat->node_zones + z;
2785 
2786 		if (!populated_zone(zone))
2787 			continue;
2788 
2789 		if (zone_watermark_ok(zone, 0,
2790 				      promo_wmark_pages(zone) + enough_wmark,
2791 				      ZONE_MOVABLE, 0))
2792 			return true;
2793 	}
2794 	return false;
2795 }
2796 
2797 /*
2798  * For memory tiering mode, when page tables are scanned, the scan
2799  * time will be recorded in struct page in addition to make page
2800  * PROT_NONE for slow memory page.  So when the page is accessed, in
2801  * hint page fault handler, the hint page fault latency is calculated
2802  * via,
2803  *
2804  *	hint page fault latency = hint page fault time - scan time
2805  *
2806  * The smaller the hint page fault latency, the higher the possibility
2807  * for the page to be hot.
2808  */
2809 static int numa_hint_fault_latency(struct folio *folio)
2810 {
2811 	int last_time, time;
2812 
2813 	time = jiffies_to_msecs(jiffies);
2814 	last_time = folio_xchg_access_time(folio, time);
2815 
2816 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
2817 }
2818 
2819 /*
2820  * For memory tiering mode, too high promotion/demotion throughput may
2821  * hurt application latency.  So we provide a mechanism to rate limit
2822  * the number of pages that are tried to be promoted.
2823  */
2824 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
2825 				      unsigned long rate_limit, int nr)
2826 {
2827 	unsigned long nr_cand;
2828 	unsigned int now, start;
2829 
2830 	now = jiffies_to_msecs(jiffies);
2831 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
2832 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2833 	start = pgdat->nbp_rl_start;
2834 	if (now - start > MSEC_PER_SEC &&
2835 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
2836 		pgdat->nbp_rl_nr_cand = nr_cand;
2837 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
2838 		return true;
2839 	return false;
2840 }
2841 
2842 #define NUMA_MIGRATION_ADJUST_STEPS	16
2843 
2844 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
2845 					    unsigned long rate_limit,
2846 					    unsigned int ref_th)
2847 {
2848 	unsigned int now, start, th_period, unit_th, th;
2849 	unsigned long nr_cand, ref_cand, diff_cand;
2850 
2851 	now = jiffies_to_msecs(jiffies);
2852 	th_period = sysctl_numa_balancing_scan_period_max;
2853 	start = pgdat->nbp_th_start;
2854 	if (now - start > th_period &&
2855 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
2856 		ref_cand = rate_limit *
2857 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
2858 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2859 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
2860 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
2861 		th = pgdat->nbp_threshold ? : ref_th;
2862 		if (diff_cand > ref_cand * 11 / 10)
2863 			th = max(th - unit_th, unit_th);
2864 		else if (diff_cand < ref_cand * 9 / 10)
2865 			th = min(th + unit_th, ref_th * 2);
2866 		pgdat->nbp_th_nr_cand = nr_cand;
2867 		pgdat->nbp_threshold = th;
2868 	}
2869 }
2870 
2871 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
2872 				int src_nid, int dst_cpu)
2873 {
2874 	struct numa_group *ng = deref_curr_numa_group(p);
2875 	int dst_nid = cpu_to_node(dst_cpu);
2876 	int last_cpupid, this_cpupid;
2877 
2878 	/*
2879 	 * Cannot migrate to memoryless nodes.
2880 	 */
2881 	if (!node_state(dst_nid, N_MEMORY))
2882 		return false;
2883 
2884 	/*
2885 	 * The pages in slow memory node should be migrated according
2886 	 * to hot/cold instead of private/shared.
2887 	 */
2888 	if (folio_use_access_time(folio)) {
2889 		struct pglist_data *pgdat;
2890 		unsigned long rate_limit;
2891 		unsigned int latency, th, def_th;
2892 		long nr = folio_nr_pages(folio);
2893 
2894 		pgdat = NODE_DATA(dst_nid);
2895 		if (pgdat_free_space_enough(pgdat)) {
2896 			/* workload changed, reset hot threshold */
2897 			pgdat->nbp_threshold = 0;
2898 			mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
2899 			return true;
2900 		}
2901 
2902 		def_th = sysctl_numa_balancing_hot_threshold;
2903 		rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
2904 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
2905 
2906 		th = pgdat->nbp_threshold ? : def_th;
2907 		latency = numa_hint_fault_latency(folio);
2908 		if (latency >= th)
2909 			return false;
2910 
2911 		return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
2912 	}
2913 
2914 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
2915 	last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
2916 
2917 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
2918 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
2919 		return false;
2920 
2921 	/*
2922 	 * Allow first faults or private faults to migrate immediately early in
2923 	 * the lifetime of a task. The magic number 4 is based on waiting for
2924 	 * two full passes of the "multi-stage node selection" test that is
2925 	 * executed below.
2926 	 */
2927 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
2928 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
2929 		return true;
2930 
2931 	/*
2932 	 * Multi-stage node selection is used in conjunction with a periodic
2933 	 * migration fault to build a temporal task<->page relation. By using
2934 	 * a two-stage filter we remove short/unlikely relations.
2935 	 *
2936 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2937 	 * a task's usage of a particular page (n_p) per total usage of this
2938 	 * page (n_t) (in a given time-span) to a probability.
2939 	 *
2940 	 * Our periodic faults will sample this probability and getting the
2941 	 * same result twice in a row, given these samples are fully
2942 	 * independent, is then given by P(n)^2, provided our sample period
2943 	 * is sufficiently short compared to the usage pattern.
2944 	 *
2945 	 * This quadric squishes small probabilities, making it less likely we
2946 	 * act on an unlikely task<->page relation.
2947 	 */
2948 	if (!cpupid_pid_unset(last_cpupid) &&
2949 				cpupid_to_nid(last_cpupid) != dst_nid)
2950 		return false;
2951 
2952 	/* Always allow migrate on private faults */
2953 	if (cpupid_match_pid(p, last_cpupid))
2954 		return true;
2955 
2956 	/* A shared fault, but p->numa_group has not been set up yet. */
2957 	if (!ng)
2958 		return true;
2959 
2960 	/*
2961 	 * Destination node is much more heavily used than the source
2962 	 * node? Allow migration.
2963 	 */
2964 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2965 					ACTIVE_NODE_FRACTION)
2966 		return true;
2967 
2968 	/*
2969 	 * Distribute memory according to CPU & memory use on each node,
2970 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2971 	 *
2972 	 * faults_cpu(dst)   3   faults_cpu(src)
2973 	 * --------------- * - > ---------------
2974 	 * faults_mem(dst)   4   faults_mem(src)
2975 	 */
2976 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2977 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2978 }
2979 
2980 /*
2981  * 'numa_type' describes the node at the moment of load balancing.
2982  */
2983 enum numa_type {
2984 	/* The node has spare capacity that can be used to run more tasks.  */
2985 	node_has_spare = 0,
2986 	/*
2987 	 * The node is fully used and the tasks don't compete for more CPU
2988 	 * cycles. Nevertheless, some tasks might wait before running.
2989 	 */
2990 	node_fully_busy,
2991 	/*
2992 	 * The node is overloaded and can't provide expected CPU cycles to all
2993 	 * tasks.
2994 	 */
2995 	node_overloaded
2996 };
2997 
2998 /* Cached statistics for all CPUs within a node */
2999 struct numa_stats {
3000 	unsigned long load;
3001 	unsigned long runnable;
3002 	unsigned long util;
3003 	/* Total compute capacity of CPUs on a node */
3004 	unsigned long compute_capacity;
3005 	unsigned int nr_running;
3006 	unsigned int weight;
3007 	enum numa_type node_type;
3008 	int idle_cpu;
3009 };
3010 
3011 struct task_numa_env {
3012 	struct task_struct *p;
3013 
3014 	int src_cpu, src_nid;
3015 	int dst_cpu, dst_nid;
3016 	int imb_numa_nr;
3017 
3018 	struct numa_stats src_stats, dst_stats;
3019 
3020 	int imbalance_pct;
3021 	int dist;
3022 
3023 	struct task_struct *best_task;
3024 	long best_imp;
3025 	int best_cpu;
3026 };
3027 
3028 static unsigned long cpu_load(struct rq *rq);
3029 static unsigned long cpu_runnable(struct rq *rq);
3030 
3031 static inline enum
3032 numa_type numa_classify(unsigned int imbalance_pct,
3033 			 struct numa_stats *ns)
3034 {
3035 	if ((ns->nr_running > ns->weight) &&
3036 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
3037 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
3038 		return node_overloaded;
3039 
3040 	if ((ns->nr_running < ns->weight) ||
3041 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
3042 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
3043 		return node_has_spare;
3044 
3045 	return node_fully_busy;
3046 }
3047 
3048 /* Forward declarations of select_idle_sibling helpers */
3049 static inline bool test_idle_cores(int cpu);
3050 static inline int numa_idle_core(int idle_core, int cpu)
3051 {
3052 	if (!sched_smt_active() ||
3053 	    idle_core >= 0 || !test_idle_cores(cpu))
3054 		return idle_core;
3055 
3056 	/*
3057 	 * Prefer cores instead of packing HT siblings
3058 	 * and triggering future load balancing.
3059 	 */
3060 	if (is_core_idle(cpu))
3061 		idle_core = cpu;
3062 
3063 	return idle_core;
3064 }
3065 
3066 /*
3067  * Gather all necessary information to make NUMA balancing placement
3068  * decisions that are compatible with standard load balancer. This
3069  * borrows code and logic from update_sg_lb_stats but sharing a
3070  * common implementation is impractical.
3071  */
3072 static void update_numa_stats(struct task_numa_env *env,
3073 			      struct numa_stats *ns, int nid,
3074 			      bool find_idle)
3075 {
3076 	int cpu, idle_core = -1;
3077 
3078 	memset(ns, 0, sizeof(*ns));
3079 	ns->idle_cpu = -1;
3080 
3081 	rcu_read_lock();
3082 	for_each_cpu(cpu, cpumask_of_node(nid)) {
3083 		struct rq *rq = cpu_rq(cpu);
3084 
3085 		ns->load += cpu_load(rq);
3086 		ns->runnable += cpu_runnable(rq);
3087 		ns->util += cpu_util_cfs(cpu);
3088 		ns->nr_running += rq->cfs.h_nr_runnable;
3089 		ns->compute_capacity += capacity_of(cpu);
3090 
3091 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
3092 			if (READ_ONCE(rq->numa_migrate_on) ||
3093 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
3094 				continue;
3095 
3096 			if (ns->idle_cpu == -1)
3097 				ns->idle_cpu = cpu;
3098 
3099 			idle_core = numa_idle_core(idle_core, cpu);
3100 		}
3101 	}
3102 	rcu_read_unlock();
3103 
3104 	ns->weight = cpumask_weight(cpumask_of_node(nid));
3105 
3106 	ns->node_type = numa_classify(env->imbalance_pct, ns);
3107 
3108 	if (idle_core >= 0)
3109 		ns->idle_cpu = idle_core;
3110 }
3111 
3112 static void task_numa_assign(struct task_numa_env *env,
3113 			     struct task_struct *p, long imp)
3114 {
3115 	struct rq *rq = cpu_rq(env->dst_cpu);
3116 
3117 	/* Check if run-queue part of active NUMA balance. */
3118 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
3119 		int cpu;
3120 		int start = env->dst_cpu;
3121 
3122 		/* Find alternative idle CPU. */
3123 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
3124 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
3125 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
3126 				continue;
3127 			}
3128 
3129 			env->dst_cpu = cpu;
3130 			rq = cpu_rq(env->dst_cpu);
3131 			if (!xchg(&rq->numa_migrate_on, 1))
3132 				goto assign;
3133 		}
3134 
3135 		/* Failed to find an alternative idle CPU */
3136 		return;
3137 	}
3138 
3139 assign:
3140 	/*
3141 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
3142 	 * found a better CPU to move/swap.
3143 	 */
3144 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
3145 		rq = cpu_rq(env->best_cpu);
3146 		WRITE_ONCE(rq->numa_migrate_on, 0);
3147 	}
3148 
3149 	if (env->best_task)
3150 		put_task_struct(env->best_task);
3151 	if (p)
3152 		get_task_struct(p);
3153 
3154 	env->best_task = p;
3155 	env->best_imp = imp;
3156 	env->best_cpu = env->dst_cpu;
3157 }
3158 
3159 static bool load_too_imbalanced(long src_load, long dst_load,
3160 				struct task_numa_env *env)
3161 {
3162 	long imb, old_imb;
3163 	long orig_src_load, orig_dst_load;
3164 	long src_capacity, dst_capacity;
3165 
3166 	/*
3167 	 * The load is corrected for the CPU capacity available on each node.
3168 	 *
3169 	 * src_load        dst_load
3170 	 * ------------ vs ---------
3171 	 * src_capacity    dst_capacity
3172 	 */
3173 	src_capacity = env->src_stats.compute_capacity;
3174 	dst_capacity = env->dst_stats.compute_capacity;
3175 
3176 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
3177 
3178 	orig_src_load = env->src_stats.load;
3179 	orig_dst_load = env->dst_stats.load;
3180 
3181 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
3182 
3183 	/* Would this change make things worse? */
3184 	return (imb > old_imb);
3185 }
3186 
3187 /*
3188  * Maximum NUMA importance can be 1998 (2*999);
3189  * SMALLIMP @ 30 would be close to 1998/64.
3190  * Used to deter task migration.
3191  */
3192 #define SMALLIMP	30
3193 
3194 /*
3195  * This checks if the overall compute and NUMA accesses of the system would
3196  * be improved if the source tasks was migrated to the target dst_cpu taking
3197  * into account that it might be best if task running on the dst_cpu should
3198  * be exchanged with the source task
3199  */
3200 static bool task_numa_compare(struct task_numa_env *env,
3201 			      long taskimp, long groupimp, bool maymove)
3202 {
3203 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
3204 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
3205 	long imp = p_ng ? groupimp : taskimp;
3206 	struct task_struct *cur;
3207 	long src_load, dst_load;
3208 	int dist = env->dist;
3209 	long moveimp = imp;
3210 	long load;
3211 	bool stopsearch = false;
3212 
3213 	if (READ_ONCE(dst_rq->numa_migrate_on))
3214 		return false;
3215 
3216 	rcu_read_lock();
3217 	cur = rcu_dereference_all(dst_rq->curr);
3218 	if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
3219 		    !cur->mm))
3220 		cur = NULL;
3221 
3222 	/*
3223 	 * Because we have preemption enabled we can get migrated around and
3224 	 * end try selecting ourselves (current == env->p) as a swap candidate.
3225 	 */
3226 	if (cur == env->p) {
3227 		stopsearch = true;
3228 		goto unlock;
3229 	}
3230 
3231 	if (!cur) {
3232 		if (maymove && moveimp >= env->best_imp)
3233 			goto assign;
3234 		else
3235 			goto unlock;
3236 	}
3237 
3238 	/* Skip this swap candidate if cannot move to the source cpu. */
3239 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
3240 		goto unlock;
3241 
3242 	/*
3243 	 * Skip this swap candidate if it is not moving to its preferred
3244 	 * node and the best task is.
3245 	 */
3246 	if (env->best_task &&
3247 	    env->best_task->numa_preferred_nid == env->src_nid &&
3248 	    cur->numa_preferred_nid != env->src_nid) {
3249 		goto unlock;
3250 	}
3251 
3252 	/*
3253 	 * "imp" is the fault differential for the source task between the
3254 	 * source and destination node. Calculate the total differential for
3255 	 * the source task and potential destination task. The more negative
3256 	 * the value is, the more remote accesses that would be expected to
3257 	 * be incurred if the tasks were swapped.
3258 	 *
3259 	 * If dst and source tasks are in the same NUMA group, or not
3260 	 * in any group then look only at task weights.
3261 	 */
3262 	cur_ng = rcu_dereference_all(cur->numa_group);
3263 	if (cur_ng == p_ng) {
3264 		/*
3265 		 * Do not swap within a group or between tasks that have
3266 		 * no group if there is spare capacity. Swapping does
3267 		 * not address the load imbalance and helps one task at
3268 		 * the cost of punishing another.
3269 		 */
3270 		if (env->dst_stats.node_type == node_has_spare)
3271 			goto unlock;
3272 
3273 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
3274 		      task_weight(cur, env->dst_nid, dist);
3275 		/*
3276 		 * Add some hysteresis to prevent swapping the
3277 		 * tasks within a group over tiny differences.
3278 		 */
3279 		if (cur_ng)
3280 			imp -= imp / 16;
3281 	} else {
3282 		/*
3283 		 * Compare the group weights. If a task is all by itself
3284 		 * (not part of a group), use the task weight instead.
3285 		 */
3286 		if (cur_ng && p_ng)
3287 			imp += group_weight(cur, env->src_nid, dist) -
3288 			       group_weight(cur, env->dst_nid, dist);
3289 		else
3290 			imp += task_weight(cur, env->src_nid, dist) -
3291 			       task_weight(cur, env->dst_nid, dist);
3292 	}
3293 
3294 	/* Discourage picking a task already on its preferred node */
3295 	if (cur->numa_preferred_nid == env->dst_nid)
3296 		imp -= imp / 16;
3297 
3298 	/*
3299 	 * Encourage picking a task that moves to its preferred node.
3300 	 * This potentially makes imp larger than it's maximum of
3301 	 * 1998 (see SMALLIMP and task_weight for why) but in this
3302 	 * case, it does not matter.
3303 	 */
3304 	if (cur->numa_preferred_nid == env->src_nid)
3305 		imp += imp / 8;
3306 
3307 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
3308 		imp = moveimp;
3309 		cur = NULL;
3310 		goto assign;
3311 	}
3312 
3313 	/*
3314 	 * Prefer swapping with a task moving to its preferred node over a
3315 	 * task that is not.
3316 	 */
3317 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
3318 	    env->best_task->numa_preferred_nid != env->src_nid) {
3319 		goto assign;
3320 	}
3321 
3322 	/*
3323 	 * If the NUMA importance is less than SMALLIMP,
3324 	 * task migration might only result in ping pong
3325 	 * of tasks and also hurt performance due to cache
3326 	 * misses.
3327 	 */
3328 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
3329 		goto unlock;
3330 
3331 	/*
3332 	 * In the overloaded case, try and keep the load balanced.
3333 	 */
3334 	load = task_h_load(env->p) - task_h_load(cur);
3335 	if (!load)
3336 		goto assign;
3337 
3338 	dst_load = env->dst_stats.load + load;
3339 	src_load = env->src_stats.load - load;
3340 
3341 	if (load_too_imbalanced(src_load, dst_load, env))
3342 		goto unlock;
3343 
3344 assign:
3345 	/* Evaluate an idle CPU for a task numa move. */
3346 	if (!cur) {
3347 		int cpu = env->dst_stats.idle_cpu;
3348 
3349 		/* Nothing cached so current CPU went idle since the search. */
3350 		if (cpu < 0)
3351 			cpu = env->dst_cpu;
3352 
3353 		/*
3354 		 * If the CPU is no longer truly idle and the previous best CPU
3355 		 * is, keep using it.
3356 		 */
3357 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
3358 		    idle_cpu(env->best_cpu)) {
3359 			cpu = env->best_cpu;
3360 		}
3361 
3362 		env->dst_cpu = cpu;
3363 	}
3364 
3365 	task_numa_assign(env, cur, imp);
3366 
3367 	/*
3368 	 * If a move to idle is allowed because there is capacity or load
3369 	 * balance improves then stop the search. While a better swap
3370 	 * candidate may exist, a search is not free.
3371 	 */
3372 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
3373 		stopsearch = true;
3374 
3375 	/*
3376 	 * If a swap candidate must be identified and the current best task
3377 	 * moves its preferred node then stop the search.
3378 	 */
3379 	if (!maymove && env->best_task &&
3380 	    env->best_task->numa_preferred_nid == env->src_nid) {
3381 		stopsearch = true;
3382 	}
3383 unlock:
3384 	rcu_read_unlock();
3385 
3386 	return stopsearch;
3387 }
3388 
3389 static void task_numa_find_cpu(struct task_numa_env *env,
3390 				long taskimp, long groupimp)
3391 {
3392 	bool maymove = false;
3393 	int cpu;
3394 
3395 	/*
3396 	 * If dst node has spare capacity, then check if there is an
3397 	 * imbalance that would be overruled by the load balancer.
3398 	 */
3399 	if (env->dst_stats.node_type == node_has_spare) {
3400 		unsigned int imbalance;
3401 		int src_running, dst_running;
3402 
3403 		/*
3404 		 * Would movement cause an imbalance? Note that if src has
3405 		 * more running tasks that the imbalance is ignored as the
3406 		 * move improves the imbalance from the perspective of the
3407 		 * CPU load balancer.
3408 		 * */
3409 		src_running = env->src_stats.nr_running - 1;
3410 		dst_running = env->dst_stats.nr_running + 1;
3411 		imbalance = max(0, dst_running - src_running);
3412 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
3413 						  env->imb_numa_nr);
3414 
3415 		/* Use idle CPU if there is no imbalance */
3416 		if (!imbalance) {
3417 			maymove = true;
3418 			if (env->dst_stats.idle_cpu >= 0) {
3419 				env->dst_cpu = env->dst_stats.idle_cpu;
3420 				task_numa_assign(env, NULL, 0);
3421 				return;
3422 			}
3423 		}
3424 	} else {
3425 		long src_load, dst_load, load;
3426 		/*
3427 		 * If the improvement from just moving env->p direction is better
3428 		 * than swapping tasks around, check if a move is possible.
3429 		 */
3430 		load = task_h_load(env->p);
3431 		dst_load = env->dst_stats.load + load;
3432 		src_load = env->src_stats.load - load;
3433 		maymove = !load_too_imbalanced(src_load, dst_load, env);
3434 	}
3435 
3436 	/* Skip CPUs if the source task cannot migrate */
3437 	for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) {
3438 		env->dst_cpu = cpu;
3439 		if (task_numa_compare(env, taskimp, groupimp, maymove))
3440 			break;
3441 	}
3442 }
3443 
3444 static int task_numa_migrate(struct task_struct *p)
3445 {
3446 	struct task_numa_env env = {
3447 		.p = p,
3448 
3449 		.src_cpu = task_cpu(p),
3450 		.src_nid = task_node(p),
3451 
3452 		.imbalance_pct = 112,
3453 
3454 		.best_task = NULL,
3455 		.best_imp = 0,
3456 		.best_cpu = -1,
3457 	};
3458 	unsigned long taskweight, groupweight;
3459 	struct sched_domain *sd;
3460 	long taskimp, groupimp;
3461 	struct numa_group *ng;
3462 	struct rq *best_rq;
3463 	int nid, ret, dist;
3464 
3465 	/*
3466 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
3467 	 * imbalance and would be the first to start moving tasks about.
3468 	 *
3469 	 * And we want to avoid any moving of tasks about, as that would create
3470 	 * random movement of tasks -- counter the numa conditions we're trying
3471 	 * to satisfy here.
3472 	 */
3473 	rcu_read_lock();
3474 	sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu));
3475 	if (sd) {
3476 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
3477 		env.imb_numa_nr = sd->imb_numa_nr;
3478 	}
3479 	rcu_read_unlock();
3480 
3481 	/*
3482 	 * Cpusets can break the scheduler domain tree into smaller
3483 	 * balance domains, some of which do not cross NUMA boundaries.
3484 	 * Tasks that are "trapped" in such domains cannot be migrated
3485 	 * elsewhere, so there is no point in (re)trying.
3486 	 */
3487 	if (unlikely(!sd)) {
3488 		sched_setnuma(p, task_node(p));
3489 		return -EINVAL;
3490 	}
3491 
3492 	env.dst_nid = p->numa_preferred_nid;
3493 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
3494 	taskweight = task_weight(p, env.src_nid, dist);
3495 	groupweight = group_weight(p, env.src_nid, dist);
3496 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
3497 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
3498 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
3499 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3500 
3501 	/* Try to find a spot on the preferred nid. */
3502 	task_numa_find_cpu(&env, taskimp, groupimp);
3503 
3504 	/*
3505 	 * Look at other nodes in these cases:
3506 	 * - there is no space available on the preferred_nid
3507 	 * - the task is part of a numa_group that is interleaved across
3508 	 *   multiple NUMA nodes; in order to better consolidate the group,
3509 	 *   we need to check other locations.
3510 	 */
3511 	ng = deref_curr_numa_group(p);
3512 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
3513 		for_each_node_state(nid, N_CPU) {
3514 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
3515 				continue;
3516 
3517 			dist = node_distance(env.src_nid, env.dst_nid);
3518 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
3519 						dist != env.dist) {
3520 				taskweight = task_weight(p, env.src_nid, dist);
3521 				groupweight = group_weight(p, env.src_nid, dist);
3522 			}
3523 
3524 			/* Only consider nodes where both task and groups benefit */
3525 			taskimp = task_weight(p, nid, dist) - taskweight;
3526 			groupimp = group_weight(p, nid, dist) - groupweight;
3527 			if (taskimp < 0 && groupimp < 0)
3528 				continue;
3529 
3530 			env.dist = dist;
3531 			env.dst_nid = nid;
3532 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3533 			task_numa_find_cpu(&env, taskimp, groupimp);
3534 		}
3535 	}
3536 
3537 	/*
3538 	 * If the task is part of a workload that spans multiple NUMA nodes,
3539 	 * and is migrating into one of the workload's active nodes, remember
3540 	 * this node as the task's preferred numa node, so the workload can
3541 	 * settle down.
3542 	 * A task that migrated to a second choice node will be better off
3543 	 * trying for a better one later. Do not set the preferred node here.
3544 	 */
3545 	if (ng) {
3546 		if (env.best_cpu == -1)
3547 			nid = env.src_nid;
3548 		else
3549 			nid = cpu_to_node(env.best_cpu);
3550 
3551 		if (nid != p->numa_preferred_nid)
3552 			sched_setnuma(p, nid);
3553 	}
3554 
3555 	/* No better CPU than the current one was found. */
3556 	if (env.best_cpu == -1) {
3557 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
3558 		return -EAGAIN;
3559 	}
3560 
3561 	best_rq = cpu_rq(env.best_cpu);
3562 	if (env.best_task == NULL) {
3563 		ret = migrate_task_to(p, env.best_cpu);
3564 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
3565 		if (ret != 0)
3566 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
3567 		return ret;
3568 	}
3569 
3570 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
3571 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
3572 
3573 	if (ret != 0)
3574 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
3575 	put_task_struct(env.best_task);
3576 	return ret;
3577 }
3578 
3579 /* Attempt to migrate a task to a CPU on the preferred node. */
3580 static void numa_migrate_preferred(struct task_struct *p)
3581 {
3582 	unsigned long interval = HZ;
3583 
3584 	/* This task has no NUMA fault statistics yet */
3585 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
3586 		return;
3587 
3588 	/* Periodically retry migrating the task to the preferred node */
3589 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
3590 	p->numa_migrate_retry = jiffies + interval;
3591 
3592 	/* Success if task is already running on preferred CPU */
3593 	if (task_node(p) == p->numa_preferred_nid)
3594 		return;
3595 
3596 	/* Otherwise, try migrate to a CPU on the preferred node */
3597 	task_numa_migrate(p);
3598 }
3599 
3600 /*
3601  * Find out how many nodes the workload is actively running on. Do this by
3602  * tracking the nodes from which NUMA hinting faults are triggered. This can
3603  * be different from the set of nodes where the workload's memory is currently
3604  * located.
3605  */
3606 static void numa_group_count_active_nodes(struct numa_group *numa_group)
3607 {
3608 	unsigned long faults, max_faults = 0;
3609 	int nid, active_nodes = 0;
3610 
3611 	for_each_node_state(nid, N_CPU) {
3612 		faults = group_faults_cpu(numa_group, nid);
3613 		if (faults > max_faults)
3614 			max_faults = faults;
3615 	}
3616 
3617 	for_each_node_state(nid, N_CPU) {
3618 		faults = group_faults_cpu(numa_group, nid);
3619 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
3620 			active_nodes++;
3621 	}
3622 
3623 	numa_group->max_faults_cpu = max_faults;
3624 	numa_group->active_nodes = active_nodes;
3625 }
3626 
3627 /*
3628  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
3629  * increments. The more local the fault statistics are, the higher the scan
3630  * period will be for the next scan window. If local/(local+remote) ratio is
3631  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
3632  * the scan period will decrease. Aim for 70% local accesses.
3633  */
3634 #define NUMA_PERIOD_SLOTS 10
3635 #define NUMA_PERIOD_THRESHOLD 7
3636 
3637 /*
3638  * Increase the scan period (slow down scanning) if the majority of
3639  * our memory is already on our local node, or if the majority of
3640  * the page accesses are shared with other processes.
3641  * Otherwise, decrease the scan period.
3642  */
3643 static void update_task_scan_period(struct task_struct *p,
3644 			unsigned long shared, unsigned long private)
3645 {
3646 	unsigned int period_slot;
3647 	int lr_ratio, ps_ratio;
3648 	int diff;
3649 
3650 	unsigned long remote = p->numa_faults_locality[0];
3651 	unsigned long local = p->numa_faults_locality[1];
3652 
3653 	/*
3654 	 * If there were no record hinting faults then either the task is
3655 	 * completely idle or all activity is in areas that are not of interest
3656 	 * to automatic numa balancing. Related to that, if there were failed
3657 	 * migration then it implies we are migrating too quickly or the local
3658 	 * node is overloaded. In either case, scan slower
3659 	 */
3660 	if (local + shared == 0 || p->numa_faults_locality[2]) {
3661 		p->numa_scan_period = min(p->numa_scan_period_max,
3662 			p->numa_scan_period << 1);
3663 
3664 		p->mm->numa_next_scan = jiffies +
3665 			msecs_to_jiffies(p->numa_scan_period);
3666 
3667 		goto out;
3668 	}
3669 
3670 	/*
3671 	 * Prepare to scale scan period relative to the current period.
3672 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
3673 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
3674 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
3675 	 */
3676 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
3677 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
3678 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
3679 
3680 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
3681 		/*
3682 		 * Most memory accesses are local. There is no need to
3683 		 * do fast NUMA scanning, since memory is already local.
3684 		 */
3685 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
3686 		if (!slot)
3687 			slot = 1;
3688 		diff = slot * period_slot;
3689 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
3690 		/*
3691 		 * Most memory accesses are shared with other tasks.
3692 		 * There is no point in continuing fast NUMA scanning,
3693 		 * since other tasks may just move the memory elsewhere.
3694 		 */
3695 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
3696 		if (!slot)
3697 			slot = 1;
3698 		diff = slot * period_slot;
3699 	} else {
3700 		/*
3701 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
3702 		 * yet they are not on the local NUMA node. Speed up
3703 		 * NUMA scanning to get the memory moved over.
3704 		 */
3705 		int ratio = max(lr_ratio, ps_ratio);
3706 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
3707 	}
3708 
3709 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
3710 			task_scan_min(p), task_scan_max(p));
3711 
3712 out:
3713 	memset(p->numa_faults_locality, 0,
3714 	       sizeof(p->numa_faults_locality));
3715 }
3716 
3717 /*
3718  * Get the fraction of time the task has been running since the last
3719  * NUMA placement cycle. The scheduler keeps similar statistics, but
3720  * decays those on a 32ms period, which is orders of magnitude off
3721  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
3722  * stats only if the task is so new there are no NUMA statistics yet.
3723  */
3724 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
3725 {
3726 	u64 runtime, delta, now;
3727 	/* Use the start of this time slice to avoid calculations. */
3728 	now = p->se.exec_start;
3729 	runtime = p->se.sum_exec_runtime;
3730 
3731 	if (p->last_task_numa_placement) {
3732 		delta = runtime - p->last_sum_exec_runtime;
3733 		*period = now - p->last_task_numa_placement;
3734 
3735 		/* Avoid time going backwards, prevent potential divide error: */
3736 		if (unlikely((s64)*period < 0))
3737 			*period = 0;
3738 	} else {
3739 		delta = p->se.avg.load_sum;
3740 		*period = LOAD_AVG_MAX;
3741 	}
3742 
3743 	p->last_sum_exec_runtime = runtime;
3744 	p->last_task_numa_placement = now;
3745 
3746 	return delta;
3747 }
3748 
3749 /*
3750  * Determine the preferred nid for a task in a numa_group. This needs to
3751  * be done in a way that produces consistent results with group_weight,
3752  * otherwise workloads might not converge.
3753  */
3754 static int preferred_group_nid(struct task_struct *p, int nid)
3755 {
3756 	nodemask_t nodes;
3757 	int dist;
3758 
3759 	/* Direct connections between all NUMA nodes. */
3760 	if (sched_numa_topology_type == NUMA_DIRECT)
3761 		return nid;
3762 
3763 	/*
3764 	 * On a system with glueless mesh NUMA topology, group_weight
3765 	 * scores nodes according to the number of NUMA hinting faults on
3766 	 * both the node itself, and on nearby nodes.
3767 	 */
3768 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
3769 		unsigned long score, max_score = 0;
3770 		int node, max_node = nid;
3771 
3772 		dist = sched_max_numa_distance;
3773 
3774 		for_each_node_state(node, N_CPU) {
3775 			score = group_weight(p, node, dist);
3776 			if (score > max_score) {
3777 				max_score = score;
3778 				max_node = node;
3779 			}
3780 		}
3781 		return max_node;
3782 	}
3783 
3784 	/*
3785 	 * Finding the preferred nid in a system with NUMA backplane
3786 	 * interconnect topology is more involved. The goal is to locate
3787 	 * tasks from numa_groups near each other in the system, and
3788 	 * untangle workloads from different sides of the system. This requires
3789 	 * searching down the hierarchy of node groups, recursively searching
3790 	 * inside the highest scoring group of nodes. The nodemask tricks
3791 	 * keep the complexity of the search down.
3792 	 */
3793 	nodes = node_states[N_CPU];
3794 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
3795 		unsigned long max_faults = 0;
3796 		nodemask_t max_group = NODE_MASK_NONE;
3797 		int a, b;
3798 
3799 		/* Are there nodes at this distance from each other? */
3800 		if (!find_numa_distance(dist))
3801 			continue;
3802 
3803 		for_each_node_mask(a, nodes) {
3804 			unsigned long faults = 0;
3805 			nodemask_t this_group;
3806 			nodes_clear(this_group);
3807 
3808 			/* Sum group's NUMA faults; includes a==b case. */
3809 			for_each_node_mask(b, nodes) {
3810 				if (node_distance(a, b) < dist) {
3811 					faults += group_faults(p, b);
3812 					node_set(b, this_group);
3813 					node_clear(b, nodes);
3814 				}
3815 			}
3816 
3817 			/* Remember the top group. */
3818 			if (faults > max_faults) {
3819 				max_faults = faults;
3820 				max_group = this_group;
3821 				/*
3822 				 * subtle: at the smallest distance there is
3823 				 * just one node left in each "group", the
3824 				 * winner is the preferred nid.
3825 				 */
3826 				nid = a;
3827 			}
3828 		}
3829 		/* Next round, evaluate the nodes within max_group. */
3830 		if (!max_faults)
3831 			break;
3832 		nodes = max_group;
3833 	}
3834 	return nid;
3835 }
3836 
3837 static void task_numa_placement(struct task_struct *p)
3838 	__context_unsafe(/* conditional locking */)
3839 {
3840 	struct sched_cache_group __maybe_unused *grp;
3841 	int seq, nid, max_nid = NUMA_NO_NODE;
3842 	unsigned long max_faults = 0;
3843 	unsigned long fault_types[2] = { 0, 0 };
3844 	unsigned long total_faults;
3845 	u64 runtime, period;
3846 	spinlock_t *group_lock = NULL;
3847 	long __maybe_unused new_fp;
3848 	struct numa_group *ng;
3849 
3850 	/*
3851 	 * The p->mm->numa_scan_seq field gets updated without
3852 	 * exclusive access. Use READ_ONCE() here to ensure
3853 	 * that the field is read in a single access:
3854 	 */
3855 	seq = READ_ONCE(p->mm->numa_scan_seq);
3856 	if (p->numa_scan_seq == seq)
3857 		return;
3858 	p->numa_scan_seq = seq;
3859 	p->numa_scan_period_max = task_scan_max(p);
3860 
3861 	total_faults = p->numa_faults_locality[0] +
3862 		       p->numa_faults_locality[1];
3863 	runtime = numa_get_avg_runtime(p, &period);
3864 
3865 	/* If the task is part of a group prevent parallel updates to group stats */
3866 	ng = deref_curr_numa_group(p);
3867 	if (ng) {
3868 		group_lock = &ng->lock;
3869 		spin_lock_irq(group_lock);
3870 	}
3871 
3872 	/* Find the node with the highest number of faults */
3873 	for_each_online_node(nid) {
3874 		/* Keep track of the offsets in numa_faults array */
3875 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
3876 		unsigned long faults = 0, group_faults = 0;
3877 		int priv;
3878 
3879 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
3880 			long diff, f_diff, f_weight;
3881 
3882 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
3883 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
3884 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
3885 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
3886 
3887 			/* Decay existing window, copy faults since last scan */
3888 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
3889 			fault_types[priv] += p->numa_faults[membuf_idx];
3890 			p->numa_faults[membuf_idx] = 0;
3891 
3892 			/*
3893 			 * Normalize the faults_from, so all tasks in a group
3894 			 * count according to CPU use, instead of by the raw
3895 			 * number of faults. Tasks with little runtime have
3896 			 * little over-all impact on throughput, and thus their
3897 			 * faults are less important.
3898 			 */
3899 			f_weight = div64_u64(runtime << 16, period + 1);
3900 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
3901 				   (total_faults + 1);
3902 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
3903 			p->numa_faults[cpubuf_idx] = 0;
3904 
3905 			p->numa_faults[mem_idx] += diff;
3906 			p->numa_faults[cpu_idx] += f_diff;
3907 			faults += p->numa_faults[mem_idx];
3908 			p->total_numa_faults += diff;
3909 			if (ng) {
3910 				/*
3911 				 * safe because we can only change our own group
3912 				 *
3913 				 * mem_idx represents the offset for a given
3914 				 * nid and priv in a specific region because it
3915 				 * is at the beginning of the numa_faults array.
3916 				 */
3917 				ng->faults[mem_idx] += diff;
3918 				ng->faults[cpu_idx] += f_diff;
3919 				ng->total_faults += diff;
3920 				group_faults += ng->faults[mem_idx];
3921 			}
3922 #ifdef CONFIG_SCHED_CACHE
3923 			/*
3924 			 * Per task p->numa_faults[mem_idx] converges,
3925 			 * so the accumulation of each task's faults
3926 			 * converges too - Given the number of threads,
3927 			 * it cannot overflow an unsigned long.
3928 			 * Racy with concurrent updates from other threads
3929 			 * sharing this mm. Acceptable since footprint is a
3930 			 * heuristic and occasional lost updates are tolerable.
3931 			 *
3932 			 * If a task exits, its corresponding footprint must
3933 			 * be subtracted from p->sched_cache_grp->footprint,
3934 			 * otherwise the footprint will not converge: the
3935 			 * exiting thread's footprint remains unchanged/undecayed.
3936 			 * See exit_mm().
3937 			 *
3938 			 * Lost updates and unsynchronized subtraction
3939 			 * in exit_mm() can cause footprint + diff to
3940 			 * go negative. Clamp to zero to prevent the
3941 			 * unsigned footprint from wrapping.
3942 			 */
3943 			scoped_guard(rcu) {
3944 				grp = rcu_dereference(p->sched_cache_grp);
3945 
3946 				if (grp) {
3947 					new_fp = (long)READ_ONCE(grp->footprint) + diff;
3948 					WRITE_ONCE(grp->footprint, max(new_fp, 0L));
3949 				}
3950 			}
3951 #endif
3952 		}
3953 
3954 		if (!ng) {
3955 			if (faults > max_faults) {
3956 				max_faults = faults;
3957 				max_nid = nid;
3958 			}
3959 		} else if (group_faults > max_faults) {
3960 			max_faults = group_faults;
3961 			max_nid = nid;
3962 		}
3963 	}
3964 
3965 	/* Cannot migrate task to CPU-less node */
3966 	max_nid = numa_nearest_node(max_nid, N_CPU);
3967 
3968 	if (ng) {
3969 		numa_group_count_active_nodes(ng);
3970 		spin_unlock_irq(group_lock);
3971 		max_nid = preferred_group_nid(p, max_nid);
3972 	}
3973 
3974 	if (max_faults) {
3975 		/* Set the new preferred node */
3976 		if (max_nid != p->numa_preferred_nid)
3977 			sched_setnuma(p, max_nid);
3978 	}
3979 
3980 	update_task_scan_period(p, fault_types[0], fault_types[1]);
3981 }
3982 
3983 static inline int get_numa_group(struct numa_group *grp)
3984 {
3985 	return refcount_inc_not_zero(&grp->refcount);
3986 }
3987 
3988 static inline void put_numa_group(struct numa_group *grp)
3989 {
3990 	if (refcount_dec_and_test(&grp->refcount))
3991 		kfree_rcu(grp, rcu);
3992 }
3993 
3994 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3995 			int *priv)
3996 {
3997 	struct numa_group *grp, *my_grp;
3998 	struct task_struct *tsk;
3999 	bool join = false;
4000 	int cpu = cpupid_to_cpu(cpupid);
4001 	int i;
4002 
4003 	if (unlikely(!deref_curr_numa_group(p))) {
4004 		unsigned int size = sizeof(struct numa_group) +
4005 				    NR_NUMA_HINT_FAULT_STATS *
4006 				    nr_node_ids * sizeof(unsigned long);
4007 
4008 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
4009 		if (!grp)
4010 			return;
4011 
4012 		refcount_set(&grp->refcount, 1);
4013 		grp->active_nodes = 1;
4014 		grp->max_faults_cpu = 0;
4015 		spin_lock_init(&grp->lock);
4016 		grp->gid = p->pid;
4017 
4018 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4019 			grp->faults[i] = p->numa_faults[i];
4020 
4021 		grp->total_faults = p->total_numa_faults;
4022 
4023 		grp->nr_tasks++;
4024 		rcu_assign_pointer(p->numa_group, grp);
4025 	}
4026 
4027 	rcu_read_lock();
4028 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
4029 
4030 	if (!cpupid_match_pid(tsk, cpupid))
4031 		goto no_join;
4032 
4033 	grp = rcu_dereference_all(tsk->numa_group);
4034 	if (!grp)
4035 		goto no_join;
4036 
4037 	my_grp = deref_curr_numa_group(p);
4038 	if (grp == my_grp)
4039 		goto no_join;
4040 
4041 	/*
4042 	 * Only join the other group if its bigger; if we're the bigger group,
4043 	 * the other task will join us.
4044 	 */
4045 	if (my_grp->nr_tasks > grp->nr_tasks)
4046 		goto no_join;
4047 
4048 	/*
4049 	 * Tie-break on the grp address.
4050 	 */
4051 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
4052 		goto no_join;
4053 
4054 	/* Always join threads in the same process. */
4055 	if (tsk->mm == current->mm)
4056 		join = true;
4057 
4058 	/* Simple filter to avoid false positives due to PID collisions */
4059 	if (flags & TNF_SHARED)
4060 		join = true;
4061 
4062 	/* Update priv based on whether false sharing was detected */
4063 	*priv = !join;
4064 
4065 	if (join && !get_numa_group(grp))
4066 		goto no_join;
4067 
4068 	rcu_read_unlock();
4069 
4070 	if (!join)
4071 		return;
4072 
4073 	WARN_ON_ONCE(irqs_disabled());
4074 	double_lock_irq(&my_grp->lock, &grp->lock);
4075 
4076 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
4077 		my_grp->faults[i] -= p->numa_faults[i];
4078 		grp->faults[i] += p->numa_faults[i];
4079 	}
4080 	my_grp->total_faults -= p->total_numa_faults;
4081 	grp->total_faults += p->total_numa_faults;
4082 
4083 	my_grp->nr_tasks--;
4084 	grp->nr_tasks++;
4085 
4086 	spin_unlock(&my_grp->lock);
4087 	spin_unlock_irq(&grp->lock);
4088 
4089 	rcu_assign_pointer(p->numa_group, grp);
4090 
4091 	put_numa_group(my_grp);
4092 	return;
4093 
4094 no_join:
4095 	rcu_read_unlock();
4096 	return;
4097 }
4098 
4099 /*
4100  * Get rid of NUMA statistics associated with a task (either current or dead).
4101  * If @final is set, the task is dead and has reached refcount zero, so we can
4102  * safely free all relevant data structures. Otherwise, there might be
4103  * concurrent reads from places like load balancing and procfs, and we should
4104  * reset the data back to default state without freeing ->numa_faults.
4105  */
4106 void task_numa_free(struct task_struct *p, bool final)
4107 {
4108 	/* safe: p either is current or is being freed by current */
4109 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
4110 	unsigned long *numa_faults = p->numa_faults;
4111 	unsigned long flags;
4112 	int i;
4113 
4114 	if (!numa_faults)
4115 		return;
4116 
4117 	if (grp) {
4118 		spin_lock_irqsave(&grp->lock, flags);
4119 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4120 			grp->faults[i] -= p->numa_faults[i];
4121 		grp->total_faults -= p->total_numa_faults;
4122 
4123 		grp->nr_tasks--;
4124 		spin_unlock_irqrestore(&grp->lock, flags);
4125 		RCU_INIT_POINTER(p->numa_group, NULL);
4126 		put_numa_group(grp);
4127 	}
4128 
4129 	if (final) {
4130 		p->numa_faults = NULL;
4131 		kfree(numa_faults);
4132 	} else {
4133 		p->total_numa_faults = 0;
4134 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4135 			numa_faults[i] = 0;
4136 	}
4137 }
4138 
4139 /*
4140  * Got a PROT_NONE fault for a page on @node.
4141  */
4142 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
4143 {
4144 	struct task_struct *p = current;
4145 	bool migrated = flags & TNF_MIGRATED;
4146 	int cpu_node = task_node(current);
4147 	int local = !!(flags & TNF_FAULT_LOCAL);
4148 	struct numa_group *ng;
4149 	int priv;
4150 
4151 	if (!static_branch_likely(&sched_numa_balancing))
4152 		return;
4153 
4154 	/* for example, ksmd faulting in a user's mm */
4155 	if (!p->mm)
4156 		return;
4157 
4158 	/*
4159 	 * NUMA faults statistics are unnecessary for the slow memory
4160 	 * node for memory tiering mode.
4161 	 */
4162 	if (!node_is_toptier(mem_node) &&
4163 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
4164 	     !cpupid_valid(last_cpupid)))
4165 		return;
4166 
4167 	/* Allocate buffer to track faults on a per-node basis */
4168 	if (unlikely(!p->numa_faults)) {
4169 		int size = sizeof(*p->numa_faults) *
4170 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
4171 
4172 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
4173 		if (!p->numa_faults)
4174 			return;
4175 
4176 		p->total_numa_faults = 0;
4177 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
4178 	}
4179 
4180 	/*
4181 	 * First accesses are treated as private, otherwise consider accesses
4182 	 * to be private if the accessing pid has not changed
4183 	 */
4184 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
4185 		priv = 1;
4186 	} else {
4187 		priv = cpupid_match_pid(p, last_cpupid);
4188 		if (!priv && !(flags & TNF_NO_GROUP))
4189 			task_numa_group(p, last_cpupid, flags, &priv);
4190 	}
4191 
4192 	/*
4193 	 * If a workload spans multiple NUMA nodes, a shared fault that
4194 	 * occurs wholly within the set of nodes that the workload is
4195 	 * actively using should be counted as local. This allows the
4196 	 * scan rate to slow down when a workload has settled down.
4197 	 */
4198 	ng = deref_curr_numa_group(p);
4199 	if (!priv && !local && ng && ng->active_nodes > 1 &&
4200 				numa_is_active_node(cpu_node, ng) &&
4201 				numa_is_active_node(mem_node, ng))
4202 		local = 1;
4203 
4204 	/*
4205 	 * Retry to migrate task to preferred node periodically, in case it
4206 	 * previously failed, or the scheduler moved us.
4207 	 */
4208 	if (time_after(jiffies, p->numa_migrate_retry)) {
4209 		task_numa_placement(p);
4210 		numa_migrate_preferred(p);
4211 	}
4212 
4213 	if (migrated)
4214 		p->numa_pages_migrated += pages;
4215 	if (flags & TNF_MIGRATE_FAIL)
4216 		p->numa_faults_locality[2] += pages;
4217 
4218 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
4219 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
4220 	p->numa_faults_locality[local] += pages;
4221 }
4222 
4223 static void reset_ptenuma_scan(struct task_struct *p)
4224 {
4225 	/*
4226 	 * We only did a read acquisition of the mmap sem, so
4227 	 * p->mm->numa_scan_seq is written to without exclusive access
4228 	 * and the update is not guaranteed to be atomic. That's not
4229 	 * much of an issue though, since this is just used for
4230 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
4231 	 * expensive, to avoid any form of compiler optimizations:
4232 	 */
4233 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
4234 	p->mm->numa_scan_offset = 0;
4235 }
4236 
4237 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
4238 {
4239 	unsigned long pids;
4240 	/*
4241 	 * Allow unconditional access first two times, so that all the (pages)
4242 	 * of VMAs get prot_none fault introduced irrespective of accesses.
4243 	 * This is also done to avoid any side effect of task scanning
4244 	 * amplifying the unfairness of disjoint set of VMAs' access.
4245 	 */
4246 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
4247 		return true;
4248 
4249 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
4250 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
4251 		return true;
4252 
4253 	/*
4254 	 * Complete a scan that has already started regardless of PID access, or
4255 	 * some VMAs may never be scanned in multi-threaded applications:
4256 	 */
4257 	if (mm->numa_scan_offset > vma->vm_start) {
4258 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
4259 		return true;
4260 	}
4261 
4262 	/*
4263 	 * This vma has not been accessed for a while, and if the number
4264 	 * the threads in the same process is low, which means no other
4265 	 * threads can help scan this vma, force a vma scan.
4266 	 */
4267 	if (READ_ONCE(mm->numa_scan_seq) >
4268 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
4269 		return true;
4270 
4271 	return false;
4272 }
4273 
4274 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
4275 
4276 /*
4277  * The expensive part of numa migration is done from task_work context.
4278  * Triggered from task_tick_numa().
4279  */
4280 static void task_numa_work(struct callback_head *work)
4281 {
4282 	unsigned long migrate, next_scan, now = jiffies;
4283 	struct task_struct *p = current;
4284 	struct mm_struct *mm = p->mm;
4285 	u64 runtime = p->se.sum_exec_runtime;
4286 	struct vm_area_struct *vma;
4287 	unsigned long start, end;
4288 	unsigned long nr_pte_updates = 0;
4289 	long pages, virtpages;
4290 	struct vma_iterator vmi;
4291 	bool vma_pids_skipped;
4292 	bool vma_pids_forced = false;
4293 
4294 	WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
4295 
4296 	work->next = work;
4297 	/*
4298 	 * Who cares about NUMA placement when they're dying.
4299 	 *
4300 	 * NOTE: make sure not to dereference p->mm before this check,
4301 	 * exit_task_work() happens _after_ exit_mm() so we could be called
4302 	 * without p->mm even though we still had it when we enqueued this
4303 	 * work.
4304 	 */
4305 	if (p->flags & PF_EXITING)
4306 		return;
4307 
4308 	/*
4309 	 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
4310 	 * no page can be migrated.
4311 	 */
4312 	if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
4313 		trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
4314 		return;
4315 	}
4316 
4317 	if (!mm->numa_next_scan) {
4318 		mm->numa_next_scan = now +
4319 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4320 	}
4321 
4322 	/*
4323 	 * Enforce maximal scan/migration frequency..
4324 	 */
4325 	migrate = mm->numa_next_scan;
4326 	if (time_before(now, migrate))
4327 		return;
4328 
4329 	if (p->numa_scan_period == 0) {
4330 		p->numa_scan_period_max = task_scan_max(p);
4331 		p->numa_scan_period = task_scan_start(p);
4332 	}
4333 
4334 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
4335 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
4336 		return;
4337 
4338 	/*
4339 	 * Delay this task enough that another task of this mm will likely win
4340 	 * the next time around.
4341 	 */
4342 	p->node_stamp += 2 * TICK_NSEC;
4343 
4344 	pages = sysctl_numa_balancing_scan_size;
4345 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
4346 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
4347 	if (!pages)
4348 		return;
4349 
4350 
4351 	if (!mmap_read_trylock(mm))
4352 		return;
4353 
4354 	/*
4355 	 * VMAs are skipped if the current PID has not trapped a fault within
4356 	 * the VMA recently. Allow scanning to be forced if there is no
4357 	 * suitable VMA remaining.
4358 	 */
4359 	vma_pids_skipped = false;
4360 
4361 retry_pids:
4362 	start = mm->numa_scan_offset;
4363 	vma_iter_init(&vmi, mm, start);
4364 	vma = vma_next(&vmi);
4365 	if (!vma) {
4366 		reset_ptenuma_scan(p);
4367 		start = 0;
4368 		vma_iter_set(&vmi, start);
4369 		vma = vma_next(&vmi);
4370 	}
4371 
4372 	for (; vma; vma = vma_next(&vmi)) {
4373 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
4374 			vma_is_hugetlb(vma) || !vma_is_mm_managed(vma)) {
4375 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
4376 			continue;
4377 		}
4378 
4379 		/*
4380 		 * Shared library pages mapped by multiple processes are not
4381 		 * migrated as it is expected they are cache replicated. Avoid
4382 		 * hinting faults in read-only file-backed mappings or the vDSO
4383 		 * as migrating the pages will be of marginal benefit.
4384 		 */
4385 		if (!vma->vm_mm ||
4386 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
4387 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
4388 			continue;
4389 		}
4390 
4391 		/*
4392 		 * Skip inaccessible VMAs to avoid any confusion between
4393 		 * PROT_NONE and NUMA hinting PTEs
4394 		 */
4395 		if (!vma_is_accessible(vma)) {
4396 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
4397 			continue;
4398 		}
4399 
4400 		/* Initialise new per-VMA NUMAB state. */
4401 		if (!vma->numab_state) {
4402 			struct vma_numab_state *ptr;
4403 
4404 			ptr = kzalloc_obj(*ptr);
4405 			if (!ptr)
4406 				continue;
4407 
4408 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
4409 				kfree(ptr);
4410 				continue;
4411 			}
4412 
4413 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
4414 
4415 			vma->numab_state->next_scan = now +
4416 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4417 
4418 			/* Reset happens after 4 times scan delay of scan start */
4419 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
4420 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4421 
4422 			/*
4423 			 * Ensure prev_scan_seq does not match numa_scan_seq,
4424 			 * to prevent VMAs being skipped prematurely on the
4425 			 * first scan:
4426 			 */
4427 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
4428 		}
4429 
4430 		/*
4431 		 * Scanning the VMAs of short lived tasks add more overhead. So
4432 		 * delay the scan for new VMAs.
4433 		 */
4434 		if (mm->numa_scan_seq && time_before(jiffies,
4435 						vma->numab_state->next_scan)) {
4436 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
4437 			continue;
4438 		}
4439 
4440 		/* RESET access PIDs regularly for old VMAs. */
4441 		if (mm->numa_scan_seq &&
4442 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
4443 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
4444 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4445 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
4446 			vma->numab_state->pids_active[1] = 0;
4447 		}
4448 
4449 		/* Do not rescan VMAs twice within the same sequence. */
4450 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
4451 			mm->numa_scan_offset = vma->vm_end;
4452 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
4453 			continue;
4454 		}
4455 
4456 		/*
4457 		 * Do not scan the VMA if task has not accessed it, unless no other
4458 		 * VMA candidate exists.
4459 		 */
4460 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
4461 			vma_pids_skipped = true;
4462 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
4463 			continue;
4464 		}
4465 
4466 		do {
4467 			start = max(start, vma->vm_start);
4468 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
4469 			end = min(end, vma->vm_end);
4470 			nr_pte_updates = change_prot_numa(vma, start, end);
4471 
4472 			/*
4473 			 * Try to scan sysctl_numa_balancing_size worth of
4474 			 * hpages that have at least one present PTE that
4475 			 * is not already PTE-numa. If the VMA contains
4476 			 * areas that are unused or already full of prot_numa
4477 			 * PTEs, scan up to virtpages, to skip through those
4478 			 * areas faster.
4479 			 */
4480 			if (nr_pte_updates)
4481 				pages -= (end - start) >> PAGE_SHIFT;
4482 			virtpages -= (end - start) >> PAGE_SHIFT;
4483 
4484 			start = end;
4485 			if (pages <= 0 || virtpages <= 0)
4486 				goto out;
4487 
4488 			cond_resched();
4489 		} while (end != vma->vm_end);
4490 
4491 		/* VMA scan is complete, do not scan until next sequence. */
4492 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
4493 
4494 		/*
4495 		 * Only force scan within one VMA at a time, to limit the
4496 		 * cost of scanning a potentially uninteresting VMA.
4497 		 */
4498 		if (vma_pids_forced)
4499 			break;
4500 	}
4501 
4502 	/*
4503 	 * If no VMAs are remaining and VMAs were skipped due to the PID
4504 	 * not accessing the VMA previously, then force a scan to ensure
4505 	 * forward progress:
4506 	 */
4507 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
4508 		vma_pids_forced = true;
4509 		goto retry_pids;
4510 	}
4511 
4512 out:
4513 	/*
4514 	 * It is possible to reach the end of the VMA list but the last few
4515 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
4516 	 * would find the !migratable VMA on the next scan but not reset the
4517 	 * scanner to the start so check it now.
4518 	 */
4519 	if (vma)
4520 		mm->numa_scan_offset = start;
4521 	else
4522 		reset_ptenuma_scan(p);
4523 	mmap_read_unlock(mm);
4524 
4525 	/*
4526 	 * Make sure tasks use at least 32x as much time to run other code
4527 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
4528 	 * Usually update_task_scan_period slows down scanning enough; on an
4529 	 * overloaded system we need to limit overhead on a per task basis.
4530 	 */
4531 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
4532 		u64 diff = p->se.sum_exec_runtime - runtime;
4533 		p->node_stamp += 32 * diff;
4534 	}
4535 }
4536 
4537 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
4538 {
4539 	int mm_users = 0;
4540 	struct mm_struct *mm = p->mm;
4541 
4542 	if (mm) {
4543 		mm_users = atomic_read(&mm->mm_users);
4544 		if (mm_users == 1) {
4545 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4546 			mm->numa_scan_seq = 0;
4547 		}
4548 	}
4549 	p->node_stamp			= 0;
4550 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
4551 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
4552 	p->numa_migrate_retry		= 0;
4553 	/* Protect against double add, see task_tick_numa and task_numa_work */
4554 	p->numa_work.next		= &p->numa_work;
4555 	p->numa_faults			= NULL;
4556 	p->numa_pages_migrated		= 0;
4557 	p->total_numa_faults		= 0;
4558 	RCU_INIT_POINTER(p->numa_group, NULL);
4559 	p->last_task_numa_placement	= 0;
4560 	p->last_sum_exec_runtime	= 0;
4561 
4562 	init_task_work(&p->numa_work, task_numa_work);
4563 
4564 	/* New address space, reset the preferred nid */
4565 	if (!(clone_flags & CLONE_VM)) {
4566 		p->numa_preferred_nid = NUMA_NO_NODE;
4567 		return;
4568 	}
4569 
4570 	/*
4571 	 * New thread, keep existing numa_preferred_nid which should be copied
4572 	 * already by arch_dup_task_struct but stagger when scans start.
4573 	 */
4574 	if (mm) {
4575 		unsigned int delay;
4576 
4577 		delay = min_t(unsigned int, task_scan_max(current),
4578 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
4579 		delay += 2 * TICK_NSEC;
4580 		p->node_stamp = delay;
4581 	}
4582 }
4583 
4584 /*
4585  * Drive the periodic memory faults..
4586  */
4587 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4588 {
4589 	struct callback_head *work = &curr->numa_work;
4590 	u64 period, now;
4591 
4592 	/*
4593 	 * We don't care about NUMA placement if we don't have memory.
4594 	 */
4595 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
4596 		return;
4597 
4598 	/*
4599 	 * Using runtime rather than walltime has the dual advantage that
4600 	 * we (mostly) drive the selection from busy threads and that the
4601 	 * task needs to have done some actual work before we bother with
4602 	 * NUMA placement.
4603 	 */
4604 	now = curr->se.sum_exec_runtime;
4605 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
4606 
4607 	if (now > curr->node_stamp + period) {
4608 		if (!curr->node_stamp)
4609 			curr->numa_scan_period = task_scan_start(curr);
4610 		curr->node_stamp += period;
4611 
4612 		if (!time_before(jiffies, curr->mm->numa_next_scan))
4613 			task_work_add(curr, work, TWA_RESUME);
4614 	}
4615 }
4616 
4617 static void update_scan_period(struct task_struct *p, int new_cpu)
4618 {
4619 	int src_nid = cpu_to_node(task_cpu(p));
4620 	int dst_nid = cpu_to_node(new_cpu);
4621 
4622 	if (!static_branch_likely(&sched_numa_balancing))
4623 		return;
4624 
4625 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
4626 		return;
4627 
4628 	if (src_nid == dst_nid)
4629 		return;
4630 
4631 	/*
4632 	 * Allow resets if faults have been trapped before one scan
4633 	 * has completed. This is most likely due to a new task that
4634 	 * is pulled cross-node due to wakeups or load balancing.
4635 	 */
4636 	if (p->numa_scan_seq) {
4637 		/*
4638 		 * Avoid scan adjustments if moving to the preferred
4639 		 * node or if the task was not previously running on
4640 		 * the preferred node.
4641 		 */
4642 		if (dst_nid == p->numa_preferred_nid ||
4643 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
4644 			src_nid != p->numa_preferred_nid))
4645 			return;
4646 	}
4647 
4648 	p->numa_scan_period = task_scan_start(p);
4649 }
4650 
4651 #else /* !CONFIG_NUMA_BALANCING: */
4652 
4653 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4654 {
4655 }
4656 
4657 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
4658 {
4659 }
4660 
4661 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
4662 {
4663 }
4664 
4665 static inline void update_scan_period(struct task_struct *p, int new_cpu)
4666 {
4667 }
4668 
4669 #endif /* !CONFIG_NUMA_BALANCING */
4670 
4671 static void
4672 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4673 {
4674 	WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4675 	update_load_add(&cfs_rq->load, se->load.weight);
4676 	if (entity_is_task(se)) {
4677 		struct task_struct *p = task_of(se);
4678 		struct rq *rq = rq_of(cfs_rq);
4679 
4680 		account_numa_enqueue(rq, p);
4681 		account_llc_enqueue(rq, p);
4682 		list_add(&se->group_node, &rq->cfs_tasks);
4683 	}
4684 	cfs_rq->nr_queued++;
4685 }
4686 
4687 static void
4688 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4689 {
4690 	WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4691 	update_load_sub(&cfs_rq->load, se->load.weight);
4692 	if (entity_is_task(se)) {
4693 		struct task_struct *p = task_of(se);
4694 		struct rq *rq = rq_of(cfs_rq);
4695 
4696 		account_numa_dequeue(rq, p);
4697 		account_llc_dequeue(rq, p);
4698 		list_del_init(&se->group_node);
4699 	}
4700 	cfs_rq->nr_queued--;
4701 }
4702 
4703 /*
4704  * Signed add and clamp on underflow.
4705  *
4706  * Explicitly do a load-store to ensure the intermediate value never hits
4707  * memory. This allows lockless observations without ever seeing the negative
4708  * values.
4709  */
4710 #define add_positive(_ptr, _val) do {                           \
4711 	typeof(_ptr) ptr = (_ptr);                              \
4712 	__signed_scalar_typeof(*ptr) val = (_val);              \
4713 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
4714 								\
4715 	res = var + val;                                        \
4716 								\
4717 	if (val < 0 && res > var)                               \
4718 		res = 0;                                        \
4719 								\
4720 	WRITE_ONCE(*ptr, res);                                  \
4721 } while (0)
4722 
4723 /*
4724  * Remove and clamp on negative, from a local variable.
4725  *
4726  * A variant of sub_positive(), which does not use explicit load-store
4727  * and is thus optimized for local variable updates.
4728  */
4729 #define lsub_positive(_ptr, _val) do {				\
4730 	typeof(_ptr) ptr = (_ptr);				\
4731 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
4732 } while (0)
4733 
4734 
4735 /*
4736  * Because of rounding, se->util_sum might ends up being +1 more than
4737  * cfs->util_sum. Although this is not a problem by itself, detaching
4738  * a lot of tasks with the rounding problem between 2 updates of
4739  * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4740  * cfs_util_avg is not.
4741  *
4742  * Check that util_sum is still above its lower bound for the new
4743  * util_avg. Given that period_contrib might have moved since the last
4744  * sync, we are only sure that util_sum must be above or equal to
4745  *    util_avg * minimum possible divider
4746  */
4747 #define __update_sa(sa, name, delta_avg, delta_sum) do {	\
4748 	add_positive(&(sa)->name##_avg, delta_avg);		\
4749 	add_positive(&(sa)->name##_sum, delta_sum);		\
4750 	(sa)->name##_sum = max_t(typeof((sa)->name##_sum),	\
4751 			       (sa)->name##_sum,		\
4752 			       (sa)->name##_avg * PELT_MIN_DIVIDER); \
4753 } while (0)
4754 
4755 static inline void
4756 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4757 {
4758 	__update_sa(&cfs_rq->avg, load, se->avg.load_avg,
4759 		    se_weight(se) * se->avg.load_sum);
4760 }
4761 
4762 static inline void
4763 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4764 {
4765 	__update_sa(&cfs_rq->avg, load, -se->avg.load_avg,
4766 		    se_weight(se) * -se->avg.load_sum);
4767 }
4768 
4769 static void
4770 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot)
4771 {
4772 	long old_weight = se->h_load.weight;
4773 
4774 	/*
4775 	 * VRUNTIME
4776 	 * --------
4777 	 *
4778 	 * COROLLARY #1: The virtual runtime of the entity needs to be
4779 	 * adjusted if re-weight at !0-lag point.
4780 	 *
4781 	 * Proof: For contradiction assume this is not true, so we can
4782 	 * re-weight without changing vruntime at !0-lag point.
4783 	 *
4784 	 *             Weight	VRuntime   Avg-VRuntime
4785 	 *     before    w          v            V
4786 	 *      after    w'         v'           V'
4787 	 *
4788 	 * Since lag needs to be preserved through re-weight:
4789 	 *
4790 	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
4791 	 *	==>	V' = (V - v)*w/w' + v		(1)
4792 	 *
4793 	 * Let W be the total weight of the entities before reweight,
4794 	 * since V' is the new weighted average of entities:
4795 	 *
4796 	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
4797 	 *
4798 	 * by using (1) & (2) we obtain:
4799 	 *
4800 	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
4801 	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
4802 	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
4803 	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
4804 	 *
4805 	 * Since we are doing at !0-lag point which means V != v, we
4806 	 * can simplify (3):
4807 	 *
4808 	 *	==>	W / (W + w' - w) = w / w'
4809 	 *	==>	Ww' = Ww + ww' - ww
4810 	 *	==>	W * (w' - w) = w * (w' - w)
4811 	 *	==>	W = w	(re-weight indicates w' != w)
4812 	 *
4813 	 * So the cfs_rq contains only one entity, hence vruntime of
4814 	 * the entity @v should always equal to the cfs_rq's weighted
4815 	 * average vruntime @V, which means we will always re-weight
4816 	 * at 0-lag point, thus breach assumption. Proof completed.
4817 	 *
4818 	 *
4819 	 * COROLLARY #2: Re-weight does NOT affect weighted average
4820 	 * vruntime of all the entities.
4821 	 *
4822 	 * Proof: According to corollary #1, Eq. (1) should be:
4823 	 *
4824 	 *	(V - v)*w = (V' - v')*w'
4825 	 *	==>    v' = V' - (V - v)*w/w'		(4)
4826 	 *
4827 	 * According to the weighted average formula, we have:
4828 	 *
4829 	 *	V' = (WV - wv + w'v') / (W - w + w')
4830 	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
4831 	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
4832 	 *	   = (WV + w'V' - Vw) / (W - w + w')
4833 	 *
4834 	 *	==>  V'*(W - w + w') = WV + w'V' - Vw
4835 	 *	==>	V' * (W - w) = (W - w) * V	(5)
4836 	 *
4837 	 * If the entity is the only one in the cfs_rq, then reweight
4838 	 * always occurs at 0-lag point, so V won't change. Or else
4839 	 * there are other entities, hence W != w, then Eq. (5) turns
4840 	 * into V' = V. So V won't change in either case, proof done.
4841 	 *
4842 	 *
4843 	 * So according to corollary #1 & #2, the effect of re-weight
4844 	 * on vruntime should be:
4845 	 *
4846 	 *	v' = V' - (V - v) * w / w'		(4)
4847 	 *	   = V  - (V - v) * w / w'
4848 	 *	   = V  - vl * w / w'
4849 	 *	   = V  - vl'
4850 	 */
4851 	se->vlag = div64_long(se->vlag * old_weight, weight);
4852 
4853 	/*
4854 	 * DEADLINE
4855 	 * --------
4856 	 *
4857 	 * When the weight changes, the virtual time slope changes and
4858 	 * we should adjust the relative virtual deadline accordingly.
4859 	 *
4860 	 *	d' = v' + (d - v)*w/w'
4861 	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
4862 	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
4863 	 *	   = V  + (d - V)*w/w'
4864 	 */
4865 	if (se->rel_deadline)
4866 		se->deadline = div64_long(se->deadline * old_weight, weight);
4867 
4868 	if (rel_vprot)
4869 		se->vprot = div64_long(se->vprot * old_weight, weight);
4870 }
4871 
4872 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se,
4873 			   unsigned long weight, bool on_rq)
4874 {
4875 	bool curr = cfs_rq->curr == se;
4876 	bool rel_vprot = false;
4877 	u64 avruntime = 0;
4878 
4879 	if (se->h_load.weight == weight)
4880 		return;
4881 
4882 	if (on_rq) {
4883 		avruntime = avg_vruntime(cfs_rq);
4884 		se->vlag = entity_lag(cfs_rq, se, avruntime);
4885 		se->deadline -= avruntime;
4886 		se->rel_deadline = 1;
4887 		if (curr && protect_slice(se)) {
4888 			se->vprot -= avruntime;
4889 			rel_vprot = true;
4890 		}
4891 
4892 		cfs_rq->h_nr_queued--;
4893 		if (!curr)
4894 			__dequeue_entity(cfs_rq, se);
4895 	}
4896 
4897 	rescale_entity(se, weight, rel_vprot);
4898 
4899 	update_load_set(&se->h_load, weight);
4900 
4901 	if (on_rq) {
4902 		if (rel_vprot)
4903 			se->vprot += avruntime;
4904 		se->deadline += avruntime;
4905 		se->rel_deadline = 0;
4906 		se->vruntime = avruntime - se->vlag;
4907 
4908 		if (!curr)
4909 			__enqueue_entity(cfs_rq, se);
4910 		cfs_rq->h_nr_queued++;
4911 	}
4912 }
4913 
4914 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
4915 			    unsigned long weight)
4916 {
4917 	if (se->load.weight == weight)
4918 		return;
4919 
4920 	if (se->on_rq) {
4921 		WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4922 		update_load_sub(&cfs_rq->load, se->load.weight);
4923 	}
4924 	dequeue_load_avg(cfs_rq, se);
4925 
4926 	update_load_set(&se->load, weight);
4927 
4928 	do {
4929 		u32 divider = get_pelt_divider(&se->avg);
4930 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
4931 	} while (0);
4932 
4933 	enqueue_load_avg(cfs_rq, se);
4934 
4935 	if (se->on_rq)
4936 		update_load_add(&cfs_rq->load, se->load.weight);
4937 }
4938 
4939 /*
4940  * weight = NICE_0_LOAD;
4941  * for_each_entity_se(se)
4942  *   weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4943  */
4944 static __always_inline
4945 unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se,
4946 				 unsigned long weight)
4947 {
4948 	weight *= se->load.weight;
4949 	if (parent_entity(se))
4950 		weight /= cfs_rq->load.weight;
4951 	else
4952 		weight /= NICE_0_LOAD;
4953 
4954 	return max(weight, MIN_SHARES);
4955 }
4956 
4957 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
4958 			       const struct load_weight *lw)
4959 {
4960 	struct sched_entity *se = &p->se;
4961 	unsigned long weight = NICE_0_LOAD;
4962 
4963 	if (se->on_rq)
4964 		update_curr_fair(rq);
4965 
4966 	reweight_entity(cfs_rq_of(se), se, lw->weight);
4967 	se->load.inv_weight = lw->inv_weight;
4968 
4969 	if (!se->on_rq)
4970 		return;
4971 
4972 	for_each_sched_entity(se)
4973 		weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4974 
4975 	reweight_eevdf(&rq->cfs, &p->se, weight, p->se.on_rq);
4976 }
4977 
4978 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
4979 
4980 #ifdef CONFIG_FAIR_GROUP_SCHED
4981 /*
4982  * All this does is approximate the hierarchical proportion which includes that
4983  * global sum we all love to hate.
4984  *
4985  * That is, the weight of a group entity, is the proportional share of the
4986  * group weight based on the group runqueue weights. That is:
4987  *
4988  *                     tg->weight * grq->load.weight
4989  *   ge->load.weight = -----------------------------               (1)
4990  *                       \Sum grq->load.weight
4991  *
4992  * Now, because computing that sum is prohibitively expensive to compute (been
4993  * there, done that) we approximate it with this average stuff. The average
4994  * moves slower and therefore the approximation is cheaper and more stable.
4995  *
4996  * So instead of the above, we substitute:
4997  *
4998  *   grq->load.weight -> grq->avg.load_avg                         (2)
4999  *
5000  * which yields the following:
5001  *
5002  *                     tg->weight * grq->avg.load_avg
5003  *   ge->load.weight = ------------------------------              (3)
5004  *                             tg->load_avg
5005  *
5006  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
5007  *
5008  * That is shares_avg, and it is right (given the approximation (2)).
5009  *
5010  * The problem with it is that because the average is slow -- it was designed
5011  * to be exactly that of course -- this leads to transients in boundary
5012  * conditions. In specific, the case where the group was idle and we start the
5013  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
5014  * yielding bad latency etc..
5015  *
5016  * Now, in that special case (1) reduces to:
5017  *
5018  *                     tg->weight * grq->load.weight
5019  *   ge->load.weight = ----------------------------- = tg->weight   (4)
5020  *                         grp->load.weight
5021  *
5022  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
5023  *
5024  * So what we do is modify our approximation (3) to approach (4) in the (near)
5025  * UP case, like:
5026  *
5027  *   ge->load.weight =
5028  *
5029  *              tg->weight * grq->load.weight
5030  *     ---------------------------------------------------         (5)
5031  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
5032  *
5033  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
5034  * we need to use grq->avg.load_avg as its lower bound, which then gives:
5035  *
5036  *
5037  *                     tg->weight * grq->load.weight
5038  *   ge->load.weight = -----------------------------		   (6)
5039  *                             tg_load_avg'
5040  *
5041  * Where:
5042  *
5043  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
5044  *                  max(grq->load.weight, grq->avg.load_avg)
5045  *
5046  * And that is shares_weight and is icky. In the (near) UP case it approaches
5047  * (4) while in the normal case it approaches (3). It consistently
5048  * overestimates the ge->load.weight and therefore:
5049  *
5050  *   \Sum ge->load.weight >= tg->weight
5051  *
5052  * hence icky!
5053  */
5054 static long __calc_smp_shares(struct cfs_rq *cfs_rq, long tg_shares, long shares_max)
5055 {
5056 	struct task_group *tg = cfs_rq->tg;
5057 	long tg_weight, load, shares;
5058 
5059 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
5060 
5061 	tg_weight = atomic_long_read(&tg->load_avg);
5062 
5063 	/* Ensure tg_weight >= load */
5064 	tg_weight -= cfs_rq->tg_load_avg_contrib;
5065 	tg_weight += load;
5066 
5067 	shares = (tg_shares * load);
5068 	if (tg_weight)
5069 		shares /= tg_weight;
5070 
5071 	/*
5072 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
5073 	 * of a group with small tg->shares value. It is a floor value which is
5074 	 * assigned as a minimum load.weight to the sched_entity representing
5075 	 * the group on a CPU.
5076 	 *
5077 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
5078 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
5079 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
5080 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
5081 	 * instead of 0.
5082 	 */
5083 	return clamp_t(long, shares, MIN_SHARES, shares_max);
5084 }
5085 
5086 static int tg_cpus(struct task_group *tg)
5087 {
5088 	int nr = num_online_cpus();
5089 
5090 	if (cpusets_enabled()) {
5091 		struct cgroup *cgrp = tg->css.cgroup;
5092 		if (cgrp)
5093 			nr = cpuset_num_cpus(cgrp);
5094 	}
5095 
5096 	/*
5097 	 * An empty cpuset would propagate a 0 shares_max into
5098 	 * __calc_smp_shares(), where clamp() yields hi when hi < lo and so
5099 	 * defeats the MIN_SHARES floor. Match tg_tasks(), which floors at 1.
5100 	 */
5101 	return max(nr, 1);
5102 }
5103 
5104 static inline int tg_tasks(struct task_group *tg)
5105 {
5106 	return max(1, atomic_long_read(&tg->runnable_avg) >> SCHED_CAPACITY_SHIFT);
5107 }
5108 
5109 /*
5110  * Func: fraction(nr_tasks * tg->shares)
5111  *
5112  * Scale tg->shares by the number of tasks.
5113  */
5114 static long calc_tasks_shares(struct cfs_rq *cfs_rq)
5115 {
5116 	struct task_group *tg = cfs_rq->tg;
5117 	int nr = tg_tasks(tg);
5118 	long tg_shares = READ_ONCE(tg->shares);
5119 	return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
5120 }
5121 
5122 /*
5123  * Func: min(fraction(nr_cpus * tg->shares), nice -20)
5124  *
5125  * Scale tg->shares by the maximal number of CPUs; but clip the max shares at
5126  * nice -20, otherwise a single spinner on a 512 CPU machine would result in
5127  * 512*NICE_0_LOAD, which is also crazy.
5128  */
5129 static long calc_max_shares(struct cfs_rq *cfs_rq)
5130 {
5131 	struct task_group *tg = cfs_rq->tg;
5132 	int nr = tg_cpus(tg);
5133 	long tg_shares = READ_ONCE(tg->shares);
5134 	long max_shares = scale_load(sched_prio_to_weight[0]);
5135 	return __calc_smp_shares(cfs_rq, tg_shares * nr, max_shares);
5136 }
5137 
5138 /*
5139  * Func: fraction(nr * tg->shares); nr = min(nr_tasks, nr_cpus)
5140  *
5141  * Scales between "smp" and "max" in a natural way. No longer needs clipping
5142  * since there are no unnatural inflations like with "max".
5143  */
5144 static long calc_concur_shares(struct cfs_rq *cfs_rq)
5145 {
5146 	struct task_group *tg = cfs_rq->tg;
5147 	int nr = min(tg_tasks(tg), tg_cpus(tg));
5148 	long tg_shares = READ_ONCE(tg->shares);
5149 	return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
5150 }
5151 
5152 /*
5153  * Func: fraction(tg->shares)
5154  *
5155  * This infamously results in tiny shares when you have many CPUs.
5156  */
5157 static long calc_smp_shares(struct cfs_rq *cfs_rq)
5158 {
5159 	struct task_group *tg = cfs_rq->tg;
5160 	long tg_shares = READ_ONCE(tg->shares);
5161 	return __calc_smp_shares(cfs_rq, tg_shares, tg_shares);
5162 }
5163 
5164 /*
5165  * Ignore this pesky SMP stuff, use (4).
5166  */
5167 static long calc_up_shares(struct cfs_rq *cfs_rq)
5168 {
5169 	struct task_group *tg = cfs_rq->tg;
5170 	return READ_ONCE(tg->shares);
5171 }
5172 
5173 DEFINE_STATIC_CALL(calc_group_shares, calc_concur_shares);
5174 
5175 void __sched_cgroup_mode_update(int mode)
5176 {
5177 	long (*func)(struct cfs_rq *);
5178 	switch (mode) {
5179 	case 0:
5180 		func = &calc_up_shares;
5181 		break;
5182 	case 1:
5183 		func = &calc_smp_shares;
5184 		break;
5185 	case 2:
5186 	default:
5187 		func = &calc_concur_shares;
5188 		break;
5189 	case 3:
5190 		func = &calc_max_shares;
5191 		break;
5192 	case 4:
5193 		func = &calc_tasks_shares;
5194 		break;
5195 	}
5196 	static_call_update(calc_group_shares, func);
5197 }
5198 
5199 /*
5200  * Recomputes the group entity based on the current state of its group
5201  * runqueue.
5202  */
5203 static void update_cfs_group(struct sched_entity *se)
5204 {
5205 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5206 	long shares;
5207 
5208 	/*
5209 	 * When a group becomes empty, preserve its weight. This matters for
5210 	 * DELAY_DEQUEUE.
5211 	 */
5212 	if (!gcfs_rq || !gcfs_rq->load.weight)
5213 		return;
5214 
5215 	shares = static_call(calc_group_shares)(gcfs_rq);
5216 	reweight_entity(cfs_rq_of(se), se, shares);
5217 }
5218 
5219 #else /* !CONFIG_FAIR_GROUP_SCHED: */
5220 static inline void update_cfs_group(struct sched_entity *se)
5221 {
5222 }
5223 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5224 
5225 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
5226 {
5227 	struct rq *rq = rq_of(cfs_rq);
5228 
5229 	if (&rq->cfs == cfs_rq) {
5230 		/*
5231 		 * There are a few boundary cases this might miss but it should
5232 		 * get called often enough that that should (hopefully) not be
5233 		 * a real problem.
5234 		 *
5235 		 * It will not get called when we go idle, because the idle
5236 		 * thread is a different class (!fair), nor will the utilization
5237 		 * number include things like RT tasks.
5238 		 *
5239 		 * As is, the util number is not freq-invariant (we'd have to
5240 		 * implement arch_scale_freq_capacity() for that).
5241 		 *
5242 		 * See cpu_util_cfs().
5243 		 */
5244 		cpufreq_update_util(rq, flags);
5245 	}
5246 }
5247 
5248 static inline bool load_avg_is_decayed(struct sched_avg *sa)
5249 {
5250 	if (sa->load_sum)
5251 		return false;
5252 
5253 	if (sa->util_sum)
5254 		return false;
5255 
5256 	if (sa->runnable_sum)
5257 		return false;
5258 
5259 	/*
5260 	 * _avg must be null when _sum are null because _avg = _sum / divider
5261 	 * Make sure that rounding and/or propagation of PELT values never
5262 	 * break this.
5263 	 */
5264 	WARN_ON_ONCE(sa->load_avg ||
5265 		      sa->util_avg ||
5266 		      sa->runnable_avg);
5267 
5268 	return true;
5269 }
5270 
5271 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
5272 {
5273 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
5274 				 cfs_rq->last_update_time_copy);
5275 }
5276 #ifdef CONFIG_FAIR_GROUP_SCHED
5277 /*
5278  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
5279  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
5280  * bottom-up, we only have to test whether the cfs_rq before us on the list
5281  * is our child.
5282  * If cfs_rq is not on the list, test whether a child needs its to be added to
5283  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
5284  */
5285 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
5286 {
5287 	struct cfs_rq *prev_cfs_rq;
5288 	struct list_head *prev;
5289 	struct rq *rq = rq_of(cfs_rq);
5290 
5291 	if (cfs_rq->on_list) {
5292 		prev = cfs_rq->leaf_cfs_rq_list.prev;
5293 	} else {
5294 		prev = rq->tmp_alone_branch;
5295 	}
5296 
5297 	if (prev == &rq->leaf_cfs_rq_list)
5298 		return false;
5299 
5300 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
5301 
5302 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
5303 }
5304 
5305 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5306 {
5307 	if (cfs_rq->load.weight)
5308 		return false;
5309 
5310 	if (!load_avg_is_decayed(&cfs_rq->avg))
5311 		return false;
5312 
5313 	if (child_cfs_rq_on_list(cfs_rq))
5314 		return false;
5315 
5316 	if (cfs_rq->tg_load_avg_contrib)
5317 		return false;
5318 
5319 	return true;
5320 }
5321 
5322 /**
5323  * update_tg_load_avg - update the tg's load avg
5324  * @cfs_rq: the cfs_rq whose avg changed
5325  *
5326  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
5327  * However, because tg->load_avg is a global value there are performance
5328  * considerations.
5329  *
5330  * In order to avoid having to look at the other cfs_rq's, we use a
5331  * differential update where we store the last value we propagated. This in
5332  * turn allows skipping updates if the differential is 'small'.
5333  *
5334  * Updating tg's load_avg is necessary before update_cfs_group().
5335  */
5336 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
5337 {
5338 	long dl, dr;
5339 	u64 now;
5340 
5341 	/*
5342 	 * No need to update load_avg for root_task_group as it is not used.
5343 	 */
5344 	if (cfs_rq->tg == &root_task_group)
5345 		return;
5346 
5347 	/* rq has been offline and doesn't contribute to the share anymore: */
5348 	if (!cpu_active(cpu_of(rq_of(cfs_rq))))
5349 		return;
5350 
5351 	/*
5352 	 * For migration heavy workloads, access to tg->load_avg can be
5353 	 * unbound. Limit the update rate to at most once per ms.
5354 	 */
5355 	now = rq_clock(rq_of(cfs_rq));
5356 	if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
5357 		return;
5358 
5359 	dl = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
5360 	dr = cfs_rq->avg.runnable_avg - cfs_rq->tg_runnable_avg_contrib;
5361 	if (abs(dl) > cfs_rq->tg_load_avg_contrib / 64 ||
5362 	    abs(dr) > cfs_rq->tg_runnable_avg_contrib / 64) {
5363 		atomic_long_add(dl, &cfs_rq->tg->load_avg);
5364 		atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5365 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
5366 		cfs_rq->tg_runnable_avg_contrib = cfs_rq->avg.runnable_avg;
5367 		cfs_rq->last_update_tg_load_avg = now;
5368 	}
5369 }
5370 
5371 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
5372 {
5373 	long dl, dr;
5374 	u64 now;
5375 
5376 	/*
5377 	 * No need to update load_avg for root_task_group, as it is not used.
5378 	 */
5379 	if (cfs_rq->tg == &root_task_group)
5380 		return;
5381 
5382 	now = rq_clock(rq_of(cfs_rq));
5383 	dl = 0 - cfs_rq->tg_load_avg_contrib;
5384 	dr = 0 - cfs_rq->tg_runnable_avg_contrib;
5385 	atomic_long_add(dl, &cfs_rq->tg->load_avg);
5386 	atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5387 	cfs_rq->tg_load_avg_contrib = 0;
5388 	cfs_rq->tg_runnable_avg_contrib = 0;
5389 	cfs_rq->last_update_tg_load_avg = now;
5390 }
5391 
5392 /* CPU offline callback: */
5393 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
5394 {
5395 	struct task_group *tg;
5396 
5397 	lockdep_assert_rq_held(rq);
5398 
5399 	/*
5400 	 * The rq clock has already been updated in
5401 	 * set_rq_offline(), so we should skip updating
5402 	 * the rq clock again in unthrottle_cfs_rq().
5403 	 */
5404 	rq_clock_start_loop_update(rq);
5405 
5406 	guard(rcu)();
5407 
5408 	list_for_each_entry_rcu(tg, &task_groups, list) {
5409 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
5410 
5411 		clear_tg_load_avg(cfs_rq);
5412 	}
5413 
5414 	rq_clock_stop_loop_update(rq);
5415 }
5416 
5417 /*
5418  * Called within set_task_rq() right before setting a task's CPU. The
5419  * caller only guarantees p->pi_lock is held; no other assumptions,
5420  * including the state of rq->lock, should be made.
5421  */
5422 void set_task_rq_fair(struct sched_entity *se,
5423 		      struct cfs_rq *prev, struct cfs_rq *next)
5424 {
5425 	u64 p_last_update_time;
5426 	u64 n_last_update_time;
5427 
5428 	if (!sched_feat(ATTACH_AGE_LOAD))
5429 		return;
5430 
5431 	/*
5432 	 * We are supposed to update the task to "current" time, then its up to
5433 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
5434 	 * getting what current time is, so simply throw away the out-of-date
5435 	 * time. This will result in the wakee task is less decayed, but giving
5436 	 * the wakee more load sounds not bad.
5437 	 */
5438 	if (!(se->avg.last_update_time && prev))
5439 		return;
5440 
5441 	p_last_update_time = cfs_rq_last_update_time(prev);
5442 	n_last_update_time = cfs_rq_last_update_time(next);
5443 
5444 	__update_load_avg_blocked_se(p_last_update_time, se);
5445 	se->avg.last_update_time = n_last_update_time;
5446 }
5447 
5448 /*
5449  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
5450  * propagate its contribution. The key to this propagation is the invariant
5451  * that for each group:
5452  *
5453  *   ge->avg == grq->avg						(1)
5454  *
5455  * _IFF_ we look at the pure running and runnable sums. Because they
5456  * represent the very same entity, just at different points in the hierarchy.
5457  *
5458  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
5459  * and simply copies the running/runnable sum over (but still wrong, because
5460  * the group entity and group rq do not have their PELT windows aligned).
5461  *
5462  * However, update_tg_cfs_load() is more complex. So we have:
5463  *
5464  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
5465  *
5466  * And since, like util, the runnable part should be directly transferable,
5467  * the following would _appear_ to be the straight forward approach:
5468  *
5469  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
5470  *
5471  * And per (1) we have:
5472  *
5473  *   ge->avg.runnable_avg == grq->avg.runnable_avg
5474  *
5475  * Which gives:
5476  *
5477  *                      ge->load.weight * grq->avg.load_avg
5478  *   ge->avg.load_avg = -----------------------------------		(4)
5479  *                               grq->load.weight
5480  *
5481  * Except that is wrong!
5482  *
5483  * Because while for entities historical weight is not important and we
5484  * really only care about our future and therefore can consider a pure
5485  * runnable sum, runqueues can NOT do this.
5486  *
5487  * We specifically want runqueues to have a load_avg that includes
5488  * historical weights. Those represent the blocked load, the load we expect
5489  * to (shortly) return to us. This only works by keeping the weights as
5490  * integral part of the sum. We therefore cannot decompose as per (3).
5491  *
5492  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
5493  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
5494  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
5495  * runnable section of these tasks overlap (or not). If they were to perfectly
5496  * align the rq as a whole would be runnable 2/3 of the time. If however we
5497  * always have at least 1 runnable task, the rq as a whole is always runnable.
5498  *
5499  * So we'll have to approximate.. :/
5500  *
5501  * Given the constraint:
5502  *
5503  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
5504  *
5505  * We can construct a rule that adds runnable to a rq by assuming minimal
5506  * overlap.
5507  *
5508  * On removal, we'll assume each task is equally runnable; which yields:
5509  *
5510  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
5511  *
5512  * XXX: only do this for the part of runnable > running ?
5513  *
5514  */
5515 static inline void
5516 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5517 {
5518 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
5519 	u32 new_sum, divider;
5520 
5521 	/* Nothing to update */
5522 	if (!delta_avg)
5523 		return;
5524 
5525 	/*
5526 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5527 	 * See ___update_load_avg() for details.
5528 	 */
5529 	divider = get_pelt_divider(&cfs_rq->avg);
5530 
5531 	/* Set new sched_entity's utilization */
5532 	se->avg.util_avg = gcfs_rq->avg.util_avg;
5533 	new_sum = se->avg.util_avg * divider;
5534 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
5535 	se->avg.util_sum = new_sum;
5536 
5537 	/* Update parent cfs_rq utilization */
5538 	__update_sa(&cfs_rq->avg, util, delta_avg, delta_sum);
5539 }
5540 
5541 static inline void
5542 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5543 {
5544 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
5545 	u64 new_sum;
5546 	u32 divider;
5547 
5548 	/* Nothing to update */
5549 	if (!delta_avg)
5550 		return;
5551 
5552 	/*
5553 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5554 	 * See ___update_load_avg() for details.
5555 	 */
5556 	divider = get_pelt_divider(&cfs_rq->avg);
5557 
5558 	/* Set new sched_entity's runnable */
5559 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
5560 	new_sum = (u64)se->avg.runnable_avg * divider;
5561 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
5562 	se->avg.runnable_sum = new_sum;
5563 
5564 	/* Update parent cfs_rq runnable */
5565 	__update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum);
5566 }
5567 
5568 static inline void
5569 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5570 {
5571 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
5572 	unsigned long load_avg;
5573 	u64 load_sum = 0;
5574 	s64 delta_sum;
5575 	u32 divider;
5576 
5577 	if (!runnable_sum)
5578 		return;
5579 
5580 	gcfs_rq->prop_runnable_sum = 0;
5581 
5582 	/*
5583 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5584 	 * See ___update_load_avg() for details.
5585 	 */
5586 	divider = get_pelt_divider(&cfs_rq->avg);
5587 
5588 	if (runnable_sum >= 0) {
5589 		/*
5590 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
5591 		 * the CPU is saturated running == runnable.
5592 		 */
5593 		runnable_sum += se->avg.load_sum;
5594 		runnable_sum = min_t(long, runnable_sum, divider);
5595 	} else {
5596 		/*
5597 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
5598 		 * assuming all tasks are equally runnable.
5599 		 */
5600 		if (scale_load_down(gcfs_rq->load.weight)) {
5601 			load_sum = div_u64(gcfs_rq->avg.load_sum,
5602 				scale_load_down(gcfs_rq->load.weight));
5603 		}
5604 
5605 		/* But make sure to not inflate se's runnable */
5606 		runnable_sum = min(se->avg.load_sum, load_sum);
5607 	}
5608 
5609 	/*
5610 	 * runnable_sum can't be lower than running_sum
5611 	 * Rescale running sum to be in the same range as runnable sum
5612 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
5613 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
5614 	 */
5615 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
5616 	runnable_sum = max(runnable_sum, running_sum);
5617 
5618 	load_sum = se_weight(se) * runnable_sum;
5619 	load_avg = div_u64(load_sum, divider);
5620 
5621 	delta_avg = load_avg - se->avg.load_avg;
5622 	if (!delta_avg)
5623 		return;
5624 
5625 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
5626 
5627 	se->avg.load_sum = runnable_sum;
5628 	se->avg.load_avg = load_avg;
5629 	__update_sa(&cfs_rq->avg, load, delta_avg, delta_sum);
5630 }
5631 
5632 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
5633 {
5634 	cfs_rq->propagate = 1;
5635 	cfs_rq->prop_runnable_sum += runnable_sum;
5636 }
5637 
5638 /* Update task and its cfs_rq load average */
5639 static inline int propagate_entity_load_avg(struct sched_entity *se)
5640 {
5641 	struct cfs_rq *cfs_rq, *gcfs_rq;
5642 
5643 	if (entity_is_task(se))
5644 		return 0;
5645 
5646 	gcfs_rq = group_cfs_rq(se);
5647 	if (!gcfs_rq->propagate)
5648 		return 0;
5649 
5650 	gcfs_rq->propagate = 0;
5651 
5652 	cfs_rq = cfs_rq_of(se);
5653 
5654 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
5655 
5656 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
5657 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
5658 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
5659 
5660 	trace_pelt_cfs_tp(cfs_rq);
5661 	trace_pelt_se_tp(se);
5662 
5663 	return 1;
5664 }
5665 
5666 /*
5667  * Check if we need to update the load and the utilization of a blocked
5668  * group_entity:
5669  */
5670 static inline bool skip_blocked_update(struct sched_entity *se)
5671 {
5672 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5673 
5674 	/*
5675 	 * If sched_entity still have not zero load or utilization, we have to
5676 	 * decay it:
5677 	 */
5678 	if (se->avg.load_avg || se->avg.util_avg)
5679 		return false;
5680 
5681 	/*
5682 	 * If there is a pending propagation, we have to update the load and
5683 	 * the utilization of the sched_entity:
5684 	 */
5685 	if (gcfs_rq->propagate)
5686 		return false;
5687 
5688 	/*
5689 	 * Otherwise, the load and the utilization of the sched_entity is
5690 	 * already zero and there is no pending propagation, so it will be a
5691 	 * waste of time to try to decay it:
5692 	 */
5693 	return true;
5694 }
5695 
5696 #else /* !CONFIG_FAIR_GROUP_SCHED: */
5697 
5698 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
5699 
5700 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
5701 
5702 static inline int propagate_entity_load_avg(struct sched_entity *se)
5703 {
5704 	return 0;
5705 }
5706 
5707 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
5708 
5709 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5710 
5711 #ifdef CONFIG_NO_HZ_COMMON
5712 static inline void migrate_se_pelt_lag(struct sched_entity *se)
5713 {
5714 	u64 throttled = 0, now, lut;
5715 	struct cfs_rq *cfs_rq;
5716 	struct rq *rq;
5717 	bool is_idle;
5718 
5719 	if (load_avg_is_decayed(&se->avg))
5720 		return;
5721 
5722 	cfs_rq = cfs_rq_of(se);
5723 	rq = rq_of(cfs_rq);
5724 
5725 	rcu_read_lock();
5726 	is_idle = is_idle_task(rcu_dereference_all(rq->curr));
5727 	rcu_read_unlock();
5728 
5729 	/*
5730 	 * The lag estimation comes with a cost we don't want to pay all the
5731 	 * time. Hence, limiting to the case where the source CPU is idle and
5732 	 * we know we are at the greatest risk to have an outdated clock.
5733 	 */
5734 	if (!is_idle)
5735 		return;
5736 
5737 	/*
5738 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
5739 	 *
5740 	 *   last_update_time (the cfs_rq's last_update_time)
5741 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
5742 	 *      = rq_clock_pelt()@cfs_rq_idle
5743 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
5744 	 *
5745 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
5746 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
5747 	 *
5748 	 *   rq_idle_lag (delta between now and rq's update)
5749 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
5750 	 *
5751 	 * We can then write:
5752 	 *
5753 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
5754 	 *          sched_clock_cpu() - rq_clock()@rq_idle
5755 	 * Where:
5756 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
5757 	 *      rq_clock()@rq_idle      is rq->clock_idle
5758 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
5759 	 *                              is cfs_rq->throttled_pelt_idle
5760 	 */
5761 
5762 #ifdef CONFIG_CFS_BANDWIDTH
5763 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
5764 	/* The clock has been stopped for throttling */
5765 	if (throttled == U64_MAX)
5766 		return;
5767 #endif
5768 	now = u64_u32_load(rq->clock_pelt_idle);
5769 	/*
5770 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
5771 	 * is observed the old clock_pelt_idle value and the new clock_idle,
5772 	 * which lead to an underestimation. The opposite would lead to an
5773 	 * overestimation.
5774 	 */
5775 	smp_rmb();
5776 	lut = cfs_rq_last_update_time(cfs_rq);
5777 
5778 	now -= throttled;
5779 	if (now < lut)
5780 		/*
5781 		 * cfs_rq->avg.last_update_time is more recent than our
5782 		 * estimation, let's use it.
5783 		 */
5784 		now = lut;
5785 	else
5786 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
5787 
5788 	__update_load_avg_blocked_se(now, se);
5789 }
5790 #else /* !CONFIG_NO_HZ_COMMON: */
5791 static void migrate_se_pelt_lag(struct sched_entity *se) {}
5792 #endif /* !CONFIG_NO_HZ_COMMON */
5793 
5794 /**
5795  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
5796  * @now: current time, as per cfs_rq_clock_pelt()
5797  * @cfs_rq: cfs_rq to update
5798  *
5799  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
5800  * avg. The immediate corollary is that all (fair) tasks must be attached.
5801  *
5802  * cfs_rq->avg is used for task_h_load() and update_cfs_group() for example.
5803  *
5804  * Return: true if the load decayed or we removed load.
5805  *
5806  * Since both these conditions indicate a changed cfs_rq->avg.load we should
5807  * call update_tg_load_avg() when this function returns true.
5808  */
5809 static inline int
5810 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
5811 {
5812 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
5813 	struct sched_avg *sa = &cfs_rq->avg;
5814 	int decayed = 0;
5815 
5816 	if (cfs_rq->removed.nr) {
5817 		unsigned long r;
5818 		u32 divider = get_pelt_divider(&cfs_rq->avg);
5819 
5820 		raw_spin_lock(&cfs_rq->removed.lock);
5821 		swap(cfs_rq->removed.util_avg, removed_util);
5822 		swap(cfs_rq->removed.load_avg, removed_load);
5823 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
5824 		cfs_rq->removed.nr = 0;
5825 		raw_spin_unlock(&cfs_rq->removed.lock);
5826 
5827 		r = removed_load;
5828 		__update_sa(sa, load, -r, -r*divider);
5829 
5830 		r = removed_util;
5831 		__update_sa(sa, util, -r, -r*divider);
5832 
5833 		r = removed_runnable;
5834 		__update_sa(sa, runnable, -r, -r*divider);
5835 
5836 		/*
5837 		 * removed_runnable is the unweighted version of removed_load so we
5838 		 * can use it to estimate removed_load_sum.
5839 		 */
5840 		add_tg_cfs_propagate(cfs_rq,
5841 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
5842 
5843 		decayed = 1;
5844 	}
5845 
5846 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
5847 	u64_u32_store_copy(sa->last_update_time,
5848 			   cfs_rq->last_update_time_copy,
5849 			   sa->last_update_time);
5850 	return decayed;
5851 }
5852 
5853 /**
5854  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
5855  * @cfs_rq: cfs_rq to attach to
5856  * @se: sched_entity to attach
5857  *
5858  * Must call update_cfs_rq_load_avg() before this, since we rely on
5859  * cfs_rq->avg.last_update_time being current.
5860  */
5861 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5862 {
5863 	/*
5864 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5865 	 * See ___update_load_avg() for details.
5866 	 */
5867 	u32 divider = get_pelt_divider(&cfs_rq->avg);
5868 
5869 	/*
5870 	 * When we attach the @se to the @cfs_rq, we must align the decay
5871 	 * window because without that, really weird and wonderful things can
5872 	 * happen.
5873 	 *
5874 	 * XXX illustrate
5875 	 */
5876 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
5877 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
5878 
5879 	/*
5880 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
5881 	 * period_contrib. This isn't strictly correct, but since we're
5882 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
5883 	 * _sum a little.
5884 	 */
5885 	se->avg.util_sum = se->avg.util_avg * divider;
5886 
5887 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
5888 
5889 	se->avg.load_sum = se->avg.load_avg * divider;
5890 	if (se_weight(se) < se->avg.load_sum)
5891 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
5892 	else
5893 		se->avg.load_sum = 1;
5894 
5895 	enqueue_load_avg(cfs_rq, se);
5896 	cfs_rq->avg.util_avg += se->avg.util_avg;
5897 	cfs_rq->avg.util_sum += se->avg.util_sum;
5898 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
5899 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
5900 
5901 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
5902 
5903 	cfs_rq_util_change(cfs_rq, 0);
5904 
5905 	trace_pelt_cfs_tp(cfs_rq);
5906 }
5907 
5908 /**
5909  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
5910  * @cfs_rq: cfs_rq to detach from
5911  * @se: sched_entity to detach
5912  *
5913  * Must call update_cfs_rq_load_avg() before this, since we rely on
5914  * cfs_rq->avg.last_update_time being current.
5915  */
5916 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5917 {
5918 	dequeue_load_avg(cfs_rq, se);
5919 	__update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum);
5920 	__update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum);
5921 
5922 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
5923 
5924 	cfs_rq_util_change(cfs_rq, 0);
5925 
5926 	trace_pelt_cfs_tp(cfs_rq);
5927 }
5928 
5929 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
5930 
5931 static inline void util_est_update(struct sched_entity *se)
5932 {
5933 	unsigned int ewma, dequeued, last_ewma_diff;
5934 
5935 	if (!sched_feat(UTIL_EST))
5936 		return;
5937 
5938 	/* Get current estimate of utilization */
5939 	ewma = READ_ONCE(se->avg.util_est);
5940 
5941 	/*
5942 	 * If the PELT values haven't changed since enqueue time,
5943 	 * skip the util_est update.
5944 	 */
5945 	if (ewma & UTIL_AVG_UNCHANGED)
5946 		return;
5947 
5948 	/* Get utilization at dequeue */
5949 	dequeued = READ_ONCE(se->avg.util_avg);
5950 
5951 	/*
5952 	 * Reset EWMA on utilization increases, the moving average is used only
5953 	 * to smooth utilization decreases.
5954 	 */
5955 	if (ewma <= dequeued) {
5956 		ewma = dequeued;
5957 		goto done;
5958 	}
5959 
5960 	/*
5961 	 * Skip update of task's estimated utilization when its members are
5962 	 * already ~1% close to its last activation value.
5963 	 */
5964 	last_ewma_diff = ewma - dequeued;
5965 	if (last_ewma_diff < UTIL_EST_MARGIN)
5966 		goto done;
5967 
5968 	/*
5969 	 * To avoid underestimate of task utilization, skip updates of EWMA if
5970 	 * we cannot grant that thread got all CPU time it wanted.
5971 	 */
5972 	if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg))
5973 		goto done;
5974 
5975 	/*
5976 	 * Update Task's estimated utilization
5977 	 *
5978 	 * When *p completes an activation we can consolidate another sample
5979 	 * of the task size. This is done by using this value to update the
5980 	 * Exponential Weighted Moving Average (EWMA):
5981 	 *
5982 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
5983 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
5984 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
5985 	 *          = w * (      -last_ewma_diff           ) +     ewma(t-1)
5986 	 *          = w * (-last_ewma_diff +  ewma(t-1) / w)
5987 	 *
5988 	 * Where 'w' is the weight of new samples, which is configured to be
5989 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5990 	 */
5991 	ewma <<= UTIL_EST_WEIGHT_SHIFT;
5992 	ewma  -= last_ewma_diff;
5993 	ewma >>= UTIL_EST_WEIGHT_SHIFT;
5994 done:
5995 	ewma |= UTIL_AVG_UNCHANGED;
5996 	WRITE_ONCE(se->avg.util_est, ewma);
5997 
5998 	trace_sched_util_est_se_tp(se);
5999 }
6000 
6001 /*
6002  * Optional action to be done while updating the load average
6003  */
6004 #define UPDATE_TG	0x01
6005 #define SKIP_AGE_LOAD	0x02
6006 #define DO_ATTACH	0x04
6007 #define DO_DETACH	0x08
6008 #define UPDATE_UTIL_EST	0x10
6009 
6010 /* Update task and its cfs_rq load average */
6011 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6012 {
6013 	u64 now = cfs_rq_clock_pelt(cfs_rq);
6014 	int decayed;
6015 
6016 	/*
6017 	 * Track task load average for carrying it to new CPU after migrated, and
6018 	 * track group sched_entity load average for task_h_load calculation in migration
6019 	 */
6020 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
6021 		__update_load_avg_se(now, cfs_rq, se);
6022 
6023 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
6024 	decayed |= propagate_entity_load_avg(se);
6025 
6026 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
6027 
6028 		/*
6029 		 * DO_ATTACH means we're here from enqueue_entity().
6030 		 * !last_update_time means we've passed through
6031 		 * migrate_task_rq_fair() indicating we migrated.
6032 		 *
6033 		 * IOW we're enqueueing a task on a new CPU.
6034 		 */
6035 		attach_entity_load_avg(cfs_rq, se);
6036 		update_tg_load_avg(cfs_rq);
6037 
6038 	} else if (flags & DO_DETACH) {
6039 		/*
6040 		 * DO_DETACH means we're here from dequeue_entity()
6041 		 * and we are migrating task out of the CPU.
6042 		 */
6043 		detach_entity_load_avg(cfs_rq, se);
6044 		update_tg_load_avg(cfs_rq);
6045 	} else if (decayed) {
6046 		cfs_rq_util_change(cfs_rq, 0);
6047 
6048 		if (flags & UPDATE_TG)
6049 			update_tg_load_avg(cfs_rq);
6050 	}
6051 
6052 	if (flags & UPDATE_UTIL_EST)
6053 		util_est_update(se);
6054 }
6055 
6056 /*
6057  * Synchronize entity load avg of dequeued entity without locking
6058  * the previous rq.
6059  */
6060 static void sync_entity_load_avg(struct sched_entity *se)
6061 {
6062 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6063 	u64 last_update_time;
6064 
6065 	last_update_time = cfs_rq_last_update_time(cfs_rq);
6066 	__update_load_avg_blocked_se(last_update_time, se);
6067 }
6068 
6069 /*
6070  * Task first catches up with cfs_rq, and then subtract
6071  * itself from the cfs_rq (task must be off the queue now).
6072  */
6073 static void remove_entity_load_avg(struct sched_entity *se)
6074 {
6075 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6076 	unsigned long flags;
6077 
6078 	/*
6079 	 * tasks cannot exit without having gone through wake_up_new_task() ->
6080 	 * enqueue_task_fair() which will have added things to the cfs_rq,
6081 	 * so we can remove unconditionally.
6082 	 */
6083 
6084 	sync_entity_load_avg(se);
6085 
6086 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
6087 	++cfs_rq->removed.nr;
6088 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
6089 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
6090 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
6091 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
6092 }
6093 
6094 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
6095 {
6096 	return cfs_rq->avg.runnable_avg;
6097 }
6098 
6099 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
6100 {
6101 	return cfs_rq->avg.load_avg;
6102 }
6103 
6104 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
6105 	__must_hold(__rq_lockp(this_rq));
6106 
6107 static inline unsigned long task_util(struct task_struct *p)
6108 {
6109 	return READ_ONCE(p->se.avg.util_avg);
6110 }
6111 
6112 static inline unsigned long _task_util_est(struct task_struct *p)
6113 {
6114 	return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
6115 }
6116 
6117 static inline unsigned long task_util_est(struct task_struct *p)
6118 {
6119 	return max(task_util(p), _task_util_est(p));
6120 }
6121 
6122 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
6123 				    struct task_struct *p)
6124 {
6125 	unsigned int enqueued;
6126 
6127 	if (!sched_feat(UTIL_EST))
6128 		return;
6129 
6130 	/* Update root cfs_rq's estimated utilization */
6131 	enqueued  = cfs_rq->avg.util_est;
6132 	enqueued += _task_util_est(p);
6133 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
6134 
6135 	trace_sched_util_est_cfs_tp(cfs_rq);
6136 }
6137 
6138 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
6139 				    struct task_struct *p)
6140 {
6141 	unsigned int enqueued;
6142 
6143 	if (!sched_feat(UTIL_EST))
6144 		return;
6145 
6146 	/* Update root cfs_rq's estimated utilization */
6147 	enqueued  = cfs_rq->avg.util_est;
6148 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
6149 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
6150 
6151 	trace_sched_util_est_cfs_tp(cfs_rq);
6152 }
6153 
6154 static inline unsigned long get_actual_cpu_capacity(int cpu)
6155 {
6156 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
6157 
6158 	capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
6159 
6160 	return capacity;
6161 }
6162 
6163 static inline int util_fits_cpu(unsigned long util,
6164 				unsigned long uclamp_min,
6165 				unsigned long uclamp_max,
6166 				int cpu)
6167 {
6168 	unsigned long capacity = capacity_of(cpu);
6169 	unsigned long capacity_orig;
6170 	bool fits, uclamp_max_fits;
6171 
6172 	/*
6173 	 * Check if the real util fits without any uclamp boost/cap applied.
6174 	 */
6175 	fits = fits_capacity(util, capacity);
6176 
6177 	if (!uclamp_is_used())
6178 		return fits;
6179 
6180 	/*
6181 	 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
6182 	 * uclamp_max. We only care about capacity pressure (by using
6183 	 * capacity_of()) for comparing against the real util.
6184 	 *
6185 	 * If a task is boosted to 1024 for example, we don't want a tiny
6186 	 * pressure to skew the check whether it fits a CPU or not.
6187 	 *
6188 	 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
6189 	 * should fit a little cpu even if there's some pressure.
6190 	 *
6191 	 * Only exception is for HW or cpufreq pressure since it has a direct impact
6192 	 * on available OPP of the system.
6193 	 *
6194 	 * We honour it for uclamp_min only as a drop in performance level
6195 	 * could result in not getting the requested minimum performance level.
6196 	 *
6197 	 * For uclamp_max, we can tolerate a drop in performance level as the
6198 	 * goal is to cap the task. So it's okay if it's getting less.
6199 	 */
6200 	capacity_orig = arch_scale_cpu_capacity(cpu);
6201 
6202 	/*
6203 	 * We want to force a task to fit a cpu as implied by uclamp_max.
6204 	 * But we do have some corner cases to cater for..
6205 	 *
6206 	 *
6207 	 *                                 C=z
6208 	 *   |                             ___
6209 	 *   |                  C=y       |   |
6210 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
6211 	 *   |      C=x        |   |      |   |
6212 	 *   |      ___        |   |      |   |
6213 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
6214 	 *   |     |   |       |   |      |   |
6215 	 *   |     |   |       |   |      |   |
6216 	 *   +----------------------------------------
6217 	 *         CPU0        CPU1       CPU2
6218 	 *
6219 	 *   In the above example if a task is capped to a specific performance
6220 	 *   point, y, then when:
6221 	 *
6222 	 *   * util = 80% of x then it does not fit on CPU0 and should migrate
6223 	 *     to CPU1
6224 	 *   * util = 80% of y then it is forced to fit on CPU1 to honour
6225 	 *     uclamp_max request.
6226 	 *
6227 	 *   which is what we're enforcing here. A task always fits if
6228 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
6229 	 *   the normal upmigration rules should withhold still.
6230 	 *
6231 	 *   Only exception is when we are on max capacity, then we need to be
6232 	 *   careful not to block overutilized state. This is so because:
6233 	 *
6234 	 *     1. There's no concept of capping at max_capacity! We can't go
6235 	 *        beyond this performance level anyway.
6236 	 *     2. The system is being saturated when we're operating near
6237 	 *        max capacity, it doesn't make sense to block overutilized.
6238 	 */
6239 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
6240 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
6241 	fits = fits || uclamp_max_fits;
6242 
6243 	/*
6244 	 *
6245 	 *                                 C=z
6246 	 *   |                             ___       (region a, capped, util >= uclamp_max)
6247 	 *   |                  C=y       |   |
6248 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
6249 	 *   |      C=x        |   |      |   |
6250 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
6251 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
6252 	 *   |     |   |       |   |      |   |
6253 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
6254 	 *   +----------------------------------------
6255 	 *         CPU0        CPU1       CPU2
6256 	 *
6257 	 * a) If util > uclamp_max, then we're capped, we don't care about
6258 	 *    actual fitness value here. We only care if uclamp_max fits
6259 	 *    capacity without taking margin/pressure into account.
6260 	 *    See comment above.
6261 	 *
6262 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
6263 	 *    fits_capacity() rules apply. Except we need to ensure that we
6264 	 *    enforce we remain within uclamp_max, see comment above.
6265 	 *
6266 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
6267 	 *    need to take into account the boosted value fits the CPU without
6268 	 *    taking margin/pressure into account.
6269 	 *
6270 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
6271 	 * just need to consider an extra check for case (c) after ensuring we
6272 	 * handle the case uclamp_min > uclamp_max.
6273 	 */
6274 	uclamp_min = min(uclamp_min, uclamp_max);
6275 	if (fits && (util < uclamp_min) &&
6276 	    (uclamp_min > get_actual_cpu_capacity(cpu)))
6277 		return -1;
6278 
6279 	return fits;
6280 }
6281 
6282 static inline int task_fits_cpu(struct task_struct *p, int cpu)
6283 {
6284 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
6285 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
6286 	unsigned long util = task_util_est(p);
6287 	/*
6288 	 * Return true only if the cpu fully fits the task requirements, which
6289 	 * include the utilization but also the performance hints.
6290 	 */
6291 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
6292 }
6293 
6294 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
6295 {
6296 	int cpu = cpu_of(rq);
6297 
6298 	if (!sched_asym_cpucap_active())
6299 		return;
6300 
6301 	/*
6302 	 * Affinity allows us to go somewhere higher?  Or are we on biggest
6303 	 * available CPU already? Or do we fit into this CPU ?
6304 	 */
6305 	if (!p || (p->nr_cpus_allowed == 1) ||
6306 	    (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
6307 	    task_fits_cpu(p, cpu)) {
6308 
6309 		rq->misfit_task_load = 0;
6310 		return;
6311 	}
6312 
6313 	/*
6314 	 * Make sure that misfit_task_load will not be null even if
6315 	 * task_h_load() returns 0.
6316 	 */
6317 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
6318 }
6319 
6320 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
6321 {
6322 	struct sched_entity *se = &p->se;
6323 
6324 	p->static_prio = NICE_TO_PRIO(attr->sched_nice);
6325 	if (attr->sched_runtime) {
6326 		se->custom_slice = 1;
6327 		se->slice = clamp_t(u64, attr->sched_runtime,
6328 				      NSEC_PER_MSEC/10,   /* HZ=1000 * 10 */
6329 				      NSEC_PER_MSEC*100); /* HZ=100  / 10 */
6330 	} else {
6331 		se->custom_slice = 0;
6332 		se->slice = sysctl_sched_base_slice;
6333 	}
6334 }
6335 
6336 static void
6337 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6338 {
6339 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
6340 	unsigned int nr_queued = cfs_rq->h_nr_queued;
6341 	bool update_zero = false;
6342 	s64 lag = 0;
6343 
6344 	if (!se->custom_slice)
6345 		se->slice = sysctl_sched_base_slice;
6346 	vslice = calc_delta_fair(se->slice, se);
6347 
6348 	if (flags & ENQUEUE_QUEUED)
6349 		nr_queued -= 1;
6350 
6351 	/*
6352 	 * Due to how V is constructed as the weighted average of entities,
6353 	 * adding tasks with positive lag, or removing tasks with negative lag
6354 	 * will move 'time' backwards, this can screw around with the lag of
6355 	 * other tasks.
6356 	 *
6357 	 * EEVDF: placement strategy #1 / #2
6358 	 */
6359 	if (sched_feat(PLACE_LAG) && nr_queued && se->vlag) {
6360 		struct sched_entity *curr = cfs_rq->curr;
6361 		long load, weight;
6362 
6363 		lag = se->vlag;
6364 
6365 		/*
6366 		 * If we want to place a task and preserve lag, we have to
6367 		 * consider the effect of the new entity on the weighted
6368 		 * average and compensate for this, otherwise lag can quickly
6369 		 * evaporate.
6370 		 *
6371 		 * Lag is defined as:
6372 		 *
6373 		 *   lag_i = S - s_i = w_i * (V - v_i)
6374 		 *
6375 		 * To avoid the 'w_i' term all over the place, we only track
6376 		 * the virtual lag:
6377 		 *
6378 		 *   vl_i = V - v_i <=> v_i = V - vl_i
6379 		 *
6380 		 * And we take V to be the weighted average of all v:
6381 		 *
6382 		 *   V = (\Sum w_j*v_j) / W
6383 		 *
6384 		 * Where W is: \Sum w_j
6385 		 *
6386 		 * Then, the weighted average after adding an entity with lag
6387 		 * vl_i is given by:
6388 		 *
6389 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
6390 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
6391 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
6392 		 *      = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
6393 		 *      = V - w_i*vl_i / (W + w_i)
6394 		 *
6395 		 * And the actual lag after adding an entity with vl_i is:
6396 		 *
6397 		 *   vl'_i = V' - v_i
6398 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
6399 		 *         = vl_i - w_i*vl_i / (W + w_i)
6400 		 *
6401 		 * Which is strictly less than vl_i. So in order to preserve lag
6402 		 * we should inflate the lag before placement such that the
6403 		 * effective lag after placement comes out right.
6404 		 *
6405 		 * As such, invert the above relation for vl'_i to get the vl_i
6406 		 * we need to use such that the lag after placement is the lag
6407 		 * we computed before dequeue.
6408 		 *
6409 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
6410 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
6411 		 *
6412 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
6413 		 *                   = W*vl_i
6414 		 *
6415 		 *   vl_i = (W + w_i)*vl'_i / W
6416 		 */
6417 		load = cfs_rq->sum_weight;
6418 		if (curr && curr->on_rq)
6419 			load += avg_vruntime_weight(cfs_rq, curr->h_load.weight);
6420 		if (WARN_ON_ONCE(!load))
6421 			load = 1;
6422 
6423 		weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
6424 
6425 		/*
6426 		 * Rewrite, because the product (W + w_i)*vl'_i might
6427 		 * overflow s64:
6428 		 *
6429 		 *   vl_i = (W + w_i)*vl'_i / W
6430 		 *        = (W*vl'_i + w_i*vl'_i) / W
6431 		 *        = vl'_i + w_i*vl'_i/W
6432 		 */
6433 		lag += div64_long(lag * weight, load);
6434 
6435 		/*
6436 		 * A heavy entity (relative to the tree) will pull the
6437 		 * avg_vruntime close to its vruntime position on enqueue. But
6438 		 * the zero_vruntime point is only updated at the next
6439 		 * update_deadline()/place_entity()/update_entity_lag().
6440 		 *
6441 		 * Specifically (see the comment near avg_vruntime_weight()):
6442 		 *
6443 		 *   sum_w_vruntime = \Sum (v_i - v0) * w_i
6444 		 *
6445 		 * Note that if v0 is near a light entity, both terms will be
6446 		 * small for the light entity, while in that case both terms
6447 		 * are large for the heavy entity, leading to risk of
6448 		 * overflow.
6449 		 *
6450 		 * OTOH if v0 is near the heavy entity, then the difference is
6451 		 * larger for the light entity, but the factor is small, while
6452 		 * for the heavy entity the difference is small but the factor
6453 		 * is large. Avoiding the multiplication overflow.
6454 		 */
6455 		if (weight > load)
6456 			update_zero = true;
6457 	}
6458 
6459 	se->vruntime = vruntime - lag;
6460 
6461 	if (update_zero)
6462 		update_zero_vruntime(cfs_rq, -lag);
6463 
6464 	if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
6465 		se->deadline += se->vruntime;
6466 		se->rel_deadline = 0;
6467 		return;
6468 	}
6469 
6470 	/*
6471 	 * When joining the competition; the existing tasks will be,
6472 	 * on average, halfway through their slice, as such start tasks
6473 	 * off with half a slice to ease into the competition.
6474 	 */
6475 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
6476 		vslice /= 2;
6477 
6478 	/*
6479 	 * EEVDF: vd_i = ve_i + r_i/w_i
6480 	 */
6481 	se->deadline = se->vruntime + vslice;
6482 }
6483 
6484 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
6485 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
6486 
6487 static void
6488 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6489 {
6490 	/*
6491 	 * When enqueuing a sched_entity, we must:
6492 	 *   - Update loads to have both entity and cfs_rq synced with now.
6493 	 *   - For group_entity, update its runnable_weight to reflect the new
6494 	 *     h_nr_runnable of its group cfs_rq.
6495 	 *   - For group_entity, update its weight to reflect the new share of
6496 	 *     its group cfs_rq
6497 	 *   - Add its new weight to cfs_rq->load.weight
6498 	 */
6499 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
6500 	se_update_runnable(se);
6501 	/*
6502 	 * XXX update_load_avg() above will have attached us to the pelt sum;
6503 	 * but update_cfs_group() here will re-adjust the weight and have to
6504 	 * undo/redo all that. Seems wasteful.
6505 	 */
6506 	update_cfs_group(se);
6507 
6508 	account_entity_enqueue(cfs_rq, se);
6509 
6510 	/* Entity has migrated, no longer consider this task hot */
6511 	if (flags & ENQUEUE_MIGRATED)
6512 		se->exec_start = 0;
6513 
6514 	check_schedstat_required();
6515 	update_stats_enqueue_fair(cfs_rq, se, flags);
6516 	se->on_rq = 1;
6517 
6518 	if (cfs_rq->nr_queued == 1) {
6519 		check_enqueue_throttle(cfs_rq);
6520 		list_add_leaf_cfs_rq(cfs_rq);
6521 #ifdef CONFIG_CFS_BANDWIDTH
6522 		if (cfs_rq->pelt_clock_throttled) {
6523 			struct rq *rq = rq_of(cfs_rq);
6524 
6525 			cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6526 				cfs_rq->throttled_clock_pelt;
6527 			cfs_rq->pelt_clock_throttled = 0;
6528 		}
6529 #endif
6530 	}
6531 }
6532 
6533 static void set_next_buddy(struct cfs_rq *cfs_rq, struct sched_entity *se)
6534 {
6535 	if (WARN_ON_ONCE(!se->on_rq || se->sched_delayed))
6536 		return;
6537 	if (se_is_idle(se))
6538 		return;
6539 	cfs_rq->next = se;
6540 }
6541 
6542 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
6543 {
6544 	if (cfs_rq->next == se)
6545 		cfs_rq->next = NULL;
6546 }
6547 
6548 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
6549 
6550 static void set_delayed(struct sched_entity *se)
6551 {
6552 	/* Only tasks can be delayed. */
6553 	WARN_ON_ONCE(!entity_is_task(se));
6554 
6555 	/*
6556 	 * Drop a task leaving the runnable set.
6557 	 * Needs to be called before sched_delayed is set.
6558 	 * clear_delayed() mirrors this after clearing the flag.
6559 	 */
6560 	pref_llc_running_dec(rq_of(cfs_rq_of(se)), task_of(se));
6561 	se->sched_delayed = 1;
6562 
6563 	for_each_sched_entity(se) {
6564 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
6565 
6566 		cfs_rq->h_nr_runnable--;
6567 	}
6568 }
6569 
6570 static void __clear_delayed(struct sched_entity *se)
6571 {
6572 	/* Only tasks can be delayed. */
6573 	WARN_ON_ONCE(!entity_is_task(se));
6574 	se->sched_delayed = 0;
6575 }
6576 
6577 static void clear_delayed(struct sched_entity *se)
6578 {
6579 	__clear_delayed(se);
6580 
6581 	/*
6582 	 * Re-add on wake, after sched_delayed is cleared. On a final delayed
6583 	 * dequeue account_llc_dequeue() already cleared pref_llc_queued, so
6584 	 * this does nothing.
6585 	 */
6586 	pref_llc_running_inc(rq_of(cfs_rq_of(se)), task_of(se));
6587 
6588 	for_each_sched_entity(se) {
6589 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
6590 
6591 		cfs_rq->h_nr_runnable++;
6592 	}
6593 }
6594 
6595 static void
6596 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6597 {
6598 	int action = UPDATE_TG;
6599 
6600 	if (entity_is_task(se)) {
6601 		if (task_on_rq_migrating(task_of(se)))
6602 			action |= DO_DETACH;
6603 
6604 		if ((flags & DEQUEUE_SLEEP) && !(flags & DEQUEUE_DELAYED))
6605 			action |= UPDATE_UTIL_EST;
6606 	}
6607 
6608 	/*
6609 	 * When dequeuing a sched_entity, we must:
6610 	 *   - Update loads to have both entity and cfs_rq synced with now.
6611 	 *   - For group_entity, update its runnable_weight to reflect the new
6612 	 *     h_nr_runnable of its group cfs_rq.
6613 	 *   - Subtract its previous weight from cfs_rq->load.weight.
6614 	 *   - For group entity, update its weight to reflect the new share
6615 	 *     of its group cfs_rq.
6616 	 */
6617 	update_load_avg(cfs_rq, se, action);
6618 	se_update_runnable(se);
6619 
6620 	update_stats_dequeue_fair(cfs_rq, se, flags);
6621 
6622 	se->on_rq = 0;
6623 	account_entity_dequeue(cfs_rq, se);
6624 
6625 	/* return excess runtime on last dequeue */
6626 	return_cfs_rq_runtime(cfs_rq);
6627 
6628 	update_cfs_group(se);
6629 
6630 	if (cfs_rq->nr_queued == 0) {
6631 		update_idle_cfs_rq_clock_pelt(cfs_rq);
6632 #ifdef CONFIG_CFS_BANDWIDTH
6633 		if (throttled_hierarchy(cfs_rq)) {
6634 			struct rq *rq = rq_of(cfs_rq);
6635 
6636 			list_del_leaf_cfs_rq(cfs_rq);
6637 			cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6638 			cfs_rq->pelt_clock_throttled = 1;
6639 		}
6640 #endif
6641 	}
6642 }
6643 
6644 static void
6645 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
6646 {
6647 	/* 'current' is not kept within the tree. */
6648 	if (se->on_rq) {
6649 		/*
6650 		 * Any task has to be enqueued before it get to execute on
6651 		 * a CPU. So account for the time it spent waiting on the
6652 		 * runqueue.
6653 		 */
6654 		update_stats_wait_end_fair(cfs_rq, se);
6655 		update_load_avg(cfs_rq, se, UPDATE_TG);
6656 	}
6657 
6658 	update_stats_curr_start(cfs_rq, se);
6659 	WARN_ON_ONCE(cfs_rq->h_curr);
6660 	cfs_rq->h_curr = se;
6661 
6662 	/*
6663 	 * Track our maximum slice length, if the CPU's load is at
6664 	 * least twice that of our own weight (i.e. don't track it
6665 	 * when there are only lesser-weight tasks around):
6666 	 */
6667 	if (schedstat_enabled() &&
6668 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
6669 		struct sched_statistics *stats;
6670 
6671 		stats = __schedstats_from_se(se);
6672 		__schedstat_set(stats->slice_max,
6673 				max((u64)stats->slice_max,
6674 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
6675 	}
6676 
6677 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
6678 }
6679 
6680 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags);
6681 
6682 static struct sched_entity *
6683 pick_next_entity(struct rq *rq, bool protect)
6684 {
6685 	struct cfs_rq *cfs_rq = &rq->cfs;
6686 	struct sched_entity *se;
6687 
6688 	se = pick_eevdf(cfs_rq, protect);
6689 	if (se->sched_delayed) {
6690 		__dequeue_task(rq, task_of(se), DEQUEUE_SLEEP | DEQUEUE_DELAYED);
6691 		/*
6692 		 * Must not reference @se again, see __block_task().
6693 		 */
6694 		return NULL;
6695 	}
6696 	return se;
6697 }
6698 
6699 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
6700 {
6701 	/*
6702 	 * If still on the runqueue then deactivate_task()
6703 	 * was not called and update_curr() has to be done:
6704 	 */
6705 	if (prev->on_rq)
6706 		update_curr(cfs_rq);
6707 
6708 	if (prev->on_rq) {
6709 		update_stats_wait_start_fair(cfs_rq, prev);
6710 		/* in !on_rq case, update occurred at dequeue */
6711 		update_load_avg(cfs_rq, prev, 0);
6712 	}
6713 	WARN_ON_ONCE(cfs_rq->h_curr != prev);
6714 	cfs_rq->h_curr = NULL;
6715 }
6716 
6717 static void
6718 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
6719 {
6720 	/*
6721 	 * Update run-time statistics of the 'current'.
6722 	 */
6723 	update_curr(cfs_rq);
6724 
6725 	/*
6726 	 * Ensure that runnable average is periodically updated.
6727 	 */
6728 	update_load_avg(cfs_rq, curr, UPDATE_TG);
6729 	update_cfs_group(curr);
6730 
6731 #ifdef CONFIG_SCHED_HRTICK
6732 	/*
6733 	 * queued ticks are scheduled to match the slice, so don't bother
6734 	 * validating it and just reschedule.
6735 	 */
6736 	if (queued) {
6737 		resched_curr(rq_of(cfs_rq));
6738 		return;
6739 	}
6740 #endif
6741 }
6742 
6743 
6744 /**************************************************
6745  * CFS bandwidth control machinery
6746  */
6747 
6748 #ifdef CONFIG_CFS_BANDWIDTH
6749 
6750 #ifdef CONFIG_JUMP_LABEL
6751 static struct static_key __cfs_bandwidth_used;
6752 
6753 static inline bool cfs_bandwidth_used(void)
6754 {
6755 	return static_key_false(&__cfs_bandwidth_used);
6756 }
6757 
6758 void cfs_bandwidth_usage_inc(void)
6759 {
6760 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
6761 }
6762 
6763 void cfs_bandwidth_usage_dec(void)
6764 {
6765 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
6766 }
6767 #else /* !CONFIG_JUMP_LABEL: */
6768 static bool cfs_bandwidth_used(void)
6769 {
6770 	return true;
6771 }
6772 
6773 void cfs_bandwidth_usage_inc(void) {}
6774 void cfs_bandwidth_usage_dec(void) {}
6775 #endif /* !CONFIG_JUMP_LABEL */
6776 
6777 static inline u64 sched_cfs_bandwidth_slice(void)
6778 {
6779 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
6780 }
6781 
6782 /*
6783  * Replenish runtime according to assigned quota. We use sched_clock_cpu
6784  * directly instead of rq->clock to avoid adding additional synchronization
6785  * around rq->lock.
6786  *
6787  * requires cfs_b->lock
6788  */
6789 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
6790 {
6791 	s64 runtime;
6792 
6793 	if (unlikely(cfs_b->quota == RUNTIME_INF))
6794 		return;
6795 
6796 	cfs_b->runtime += cfs_b->quota;
6797 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
6798 	if (runtime > 0) {
6799 		cfs_b->burst_time += runtime;
6800 		cfs_b->nr_burst++;
6801 	}
6802 
6803 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
6804 	cfs_b->runtime_snap = cfs_b->runtime;
6805 }
6806 
6807 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6808 {
6809 	return &tg->cfs_bandwidth;
6810 }
6811 
6812 /* returns 0 on failure to allocate runtime */
6813 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
6814 				   struct cfs_rq *cfs_rq, u64 target_runtime)
6815 {
6816 	u64 min_amount, amount = 0;
6817 
6818 	lockdep_assert_held(&cfs_b->lock);
6819 
6820 	/* note: this is a positive sum as runtime_remaining <= 0 */
6821 	min_amount = target_runtime - cfs_rq->runtime_remaining;
6822 
6823 	if (cfs_b->quota == RUNTIME_INF)
6824 		amount = min_amount;
6825 	else {
6826 		start_cfs_bandwidth(cfs_b);
6827 
6828 		if (cfs_b->runtime > 0) {
6829 			amount = min(cfs_b->runtime, min_amount);
6830 			cfs_b->runtime -= amount;
6831 			cfs_b->idle = 0;
6832 		}
6833 	}
6834 
6835 	cfs_rq->runtime_remaining += amount;
6836 
6837 	return cfs_rq->runtime_remaining > 0;
6838 }
6839 
6840 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq);
6841 
6842 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6843 {
6844 	/* dock delta_exec before expiring quota (as it could span periods) */
6845 	cfs_rq->runtime_remaining -= delta_exec;
6846 
6847 	if (likely(cfs_rq->runtime_remaining > 0))
6848 		return false;
6849 
6850 	if (cfs_rq->throttled)
6851 		return true;
6852 	/*
6853 	 * throttle_cfs_rq() will try to extend the runtime first
6854 	 * before throttling the hierarchy.
6855 	 */
6856 	return throttle_cfs_rq(cfs_rq);
6857 }
6858 
6859 static __always_inline
6860 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6861 {
6862 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
6863 		return false;
6864 
6865 	return __account_cfs_rq_runtime(cfs_rq, delta_exec);
6866 }
6867 
6868 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6869 {
6870 	return cfs_bandwidth_used() && cfs_rq->throttled;
6871 }
6872 
6873 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6874 {
6875 	return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
6876 }
6877 
6878 /* check whether cfs_rq, or any parent, is throttled */
6879 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6880 {
6881 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
6882 }
6883 
6884 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6885 {
6886 	return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu));
6887 }
6888 
6889 static inline bool task_is_throttled(struct task_struct *p)
6890 {
6891 	return cfs_bandwidth_used() && p->throttled;
6892 }
6893 
6894 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
6895 static void throttle_cfs_rq_work(struct callback_head *work)
6896 {
6897 	struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
6898 	struct sched_entity *se;
6899 	struct cfs_rq *cfs_rq;
6900 	struct rq *rq;
6901 
6902 	WARN_ON_ONCE(p != current);
6903 	p->sched_throttle_work.next = &p->sched_throttle_work;
6904 
6905 	/*
6906 	 * If task is exiting, then there won't be a return to userspace, so we
6907 	 * don't have to bother with any of this.
6908 	 */
6909 	if ((p->flags & PF_EXITING))
6910 		return;
6911 
6912 	scoped_guard(task_rq_lock, p) {
6913 		se = &p->se;
6914 		cfs_rq = cfs_rq_of(se);
6915 
6916 		/* Raced, forget */
6917 		if (p->sched_class != &fair_sched_class)
6918 			return;
6919 
6920 		/*
6921 		 * If not in limbo, then either replenish has happened or this
6922 		 * task got migrated out of the throttled cfs_rq, move along.
6923 		 */
6924 		if (!cfs_rq->throttle_count)
6925 			return;
6926 		rq = scope.rq;
6927 		update_rq_clock(rq);
6928 		WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
6929 		dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
6930 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6931 		/*
6932 		 * Must not set throttled before dequeue or dequeue will
6933 		 * mistakenly regard this task as an already throttled one.
6934 		 */
6935 		p->throttled = true;
6936 		resched_curr(rq);
6937 	}
6938 }
6939 
6940 void init_cfs_throttle_work(struct task_struct *p)
6941 {
6942 	init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
6943 	/* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
6944 	p->sched_throttle_work.next = &p->sched_throttle_work;
6945 	INIT_LIST_HEAD(&p->throttle_node);
6946 }
6947 
6948 /*
6949  * Task is throttled and someone wants to dequeue it again:
6950  * it could be sched/core when core needs to do things like
6951  * task affinity change, task group change, task sched class
6952  * change etc. and in these cases, DEQUEUE_SLEEP is not set;
6953  * or the task is blocked after throttled due to freezer etc.
6954  * and in these cases, DEQUEUE_SLEEP is set.
6955  */
6956 static void detach_task_cfs_rq(struct task_struct *p);
6957 static void dequeue_throttled_task(struct task_struct *p, int flags)
6958 {
6959 	WARN_ON_ONCE(p->se.on_rq);
6960 	list_del_init(&p->throttle_node);
6961 
6962 	/* Task blocked after throttling or is leaving the fair class: */
6963 	if (flags & (DEQUEUE_SLEEP | DEQUEUE_CLASS)) {
6964 		p->throttled = false;
6965 		return;
6966 	}
6967 
6968 	/*
6969 	 * task is migrating off its old cfs_rq, detach
6970 	 * the task's load from its old cfs_rq.
6971 	 */
6972 	if (task_on_rq_migrating(p))
6973 		detach_task_cfs_rq(p);
6974 }
6975 
6976 static bool enqueue_throttled_task(struct task_struct *p)
6977 {
6978 	struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
6979 
6980 	/* @p should have gone through dequeue_throttled_task() first */
6981 	WARN_ON_ONCE(!list_empty(&p->throttle_node));
6982 
6983 	/*
6984 	 * If the throttled task @p is enqueued to a throttled cfs_rq,
6985 	 * take the fast path by directly putting the task on the
6986 	 * target cfs_rq's limbo list.
6987 	 *
6988 	 * Do not do that when @p is current because the following race can
6989 	 * cause @p's group_node to be incorectly re-insterted in its rq's
6990 	 * cfs_tasks list, despite being throttled:
6991 	 *
6992 	 *     cpuX                       cpuY
6993 	 *   p ret2user
6994 	 *  throttle_cfs_rq_work()  sched_move_task(p)
6995 	 *  LOCK task_rq_lock
6996 	 *  dequeue_task_fair(p)
6997 	 *  UNLOCK task_rq_lock
6998 	 *                          LOCK task_rq_lock
6999 	 *                          task_current_donor(p) == true
7000 	 *                          task_on_rq_queued(p) == true
7001 	 *                          dequeue_task(p)
7002 	 *                          put_prev_task(p)
7003 	 *                          sched_change_group()
7004 	 *                          enqueue_task(p) -> p's new cfs_rq
7005 	 *                                             is throttled, go
7006 	 *                                             fast path and skip
7007 	 *                                             actual enqueue
7008 	 *                          set_next_task(p)
7009 	 *                    list_move(&se->group_node, &rq->cfs_tasks); // bug
7010 	 *  schedule()
7011 	 *
7012 	 * In the above race case, @p current cfs_rq is in the same rq as
7013 	 * its previous cfs_rq because sched_move_task() only moves a task
7014 	 * to a different group from the same rq, so we can use its current
7015 	 * cfs_rq to derive rq and test if the task is current.
7016 	 */
7017 	if (throttled_hierarchy(cfs_rq) &&
7018 	    !task_current_donor(rq_of(cfs_rq), p)) {
7019 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
7020 		return true;
7021 	}
7022 
7023 	/* we can't take the fast path, do an actual enqueue*/
7024 	p->throttled = false;
7025 	return false;
7026 }
7027 
7028 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
7029 static int tg_unthrottle_up(struct task_group *tg, void *data)
7030 {
7031 	struct rq *rq = data;
7032 	struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7033 	struct task_struct *p, *tmp;
7034 	LIST_HEAD(throttled_tasks);
7035 
7036 	/*
7037 	 * If cfs_rq->curr is set, the cfs_rq might not have caught up
7038 	 * since the last clock update. Do it now before we begin
7039 	 * queueing task onto it to save the need for unnecessarily
7040 	 * unthrottle the hierarchy for this cfs_rq to be throttled
7041 	 * right back again.
7042 	 */
7043 	update_curr(cfs_rq);
7044 
7045 	if (--cfs_rq->throttle_count)
7046 		return 0;
7047 
7048 	if (cfs_rq->pelt_clock_throttled) {
7049 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
7050 					     cfs_rq->throttled_clock_pelt;
7051 		cfs_rq->pelt_clock_throttled = 0;
7052 	}
7053 
7054 	if (cfs_rq->throttled_clock_self) {
7055 		u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
7056 
7057 		cfs_rq->throttled_clock_self = 0;
7058 
7059 		if (WARN_ON_ONCE((s64)delta < 0))
7060 			delta = 0;
7061 
7062 		cfs_rq->throttled_clock_self_time += delta;
7063 	}
7064 
7065 	/*
7066 	 * Move the tasks to a local list since an update_curr() during
7067 	 * enqueue_task_fair() can throttle a higher cfs_rq, and it can
7068 	 * see the "throttled_limbo_list" being non-empty in
7069 	 * tg_throttle_down() if throttle_count turned 0 above.
7070 	 */
7071 	list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks);
7072 
7073 	/* Re-enqueue the tasks that have been throttled at this level. */
7074 	list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) {
7075 		/*
7076 		 * Back to being throttled! Break out and put the remaining
7077 		 * tasks back onto the limbo_list to prevent running them
7078 		 * unnecessarily.
7079 		 */
7080 		if (cfs_rq->throttle_count)
7081 			break;
7082 
7083 		list_del_init(&p->throttle_node);
7084 		p->throttled = false;
7085 		enqueue_task_fair(rq, p, ENQUEUE_WAKEUP);
7086 	}
7087 
7088 	list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list);
7089 
7090 	/* Add cfs_rq with load or one or more already running entities to the list */
7091 	if (!cfs_rq_is_decayed(cfs_rq))
7092 		list_add_leaf_cfs_rq(cfs_rq);
7093 
7094 	return 0;
7095 }
7096 
7097 static inline bool task_has_throttle_work(struct task_struct *p)
7098 {
7099 	return p->sched_throttle_work.next != &p->sched_throttle_work;
7100 }
7101 
7102 static inline void task_throttle_setup_work(struct task_struct *p)
7103 {
7104 	if (task_has_throttle_work(p))
7105 		return;
7106 
7107 	/*
7108 	 * Kthreads and exiting tasks don't return to userspace, so adding the
7109 	 * work is pointless
7110 	 */
7111 	if ((p->flags & (PF_EXITING | PF_KTHREAD)))
7112 		return;
7113 
7114 	task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
7115 }
7116 
7117 static void record_throttle_clock(struct cfs_rq *cfs_rq)
7118 {
7119 	struct rq *rq = rq_of(cfs_rq);
7120 
7121 	if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
7122 		cfs_rq->throttled_clock = rq_clock(rq);
7123 
7124 	if (!cfs_rq->throttled_clock_self)
7125 		cfs_rq->throttled_clock_self = rq_clock(rq);
7126 }
7127 
7128 static int tg_throttle_down(struct task_group *tg, void *data)
7129 {
7130 	struct rq *rq = data;
7131 	struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7132 
7133 	if (cfs_rq->throttle_count++)
7134 		return 0;
7135 
7136 	/*
7137 	 * For cfs_rqs that still have entities enqueued, PELT clock
7138 	 * stop happens at dequeue time when all entities are dequeued.
7139 	 */
7140 	if (!cfs_rq->nr_queued) {
7141 		list_del_leaf_cfs_rq(cfs_rq);
7142 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
7143 		cfs_rq->pelt_clock_throttled = 1;
7144 	}
7145 
7146 	WARN_ON_ONCE(cfs_rq->throttled_clock_self);
7147 	WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
7148 	return 0;
7149 }
7150 
7151 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
7152 {
7153 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7154 	struct sched_entity *curr = cfs_rq->h_curr;
7155 	struct rq *rq = rq_of(cfs_rq);
7156 
7157 	scoped_guard(raw_spinlock, &cfs_b->lock) {
7158 		u64 target_runtime = 1;
7159 
7160 		/*
7161 		 * If cfs_rq->h_curr is still runnable, we are here from an
7162 		 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice
7163 		 * worth of bandwidth to continue running.
7164 		 *
7165 		 * If the curr is not runnable, just request enough bandwidth
7166 		 * to be runnable next time the pick selects this cfs_rq.
7167 		 */
7168 		if (curr && curr->on_rq)
7169 			target_runtime = sched_cfs_bandwidth_slice();
7170 
7171 		/*
7172 		 * Check if We have raced with bandwidth becoming available. If
7173 		 * we actually throttled the timer might not unthrottle us for
7174 		 * an entire period. We additionally needed to make sure that
7175 		 * any subsequent check_cfs_rq_runtime calls agree not to
7176 		 * throttle us, as we may commit to do cfs put_prev+pick_next,
7177 		 * so we ask for 1ns of runtime rather than just check cfs_b.
7178 		 *
7179 		 * This will start the period timer if necessary.
7180 		 */
7181 		if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime))
7182 			return false;
7183 
7184 		/*
7185 		 * No bandwidth available; Add ourselves on the list to be
7186 		 * unthrottled later.
7187 		 */
7188 		list_add_tail_rcu(&cfs_rq->throttled_list,
7189 				  &cfs_b->throttled_cfs_rq);
7190 	}
7191 
7192 	/* freeze hierarchy runnable averages while throttled */
7193 	scoped_guard(rcu)
7194 		walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
7195 
7196 	/*
7197 	 * Note: distribution will already see us throttled via the
7198 	 * throttled-list.  rq->lock protects completion.
7199 	 */
7200 	cfs_rq->throttled = 1;
7201 	WARN_ON_ONCE(cfs_rq->throttled_clock);
7202 
7203 	/*
7204 	 * If current hierarchy was throttled, add throttle work to the
7205 	 * current donor. In case of proxy-execution, the execution
7206 	 * context cannot exit to the userspace while holding a mutex
7207 	 * and the rule of throttle deferral to only throttle the
7208 	 * throttled context at exit to userspace is still preserved.
7209 	 */
7210 	if (curr && curr->on_rq)
7211 		task_throttle_setup_work(rq->donor);
7212 
7213 	return true;
7214 }
7215 
7216 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
7217 {
7218 	struct rq *rq = rq_of(cfs_rq);
7219 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7220 	struct sched_entity *se = cfs_rq_se(cfs_rq);
7221 
7222 	/*
7223 	 * It's possible we are called with runtime_remaining < 0 due to things
7224 	 * like async unthrottled us with a positive runtime_remaining but other
7225 	 * still running entities consumed those runtime before we reached here.
7226 	 *
7227 	 * We can't unthrottle this cfs_rq without any runtime remaining because
7228 	 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
7229 	 * which is not supposed to happen on unthrottle path.
7230 	 *
7231 	 * Catch up on the remaining runtime since last clock update before
7232 	 * checking runtime remaining.
7233 	 */
7234 	update_curr(cfs_rq);
7235 	if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
7236 		return;
7237 
7238 	cfs_rq->throttled = 0;
7239 
7240 	scoped_guard(raw_spinlock, &cfs_b->lock) {
7241 		list_del_rcu(&cfs_rq->throttled_list);
7242 
7243 		if (!cfs_rq->throttled_clock)
7244 			break;
7245 
7246 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
7247 		cfs_rq->throttled_clock = 0;
7248 	}
7249 
7250 	/* update hierarchical throttle state */
7251 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
7252 
7253 	if (!cfs_rq->load.weight) {
7254 		if (!cfs_rq->on_list)
7255 			return;
7256 		/*
7257 		 * Nothing to run but something to decay (on_list)?
7258 		 * Complete the branch.
7259 		 */
7260 		for_each_sched_entity(se) {
7261 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
7262 				break;
7263 		}
7264 	}
7265 
7266 	assert_list_leaf_cfs_rq(rq);
7267 
7268 	/* Determine whether we need to wake up potentially idle CPU: */
7269 	if (rq->curr == rq->idle && rq->cfs.h_nr_queued)
7270 		resched_curr(rq);
7271 }
7272 
7273 static void __cfsb_csd_unthrottle(void *arg)
7274 {
7275 	struct cfs_rq *cursor, *tmp;
7276 	struct rq *rq = arg;
7277 
7278 	guard(rq_lock)(rq);
7279 
7280 	/*
7281 	 * Iterating over the list can trigger several call to
7282 	 * update_rq_clock() in unthrottle_cfs_rq().
7283 	 * Do it once and skip the potential next ones.
7284 	 */
7285 	update_rq_clock(rq);
7286 	rq_clock_start_loop_update(rq);
7287 
7288 	/*
7289 	 * Since we hold rq lock we're safe from concurrent manipulation of
7290 	 * the CSD list. However, this RCU critical section annotates the
7291 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
7292 	 * race with group being freed in the window between removing it
7293 	 * from the list and advancing to the next entry in the list.
7294 	 */
7295 	guard(rcu)();
7296 
7297 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
7298 				 throttled_csd_list) {
7299 		list_del_init(&cursor->throttled_csd_list);
7300 
7301 		if (cfs_rq_throttled(cursor))
7302 			unthrottle_cfs_rq(cursor);
7303 	}
7304 
7305 	rq_clock_stop_loop_update(rq);
7306 }
7307 
7308 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7309 {
7310 	struct rq *rq = rq_of(cfs_rq);
7311 	bool first;
7312 
7313 	if (rq == this_rq()) {
7314 		update_rq_clock(rq);
7315 		unthrottle_cfs_rq(cfs_rq);
7316 		return;
7317 	}
7318 
7319 	/* Already enqueued */
7320 	if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
7321 		return;
7322 
7323 	first = list_empty(&rq->cfsb_csd_list);
7324 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7325 	if (first)
7326 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
7327 }
7328 
7329 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7330 {
7331 	lockdep_assert_rq_held(rq_of(cfs_rq));
7332 
7333 	if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
7334 	    cfs_rq->runtime_remaining <= 0))
7335 		return;
7336 
7337 	__unthrottle_cfs_rq_async(cfs_rq);
7338 }
7339 
7340 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
7341 {
7342 	bool throttled = false, unthrottle_local = false;
7343 	int this_cpu = smp_processor_id();
7344 	u64 runtime, remaining = 1;
7345 	struct cfs_rq *cfs_rq;
7346 	struct rq *rq;
7347 
7348 	guard(rcu)();
7349 
7350 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
7351 				throttled_list) {
7352 		rq = rq_of(cfs_rq);
7353 
7354 		if (!remaining) {
7355 			throttled = true;
7356 			break;
7357 		}
7358 
7359 		guard(rq_lock_irqsave)(rq);
7360 
7361 		if (!cfs_rq_throttled(cfs_rq))
7362 			continue;
7363 
7364 		/* Already queued for async unthrottle */
7365 		if (!list_empty(&cfs_rq->throttled_csd_list))
7366 			continue;
7367 
7368 		if (cfs_rq->h_curr) {
7369 			update_rq_clock(rq);
7370 			update_curr(cfs_rq);
7371 		}
7372 
7373 		/* By the above checks, this should never be true */
7374 		WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
7375 
7376 		scoped_guard(raw_spinlock, &cfs_b->lock) {
7377 			runtime = -cfs_rq->runtime_remaining + 1;
7378 			if (runtime > cfs_b->runtime)
7379 				runtime = cfs_b->runtime;
7380 			cfs_b->runtime -= runtime;
7381 			remaining = cfs_b->runtime;
7382 		}
7383 
7384 		cfs_rq->runtime_remaining += runtime;
7385 
7386 		/*
7387 		 * Ran out of bandwidth during distribution!
7388 		 * Indicate throttled entities and break early.
7389 		 */
7390 		if (cfs_rq->runtime_remaining <= 0) {
7391 			throttled = true;
7392 			break;
7393 		}
7394 
7395 		/* we check whether we're throttled above */
7396 		if (cpu_of(rq) != this_cpu) {
7397 			unthrottle_cfs_rq_async(cfs_rq);
7398 			continue;
7399 		}
7400 
7401 		/*
7402 		 * Allow a parallel async unthrottle to unthrottle
7403 		 * this cfs_rq too via __cfsb_csd_unthrottle().
7404 		 * If we are first, do it ourselves at the end and
7405 		 * save on an IPI from remote CPUs.
7406 		 */
7407 		unthrottle_local = list_empty(&rq->cfsb_csd_list);
7408 		list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7409 	}
7410 
7411 	if (unthrottle_local) {
7412 		/*
7413 		 * Protect against an IPI that is also trying to flush
7414 		 * the unthrottled cfs_rq(s) from this CPU's csd_list.
7415 		 */
7416 		scoped_guard(irqsave)
7417 			__cfsb_csd_unthrottle(cpu_rq(this_cpu));
7418 	}
7419 
7420 	return throttled;
7421 }
7422 
7423 /*
7424  * Responsible for refilling a task_group's bandwidth and unthrottling its
7425  * cfs_rqs as appropriate. If there has been no activity within the last
7426  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
7427  * used to track this state.
7428  */
7429 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
7430 	__must_hold(&cfs_b->lock)
7431 {
7432 	int throttled;
7433 
7434 	/* no need to continue the timer with no bandwidth constraint */
7435 	if (cfs_b->quota == RUNTIME_INF)
7436 		goto out_deactivate;
7437 
7438 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
7439 	cfs_b->nr_periods += overrun;
7440 
7441 	/* Refill extra burst quota even if cfs_b->idle */
7442 	__refill_cfs_bandwidth_runtime(cfs_b);
7443 
7444 	/*
7445 	 * idle depends on !throttled (for the case of a large deficit), and if
7446 	 * we're going inactive then everything else can be deferred
7447 	 */
7448 	if (cfs_b->idle && !throttled)
7449 		goto out_deactivate;
7450 
7451 	if (!throttled) {
7452 		/* mark as potentially idle for the upcoming period */
7453 		cfs_b->idle = 1;
7454 		return 0;
7455 	}
7456 
7457 	/* account preceding periods in which throttling occurred */
7458 	cfs_b->nr_throttled += overrun;
7459 
7460 	/*
7461 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
7462 	 */
7463 	while (throttled && cfs_b->runtime > 0) {
7464 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
7465 		/* we can't nest cfs_b->lock while distributing bandwidth */
7466 		throttled = distribute_cfs_runtime(cfs_b);
7467 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
7468 	}
7469 
7470 	/*
7471 	 * While we are ensured activity in the period following an
7472 	 * unthrottle, this also covers the case in which the new bandwidth is
7473 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
7474 	 * timer to remain active while there are any throttled entities.)
7475 	 */
7476 	cfs_b->idle = 0;
7477 
7478 	return 0;
7479 
7480 out_deactivate:
7481 	return 1;
7482 }
7483 
7484 /* a cfs_rq won't donate quota below this amount */
7485 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
7486 /* minimum remaining period time to redistribute slack quota */
7487 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
7488 /* how long we wait to gather additional slack before distributing */
7489 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
7490 
7491 /*
7492  * Are we near the end of the current quota period?
7493  *
7494  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
7495  * hrtimer base being cleared by hrtimer_start. In the case of
7496  * migrate_hrtimers, base is never cleared, so we are fine.
7497  */
7498 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
7499 {
7500 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
7501 	s64 remaining;
7502 
7503 	/* if the call-back is running a quota refresh is already occurring */
7504 	if (hrtimer_callback_running(refresh_timer))
7505 		return 1;
7506 
7507 	/* is a quota refresh about to occur? */
7508 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
7509 	if (remaining < (s64)min_expire)
7510 		return 1;
7511 
7512 	return 0;
7513 }
7514 
7515 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
7516 {
7517 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
7518 
7519 	/* if there's a quota refresh soon don't bother with slack */
7520 	if (runtime_refresh_within(cfs_b, min_left))
7521 		return;
7522 
7523 	/* don't push forwards an existing deferred unthrottle */
7524 	if (cfs_b->slack_started)
7525 		return;
7526 	cfs_b->slack_started = true;
7527 
7528 	hrtimer_start(&cfs_b->slack_timer,
7529 			ns_to_ktime(cfs_bandwidth_slack_period),
7530 			HRTIMER_MODE_REL);
7531 }
7532 
7533 /* we know any runtime found here is valid as update_curr() precedes return */
7534 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7535 {
7536 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7537 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
7538 
7539 	if (slack_runtime <= 0)
7540 		return;
7541 
7542 	guard(raw_spinlock)(&cfs_b->lock);
7543 
7544 	if (cfs_b->quota != RUNTIME_INF) {
7545 		cfs_b->runtime += slack_runtime;
7546 
7547 		/* we are under rq->lock, defer unthrottling using a timer */
7548 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
7549 		    !list_empty(&cfs_b->throttled_cfs_rq))
7550 			start_cfs_slack_bandwidth(cfs_b);
7551 	}
7552 
7553 	/* even if it's not valid for return we don't want to try again */
7554 	cfs_rq->runtime_remaining -= slack_runtime;
7555 }
7556 
7557 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7558 {
7559 	if (!cfs_bandwidth_used())
7560 		return;
7561 
7562 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
7563 		return;
7564 
7565 	__return_cfs_rq_runtime(cfs_rq);
7566 }
7567 
7568 /*
7569  * This is done with a timer (instead of inline with bandwidth return) since
7570  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
7571  */
7572 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
7573 {
7574 	/* confirm we're still not at a refresh boundary */
7575 	scoped_guard(raw_spinlock_irqsave, &cfs_b->lock) {
7576 		u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
7577 
7578 		cfs_b->slack_started = false;
7579 
7580 		if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
7581 			return;
7582 
7583 		if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
7584 			runtime = cfs_b->runtime;
7585 
7586 		if (!runtime)
7587 			return;
7588 	}
7589 
7590 	distribute_cfs_runtime(cfs_b);
7591 }
7592 
7593 /*
7594  * When a group wakes up we want to make sure that its quota is not already
7595  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
7596  * runtime as update_curr() throttling can not trigger until it's on-rq.
7597  */
7598 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
7599 {
7600 	if (!cfs_bandwidth_used())
7601 		return;
7602 
7603 	/* an active group must be handled by the update_curr() path */
7604 	if (!cfs_rq->runtime_enabled || cfs_rq->h_curr)
7605 		return;
7606 
7607 	/* ensure the group is not already throttled */
7608 	if (cfs_rq_throttled(cfs_rq))
7609 		return;
7610 
7611 	/* update runtime allocation */
7612 	account_cfs_rq_runtime(cfs_rq, 0);
7613 }
7614 
7615 static void sync_throttle(struct task_group *tg, int cpu)
7616 {
7617 	struct cfs_rq *pcfs_rq, *cfs_rq;
7618 
7619 	if (!cfs_bandwidth_used())
7620 		return;
7621 
7622 	if (!tg->parent)
7623 		return;
7624 
7625 	cfs_rq = tg_cfs_rq(tg, cpu);
7626 	pcfs_rq = tg_cfs_rq(tg->parent, cpu);
7627 
7628 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
7629 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
7630 
7631 	/*
7632 	 * It is not enough to sync the "pelt_clock_throttled" indicator
7633 	 * with the parent cfs_rq when the hierarchy is not queued.
7634 	 * Always join a throttled hierarchy with PELT clock throttled
7635 	 * and leaf it to the first enqueue, or distribution to
7636 	 * unthrottle the PELT clock.
7637 	 */
7638 	if (cfs_rq->throttle_count)
7639 		cfs_rq->pelt_clock_throttled = 1;
7640 }
7641 
7642 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
7643 {
7644 	struct cfs_bandwidth *cfs_b =
7645 		container_of(timer, struct cfs_bandwidth, slack_timer);
7646 
7647 	do_sched_cfs_slack_timer(cfs_b);
7648 
7649 	return HRTIMER_NORESTART;
7650 }
7651 
7652 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
7653 {
7654 	struct cfs_bandwidth *cfs_b =
7655 		container_of(timer, struct cfs_bandwidth, period_timer);
7656 	int overrun;
7657 	int idle = 0;
7658 	int count = 0;
7659 
7660 	CLASS(raw_spinlock_irqsave, cfsb_guard)(&cfs_b->lock);
7661 
7662 	for (;;) {
7663 		overrun = hrtimer_forward_now(timer, cfs_b->period);
7664 		if (!overrun)
7665 			break;
7666 
7667 		idle = do_sched_cfs_period_timer(cfs_b, overrun, cfsb_guard.flags);
7668 
7669 		if (++count > 3) {
7670 			u64 new, old = ktime_to_ns(cfs_b->period);
7671 
7672 			/*
7673 			 * Grow period by a factor of 2 to avoid losing precision.
7674 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
7675 			 * to fail.
7676 			 */
7677 			new = old * 2;
7678 			if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
7679 				cfs_b->period = ns_to_ktime(new);
7680 				cfs_b->quota *= 2;
7681 				cfs_b->burst *= 2;
7682 
7683 				pr_warn_ratelimited(
7684 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7685 					smp_processor_id(),
7686 					div_u64(new, NSEC_PER_USEC),
7687 					div_u64(cfs_b->quota, NSEC_PER_USEC));
7688 			} else {
7689 				pr_warn_ratelimited(
7690 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7691 					smp_processor_id(),
7692 					div_u64(old, NSEC_PER_USEC),
7693 					div_u64(cfs_b->quota, NSEC_PER_USEC));
7694 			}
7695 
7696 			/* reset count so we don't come right back in here */
7697 			count = 0;
7698 		}
7699 	}
7700 
7701 	if (idle) {
7702 		cfs_b->period_active = 0;
7703 		return HRTIMER_NORESTART;
7704 	}
7705 
7706 	return HRTIMER_RESTART;
7707 }
7708 
7709 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
7710 {
7711 	raw_spin_lock_init(&cfs_b->lock);
7712 	cfs_b->runtime = 0;
7713 	cfs_b->quota = RUNTIME_INF;
7714 	cfs_b->period = us_to_ktime(default_bw_period_us());
7715 	cfs_b->burst = 0;
7716 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
7717 
7718 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
7719 	hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
7720 		      HRTIMER_MODE_ABS_PINNED);
7721 
7722 	/* Add a random offset so that timers interleave */
7723 	hrtimer_set_expires(&cfs_b->period_timer,
7724 			    get_random_u32_below(cfs_b->period));
7725 	hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
7726 		      HRTIMER_MODE_REL);
7727 	cfs_b->slack_started = false;
7728 }
7729 
7730 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7731 {
7732 	cfs_rq->runtime_enabled = 0;
7733 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
7734 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
7735 	INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
7736 }
7737 
7738 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7739 {
7740 	lockdep_assert_held(&cfs_b->lock);
7741 
7742 	if (cfs_b->period_active)
7743 		return;
7744 
7745 	cfs_b->period_active = 1;
7746 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
7747 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
7748 }
7749 
7750 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7751 {
7752 	int __maybe_unused i;
7753 
7754 	/* init_cfs_bandwidth() was not called */
7755 	if (!cfs_b->throttled_cfs_rq.next)
7756 		return;
7757 
7758 	hrtimer_cancel(&cfs_b->period_timer);
7759 	hrtimer_cancel(&cfs_b->slack_timer);
7760 
7761 	/*
7762 	 * It is possible that we still have some cfs_rq's pending on a CSD
7763 	 * list, though this race is very rare. In order for this to occur, we
7764 	 * must have raced with the last task leaving the group while there
7765 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
7766 	 * CSD item but the remote cpu has not yet processed it. To handle this,
7767 	 * we can simply flush all pending CSD work inline here. We're
7768 	 * guaranteed at this point that no additional cfs_rq of this group can
7769 	 * join a CSD list.
7770 	 */
7771 	for_each_possible_cpu(i) {
7772 		struct rq *rq = cpu_rq(i);
7773 
7774 		if (list_empty(&rq->cfsb_csd_list))
7775 			continue;
7776 
7777 		scoped_guard(irqsave)
7778 			__cfsb_csd_unthrottle(rq);
7779 	}
7780 }
7781 
7782 /*
7783  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
7784  *
7785  * The race is harmless, since modifying bandwidth settings of unhooked group
7786  * bits doesn't do much.
7787  */
7788 
7789 /* cpu online callback */
7790 static void __maybe_unused update_runtime_enabled(struct rq *rq)
7791 {
7792 	struct task_group *tg;
7793 
7794 	lockdep_assert_rq_held(rq);
7795 
7796 	guard(rcu)();
7797 
7798 	list_for_each_entry_rcu(tg, &task_groups, list) {
7799 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7800 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7801 
7802 		scoped_guard(raw_spinlock, &cfs_b->lock)
7803 			cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
7804 	}
7805 }
7806 
7807 /* cpu offline callback */
7808 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
7809 {
7810 	struct task_group *tg;
7811 
7812 	lockdep_assert_rq_held(rq);
7813 
7814 	// Do not unthrottle for an active CPU
7815 	if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
7816 		return;
7817 
7818 	/*
7819 	 * The rq clock has already been updated in the
7820 	 * set_rq_offline(), so we should skip updating
7821 	 * the rq clock again in unthrottle_cfs_rq().
7822 	 */
7823 	rq_clock_start_loop_update(rq);
7824 
7825 	guard(rcu)();
7826 
7827 	list_for_each_entry_rcu(tg, &task_groups, list) {
7828 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7829 
7830 		if (!cfs_rq->runtime_enabled)
7831 			continue;
7832 
7833 		/*
7834 		 * Offline rq is schedulable till CPU is completely disabled
7835 		 * in take_cpu_down(), so we prevent new cfs throttling here.
7836 		 */
7837 		cfs_rq->runtime_enabled = 0;
7838 
7839 		if (!cfs_rq_throttled(cfs_rq))
7840 			continue;
7841 
7842 		/*
7843 		 * clock_task is not advancing so we just need to make sure
7844 		 * there's some valid quota amount
7845 		 */
7846 		cfs_rq->runtime_remaining = 1;
7847 		unthrottle_cfs_rq(cfs_rq);
7848 	}
7849 
7850 	rq_clock_stop_loop_update(rq);
7851 }
7852 
7853 bool cfs_task_bw_constrained(struct task_struct *p)
7854 {
7855 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
7856 
7857 	if (!cfs_bandwidth_used())
7858 		return false;
7859 
7860 	if (cfs_rq->runtime_enabled ||
7861 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
7862 		return true;
7863 
7864 	return false;
7865 }
7866 
7867 #ifdef CONFIG_NO_HZ_FULL
7868 /* called from pick_next_task_fair() */
7869 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
7870 {
7871 	int cpu = cpu_of(rq);
7872 
7873 	if (!cfs_bandwidth_used())
7874 		return;
7875 
7876 	if (!tick_nohz_full_cpu(cpu))
7877 		return;
7878 
7879 	if (rq->nr_running != 1)
7880 		return;
7881 
7882 	/*
7883 	 *  We know there is only one task runnable and we've just picked it. The
7884 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
7885 	 *  be otherwise able to stop the tick. Just need to check if we are using
7886 	 *  bandwidth control.
7887 	 */
7888 	if (cfs_task_bw_constrained(p))
7889 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
7890 }
7891 #endif /* CONFIG_NO_HZ_FULL */
7892 
7893 #else /* !CONFIG_CFS_BANDWIDTH: */
7894 
7895 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; }
7896 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
7897 static inline void sync_throttle(struct task_group *tg, int cpu) {}
7898 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
7899 static void task_throttle_setup_work(struct task_struct *p) {}
7900 static bool task_is_throttled(struct task_struct *p) { return false; }
7901 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
7902 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
7903 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
7904 
7905 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
7906 {
7907 	return 0;
7908 }
7909 
7910 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
7911 {
7912 	return false;
7913 }
7914 
7915 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
7916 {
7917 	return 0;
7918 }
7919 
7920 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
7921 {
7922 	return 0;
7923 }
7924 
7925 #ifdef CONFIG_FAIR_GROUP_SCHED
7926 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
7927 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
7928 #endif
7929 
7930 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
7931 {
7932 	return NULL;
7933 }
7934 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
7935 static inline void update_runtime_enabled(struct rq *rq) {}
7936 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
7937 #ifdef CONFIG_CGROUP_SCHED
7938 bool cfs_task_bw_constrained(struct task_struct *p)
7939 {
7940 	return false;
7941 }
7942 #endif
7943 #endif /* !CONFIG_CFS_BANDWIDTH */
7944 
7945 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
7946 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
7947 #endif
7948 
7949 /**************************************************
7950  * CFS operations on tasks:
7951  */
7952 
7953 #ifdef CONFIG_SCHED_HRTICK
7954 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
7955 {
7956 	struct sched_entity *se = &p->se;
7957 	unsigned long scale = 1024;
7958 	unsigned long util = 0;
7959 	u64 vdelta;
7960 	u64 delta;
7961 
7962 	WARN_ON_ONCE(task_rq(p) != rq);
7963 
7964 	if (rq->cfs.h_nr_queued <= 1)
7965 		return;
7966 
7967 	/*
7968 	 * Compute time until virtual deadline
7969 	 */
7970 	vdelta = se->deadline - se->vruntime;
7971 	if ((s64)vdelta < 0) {
7972 		if (task_current_donor(rq, p))
7973 			resched_curr(rq);
7974 		return;
7975 	}
7976 	delta = (se->h_load.weight * vdelta) / NICE_0_LOAD;
7977 
7978 	/*
7979 	 * Correct for instantaneous load of other classes.
7980 	 */
7981 	util += cpu_util_irq(rq);
7982 	if (util && util < 1024) {
7983 		scale *= 1024;
7984 		scale /= (1024 - util);
7985 	}
7986 
7987 	hrtick_start(rq, (scale * delta) / 1024);
7988 }
7989 
7990 /*
7991  * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1.
7992  */
7993 static void hrtick_update(struct rq *rq)
7994 {
7995 	struct task_struct *donor = rq->donor;
7996 
7997 	if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
7998 		return;
7999 
8000 	if (hrtick_active(rq))
8001 		return;
8002 
8003 	hrtick_start_fair(rq, donor);
8004 }
8005 #else /* !CONFIG_SCHED_HRTICK: */
8006 static inline void
8007 hrtick_start_fair(struct rq *rq, struct task_struct *p)
8008 {
8009 }
8010 
8011 static inline void hrtick_update(struct rq *rq)
8012 {
8013 }
8014 #endif /* !CONFIG_SCHED_HRTICK */
8015 
8016 static inline bool cpu_overutilized(int cpu)
8017 {
8018 	unsigned long rq_util_max;
8019 
8020 	if (!sched_energy_enabled())
8021 		return false;
8022 
8023 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
8024 
8025 	/* Return true only if the utilization doesn't fit CPU's capacity */
8026 	return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu);
8027 }
8028 
8029 /*
8030  * overutilized value make sense only if EAS is enabled
8031  */
8032 static inline bool is_rd_overutilized(struct root_domain *rd)
8033 {
8034 	return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
8035 }
8036 
8037 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
8038 {
8039 	if (!sched_energy_enabled())
8040 		return;
8041 
8042 	WRITE_ONCE(rd->overutilized, flag);
8043 	trace_sched_overutilized_tp(rd, flag);
8044 }
8045 
8046 static inline void check_update_overutilized_status(struct rq *rq)
8047 {
8048 	/*
8049 	 * overutilized field is used for load balancing decisions only
8050 	 * if energy aware scheduler is being used
8051 	 */
8052 
8053 	if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
8054 		set_rd_overutilized(rq->rd, 1);
8055 }
8056 
8057 /* Runqueue only has SCHED_IDLE tasks enqueued */
8058 static int sched_idle_rq(struct rq *rq)
8059 {
8060 	return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
8061 			rq->nr_running);
8062 }
8063 
8064 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p)
8065 {
8066 	return sched_idle_rq(rq) && !task_has_idle_policy(p);
8067 }
8068 
8069 static int choose_idle_cpu(int cpu, struct task_struct *p)
8070 {
8071 	return available_idle_cpu(cpu) ||
8072 	       choose_sched_idle_rq(cpu_rq(cpu), p);
8073 }
8074 
8075 static void
8076 requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
8077 {
8078 	/*
8079 	 * se->sched_delayed should imply: se->on_rq == 1.
8080 	 * Because a delayed entity is one that is still on
8081 	 * the runqueue competing until elegibility.
8082 	 */
8083 	WARN_ON_ONCE(!se->sched_delayed);
8084 	WARN_ON_ONCE(!se->on_rq);
8085 
8086 	if (update_entity_lag(cfs_rq, se)) {
8087 		cfs_rq->h_nr_queued--;
8088 		if (se != cfs_rq->curr)
8089 			__dequeue_entity(cfs_rq, se);
8090 		place_entity(cfs_rq, se, 0);
8091 		if (se != cfs_rq->curr)
8092 			__enqueue_entity(cfs_rq, se);
8093 		cfs_rq->h_nr_queued++;
8094 	}
8095 
8096 	update_load_avg(cfs_rq, se, 0);
8097 	clear_delayed(se);
8098 }
8099 
8100 static unsigned long enqueue_hierarchy(struct task_struct *p, int flags)
8101 {
8102 	unsigned long weight = NICE_0_LOAD;
8103 	struct sched_entity *se = &p->se;
8104 	int h_nr_idle = task_has_idle_policy(p);
8105 	int h_nr_runnable = 1;
8106 
8107 	/*
8108 	 * Accounted via requeue_delayed_entity() calling
8109 	 * clear_delayed() when delayed task wakes up.
8110 	 */
8111 	if (se->sched_delayed)
8112 		h_nr_runnable = 0;
8113 
8114 	for_each_sched_entity(se) {
8115 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
8116 
8117 		update_curr(cfs_rq);
8118 
8119 		if (!se->on_rq) {
8120 			enqueue_entity(cfs_rq, se, flags);
8121 		} else {
8122 			update_load_avg(cfs_rq, se, UPDATE_TG);
8123 			se_update_runnable(se);
8124 			update_cfs_group(se);
8125 		}
8126 
8127 		cfs_rq->h_nr_runnable += h_nr_runnable;
8128 		cfs_rq->h_nr_queued++;
8129 		cfs_rq->h_nr_idle += h_nr_idle;
8130 
8131 		if (cfs_rq_is_idle(cfs_rq))
8132 			h_nr_idle = 1;
8133 
8134 		weight = __calc_prop_weight(cfs_rq, se, weight);
8135 
8136 		flags = ENQUEUE_WAKEUP;
8137 	}
8138 
8139 	return weight;
8140 }
8141 
8142 /* Update curr's vruntime before placing entity or updating lag */
8143 static inline void update_curr_eevdf(struct cfs_rq *cfs_rq)
8144 {
8145 	if (!cfs_rq->curr)
8146 		return;
8147 
8148 	update_curr(cfs_rq_of(cfs_rq->curr));
8149 }
8150 
8151 /*
8152  * The enqueue_task method is called before nr_running is
8153  * increased. Here we update the fair scheduling stats and
8154  * then put the task into the rbtree:
8155  */
8156 static void
8157 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
8158 {
8159 	int rq_h_nr_queued = rq->cfs.h_nr_queued;
8160 	int task_new = !(flags & ENQUEUE_WAKEUP);
8161 	struct sched_entity *se = &p->se;
8162 	struct cfs_rq *cfs_rq = &rq->cfs;
8163 	unsigned long weight;
8164 	bool curr;
8165 
8166 	if (task_is_throttled(p) && enqueue_throttled_task(p))
8167 		return;
8168 
8169 	/*
8170 	 * The code below (indirectly) updates schedutil which looks at
8171 	 * the cfs_rq utilization to select a frequency.
8172 	 * Let's add the task's estimated utilization to the cfs_rq's
8173 	 * estimated utilization, before we update schedutil.
8174 	 */
8175 	if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
8176 		util_est_enqueue(cfs_rq, p);
8177 
8178 	update_curr_eevdf(cfs_rq);
8179 
8180 	if (flags & ENQUEUE_DELAYED) {
8181 		requeue_delayed_entity(cfs_rq, se);
8182 		return;
8183 	}
8184 
8185 	/* Wakeup of delayed tasks must be handled above. */
8186 	WARN_ON_ONCE(!task_new && se->sched_delayed);
8187 
8188 	/*
8189 	 * If in_iowait is set, the code below may not trigger any cpufreq
8190 	 * utilization updates, so do it here explicitly with the IOWAIT flag
8191 	 * passed.
8192 	 */
8193 	if (p->in_iowait)
8194 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
8195 
8196 	curr = (cfs_rq->curr == se);
8197 	/*
8198 	 * This can actually happen with CFS_BANDWIDTH, a task can be throttled
8199 	 * and dequeued, unthrottled from another CPU and then enqueued again
8200 	 * before schedule().
8201 	 */
8202 	if (curr)
8203 		place_entity(cfs_rq, se, flags);
8204 
8205 	weight = enqueue_hierarchy(p, flags);
8206 
8207 	if (!curr) {
8208 		reweight_eevdf(cfs_rq, se, weight, false);
8209 		place_entity(cfs_rq, se, flags | ENQUEUE_QUEUED);
8210 		__enqueue_entity(cfs_rq, se);
8211 	}
8212 
8213 	if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
8214 		dl_server_start(&rq->fair_server);
8215 
8216 	/* At this point se is NULL and we are at root level*/
8217 	add_nr_running(rq, 1);
8218 
8219 	/*
8220 	 * Since new tasks are assigned an initial util_avg equal to
8221 	 * half of the spare capacity of their CPU, tiny tasks have the
8222 	 * ability to cross the overutilized threshold, which will
8223 	 * result in the load balancer ruining all the task placement
8224 	 * done by EAS. As a way to mitigate that effect, do not account
8225 	 * for the first enqueue operation of new tasks during the
8226 	 * overutilized flag detection.
8227 	 *
8228 	 * A better way of solving this problem would be to wait for
8229 	 * the PELT signals of tasks to converge before taking them
8230 	 * into account, but that is not straightforward to implement,
8231 	 * and the following generally works well enough in practice.
8232 	 */
8233 	if (!task_new)
8234 		check_update_overutilized_status(rq);
8235 
8236 	assert_list_leaf_cfs_rq(rq);
8237 
8238 	hrtick_update(rq);
8239 }
8240 
8241 static void dequeue_hierarchy(struct task_struct *p, int flags)
8242 {
8243 	struct sched_entity *se = &p->se;
8244 	bool task_throttled = flags & DEQUEUE_THROTTLE;
8245 	int h_nr_runnable = 0;
8246 	int h_nr_idle = task_has_idle_policy(p);
8247 	bool dequeue = true;
8248 
8249 	/* Already accounted via set_delayed(). */
8250 	if (se->sched_delayed)
8251 		h_nr_runnable = 0;
8252 
8253 	for_each_sched_entity(se) {
8254 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
8255 
8256 		update_curr(cfs_rq);
8257 
8258 		if (dequeue) {
8259 			dequeue_entity(cfs_rq, se, flags);
8260 			/* Don't dequeue parent if it has other entities besides us */
8261 			if (cfs_rq->load.weight)
8262 				dequeue = false;
8263 		} else {
8264 			update_load_avg(cfs_rq, se, UPDATE_TG);
8265 			se_update_runnable(se);
8266 			update_cfs_group(se);
8267 		}
8268 
8269 		cfs_rq->h_nr_runnable -= h_nr_runnable;
8270 		cfs_rq->h_nr_queued--;
8271 		cfs_rq->h_nr_idle -= h_nr_idle;
8272 
8273 		if (cfs_rq_is_idle(cfs_rq))
8274 			h_nr_idle = 1;
8275 
8276 		if (throttled_hierarchy(cfs_rq) && task_throttled)
8277 			record_throttle_clock(cfs_rq);
8278 
8279 		flags |= DEQUEUE_SLEEP;
8280 		flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
8281 	}
8282 }
8283 
8284 /*
8285  * The part of dequeue_task_fair() that is needed to dequeue delayed tasks.
8286  *
8287  * Returns:
8288  *   true  - dequeued
8289  *   false - delayed
8290  */
8291 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags)
8292 {
8293 	struct sched_entity *se = &p->se;
8294 	struct cfs_rq *cfs_rq = &rq->cfs;
8295 	bool was_sched_idle = sched_idle_rq(rq);
8296 	bool task_sleep = flags & DEQUEUE_SLEEP;
8297 	bool task_delayed = flags & DEQUEUE_DELAYED;
8298 
8299 	clear_buddies(cfs_rq, se);
8300 
8301 	update_curr_eevdf(cfs_rq);
8302 	update_entity_lag(cfs_rq, se);
8303 
8304 	if (flags & DEQUEUE_DELAYED) {
8305 		WARN_ON_ONCE(!se->sched_delayed);
8306 	} else {
8307 		bool delay = task_sleep;
8308 		/*
8309 		 * DELAY_DEQUEUE relies on spurious wakeups, special task
8310 		 * states must not suffer spurious wakeups, excempt them.
8311 		 */
8312 		if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
8313 			delay = false;
8314 
8315 		WARN_ON_ONCE(delay && se->sched_delayed);
8316 
8317 		if (sched_feat(DELAY_DEQUEUE) && delay &&
8318 		    !entity_eligible(cfs_rq, se)) {
8319 			update_load_avg(cfs_rq_of(se), se, UPDATE_UTIL_EST);
8320 			set_delayed(se);
8321 			return false;
8322 		}
8323 	}
8324 
8325 	dequeue_hierarchy(p, flags);
8326 
8327 	if (sched_feat(PLACE_REL_DEADLINE) && !task_sleep) {
8328 		se->deadline -= se->vruntime;
8329 		se->rel_deadline = 1;
8330 	}
8331 	if (se != cfs_rq->curr)
8332 		__dequeue_entity(cfs_rq, se);
8333 
8334 	sub_nr_running(rq, 1);
8335 
8336 	/* balance early to pull high priority tasks */
8337 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
8338 		rq->next_balance = jiffies;
8339 
8340 	if (task_delayed) {
8341 		/*
8342 		 * Skip accounting since set_delayed() has already
8343 		 * adjusted it. Just clear se->sched_delayed.
8344 		 */
8345 		__clear_delayed(se);
8346 
8347 		WARN_ON_ONCE(!task_sleep);
8348 		WARN_ON_ONCE(p->on_rq != 1);
8349 
8350 		/*
8351 		 * Fix-up what block_task() skipped.
8352 		 *
8353 		 * Must be last, @p might not be valid after this.
8354 		 */
8355 		__block_task(rq, p);
8356 	}
8357 
8358 	return true;
8359 }
8360 
8361 /*
8362  * The dequeue_task method is called before nr_running is
8363  * decreased. We remove the task from the rbtree and
8364  * update the fair scheduling stats:
8365  */
8366 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
8367 {
8368 	if (task_is_throttled(p)) {
8369 		dequeue_throttled_task(p, flags);
8370 		return true;
8371 	}
8372 
8373 	if (!p->se.sched_delayed)
8374 		util_est_dequeue(&rq->cfs, p);
8375 
8376 	if (!__dequeue_task(rq, p, flags))
8377 		return false;
8378 
8379 	/*
8380 	 * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED).
8381 	 */
8382 	return true;
8383 }
8384 
8385 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
8386 {
8387 	return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
8388 }
8389 
8390 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
8391 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
8392 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
8393 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
8394 
8395 #ifdef CONFIG_NO_HZ_COMMON
8396 
8397 static struct {
8398 	cpumask_var_t idle_cpus_mask;
8399 	int has_blocked_load;		/* Idle CPUS has blocked load */
8400 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
8401 	unsigned long next_balance;     /* in jiffy units */
8402 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
8403 } nohz ____cacheline_aligned;
8404 
8405 #endif /* CONFIG_NO_HZ_COMMON */
8406 
8407 static unsigned long cpu_load(struct rq *rq)
8408 {
8409 	return cfs_rq_load_avg(&rq->cfs);
8410 }
8411 
8412 /*
8413  * cpu_load_without - compute CPU load without any contributions from *p
8414  * @cpu: the CPU which load is requested
8415  * @p: the task which load should be discounted
8416  *
8417  * The load of a CPU is defined by the load of tasks currently enqueued on that
8418  * CPU as well as tasks which are currently sleeping after an execution on that
8419  * CPU.
8420  *
8421  * This method returns the load of the specified CPU by discounting the load of
8422  * the specified task, whenever the task is currently contributing to the CPU
8423  * load.
8424  */
8425 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
8426 {
8427 	struct cfs_rq *cfs_rq;
8428 	unsigned int load;
8429 
8430 	/* Task has no contribution or is new */
8431 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8432 		return cpu_load(rq);
8433 
8434 	cfs_rq = &rq->cfs;
8435 	load = READ_ONCE(cfs_rq->avg.load_avg);
8436 
8437 	/* Discount task's util from CPU's util */
8438 	lsub_positive(&load, task_h_load(p));
8439 
8440 	return load;
8441 }
8442 
8443 static unsigned long cpu_runnable(struct rq *rq)
8444 {
8445 	return cfs_rq_runnable_avg(&rq->cfs);
8446 }
8447 
8448 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
8449 {
8450 	struct cfs_rq *cfs_rq;
8451 	unsigned int runnable;
8452 
8453 	/* Task has no contribution or is new */
8454 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8455 		return cpu_runnable(rq);
8456 
8457 	cfs_rq = &rq->cfs;
8458 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
8459 
8460 	/* Discount task's runnable from CPU's runnable */
8461 	lsub_positive(&runnable, p->se.avg.runnable_avg);
8462 
8463 	return runnable;
8464 }
8465 
8466 static unsigned long capacity_of(int cpu)
8467 {
8468 	return cpu_rq(cpu)->cpu_capacity;
8469 }
8470 
8471 static void record_wakee(struct task_struct *p)
8472 {
8473 	/*
8474 	 * Only decay a single time; tasks that have less then 1 wakeup per
8475 	 * jiffy will not have built up many flips.
8476 	 */
8477 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
8478 		current->wakee_flips >>= 1;
8479 		current->wakee_flip_decay_ts = jiffies;
8480 	}
8481 
8482 	if (current->last_wakee != p) {
8483 		current->last_wakee = p;
8484 		current->wakee_flips++;
8485 	}
8486 }
8487 
8488 /*
8489  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
8490  *
8491  * A waker of many should wake a different task than the one last awakened
8492  * at a frequency roughly N times higher than one of its wakees.
8493  *
8494  * In order to determine whether we should let the load spread vs consolidating
8495  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
8496  * partner, and a factor of lls_size higher frequency in the other.
8497  *
8498  * With both conditions met, we can be relatively sure that the relationship is
8499  * non-monogamous, with partner count exceeding socket size.
8500  *
8501  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
8502  * whatever is irrelevant, spread criteria is apparent partner count exceeds
8503  * socket size.
8504  */
8505 static int wake_wide(struct task_struct *p)
8506 {
8507 	unsigned int master = current->wakee_flips;
8508 	unsigned int slave = p->wakee_flips;
8509 	int factor = __this_cpu_read(sd_llc_size);
8510 
8511 	if (master < slave)
8512 		swap(master, slave);
8513 	if (slave < factor || master < slave * factor)
8514 		return 0;
8515 	return 1;
8516 }
8517 
8518 /*
8519  * The purpose of wake_affine() is to quickly determine on which CPU we can run
8520  * soonest. For the purpose of speed we only consider the waking and previous
8521  * CPU.
8522  *
8523  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
8524  *			cache-affine and is (or	will be) idle.
8525  *
8526  * wake_affine_weight() - considers the weight to reflect the average
8527  *			  scheduling latency of the CPUs. This seems to work
8528  *			  for the overloaded case.
8529  */
8530 static int
8531 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
8532 {
8533 	/*
8534 	 * If this_cpu is idle, it implies the wakeup is from interrupt
8535 	 * context. Only allow the move if cache is shared. Otherwise an
8536 	 * interrupt intensive workload could force all tasks onto one
8537 	 * node depending on the IO topology or IRQ affinity settings.
8538 	 *
8539 	 * If the prev_cpu is idle and cache affine then avoid a migration.
8540 	 * There is no guarantee that the cache hot data from an interrupt
8541 	 * is more important than cache hot data on the prev_cpu and from
8542 	 * a cpufreq perspective, it's better to have higher utilisation
8543 	 * on one CPU.
8544 	 */
8545 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
8546 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
8547 
8548 	if (sync) {
8549 		struct rq *rq = cpu_rq(this_cpu);
8550 
8551 		if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
8552 			return this_cpu;
8553 	}
8554 
8555 	if (available_idle_cpu(prev_cpu))
8556 		return prev_cpu;
8557 
8558 	return nr_cpumask_bits;
8559 }
8560 
8561 static int
8562 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
8563 		   int this_cpu, int prev_cpu, int sync)
8564 {
8565 	s64 this_eff_load, prev_eff_load;
8566 	unsigned long task_load;
8567 
8568 	this_eff_load = cpu_load(cpu_rq(this_cpu));
8569 
8570 	if (sync) {
8571 		unsigned long current_load = task_h_load(current);
8572 
8573 		if (current_load > this_eff_load)
8574 			return this_cpu;
8575 
8576 		this_eff_load -= current_load;
8577 	}
8578 
8579 	task_load = task_h_load(p);
8580 
8581 	this_eff_load += task_load;
8582 	if (sched_feat(WA_BIAS))
8583 		this_eff_load *= 100;
8584 	this_eff_load *= capacity_of(prev_cpu);
8585 
8586 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
8587 	prev_eff_load -= task_load;
8588 	if (sched_feat(WA_BIAS))
8589 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
8590 	prev_eff_load *= capacity_of(this_cpu);
8591 
8592 	/*
8593 	 * If sync, adjust the weight of prev_eff_load such that if
8594 	 * prev_eff == this_eff that select_idle_sibling() will consider
8595 	 * stacking the wakee on top of the waker if no other CPU is
8596 	 * idle.
8597 	 */
8598 	if (sync)
8599 		prev_eff_load += 1;
8600 
8601 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
8602 }
8603 
8604 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
8605 		       int this_cpu, int prev_cpu, int sync)
8606 {
8607 	int target = nr_cpumask_bits;
8608 
8609 	if (sched_feat(WA_IDLE))
8610 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
8611 
8612 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
8613 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
8614 
8615 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
8616 	if (target != this_cpu)
8617 		return prev_cpu;
8618 
8619 	schedstat_inc(sd->ttwu_move_affine);
8620 	schedstat_inc(p->stats.nr_wakeups_affine);
8621 	return target;
8622 }
8623 
8624 static struct sched_group *
8625 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
8626 
8627 /*
8628  * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
8629  */
8630 static int
8631 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
8632 {
8633 	unsigned long load, min_load = ULONG_MAX;
8634 	u64 min_exit_latency = U64_MAX;
8635 	unsigned int nr_candidates = 0;
8636 	int least_loaded_cpu = this_cpu;
8637 	int shallowest_idle_cpu = -1;
8638 	int i;
8639 
8640 	/* Check if we have any choice: */
8641 	if (group->group_weight == 1)
8642 		return cpumask_first(sched_group_span(group));
8643 
8644 	/* Traverse only the allowed CPUs */
8645 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
8646 		struct rq *rq = cpu_rq(i);
8647 
8648 		if (!sched_core_cookie_match(rq, p))
8649 			continue;
8650 
8651 		if (choose_sched_idle_rq(rq, p))
8652 			return i;
8653 
8654 		if (available_idle_cpu(i)) {
8655 			struct cpuidle_state *idle = idle_get_state(rq);
8656 			u64 exit_latency = idle ? idle->exit_latency : U64_MAX;
8657 
8658 			if (shallowest_idle_cpu == -1 || exit_latency < min_exit_latency) {
8659 				min_exit_latency = exit_latency;
8660 				shallowest_idle_cpu = i;
8661 				nr_candidates = 1;
8662 			} else if (exit_latency == min_exit_latency) {
8663 				nr_candidates++;
8664 				if (!reciprocal_scale(sched_rng(), nr_candidates))
8665 					shallowest_idle_cpu = i;
8666 			}
8667 		} else if (shallowest_idle_cpu == -1) {
8668 			load = cpu_load(cpu_rq(i));
8669 			if (load < min_load) {
8670 				min_load = load;
8671 				least_loaded_cpu = i;
8672 			}
8673 		}
8674 	}
8675 
8676 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
8677 }
8678 
8679 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
8680 				  int cpu, int prev_cpu, int sd_flag)
8681 {
8682 	int new_cpu = cpu;
8683 
8684 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
8685 		return prev_cpu;
8686 
8687 	/*
8688 	 * We need task's util for cpu_util_without, sync it up to
8689 	 * prev_cpu's last_update_time.
8690 	 */
8691 	if (!(sd_flag & SD_BALANCE_FORK))
8692 		sync_entity_load_avg(&p->se);
8693 
8694 	while (sd) {
8695 		struct sched_group *group;
8696 		struct sched_domain *tmp;
8697 		int weight;
8698 
8699 		if (!(sd->flags & sd_flag)) {
8700 			sd = sd->child;
8701 			continue;
8702 		}
8703 
8704 		group = sched_balance_find_dst_group(sd, p, cpu);
8705 		if (!group) {
8706 			sd = sd->child;
8707 			continue;
8708 		}
8709 
8710 		new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
8711 		if (new_cpu == cpu) {
8712 			/* Now try balancing at a lower domain level of 'cpu': */
8713 			sd = sd->child;
8714 			continue;
8715 		}
8716 
8717 		/* Now try balancing at a lower domain level of 'new_cpu': */
8718 		cpu = new_cpu;
8719 		weight = sd->span_weight;
8720 		sd = NULL;
8721 		for_each_domain(cpu, tmp) {
8722 			if (weight <= tmp->span_weight)
8723 				break;
8724 			if (tmp->flags & sd_flag)
8725 				sd = tmp;
8726 		}
8727 	}
8728 
8729 	return new_cpu;
8730 }
8731 
8732 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
8733 {
8734 	if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p))
8735 		return cpu;
8736 
8737 	return -1;
8738 }
8739 
8740 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
8741 EXPORT_SYMBOL_GPL(sched_smt_present);
8742 
8743 static inline void set_idle_cores(int cpu, int val)
8744 {
8745 	struct sched_domain_shared *sds;
8746 
8747 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8748 	if (sds)
8749 		WRITE_ONCE(sds->has_idle_cores, val);
8750 }
8751 
8752 static inline bool test_idle_cores(int cpu)
8753 {
8754 	struct sched_domain_shared *sds;
8755 
8756 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8757 	if (sds)
8758 		return READ_ONCE(sds->has_idle_cores);
8759 
8760 	return false;
8761 }
8762 
8763 /*
8764  * Redirect a CPU to a higher-priority available sibling in its SMT domain,
8765  * subject to task affinity.
8766  */
8767 static inline int select_idle_smt_cpu(struct task_struct *p, int cpu)
8768 {
8769 	struct sched_domain *sd;
8770 	int best = cpu;
8771 	int sibling;
8772 
8773 	if (!sched_smt_active())
8774 		return cpu;
8775 
8776 	sd = rcu_dereference_all(cpu_rq(cpu)->sd);
8777 	if (!sd || !(sd->flags & SD_SHARE_CPUCAPACITY) ||
8778 	    !(sd->flags & SD_ASYM_PACKING))
8779 		return cpu;
8780 
8781 	for_each_cpu_and(sibling, sched_domain_span(sd), p->cpus_ptr) {
8782 		if (sibling == best || !choose_idle_cpu(sibling, p))
8783 			continue;
8784 
8785 		if (sched_asym_prefer(sibling, best))
8786 			best = sibling;
8787 	}
8788 
8789 	return best;
8790 }
8791 
8792 /*
8793  * Scans the local SMT mask to see if the entire core is idle, and records this
8794  * information in sd_balance_shared->has_idle_cores.
8795  *
8796  * Since SMT siblings share all cache levels, inspecting this limited remote
8797  * state should be fairly cheap.
8798  */
8799 void __update_idle_core(struct rq *rq)
8800 {
8801 	int core = cpu_of(rq);
8802 	int cpu;
8803 
8804 	rcu_read_lock();
8805 	if (test_idle_cores(core))
8806 		goto unlock;
8807 
8808 	for_each_cpu(cpu, cpu_smt_mask(core)) {
8809 		if (cpu == core)
8810 			continue;
8811 
8812 		if (!available_idle_cpu(cpu))
8813 			goto unlock;
8814 	}
8815 
8816 	set_idle_cores(core, 1);
8817 unlock:
8818 	rcu_read_unlock();
8819 }
8820 
8821 /*
8822  * Scan the entire LLC domain for idle cores; this dynamically switches off if
8823  * there are no idle cores left in the system; tracked through
8824  * sd_balance_shared->has_idle_cores and enabled through update_idle_core()
8825  * above.
8826  */
8827 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
8828 {
8829 	bool idle = true;
8830 	int cpu;
8831 
8832 	for_each_cpu(cpu, cpu_smt_mask(core)) {
8833 		if (!available_idle_cpu(cpu)) {
8834 			idle = false;
8835 			if (*idle_cpu == -1) {
8836 				if (choose_sched_idle_rq(cpu_rq(cpu), p) &&
8837 				    cpumask_test_cpu(cpu, cpus)) {
8838 					*idle_cpu = cpu;
8839 					break;
8840 				}
8841 				continue;
8842 			}
8843 			break;
8844 		}
8845 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
8846 			*idle_cpu = cpu;
8847 	}
8848 
8849 	if (idle)
8850 		return core;
8851 
8852 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
8853 	return -1;
8854 }
8855 
8856 /*
8857  * Scan the local SMT mask for idle CPUs.
8858  */
8859 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
8860 {
8861 	int cpu;
8862 
8863 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
8864 		if (cpu == target)
8865 			continue;
8866 		/*
8867 		 * Check if the CPU is in the LLC scheduling domain of @target.
8868 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
8869 		 */
8870 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8871 			continue;
8872 		if (choose_idle_cpu(cpu, p))
8873 			return cpu;
8874 	}
8875 
8876 	return -1;
8877 }
8878 
8879 /*
8880  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
8881  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
8882  * average idle time for this rq (as found in rq->avg_idle).
8883  */
8884 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
8885 {
8886 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8887 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
8888 
8889 	if (sched_feat(SIS_UTIL) && sd->shared) {
8890 		/*
8891 		 * Increment because !--nr is the condition to stop scan.
8892 		 *
8893 		 * Since "sd" is "sd_llc" for target CPU dereferenced in the
8894 		 * caller, it is safe to directly dereference "sd->shared".
8895 		 * Topology bits always ensure it assigned for "sd_llc" abd it
8896 		 * cannot disappear as long as we have a RCU protected
8897 		 * reference to one the associated "sd" here.
8898 		 */
8899 		nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
8900 		/* overloaded LLC is unlikely to have idle cpu/core */
8901 		if (nr == 1)
8902 			return -1;
8903 	}
8904 
8905 	if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr))
8906 		return -1;
8907 
8908 	if (static_branch_unlikely(&sched_cluster_active)) {
8909 		struct sched_group *sg = sd->groups;
8910 
8911 		if (sg->flags & SD_CLUSTER) {
8912 			for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
8913 				if (!cpumask_test_cpu(cpu, cpus))
8914 					continue;
8915 
8916 				if (has_idle_core) {
8917 					i = select_idle_core(p, cpu, cpus, &idle_cpu);
8918 					if ((unsigned int)i < nr_cpumask_bits)
8919 						return i;
8920 				} else {
8921 					if (--nr <= 0)
8922 						return -1;
8923 					idle_cpu = __select_idle_cpu(cpu, p);
8924 					if ((unsigned int)idle_cpu < nr_cpumask_bits)
8925 						return idle_cpu;
8926 				}
8927 			}
8928 			cpumask_andnot(cpus, cpus, sched_group_span(sg));
8929 		}
8930 	}
8931 
8932 	for_each_cpu_wrap(cpu, cpus, target + 1) {
8933 		if (has_idle_core) {
8934 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
8935 			if ((unsigned int)i < nr_cpumask_bits)
8936 				return i;
8937 
8938 		} else {
8939 			if (--nr <= 0)
8940 				return -1;
8941 			idle_cpu = __select_idle_cpu(cpu, p);
8942 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
8943 				break;
8944 		}
8945 	}
8946 
8947 	if (has_idle_core)
8948 		set_idle_cores(target, false);
8949 
8950 	return idle_cpu;
8951 }
8952 
8953 /*
8954  * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks,
8955  * where lower values indicate a better fit - see select_idle_capacity().
8956  *
8957  * A CPU that both fits the task and sits on a fully-idle SMT core is returned
8958  * immediately and is never assigned one of these ranks. On !SMT every CPU is
8959  * its own "core", so the early return covers all fits-and-idle cases and the
8960  * core-tier ranks below become unreachable.
8961  *
8962  *   Rank                            Val  Tier    Meaning
8963  *   ------------------------------  ---  ------  ---------------------------
8964  *   ASYM_IDLE_UCLAMP_MISFIT         -4   core    Idle core; capacity fits
8965  *                                                util but uclamp_min misses.
8966  *   ASYM_IDLE_COMPLETE_MISFIT       -3   core    Idle core; capacity does
8967  *                                                not fit. Still beats every
8968  *                                                thread-tier rank: a busy
8969  *                                                sibling cuts effective
8970  *                                                capacity more than a
8971  *                                                misfit hurts a quiet core.
8972  *   ASYM_IDLE_THREAD_FITS           -2   thread  Busy SMT sibling; capacity
8973  *                                                fits util + uclamp.
8974  *   ASYM_IDLE_THREAD_UCLAMP_MISFIT  -1   thread  Busy SMT sibling; capacity
8975  *                                                fits but uclamp_min misses
8976  *                                                (native util_fits_cpu()
8977  *                                                return value).
8978  *   ASYM_IDLE_THREAD_MISFIT          0   thread  Busy SMT sibling; capacity
8979  *                                                does not fit.
8980  *
8981  * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core,
8982  * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier:
8983  *
8984  *   ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT   (-4)
8985  *   ASYM_IDLE_THREAD_MISFIT         (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3)
8986  *
8987  * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core
8988  * candidate early-returns from select_idle_capacity().
8989  */
8990 enum asym_fits_state {
8991 	ASYM_IDLE_UCLAMP_MISFIT = -4,
8992 	ASYM_IDLE_COMPLETE_MISFIT,
8993 	ASYM_IDLE_THREAD_FITS,
8994 	ASYM_IDLE_THREAD_UCLAMP_MISFIT,
8995 	ASYM_IDLE_THREAD_MISFIT,
8996 
8997 	/* util_fits_cpu() bias for idle core */
8998 	ASYM_IDLE_CORE_BIAS = -3,
8999 };
9000 
9001 /*
9002  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
9003  * the task fits. If no CPU is big enough, but there are idle ones, try to
9004  * maximize capacity.
9005  */
9006 static int
9007 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
9008 {
9009 	/*
9010 	 * On !SMT systems, has_idle_core is always false and preferred_core
9011 	 * is always true (CPU == core), so the SMT preference logic below
9012 	 * collapses to the plain capacity scan.
9013 	 */
9014 	bool has_idle_core = sched_smt_active() && test_idle_cores(target);
9015 	unsigned long task_util, util_min, util_max, best_cap = 0;
9016 	int fits, best_fits = ASYM_IDLE_THREAD_MISFIT;
9017 	int cpu, best_cpu = -1;
9018 	struct cpumask *cpus;
9019 	int nr = INT_MAX;
9020 
9021 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
9022 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
9023 
9024 	task_util = task_util_est(p);
9025 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
9026 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
9027 
9028 	if (sched_feat(SIS_UTIL) && sd->shared) {
9029 		/*
9030 		 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits
9031 		 * the scan when not preferring an idle core.
9032 		 */
9033 		nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
9034 		/* overloaded domain is unlikely to have idle cpu/core */
9035 		if (nr == 1)
9036 			return -1;
9037 	}
9038 
9039 	for_each_cpu_wrap(cpu, cpus, target) {
9040 		bool preferred_core = !has_idle_core || is_core_idle(cpu);
9041 		unsigned long cpu_cap = capacity_of(cpu);
9042 
9043 		/*
9044 		 * Stop when the nr_idle_scan is exhausted (mirrors
9045 		 * select_idle_cpu() logic).
9046 		 */
9047 		if (!has_idle_core && --nr <= 0)
9048 			return best_cpu;
9049 
9050 		if (!choose_idle_cpu(cpu, p))
9051 			continue;
9052 
9053 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
9054 
9055 		/*
9056 		 * Perfect fit: capacity satisfies util + uclamp and the CPU
9057 		 * sits on a fully-idle SMT core, this is a !SMT system, or
9058 		 * there is no idle core to find.
9059 		 * Short-circuit the rank-based selection and return
9060 		 * immediately.
9061 		 */
9062 		if (fits > 0 && preferred_core)
9063 			return cpu;
9064 		/*
9065 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
9066 		 * Look for the CPU with best capacity.
9067 		 */
9068 		else if (fits < 0)
9069 			cpu_cap = get_actual_cpu_capacity(cpu);
9070 		/*
9071 		 * fits > 0 implies we are not on a preferred core, but the util
9072 		 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS
9073 		 * so the effective range becomes
9074 		 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where:
9075 		 *    ASYM_IDLE_THREAD_MISFIT - does not fit
9076 		 *    ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN
9077 		 *    ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core
9078 		 */
9079 		else if (fits > 0)
9080 			fits = ASYM_IDLE_THREAD_FITS;
9081 
9082 		/*
9083 		 * If we are on a preferred core, translate the range of fits
9084 		 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to
9085 		 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT].
9086 		 * This ensures that an idle core is always given priority over
9087 		 * (partially) busy core.
9088 		 *
9089 		 * A fully fitting idle core would have returned early and hence
9090 		 * fits > 0 for preferred_core need not be dealt with.
9091 		 */
9092 		if (preferred_core)
9093 			fits += ASYM_IDLE_CORE_BIAS;
9094 
9095 		/*
9096 		 * First, select CPU which fits better (lower is more preferred).
9097 		 * Then, select the one with best capacity at same level.
9098 		 */
9099 		if ((fits < best_fits) ||
9100 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
9101 			best_cap = cpu_cap;
9102 			best_cpu = cpu;
9103 			best_fits = fits;
9104 		}
9105 	}
9106 
9107 	/*
9108 	 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]
9109 	 * range means the chosen CPU is in a fully idle SMT core. Values above
9110 	 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best.
9111 	 *
9112 	 * The asym-capacity wakeup path returns from select_idle_sibling()
9113 	 * after this function and never runs select_idle_cpu(), so the usual
9114 	 * select_idle_cpu() tail that clears idle cores must live here when the
9115 	 * idle-core preference did not win.
9116 	 */
9117 	if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT)
9118 		set_idle_cores(target, false);
9119 
9120 	return best_cpu;
9121 }
9122 
9123 static inline bool asym_fits_cpu(unsigned long util,
9124 				 unsigned long util_min,
9125 				 unsigned long util_max,
9126 				 int cpu)
9127 {
9128 	if (sched_asym_cpucap_active()) {
9129 		/*
9130 		 * Return true only if the cpu fully fits the task requirements
9131 		 * which include the utilization and the performance hints.
9132 		 *
9133 		 * When SMT is active, also require that the core has no busy
9134 		 * siblings.
9135 		 *
9136 		 * Note: gating on is_core_idle() also makes the early-bailout
9137 		 * candidates in select_idle_sibling() (target, prev,
9138 		 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the
9139 		 * NO_ASYM path does not do.
9140 		 */
9141 		return (!sched_smt_active() || is_core_idle(cpu)) &&
9142 		       (util_fits_cpu(util, util_min, util_max, cpu) > 0);
9143 	}
9144 
9145 	return true;
9146 }
9147 
9148 /*
9149  * Try and locate an idle core/thread in the LLC cache domain.
9150  */
9151 static int select_idle_sibling(struct task_struct *p, int prev, int target)
9152 {
9153 	bool has_idle_core = false;
9154 	struct sched_domain *sd;
9155 	unsigned long task_util, util_min, util_max;
9156 	int i, recent_used_cpu, prev_aff = -1;
9157 
9158 	/*
9159 	 * On asymmetric system, update task utilization because we will check
9160 	 * that the task fits with CPU's capacity.
9161 	 */
9162 	if (sched_asym_cpucap_active()) {
9163 		sync_entity_load_avg(&p->se);
9164 		task_util = task_util_est(p);
9165 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
9166 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
9167 	}
9168 
9169 	/*
9170 	 * per-cpu select_rq_mask usage
9171 	 */
9172 	lockdep_assert_irqs_disabled();
9173 
9174 	if (choose_idle_cpu(target, p) &&
9175 	    asym_fits_cpu(task_util, util_min, util_max, target))
9176 		goto select_smt_priority;
9177 
9178 	/*
9179 	 * If the previous CPU is cache affine and idle, don't be stupid:
9180 	 */
9181 	if (prev != target && cpus_share_cache(prev, target) &&
9182 	    choose_idle_cpu(prev, p) &&
9183 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
9184 
9185 		if (!static_branch_unlikely(&sched_cluster_active) ||
9186 		    cpus_share_resources(prev, target)) {
9187 			target = prev;
9188 			goto select_smt_priority;
9189 		}
9190 
9191 		prev_aff = prev;
9192 	}
9193 
9194 	/*
9195 	 * Allow a per-cpu kthread to stack with the wakee if the
9196 	 * kworker thread and the tasks previous CPUs are the same.
9197 	 * The assumption is that the wakee queued work for the
9198 	 * per-cpu kthread that is now complete and the wakeup is
9199 	 * essentially a sync wakeup. An obvious example of this
9200 	 * pattern is IO completions.
9201 	 */
9202 	if (is_per_cpu_kthread(current) &&
9203 	    in_task() &&
9204 	    prev == smp_processor_id() &&
9205 	    this_rq()->nr_running <= 1 &&
9206 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
9207 		target = prev;
9208 		goto select_smt_priority;
9209 	}
9210 
9211 	/* Check a recently used CPU as a potential idle candidate: */
9212 	recent_used_cpu = p->recent_used_cpu;
9213 	p->recent_used_cpu = prev;
9214 	if (recent_used_cpu != prev &&
9215 	    recent_used_cpu != target &&
9216 	    cpus_share_cache(recent_used_cpu, target) &&
9217 	    choose_idle_cpu(recent_used_cpu, p) &&
9218 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
9219 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
9220 
9221 		if (!static_branch_unlikely(&sched_cluster_active) ||
9222 		    cpus_share_resources(recent_used_cpu, target)) {
9223 			target = recent_used_cpu;
9224 			goto select_smt_priority;
9225 		}
9226 
9227 	} else {
9228 		recent_used_cpu = -1;
9229 	}
9230 
9231 	/*
9232 	 * For asymmetric CPU capacity systems, our domain of interest is
9233 	 * sd_asym_cpucapacity rather than sd_llc.
9234 	 */
9235 	if (sched_asym_cpucap_active()) {
9236 		sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target));
9237 		/*
9238 		 * On an asymmetric CPU capacity system where an exclusive
9239 		 * cpuset defines a symmetric island (i.e. one unique
9240 		 * capacity_orig value through the cpuset), the key will be set
9241 		 * but the CPUs within that cpuset will not have a domain with
9242 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
9243 		 * capacity path.
9244 		 */
9245 		if (sd) {
9246 			i = select_idle_capacity(p, sd, target);
9247 			if ((unsigned int)i < nr_cpumask_bits) {
9248 				target = i;
9249 				goto select_smt_priority;
9250 			}
9251 			return target;
9252 		}
9253 	}
9254 
9255 	sd = rcu_dereference_all(per_cpu(sd_llc, target));
9256 	if (!sd)
9257 		return target;
9258 
9259 	if (sched_smt_active()) {
9260 		has_idle_core = test_idle_cores(target);
9261 
9262 		if (!has_idle_core && cpus_share_cache(prev, target)) {
9263 			i = select_idle_smt(p, sd, prev);
9264 			if ((unsigned int)i < nr_cpumask_bits) {
9265 				target = i;
9266 				goto select_smt_priority;
9267 			}
9268 		}
9269 	}
9270 
9271 	i = select_idle_cpu(p, sd, has_idle_core, target);
9272 	if ((unsigned int)i < nr_cpumask_bits) {
9273 		target = i;
9274 		goto select_smt_priority;
9275 	}
9276 
9277 	/*
9278 	 * For cluster machines which have lower sharing cache like L2 or
9279 	 * LLC Tag, we tend to find an idle CPU in the target's cluster
9280 	 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
9281 	 * use them if possible when no idle CPU found in select_idle_cpu().
9282 	 */
9283 	if ((unsigned int)prev_aff < nr_cpumask_bits) {
9284 		target = prev_aff;
9285 		goto select_smt_priority;
9286 	}
9287 	if ((unsigned int)recent_used_cpu < nr_cpumask_bits) {
9288 		target = recent_used_cpu;
9289 		goto select_smt_priority;
9290 	}
9291 
9292 	return target;
9293 
9294 select_smt_priority:
9295 	return select_idle_smt_cpu(p, target);
9296 }
9297 
9298 /**
9299  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
9300  * @cpu: the CPU to get the utilization for
9301  * @p: task for which the CPU utilization should be predicted or NULL
9302  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
9303  * @boost: 1 to enable boosting, otherwise 0
9304  *
9305  * The unit of the return value must be the same as the one of CPU capacity
9306  * so that CPU utilization can be compared with CPU capacity.
9307  *
9308  * CPU utilization is the sum of running time of runnable tasks plus the
9309  * recent utilization of currently non-runnable tasks on that CPU.
9310  * It represents the amount of CPU capacity currently used by CFS tasks in
9311  * the range [0..max CPU capacity] with max CPU capacity being the CPU
9312  * capacity at f_max.
9313  *
9314  * The estimated CPU utilization is defined as the maximum between CPU
9315  * utilization and sum of the estimated utilization of the currently
9316  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
9317  * previously-executed tasks, which helps better deduce how busy a CPU will
9318  * be when a long-sleeping task wakes up. The contribution to CPU utilization
9319  * of such a task would be significantly decayed at this point of time.
9320  *
9321  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
9322  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
9323  * utilization. Boosting is implemented in cpu_util() so that internal
9324  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
9325  * latter via cpu_util_cfs_boost().
9326  *
9327  * CPU utilization can be higher than the current CPU capacity
9328  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
9329  * of rounding errors as well as task migrations or wakeups of new tasks.
9330  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
9331  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
9332  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
9333  * capacity. CPU utilization is allowed to overshoot current CPU capacity
9334  * though since this is useful for predicting the CPU capacity required
9335  * after task migrations (scheduler-driven DVFS).
9336  *
9337  * Return: (Boosted) (estimated) utilization for the specified CPU.
9338  */
9339 static unsigned long
9340 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
9341 {
9342 	bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu;
9343 	bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu;
9344 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
9345 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
9346 	unsigned long runnable;
9347 
9348 	/*
9349 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
9350 	 * contribution. If @p migrates from another CPU to @cpu add its
9351 	 * contribution. In all the other cases @cpu is not impacted by the
9352 	 * migration so its util_avg is already correct.
9353 	 */
9354 	if (add_task)
9355 		util += task_util(p);
9356 	else if (sub_task)
9357 		lsub_positive(&util, task_util(p));
9358 
9359 	if (boost) {
9360 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
9361 		if (add_task)
9362 			runnable += READ_ONCE(p->se.avg.runnable_avg);
9363 		else if (sub_task)
9364 			lsub_positive(&runnable,
9365 				      READ_ONCE(p->se.avg.runnable_avg));
9366 		util = max(util, runnable);
9367 	}
9368 
9369 	if (sched_feat(UTIL_EST)) {
9370 		unsigned long util_est;
9371 
9372 		util_est = READ_ONCE(cfs_rq->avg.util_est);
9373 
9374 		/*
9375 		 * During wake-up @p isn't enqueued yet and doesn't contribute
9376 		 * to any cpu_rq(cpu)->cfs.avg.util_est.
9377 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
9378 		 * has been enqueued.
9379 		 *
9380 		 * During exec (@dst_cpu = -1) @p is enqueued and does
9381 		 * contribute to cpu_rq(cpu)->cfs.util_est.
9382 		 * Remove it to "simulate" cpu_util without @p's contribution.
9383 		 *
9384 		 * Despite the task_on_rq_queued(@p) check there is still a
9385 		 * small window for a possible race when an exec
9386 		 * select_task_rq_fair() races with LB's detach_task().
9387 		 *
9388 		 *   detach_task()
9389 		 *     deactivate_task()
9390 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
9391 		 *       -------------------------------- A
9392 		 *       dequeue_task()                    \
9393 		 *         dequeue_task_fair()              + Race Time
9394 		 *           util_est_dequeue()            /
9395 		 *       -------------------------------- B
9396 		 *
9397 		 * The additional check "current == p" is required to further
9398 		 * reduce the race window.
9399 		 */
9400 		if (dst_cpu == cpu)
9401 			util_est += _task_util_est(p);
9402 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
9403 			lsub_positive(&util_est, _task_util_est(p));
9404 
9405 		util = max(util, util_est);
9406 	}
9407 
9408 	return min(util, arch_scale_cpu_capacity(cpu));
9409 }
9410 
9411 unsigned long cpu_util_cfs(int cpu)
9412 {
9413 	return cpu_util(cpu, NULL, -1, 0);
9414 }
9415 
9416 unsigned long cpu_util_cfs_boost(int cpu)
9417 {
9418 	return cpu_util(cpu, NULL, -1, 1);
9419 }
9420 
9421 /*
9422  * cpu_util_without: compute cpu utilization without any contributions from *p
9423  * @cpu: the CPU which utilization is requested
9424  * @p: the task which utilization should be discounted
9425  *
9426  * The utilization of a CPU is defined by the utilization of tasks currently
9427  * enqueued on that CPU as well as tasks which are currently sleeping after an
9428  * execution on that CPU.
9429  *
9430  * This method returns the utilization of the specified CPU by discounting the
9431  * utilization of the specified task, whenever the task is currently
9432  * contributing to the CPU utilization.
9433  */
9434 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
9435 {
9436 	/* Task has no contribution or is new */
9437 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9438 		p = NULL;
9439 
9440 	return cpu_util(cpu, p, -1, 0);
9441 }
9442 
9443 /*
9444  * This function computes an effective utilization for the given CPU, to be
9445  * used for frequency selection given the linear relation: f = u * f_max.
9446  *
9447  * The scheduler tracks the following metrics:
9448  *
9449  *   cpu_util_{cfs,rt,dl,irq}()
9450  *   cpu_bw_dl()
9451  *
9452  * Where the cfs,rt and dl util numbers are tracked with the same metric and
9453  * synchronized windows and are thus directly comparable.
9454  *
9455  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
9456  * which excludes things like IRQ and steal-time. These latter are then accrued
9457  * in the IRQ utilization.
9458  *
9459  * The DL bandwidth number OTOH is not a measured metric but a value computed
9460  * based on the task model parameters and gives the minimal utilization
9461  * required to meet deadlines.
9462  */
9463 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
9464 				 unsigned long *min,
9465 				 unsigned long *max)
9466 {
9467 	unsigned long util, irq, scale;
9468 	struct rq *rq = cpu_rq(cpu);
9469 
9470 	scale = arch_scale_cpu_capacity(cpu);
9471 
9472 	/*
9473 	 * Early check to see if IRQ/steal time saturates the CPU, can be
9474 	 * because of inaccuracies in how we track these -- see
9475 	 * update_irq_load_avg().
9476 	 */
9477 	irq = cpu_util_irq(rq);
9478 	if (unlikely(irq >= scale)) {
9479 		if (min)
9480 			*min = scale;
9481 		if (max)
9482 			*max = scale;
9483 		return scale;
9484 	}
9485 
9486 	if (min) {
9487 		/*
9488 		 * The minimum utilization returns the highest level between:
9489 		 * - the computed DL bandwidth needed with the IRQ pressure which
9490 		 *   steals time to the deadline task.
9491 		 * - The minimum performance requirement for CFS and/or RT.
9492 		 */
9493 		*min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
9494 
9495 		/*
9496 		 * When an RT task is runnable and uclamp is not used, we must
9497 		 * ensure that the task will run at maximum compute capacity.
9498 		 */
9499 		if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
9500 			*min = max(*min, scale);
9501 	}
9502 
9503 	/*
9504 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
9505 	 * CFS tasks and we use the same metric to track the effective
9506 	 * utilization (PELT windows are synchronized) we can directly add them
9507 	 * to obtain the CPU's actual utilization.
9508 	 */
9509 	util = util_cfs + cpu_util_rt(rq);
9510 	util += cpu_util_dl(rq);
9511 
9512 	/*
9513 	 * The maximum hint is a soft bandwidth requirement, which can be lower
9514 	 * than the actual utilization because of uclamp_max requirements.
9515 	 */
9516 	if (max)
9517 		*max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
9518 
9519 	if (util >= scale)
9520 		return scale;
9521 
9522 	/*
9523 	 * There is still idle time; further improve the number by using the
9524 	 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
9525 	 * need to scale the task numbers:
9526 	 *
9527 	 *              max - irq
9528 	 *   U' = irq + --------- * U
9529 	 *                 max
9530 	 */
9531 	util = scale_irq_capacity(util, irq, scale);
9532 	util += irq;
9533 
9534 	return min(scale, util);
9535 }
9536 
9537 unsigned long sched_cpu_util(int cpu)
9538 {
9539 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
9540 }
9541 
9542 /*
9543  * energy_env - Utilization landscape for energy estimation.
9544  * @task_busy_time: Utilization contribution by the task for which we test the
9545  *                  placement. Given by eenv_task_busy_time().
9546  * @pd_busy_time:   Utilization of the whole perf domain without the task
9547  *                  contribution. Given by eenv_pd_busy_time().
9548  * @cpu_cap:        Maximum CPU capacity for the perf domain.
9549  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
9550  */
9551 struct energy_env {
9552 	unsigned long task_busy_time;
9553 	unsigned long pd_busy_time;
9554 	unsigned long cpu_cap;
9555 	unsigned long pd_cap;
9556 };
9557 
9558 /*
9559  * Compute the task busy time for compute_energy(). This time cannot be
9560  * injected directly into effective_cpu_util() because of the IRQ scaling.
9561  * The latter only makes sense with the most recent CPUs where the task has
9562  * run.
9563  */
9564 static inline void eenv_task_busy_time(struct energy_env *eenv,
9565 				       struct task_struct *p, int prev_cpu)
9566 {
9567 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
9568 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
9569 
9570 	if (unlikely(irq >= max_cap))
9571 		busy_time = max_cap;
9572 	else
9573 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
9574 
9575 	eenv->task_busy_time = busy_time;
9576 }
9577 
9578 /*
9579  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
9580  * utilization for each @pd_cpus, it however doesn't take into account
9581  * clamping since the ratio (utilization / cpu_capacity) is already enough to
9582  * scale the EM reported power consumption at the (eventually clamped)
9583  * cpu_capacity.
9584  *
9585  * The contribution of the task @p for which we want to estimate the
9586  * energy cost is removed (by cpu_util()) and must be calculated
9587  * separately (see eenv_task_busy_time). This ensures:
9588  *
9589  *   - A stable PD utilization, no matter which CPU of that PD we want to place
9590  *     the task on.
9591  *
9592  *   - A fair comparison between CPUs as the task contribution (task_util())
9593  *     will always be the same no matter which CPU utilization we rely on
9594  *     (util_avg or util_est).
9595  *
9596  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
9597  * exceed @eenv->pd_cap.
9598  */
9599 static inline void eenv_pd_busy_time(struct energy_env *eenv,
9600 				     struct cpumask *pd_cpus,
9601 				     struct task_struct *p)
9602 {
9603 	unsigned long busy_time = 0;
9604 	int cpu;
9605 
9606 	for_each_cpu(cpu, pd_cpus) {
9607 		unsigned long util = cpu_util(cpu, p, -1, 0);
9608 
9609 		busy_time += effective_cpu_util(cpu, util, NULL, NULL);
9610 	}
9611 
9612 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
9613 }
9614 
9615 /*
9616  * Compute the maximum utilization for compute_energy() when the task @p
9617  * is placed on the cpu @dst_cpu.
9618  *
9619  * Returns the maximum utilization among @eenv->cpus. This utilization can't
9620  * exceed @eenv->cpu_cap.
9621  */
9622 static inline unsigned long
9623 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
9624 		 struct task_struct *p, int dst_cpu)
9625 {
9626 	unsigned long max_util = 0;
9627 	int cpu;
9628 
9629 	for_each_cpu(cpu, pd_cpus) {
9630 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
9631 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
9632 		unsigned long eff_util, min, max;
9633 
9634 		/*
9635 		 * Performance domain frequency: utilization clamping
9636 		 * must be considered since it affects the selection
9637 		 * of the performance domain frequency.
9638 		 * NOTE: in case RT tasks are running, by default the min
9639 		 * utilization can be max OPP.
9640 		 */
9641 		eff_util = effective_cpu_util(cpu, util, &min, &max);
9642 
9643 		/* Task's uclamp can modify min and max value */
9644 		if (tsk && uclamp_is_used()) {
9645 			min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
9646 
9647 			/*
9648 			 * If there is no active max uclamp constraint,
9649 			 * directly use task's one, otherwise keep max.
9650 			 */
9651 			if (uclamp_rq_is_idle(cpu_rq(cpu)))
9652 				max = uclamp_eff_value(p, UCLAMP_MAX);
9653 			else
9654 				max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
9655 		}
9656 
9657 		eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
9658 		max_util = max(max_util, eff_util);
9659 	}
9660 
9661 	return min(max_util, eenv->cpu_cap);
9662 }
9663 
9664 /*
9665  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
9666  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
9667  * contribution is ignored.
9668  */
9669 static inline unsigned long
9670 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
9671 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
9672 {
9673 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
9674 	unsigned long busy_time = eenv->pd_busy_time;
9675 	unsigned long energy;
9676 
9677 	if (dst_cpu >= 0)
9678 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
9679 
9680 	energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
9681 
9682 	trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
9683 
9684 	return energy;
9685 }
9686 
9687 /*
9688  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
9689  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
9690  * spare capacity in each performance domain and uses it as a potential
9691  * candidate to execute the task. Then, it uses the Energy Model to figure
9692  * out which of the CPU candidates is the most energy-efficient.
9693  *
9694  * The rationale for this heuristic is as follows. In a performance domain,
9695  * all the most energy efficient CPU candidates (according to the Energy
9696  * Model) are those for which we'll request a low frequency. When there are
9697  * several CPUs for which the frequency request will be the same, we don't
9698  * have enough data to break the tie between them, because the Energy Model
9699  * only includes active power costs. With this model, if we assume that
9700  * frequency requests follow utilization (e.g. using schedutil), the CPU with
9701  * the maximum spare capacity in a performance domain is guaranteed to be among
9702  * the best candidates of the performance domain.
9703  *
9704  * In practice, it could be preferable from an energy standpoint to pack
9705  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
9706  * but that could also hurt our chances to go cluster idle, and we have no
9707  * ways to tell with the current Energy Model if this is actually a good
9708  * idea or not. So, find_energy_efficient_cpu() basically favors
9709  * cluster-packing, and spreading inside a cluster. That should at least be
9710  * a good thing for latency, and this is consistent with the idea that most
9711  * of the energy savings of EAS come from the asymmetry of the system, and
9712  * not so much from breaking the tie between identical CPUs. That's also the
9713  * reason why EAS is enabled in the topology code only for systems where
9714  * SD_ASYM_CPUCAPACITY is set.
9715  *
9716  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
9717  * they don't have any useful utilization data yet and it's not possible to
9718  * forecast their impact on energy consumption. Consequently, they will be
9719  * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
9720  * to be energy-inefficient in some use-cases. The alternative would be to
9721  * bias new tasks towards specific types of CPUs first, or to try to infer
9722  * their util_avg from the parent task, but those heuristics could hurt
9723  * other use-cases too. So, until someone finds a better way to solve this,
9724  * let's keep things simple by re-using the existing slow path.
9725  */
9726 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
9727 {
9728 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
9729 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
9730 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
9731 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
9732 	struct root_domain *rd = this_rq()->rd;
9733 	int cpu, best_energy_cpu, target = -1;
9734 	int prev_fits = -1, best_fits = -1;
9735 	unsigned long best_actual_cap = 0;
9736 	unsigned long prev_actual_cap = 0;
9737 	struct sched_domain *sd;
9738 	struct perf_domain *pd;
9739 	struct energy_env eenv;
9740 
9741 	pd = rcu_dereference_all(rd->pd);
9742 	if (!pd)
9743 		return target;
9744 
9745 	/*
9746 	 * Energy-aware wake-up happens on the lowest sched_domain starting
9747 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
9748 	 */
9749 	sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity));
9750 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
9751 		sd = sd->parent;
9752 	if (!sd)
9753 		return target;
9754 
9755 	target = prev_cpu;
9756 
9757 	sync_entity_load_avg(&p->se);
9758 	if (!task_util_est(p) && p_util_min == 0)
9759 		return target;
9760 
9761 	eenv_task_busy_time(&eenv, p, prev_cpu);
9762 
9763 	for (; pd; pd = pd->next) {
9764 		unsigned long util_min = p_util_min, util_max = p_util_max;
9765 		unsigned long cpu_cap, cpu_actual_cap, util;
9766 		long prev_spare_cap = -1, max_spare_cap = -1;
9767 		unsigned long rq_util_min, rq_util_max;
9768 		unsigned long cur_delta, base_energy;
9769 		int max_spare_cap_cpu = -1;
9770 		int fits, max_fits = -1;
9771 
9772 		if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask))
9773 			continue;
9774 
9775 		/* Account external pressure for the energy estimation */
9776 		cpu = cpumask_first(cpus);
9777 		cpu_actual_cap = get_actual_cpu_capacity(cpu);
9778 
9779 		eenv.cpu_cap = cpu_actual_cap;
9780 		eenv.pd_cap = 0;
9781 
9782 		for_each_cpu(cpu, cpus) {
9783 			struct rq *rq = cpu_rq(cpu);
9784 
9785 			eenv.pd_cap += cpu_actual_cap;
9786 
9787 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
9788 				continue;
9789 
9790 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
9791 				continue;
9792 
9793 			util = cpu_util(cpu, p, cpu, 0);
9794 			cpu_cap = capacity_of(cpu);
9795 
9796 			/*
9797 			 * Skip CPUs that cannot satisfy the capacity request.
9798 			 * IOW, placing the task there would make the CPU
9799 			 * overutilized. Take uclamp into account to see how
9800 			 * much capacity we can get out of the CPU; this is
9801 			 * aligned with sched_cpu_util().
9802 			 */
9803 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
9804 				/*
9805 				 * Open code uclamp_rq_util_with() except for
9806 				 * the clamp() part. I.e.: apply max aggregation
9807 				 * only. util_fits_cpu() logic requires to
9808 				 * operate on non clamped util but must use the
9809 				 * max-aggregated uclamp_{min, max}.
9810 				 */
9811 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
9812 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
9813 
9814 				util_min = max(rq_util_min, p_util_min);
9815 				util_max = max(rq_util_max, p_util_max);
9816 			}
9817 
9818 			fits = util_fits_cpu(util, util_min, util_max, cpu);
9819 			if (!fits)
9820 				continue;
9821 
9822 			lsub_positive(&cpu_cap, util);
9823 
9824 			if (cpu == prev_cpu) {
9825 				/* Always use prev_cpu as a candidate. */
9826 				prev_spare_cap = cpu_cap;
9827 				prev_fits = fits;
9828 			} else if ((fits > max_fits) ||
9829 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
9830 				/*
9831 				 * Find the CPU with the maximum spare capacity
9832 				 * among the remaining CPUs in the performance
9833 				 * domain.
9834 				 */
9835 				max_spare_cap = cpu_cap;
9836 				max_spare_cap_cpu = cpu;
9837 				max_fits = fits;
9838 			}
9839 		}
9840 
9841 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
9842 			continue;
9843 
9844 		eenv_pd_busy_time(&eenv, cpus, p);
9845 		/* Compute the 'base' energy of the pd, without @p */
9846 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
9847 
9848 		/* Evaluate the energy impact of using prev_cpu. */
9849 		if (prev_spare_cap > -1) {
9850 			prev_delta = compute_energy(&eenv, pd, cpus, p,
9851 						    prev_cpu);
9852 			/* CPU utilization has changed */
9853 			if (prev_delta < base_energy)
9854 				return target;
9855 			prev_delta -= base_energy;
9856 			prev_actual_cap = cpu_actual_cap;
9857 			best_delta = min(best_delta, prev_delta);
9858 		}
9859 
9860 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
9861 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
9862 			/* Current best energy cpu fits better */
9863 			if (max_fits < best_fits)
9864 				continue;
9865 
9866 			/*
9867 			 * Both don't fit performance hint (i.e. uclamp_min)
9868 			 * but best energy cpu has better capacity.
9869 			 */
9870 			if ((max_fits < 0) &&
9871 			    (cpu_actual_cap <= best_actual_cap))
9872 				continue;
9873 
9874 			cur_delta = compute_energy(&eenv, pd, cpus, p,
9875 						   max_spare_cap_cpu);
9876 			/* CPU utilization has changed */
9877 			if (cur_delta < base_energy)
9878 				return target;
9879 			cur_delta -= base_energy;
9880 
9881 			/*
9882 			 * Both fit for the task but best energy cpu has lower
9883 			 * energy impact.
9884 			 */
9885 			if ((max_fits > 0) && (best_fits > 0) &&
9886 			    (cur_delta >= best_delta))
9887 				continue;
9888 
9889 			best_delta = cur_delta;
9890 			best_energy_cpu = max_spare_cap_cpu;
9891 			best_fits = max_fits;
9892 			best_actual_cap = cpu_actual_cap;
9893 		}
9894 	}
9895 
9896 	if ((best_fits > prev_fits) ||
9897 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
9898 	    ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
9899 		target = best_energy_cpu;
9900 
9901 	return target;
9902 }
9903 
9904 /*
9905  * select_task_rq_fair: Select target runqueue for the waking task in domains
9906  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
9907  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
9908  *
9909  * Balances load by selecting the idlest CPU in the idlest group, or under
9910  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
9911  *
9912  * Returns the target CPU number.
9913  */
9914 static int
9915 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
9916 {
9917 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
9918 	struct sched_domain *tmp, *sd = NULL;
9919 	int cpu = smp_processor_id();
9920 	int new_cpu = prev_cpu;
9921 	int want_affine = 0;
9922 	/* SD_flags and WF_flags share the first nibble */
9923 	int sd_flag = wake_flags & 0xF;
9924 
9925 	/*
9926 	 * required for stable ->cpus_allowed
9927 	 */
9928 	lockdep_assert_held(&p->pi_lock);
9929 	if (wake_flags & WF_TTWU) {
9930 		record_wakee(p);
9931 
9932 		if ((wake_flags & WF_CURRENT_CPU) &&
9933 		    cpumask_test_cpu(cpu, p->cpus_ptr))
9934 			return cpu;
9935 
9936 		if (!is_rd_overutilized(this_rq()->rd)) {
9937 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
9938 			if (new_cpu >= 0)
9939 				return new_cpu;
9940 			new_cpu = prev_cpu;
9941 		}
9942 
9943 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
9944 	}
9945 
9946 	for_each_domain(cpu, tmp) {
9947 		/*
9948 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
9949 		 * cpu is a valid SD_WAKE_AFFINE target.
9950 		 */
9951 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
9952 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
9953 			if (cpu != prev_cpu)
9954 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
9955 
9956 			sd = NULL; /* Prefer wake_affine over balance flags */
9957 			break;
9958 		}
9959 
9960 		/*
9961 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
9962 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
9963 		 * will usually go to the fast path.
9964 		 */
9965 		if (tmp->flags & sd_flag)
9966 			sd = tmp;
9967 		else if (!want_affine)
9968 			break;
9969 	}
9970 
9971 	/* Slow path */
9972 	if (unlikely(sd)) {
9973 		new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
9974 		return select_idle_smt_cpu(p, new_cpu);
9975 	}
9976 
9977 	/* Fast path */
9978 	if (wake_flags & WF_TTWU)
9979 		return select_idle_sibling(p, prev_cpu, new_cpu);
9980 
9981 	return new_cpu;
9982 }
9983 
9984 /*
9985  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
9986  * cfs_rq_of(p) references at time of call are still valid and identify the
9987  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
9988  */
9989 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
9990 {
9991 	struct sched_entity *se = &p->se;
9992 
9993 	if (!task_on_rq_migrating(p)) {
9994 		remove_entity_load_avg(se);
9995 
9996 		/*
9997 		 * Here, the task's PELT values have been updated according to
9998 		 * the current rq's clock. But if that clock hasn't been
9999 		 * updated in a while, a substantial idle time will be missed,
10000 		 * leading to an inflation after wake-up on the new rq.
10001 		 *
10002 		 * Estimate the missing time from the cfs_rq last_update_time
10003 		 * and update sched_avg to improve the PELT continuity after
10004 		 * migration.
10005 		 */
10006 		migrate_se_pelt_lag(se);
10007 	}
10008 
10009 	/* Tell new CPU we are migrated */
10010 	se->avg.last_update_time = 0;
10011 
10012 	update_scan_period(p, new_cpu);
10013 }
10014 
10015 static void task_dead_fair(struct task_struct *p)
10016 {
10017 	struct sched_entity *se = &p->se;
10018 	remove_entity_load_avg(se);
10019 }
10020 
10021 /*
10022  * Set the max capacity the task is allowed to run at for misfit detection.
10023  */
10024 static void set_task_max_allowed_capacity(struct task_struct *p)
10025 {
10026 	struct asym_cap_data *entry;
10027 
10028 	if (!sched_asym_cpucap_active())
10029 		return;
10030 
10031 	rcu_read_lock();
10032 	list_for_each_entry_rcu(entry, &asym_cap_list, link) {
10033 		cpumask_t *cpumask;
10034 
10035 		cpumask = cpu_capacity_span(entry);
10036 		if (!cpumask_intersects(p->cpus_ptr, cpumask))
10037 			continue;
10038 
10039 		p->max_allowed_capacity = entry->capacity;
10040 		break;
10041 	}
10042 	rcu_read_unlock();
10043 }
10044 
10045 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
10046 {
10047 	set_cpus_allowed_common(p, ctx);
10048 	set_task_max_allowed_capacity(p);
10049 }
10050 
10051 enum preempt_wakeup_action {
10052 	PREEMPT_WAKEUP_NONE,	/* No preemption. */
10053 	PREEMPT_WAKEUP_SHORT,	/* Ignore slice protection. */
10054 	PREEMPT_WAKEUP_PICK,	/* Let pick_eevdf() decide. */
10055 	PREEMPT_WAKEUP_RESCHED,	/* Force reschedule. */
10056 };
10057 
10058 static inline bool set_preempt_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
10059 {
10060 	/*
10061 	 * Keep existing buddy if the deadline is sooner than pse.
10062 	 * The older buddy may be cache cold and completely unrelated
10063 	 * to the current wakeup but that is unpredictable where as
10064 	 * obeying the deadline is more in line with EEVDF objectives.
10065 	 */
10066 	if (cfs_rq->next && entity_before(cfs_rq->next, pse))
10067 		return false;
10068 
10069 	set_next_buddy(cfs_rq, pse);
10070 	return true;
10071 }
10072 
10073 static inline bool set_short_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
10074 {
10075 	if (cfs_rq->next) {
10076 		if (cfs_rq->next->slice < pse->slice)
10077 			return false;
10078 
10079 		if (cfs_rq->next->slice == pse->slice &&
10080 		    entity_before(cfs_rq->next, pse))
10081 			return false;
10082 	}
10083 
10084 	set_next_buddy(cfs_rq, pse);
10085 	return true;
10086 }
10087 
10088 /*
10089  * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
10090  * strictly enforced because the hint is either misunderstood or
10091  * multiple tasks must be woken up.
10092  */
10093 static inline enum preempt_wakeup_action
10094 preempt_sync(struct rq *rq, int wake_flags,
10095 	     struct sched_entity *pse, struct sched_entity *se)
10096 {
10097 	u64 threshold, delta;
10098 
10099 	/*
10100 	 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
10101 	 * though it is likely harmless.
10102 	 */
10103 	WARN_ON_ONCE(!(wake_flags & WF_TTWU));
10104 
10105 	threshold = sysctl_sched_migration_cost;
10106 	delta = rq_clock_task(rq) - se->exec_start;
10107 	if ((s64)delta < 0)
10108 		delta = 0;
10109 
10110 	/*
10111 	 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
10112 	 * could run on other CPUs. Reduce the threshold before preemption is
10113 	 * allowed to an arbitrary lower value as it is more likely (but not
10114 	 * guaranteed) the waker requires the wakee to finish.
10115 	 */
10116 	if (wake_flags & WF_RQ_SELECTED)
10117 		threshold >>= 2;
10118 
10119 	/*
10120 	 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
10121 	 * wakeups to be issued.
10122 	 */
10123 	if (entity_before(pse, se) && delta >= threshold)
10124 		return PREEMPT_WAKEUP_RESCHED;
10125 
10126 	return PREEMPT_WAKEUP_NONE;
10127 }
10128 
10129 /*
10130  * Preempt the current task with a newly woken task if needed:
10131  */
10132 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags)
10133 {
10134 	enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
10135 	struct task_struct *donor = rq->donor;
10136 	struct sched_entity *nse, *se = &donor->se, *pse = &p->se;
10137 	struct cfs_rq *cfs_rq = &rq->cfs;
10138 	int cse_is_idle, pse_is_idle;
10139 
10140 	/*
10141 	 * XXX Getting preempted by higher class, try and find idle CPU?
10142 	 */
10143 	if (p->sched_class != &fair_sched_class ||
10144 	    donor->sched_class != &fair_sched_class)
10145 		return;
10146 
10147 	if (unlikely(se == pse))
10148 		return;
10149 
10150 	/*
10151 	 * This is possible from callers such as attach_tasks(), in which we
10152 	 * unconditionally wakeup_preempt() after an enqueue (which may have
10153 	 * lead to a throttle).  This both saves work and prevents false
10154 	 * next-buddy nomination below.
10155 	 */
10156 	if (task_is_throttled(p))
10157 		return;
10158 
10159 	/*
10160 	 * We can come here with TIF_NEED_RESCHED already set from new task
10161 	 * wake up path.
10162 	 *
10163 	 * Note: this also catches the edge-case of curr being in a throttled
10164 	 * group (e.g. via set_curr_task), since update_curr() (in the
10165 	 * enqueue of curr) will have resulted in resched being set.  This
10166 	 * prevents us from potentially nominating it as a false LAST_BUDDY
10167 	 * below.
10168 	 */
10169 	if (!sched_feat(PREEMPT_SHORT) && test_tsk_need_resched(rq->curr))
10170 		return;
10171 
10172 	if (!sched_feat(WAKEUP_PREEMPTION))
10173 		return;
10174 
10175 	WARN_ON_ONCE(!pse);
10176 
10177 	cse_is_idle = se_is_idle(se);
10178 	pse_is_idle = se_is_idle(pse);
10179 
10180 	nse = se;
10181 	/*
10182 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
10183 	 * in the inverse case).
10184 	 */
10185 	if (cse_is_idle && !pse_is_idle)
10186 		goto preempt;
10187 
10188 	update_curr_fair(rq);
10189 
10190 	if (cse_is_idle != pse_is_idle)
10191 		goto update;
10192 
10193 	/*
10194 	 * BATCH and IDLE tasks do not preempt others.
10195 	 */
10196 	if (unlikely(!normal_policy(p->policy)))
10197 		goto update;
10198 
10199 	/*
10200 	 * Do not preempt for tasks that are sched_delayed as it would violate
10201 	 * EEVDF to forcibly queue an ineligible task.
10202 	 */
10203 	if (pse->sched_delayed)
10204 		goto update;
10205 
10206 	/*
10207 	 * If @p has a shorter slice than current and @p is eligible, override
10208 	 * current's slice protection in order to allow preemption.
10209 	 */
10210 	if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
10211 		preempt_action = PREEMPT_WAKEUP_SHORT;
10212 		goto pick;
10213 	}
10214 
10215 	/*
10216 	 * Ignore wakee preemption on WF_FORK as it is less likely that
10217 	 * there is shared data as exec often follow fork.
10218 	 */
10219 	if (wake_flags & WF_FORK)
10220 		goto update;
10221 
10222 	/* Prefer picking wakee soon if appropriate. */
10223 	if (sched_feat(NEXT_BUDDY) && set_preempt_buddy(cfs_rq, pse)) {
10224 		/*
10225 		 * Decide whether to obey WF_SYNC hint for a new buddy. Old
10226 		 * buddies are ignored as they may not be relevant to the
10227 		 * waker and less likely to be cache hot.
10228 		 */
10229 		if (wake_flags & WF_SYNC)
10230 			preempt_action = preempt_sync(rq, wake_flags, pse, se);
10231 	}
10232 
10233 	switch (preempt_action) {
10234 	case PREEMPT_WAKEUP_NONE:
10235 		return;
10236 	case PREEMPT_WAKEUP_RESCHED:
10237 		goto preempt;
10238 	case PREEMPT_WAKEUP_SHORT:
10239 		fallthrough;
10240 	case PREEMPT_WAKEUP_PICK:
10241 		break;
10242 	}
10243 
10244 pick:
10245 	if (cfs_rq->h_nr_queued) {
10246 		nse = pick_next_entity(rq, preempt_action != PREEMPT_WAKEUP_SHORT);
10247 		if (unlikely(!nse))
10248 			goto pick;
10249 
10250 		/* If @p has become the most eligible task, force preemption */
10251 		if (nse == pse)
10252 			goto preempt;
10253 	}
10254 
10255 	/*
10256 	 * If @p is eligible but not the next task to run then cancel protection
10257 	 * to prevent large scheduling latency
10258 	 */
10259 	if (preempt_action == PREEMPT_WAKEUP_SHORT && entity_eligible(cfs_rq, pse))
10260 		goto preempt;
10261 update:
10262 	if (sched_feat(RUN_TO_PARITY))
10263 		update_protect_slice(cfs_rq, se);
10264 
10265 	return;
10266 
10267 preempt:
10268 	cancel_protect_slice(se);
10269 
10270 	if (preempt_action == PREEMPT_WAKEUP_SHORT)
10271 		set_short_buddy(cfs_rq, pse);
10272 
10273 	resched_curr_lazy(rq);
10274 }
10275 
10276 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
10277 	__must_hold(__rq_lockp(rq))
10278 {
10279 	struct cfs_rq *cfs_rq = &rq->cfs;
10280 	struct sched_entity *se;
10281 	struct task_struct *p;
10282 	int new_tasks;
10283 
10284 again:
10285 	if (!cfs_rq->h_nr_queued)
10286 		goto idle;
10287 
10288 	/* Might not have done put_prev_entity() */
10289 	if (cfs_rq->curr && cfs_rq->curr->on_rq)
10290 		update_curr_eevdf(cfs_rq);
10291 
10292 	se = pick_next_entity(rq, true);
10293 	if (!se)
10294 		goto again;
10295 
10296 	p = task_of(se);
10297 	return p;
10298 
10299 idle:
10300 	if (sched_core_enabled(rq))
10301 		return NULL;
10302 
10303 	new_tasks = sched_balance_newidle(rq, rf);
10304 	if (new_tasks < 0)
10305 		return RETRY_TASK;
10306 	if (new_tasks > 0)
10307 		goto again;
10308 	return NULL;
10309 }
10310 
10311 static struct task_struct *
10312 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
10313 	__must_hold(__rq_lockp(dl_se->rq))
10314 {
10315 	return pick_task_fair(dl_se->rq, rf);
10316 }
10317 
10318 void fair_server_init(struct rq *rq)
10319 {
10320 	struct sched_dl_entity *dl_se = &rq->fair_server;
10321 
10322 	init_dl_entity(dl_se);
10323 
10324 	dl_server_init(dl_se, rq, fair_server_pick_task);
10325 }
10326 
10327 /*
10328  * Account for a descheduled task:
10329  */
10330 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
10331 {
10332 	struct sched_entity *se = &prev->se;
10333 	struct cfs_rq *cfs_rq = &rq->cfs;
10334 	struct sched_entity *nse = NULL;
10335 
10336 #ifdef CONFIG_FAIR_GROUP_SCHED
10337 	if (next && next->sched_class == &fair_sched_class)
10338 		nse = &next->se;
10339 #endif
10340 
10341 	while (se) {
10342 		cfs_rq = cfs_rq_of(se);
10343 		if (!nse || cfs_rq->h_curr)
10344 			put_prev_entity(cfs_rq, se);
10345 #ifdef CONFIG_FAIR_GROUP_SCHED
10346 		if (nse) {
10347 			if (is_same_group(se, nse))
10348 				break;
10349 
10350 			int d = nse->depth - se->depth;
10351 			if (d >= 0) {
10352 				/* nse has equal or greater depth, ascend */
10353 				nse = parent_entity(nse);
10354 				/* if nse is the deeper, do not ascend se */
10355 				if (d > 0)
10356 					continue;
10357 			}
10358 		}
10359 #endif
10360 		se = parent_entity(se);
10361 	}
10362 
10363 	/* Put 'current' back into the tree. */
10364 	cfs_rq = &rq->cfs;
10365 	se = &prev->se;
10366 	WARN_ON_ONCE(cfs_rq->curr != se);
10367 	cfs_rq->curr = NULL;
10368 	if (se->on_rq)
10369 		__enqueue_entity(cfs_rq, se);
10370 }
10371 
10372 /*
10373  * sched_yield() is very simple
10374  */
10375 static void yield_task_fair(struct rq *rq)
10376 {
10377 	struct task_struct *curr = rq->donor;
10378 	struct sched_entity *se = &curr->se;
10379 	struct cfs_rq *cfs_rq = &rq->cfs;
10380 
10381 	/*
10382 	 * Are we the only task in the tree?
10383 	 */
10384 	if (unlikely(rq->nr_running == 1))
10385 		return;
10386 
10387 	clear_buddies(cfs_rq, se);
10388 
10389 	update_rq_clock(rq);
10390 	/*
10391 	 * Update run-time statistics of the 'current'.
10392 	 */
10393 	update_curr_eevdf(cfs_rq);
10394 	/*
10395 	 * Tell update_rq_clock() that we've just updated,
10396 	 * so we don't do microscopic update in schedule()
10397 	 * and double the fastpath cost.
10398 	 */
10399 	rq_clock_skip_update(rq);
10400 
10401 	/*
10402 	 * Forfeit the remaining vruntime, only if the entity is eligible. This
10403 	 * condition is necessary because in core scheduling we prefer to run
10404 	 * ineligible tasks rather than force idling. If this happens we may
10405 	 * end up in a loop where the core scheduler picks the yielding task,
10406 	 * which yields immediately again; without the condition the vruntime
10407 	 * ends up quickly running away.
10408 	 */
10409 	if (entity_eligible(cfs_rq, se)) {
10410 		se->vruntime = se->deadline;
10411 		update_deadline(cfs_rq, se);
10412 	}
10413 }
10414 
10415 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
10416 {
10417 	struct sched_entity *se = &p->se;
10418 
10419 	/* !se->on_rq also covers throttled task */
10420 	if (!se->on_rq || se->sched_delayed)
10421 		return false;
10422 
10423 	/* Tell the scheduler that we'd really like se to run next. */
10424 	set_next_buddy(&task_rq(p)->cfs, se);
10425 
10426 	yield_task_fair(rq);
10427 
10428 	return true;
10429 }
10430 
10431 /**************************************************
10432  * Fair scheduling class load-balancing methods.
10433  *
10434  * BASICS
10435  *
10436  * The purpose of load-balancing is to achieve the same basic fairness the
10437  * per-CPU scheduler provides, namely provide a proportional amount of compute
10438  * time to each task. This is expressed in the following equation:
10439  *
10440  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
10441  *
10442  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
10443  * W_i,0 is defined as:
10444  *
10445  *   W_i,0 = \Sum_j w_i,j                                             (2)
10446  *
10447  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
10448  * is derived from the nice value as per sched_prio_to_weight[].
10449  *
10450  * The weight average is an exponential decay average of the instantaneous
10451  * weight:
10452  *
10453  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
10454  *
10455  * C_i is the compute capacity of CPU i, typically it is the
10456  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
10457  * can also include other factors [XXX].
10458  *
10459  * To achieve this balance we define a measure of imbalance which follows
10460  * directly from (1):
10461  *
10462  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
10463  *
10464  * We them move tasks around to minimize the imbalance. In the continuous
10465  * function space it is obvious this converges, in the discrete case we get
10466  * a few fun cases generally called infeasible weight scenarios.
10467  *
10468  * [XXX expand on:
10469  *     - infeasible weights;
10470  *     - local vs global optima in the discrete case. ]
10471  *
10472  *
10473  * SCHED DOMAINS
10474  *
10475  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
10476  * for all i,j solution, we create a tree of CPUs that follows the hardware
10477  * topology where each level pairs two lower groups (or better). This results
10478  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
10479  * tree to only the first of the previous level and we decrease the frequency
10480  * of load-balance at each level inversely proportional to the number of CPUs in
10481  * the groups.
10482  *
10483  * This yields:
10484  *
10485  *     log_2 n     1     n
10486  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
10487  *     i = 0      2^i   2^i
10488  *                               `- size of each group
10489  *         |         |     `- number of CPUs doing load-balance
10490  *         |         `- freq
10491  *         `- sum over all levels
10492  *
10493  * Coupled with a limit on how many tasks we can migrate every balance pass,
10494  * this makes (5) the runtime complexity of the balancer.
10495  *
10496  * An important property here is that each CPU is still (indirectly) connected
10497  * to every other CPU in at most O(log n) steps:
10498  *
10499  * The adjacency matrix of the resulting graph is given by:
10500  *
10501  *             log_2 n
10502  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
10503  *             k = 0
10504  *
10505  * And you'll find that:
10506  *
10507  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
10508  *
10509  * Showing there's indeed a path between every CPU in at most O(log n) steps.
10510  * The task movement gives a factor of O(m), giving a convergence complexity
10511  * of:
10512  *
10513  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
10514  *
10515  *
10516  * WORK CONSERVING
10517  *
10518  * In order to avoid CPUs going idle while there's still work to do, new idle
10519  * balancing is more aggressive and has the newly idle CPU iterate up the domain
10520  * tree itself instead of relying on other CPUs to bring it work.
10521  *
10522  * This adds some complexity to both (5) and (8) but it reduces the total idle
10523  * time.
10524  *
10525  * [XXX more?]
10526  *
10527  *
10528  * CGROUPS
10529  *
10530  * Cgroups make a horror show out of (2), instead of a simple sum we get:
10531  *
10532  *                                s_k,i
10533  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
10534  *                                 S_k
10535  *
10536  * Where
10537  *
10538  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
10539  *
10540  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
10541  *
10542  * The big problem is S_k, its a global sum needed to compute a local (W_i)
10543  * property.
10544  *
10545  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
10546  *      rewrite all of this once again.]
10547  */
10548 
10549 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
10550 
10551 enum fbq_type { regular, remote, all };
10552 
10553 /*
10554  * 'group_type' describes the group of CPUs at the moment of load balancing.
10555  *
10556  * The enum is ordered by pulling priority, with the group with lowest priority
10557  * first so the group_type can simply be compared when selecting the busiest
10558  * group. See update_sd_pick_busiest().
10559  */
10560 enum group_type {
10561 	/* The group has spare capacity that can be used to run more tasks.  */
10562 	group_has_spare = 0,
10563 	/*
10564 	 * The group is fully used and the tasks don't compete for more CPU
10565 	 * cycles. Nevertheless, some tasks might wait before running.
10566 	 */
10567 	group_fully_busy,
10568 	/*
10569 	 * One task doesn't fit with CPU's capacity and must be migrated to a
10570 	 * more powerful CPU.
10571 	 */
10572 	group_misfit_task,
10573 	/*
10574 	 * Balance SMT group that's fully busy. Can benefit from migration
10575 	 * a task on SMT with busy sibling to another CPU on idle core.
10576 	 */
10577 	group_smt_balance,
10578 	/*
10579 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
10580 	 * and the task should be migrated to it instead of running on the
10581 	 * current CPU.
10582 	 */
10583 	group_asym_packing,
10584 	/*
10585 	 * The tasks' affinity constraints previously prevented the scheduler
10586 	 * from balancing the load across the system.
10587 	 */
10588 	group_imbalanced,
10589 	/*
10590 	 * There are tasks running on non-preferred LLC, possible to move
10591 	 * them to their preferred LLC without creating too much imbalance.
10592 	 * The priority of group_llc_balance is lower than that of
10593 	 * group_overloaded and higher than that of all other group types.
10594 	 * This is because group_llc_balance may exacerbate load imbalance.
10595 	 * If the LLC balancing attempt fails, the nr_balance_failed
10596 	 * mechanism will trigger other group types to rebalance the load.
10597 	 */
10598 	group_llc_balance,
10599 	/*
10600 	 * The CPU is overloaded and can't provide expected CPU cycles to all
10601 	 * tasks.
10602 	 */
10603 	group_overloaded
10604 };
10605 
10606 enum migration_type {
10607 	migrate_load = 0,
10608 	migrate_util,
10609 	migrate_task,
10610 	migrate_misfit,
10611 	migrate_llc_task
10612 };
10613 
10614 #define LBF_ALL_PINNED	0x01
10615 #define LBF_NEED_BREAK	0x02
10616 #define LBF_DST_PINNED  0x04
10617 #define LBF_SOME_PINNED	0x08
10618 #define LBF_ACTIVE_LB	0x10
10619 #define LBF_LLC_PINNED	0x20
10620 #define LBF_ACTIVE_LB_LLC	0x40
10621 
10622 struct lb_env {
10623 	struct sched_domain	*sd;
10624 
10625 	struct rq		*src_rq;
10626 	int			src_cpu;
10627 
10628 	int			dst_cpu;
10629 	struct rq		*dst_rq;
10630 	bool			dst_core_idle;
10631 
10632 	struct cpumask		*dst_grpmask;
10633 	int			new_dst_cpu;
10634 	enum cpu_idle_type	idle;
10635 	long			imbalance;
10636 	/* The set of CPUs under consideration for load-balancing */
10637 	struct cpumask		*cpus;
10638 
10639 	unsigned int		flags;
10640 
10641 	unsigned int		loop;
10642 	unsigned int		loop_break;
10643 	unsigned int		loop_max;
10644 
10645 	enum fbq_type		fbq_type;
10646 	enum migration_type	migration_type;
10647 	struct list_head	tasks;
10648 };
10649 
10650 /*
10651  * Is this task likely cache-hot:
10652  */
10653 static int task_hot(struct task_struct *p, struct lb_env *env)
10654 {
10655 	s64 delta;
10656 
10657 	lockdep_assert_rq_held(env->src_rq);
10658 
10659 	if (p->sched_class != &fair_sched_class)
10660 		return 0;
10661 
10662 	if (unlikely(task_has_idle_policy(p)))
10663 		return 0;
10664 
10665 	/* SMT siblings share cache */
10666 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
10667 		return 0;
10668 
10669 	/*
10670 	 * Buddy candidates are cache hot:
10671 	 */
10672 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
10673 	    (&p->se == cfs_rq_of(&p->se)->next))
10674 		return 1;
10675 
10676 	if (sysctl_sched_migration_cost == -1)
10677 		return 1;
10678 
10679 	/*
10680 	 * Don't migrate task if the task's cookie does not match
10681 	 * with the destination CPU's core cookie.
10682 	 */
10683 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
10684 		return 1;
10685 
10686 	if (sysctl_sched_migration_cost == 0)
10687 		return 0;
10688 
10689 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
10690 
10691 	return delta < (s64)sysctl_sched_migration_cost;
10692 }
10693 
10694 #ifdef CONFIG_NUMA_BALANCING
10695 /*
10696  * Returns a positive value, if task migration degrades locality.
10697  * Returns 0, if task migration is not affected by locality.
10698  * Returns a negative value, if task migration improves locality i.e migration preferred.
10699  */
10700 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
10701 {
10702 	struct numa_group *numa_group = rcu_dereference_all(p->numa_group);
10703 	unsigned long src_weight, dst_weight;
10704 	int src_nid, dst_nid, dist;
10705 
10706 	if (!static_branch_likely(&sched_numa_balancing))
10707 		return 0;
10708 
10709 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
10710 		return 0;
10711 
10712 	src_nid = cpu_to_node(env->src_cpu);
10713 	dst_nid = cpu_to_node(env->dst_cpu);
10714 
10715 	if (src_nid == dst_nid)
10716 		return 0;
10717 
10718 	/* Migrating away from the preferred node is always bad. */
10719 	if (src_nid == p->numa_preferred_nid) {
10720 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
10721 			return 1;
10722 		else
10723 			return 0;
10724 	}
10725 
10726 	/* Encourage migration to the preferred node. */
10727 	if (dst_nid == p->numa_preferred_nid)
10728 		return -1;
10729 
10730 	/* Leaving a core idle is often worse than degrading locality. */
10731 	if (env->idle == CPU_IDLE)
10732 		return 0;
10733 
10734 	dist = node_distance(src_nid, dst_nid);
10735 	if (numa_group) {
10736 		src_weight = group_weight(p, src_nid, dist);
10737 		dst_weight = group_weight(p, dst_nid, dist);
10738 	} else {
10739 		src_weight = task_weight(p, src_nid, dist);
10740 		dst_weight = task_weight(p, dst_nid, dist);
10741 	}
10742 
10743 	return src_weight - dst_weight;
10744 }
10745 
10746 #else /* !CONFIG_NUMA_BALANCING: */
10747 static inline long migrate_degrades_locality(struct task_struct *p,
10748 					     struct lb_env *env)
10749 {
10750 	return 0;
10751 }
10752 #endif /* !CONFIG_NUMA_BALANCING */
10753 
10754 /*
10755  * Check whether the task is ineligible on the destination cpu
10756  *
10757  * When the PLACE_LAG scheduling feature is enabled and
10758  * dst_cfs_rq->nr_queued is greater than 1, if the task
10759  * is ineligible, it will also be ineligible when
10760  * it is migrated to the destination cpu.
10761  */
10762 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
10763 {
10764 	struct cfs_rq *dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
10765 
10766 	if (sched_feat(PLACE_LAG) && dst_cfs_rq->h_nr_queued &&
10767 	    !entity_eligible(&task_rq(p)->cfs, &p->se))
10768 		return 1;
10769 
10770 	return 0;
10771 }
10772 
10773 #ifdef CONFIG_SCHED_CACHE
10774 /*
10775  * The margin used when comparing LLC utilization with CPU capacity.
10776  * It determines the LLC load level where active LLC aggregation is
10777  * done.
10778  * Derived from fits_capacity().
10779  *
10780  * (default: ~50%, tunable via debugfs)
10781  */
10782 static bool fits_llc_capacity(unsigned long util, unsigned long max)
10783 {
10784 	u32 aggr_pct = llc_overaggr_pct;
10785 
10786 	/*
10787 	 * For single core systems, raise the aggregation
10788 	 * threshold to accommodate more tasks.
10789 	 */
10790 	if (cpu_smt_num_threads == 1)
10791 		aggr_pct = (aggr_pct * 3 / 2);
10792 
10793 	return util * 100 < max * aggr_pct;
10794 }
10795 
10796 /*
10797  * The margin used when comparing utilization.
10798  * is 'util1' noticeably greater than 'util2'
10799  * Derived from capacity_greater().
10800  * Bias is in perentage.
10801  */
10802 /* Allows dst util to be bigger than src util by up to bias percent */
10803 #define util_greater(util1, util2) \
10804 	((util1) * 100 > (util2) * (100 + llc_imb_pct))
10805 
10806 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util,
10807 					 unsigned long *cap)
10808 {
10809 	struct sched_domain_shared *sd_share;
10810 
10811 	sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
10812 	if (!sd_share)
10813 		return false;
10814 
10815 	*util = READ_ONCE(sd_share->util_avg);
10816 	*cap = READ_ONCE(sd_share->capacity);
10817 
10818 	return true;
10819 }
10820 
10821 /*
10822  * Decision matrix according to the LLC utilization. To
10823  * decide whether we can do task aggregation across LLC.
10824  *
10825  * By default, 50% is the threshold for treating the LLC
10826  * as busy. The reason for choosing 50% is to avoid saturation
10827  * of SMT-2, and it is also a safe cutoff for other SMT-n
10828  * platforms. SMT-1 has higher threshold because it is
10829  * supposed to accommodate more tasks, see fits_llc_capacity().
10830  *
10831  * 20% is the utilization imbalance percentage to decide
10832  * if the preferred LLC is busier than the non-preferred LLC.
10833  * 20 is a little higher than the LLC domain's imbalance_pct
10834  * 17. The hysteresis is used to avoid task bouncing between the
10835  * preferred LLC and the non-preferred LLC, and it will
10836  * be turned into tunable debugfs.
10837  *
10838  * 1. moving towards the preferred LLC, dst is the preferred
10839  *    LLC, src is not.
10840  *
10841  * src \ dst      30%  40%  50%  60%
10842  * 30%            Y    Y    Y    N
10843  * 40%            Y    Y    Y    Y
10844  * 50%            Y    Y    G    G
10845  * 60%            Y    Y    G    G
10846  *
10847  * 2. moving out of the preferred LLC, src is the preferred
10848  *    LLC, dst is not:
10849  *
10850  * src \ dst      30%  40%  50%  60%
10851  * 30%            N    N    N    N
10852  * 40%            N    N    N    N
10853  * 50%            N    N    G    G
10854  * 60%            Y    N    G    G
10855  *
10856  * src :      src_util
10857  * dst :      dst_util
10858  * Y :        Yes, migrate
10859  * N :        No, do not migrate
10860  * G :        let the Generic load balance to even the load.
10861  *
10862  * The intention is that if both LLCs are quite busy, cache aware
10863  * load balance should not be performed, and generic load balance
10864  * should take effect. However, if one is busy and the other is not,
10865  * the preferred LLC capacity(50%) and imbalance criteria(20%) should
10866  * be considered to determine whether LLC aggregation should be
10867  * performed to bias the load towards the preferred LLC.
10868  */
10869 
10870 /* migration decision, 3 states are orthogonal. */
10871 enum llc_mig {
10872 	mig_forbid = 0,		/* N: Don't migrate task, respect LLC preference */
10873 	mig_llc,		/* Y: Do LLC preference based migration */
10874 	mig_unrestricted	/* G: Don't restrict generic load balance migration */
10875 };
10876 
10877 /*
10878  * Check if task can be moved from the source LLC to the
10879  * destination LLC without breaking cache aware preferrence.
10880  * src_cpu and dst_cpu are arbitrary CPUs within the source
10881  * and destination LLCs, respectively.
10882  */
10883 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu,
10884 				    unsigned long tsk_util,
10885 				    bool to_pref)
10886 {
10887 	unsigned long src_util, dst_util, src_cap, dst_cap;
10888 
10889 	if (!get_llc_stats(src_cpu, &src_util, &src_cap) ||
10890 	    !get_llc_stats(dst_cpu, &dst_util, &dst_cap))
10891 		return mig_unrestricted;
10892 
10893 	src_util = src_util < tsk_util ? 0 : src_util - tsk_util;
10894 	dst_util = dst_util + tsk_util;
10895 
10896 	if (!fits_llc_capacity(dst_util, dst_cap) &&
10897 	    !fits_llc_capacity(src_util, src_cap))
10898 		return mig_unrestricted;
10899 
10900 	if (to_pref) {
10901 		/*
10902 		 * Don't migrate if we will get preferred LLC too
10903 		 * heavily loaded and if the dest is much busier
10904 		 * than the src, in which case migration will
10905 		 * increase the imbalance too much.
10906 		 */
10907 		if (!fits_llc_capacity(dst_util, dst_cap) &&
10908 		    util_greater(dst_util, src_util))
10909 			return mig_forbid;
10910 	} else {
10911 		/*
10912 		 * Don't migrate if we will leave preferred LLC
10913 		 * too idle, or if this migration leads to the
10914 		 * non-preferred LLC falls within sysctl_aggr_imb percent
10915 		 * of preferred LLC, leading to migration again
10916 		 * back to preferred LLC.
10917 		 */
10918 		if (fits_llc_capacity(src_util, src_cap) ||
10919 		    !util_greater(src_util, dst_util))
10920 			return mig_forbid;
10921 	}
10922 	return mig_llc;
10923 }
10924 
10925 static inline bool task_misfits_asym_cpu(struct lb_env *env, struct task_struct *p)
10926 {
10927 	/*
10928 	 * On asymmetric CPU capacity domains, do not let cache-aware
10929 	 * balancing pull the task onto a destination CPU that cannot
10930 	 * accommodate it. Doing so would turn the task into a misfit on
10931 	 * the destination, trading a cache-locality gain for a capacity
10932 	 * loss. If the task already does not fit its source CPU, the move
10933 	 * cannot make things worse, so let the LLC preference decide.
10934 	 */
10935 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && p &&
10936 	    !task_fits_cpu(p, env->dst_cpu) &&
10937 	    task_fits_cpu(p, env->src_cpu))
10938 		return true;
10939 
10940 	return false;
10941 }
10942 
10943 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu);
10944 
10945 /*
10946  * Check if task p can migrate from source LLC to
10947  * destination LLC in terms of cache aware load balance.
10948  */
10949 static enum llc_mig can_migrate_llc_task(struct lb_env *env,
10950 					 struct task_struct *p)
10951 {
10952 	struct sched_cache_group *grp;
10953 	bool to_pref;
10954 	int cpu, src_cpu, dst_cpu;
10955 
10956 	if (task_misfits_asym_cpu(env, p))
10957 		return mig_forbid;
10958 
10959 	src_cpu = env->src_cpu;
10960 	dst_cpu = env->dst_cpu;
10961 	grp = rcu_dereference_all(p->sched_cache_grp);
10962 	if (!grp)
10963 		return mig_unrestricted;
10964 
10965 	cpu = READ_ONCE(grp->cpu);
10966 	if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu))
10967 		return mig_unrestricted;
10968 
10969 	/* Prioritize asym packing to idle core over cache awareness */
10970 	if (env->idle && sched_asym(env->sd, dst_cpu, src_cpu))
10971 		return mig_unrestricted;
10972 
10973 	/* skip cache aware load balance for too many threads */
10974 	if (invalid_llc_nr(grp, p, dst_cpu) ||
10975 	    exceed_llc_capacity(grp, dst_cpu)) {
10976 		if (READ_ONCE(grp->cpu) != -1)
10977 			WRITE_ONCE(grp->cpu, -1);
10978 		return mig_unrestricted;
10979 	}
10980 
10981 	if (cpus_share_cache(dst_cpu, cpu))
10982 		to_pref = true;
10983 	else if (cpus_share_cache(src_cpu, cpu))
10984 		to_pref = false;
10985 	else
10986 		return mig_unrestricted;
10987 
10988 	return can_migrate_llc(src_cpu, dst_cpu,
10989 			       task_util(p), to_pref);
10990 }
10991 
10992 /*
10993  * Check if active load balance breaks LLC locality in
10994  * terms of cache aware load balance. The load level and
10995  * imbalance do not warrant breaking LLC preference per
10996  * the can_migrate_llc() policy. Here, the benefit of
10997  * LLC locality outweighs the power efficiency gained from
10998  * migrating the only runnable task away.
10999  */
11000 static inline bool
11001 alb_break_llc(struct lb_env *env)
11002 {
11003 	if (!sched_cache_enabled())
11004 		return false;
11005 
11006 	if (cpus_share_cache(env->src_cpu, env->dst_cpu))
11007 		return false;
11008 	/*
11009 	 * All tasks prefer to stay on their current CPU.
11010 	 * Do not pull a task from its preferred CPU if:
11011 	 * 1. It is the only task running and does not exceed
11012 	 *    imbalance allowance; OR
11013 	 * 2. Migrating it away from its preferred LLC would violate
11014 	 *    the cache-aware scheduling policy.
11015 	 */
11016 	if (env->src_rq->nr_pref_llc_running &&
11017 	    env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) {
11018 		unsigned long util = 0;
11019 		struct task_struct *cur;
11020 
11021 		/*
11022 		 * Migrating misfit tasks from current CPU
11023 		 * to CPU with a better fit.
11024 		 * Prioritize that over LLC preference.
11025 		 */
11026 		if (env->migration_type == migrate_misfit)
11027 			return false;
11028 
11029 		if (env->src_rq->nr_running <= 1)
11030 			return true;
11031 
11032 		cur = rcu_dereference_all(env->src_rq->curr);
11033 		/*
11034 		 * Active balance only detaches CFS tasks, so a non-fair
11035 		 * curr is never migrated. Ignore it and avoid using its
11036 		 * state util in the misfit and LLC checks.
11037 		 */
11038 		if (cur && cur->sched_class != &fair_sched_class)
11039 			cur = NULL;
11040 		if (cur)
11041 			util = task_util(cur);
11042 
11043 		if (task_misfits_asym_cpu(env, cur) ||
11044 		    can_migrate_llc(env->src_cpu, env->dst_cpu,
11045 				    util, false) == mig_forbid)
11046 			return true;
11047 	}
11048 
11049 	return false;
11050 }
11051 
11052 /*
11053  * Returns true if p's preferred LLC does not match the destination CPU
11054  * under migrate_llc_task semantics. Passive LB passes migrate_llc_task
11055  * in env->migration_type, while active LB carries LBF_ACTIVE_LB_LLC in
11056  * env->flags to avoid overwriting env->migration_type.
11057  */
11058 static inline bool
11059 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env)
11060 {
11061 	return sched_cache_enabled() &&
11062 	       (env->migration_type == migrate_llc_task ||
11063 		env->flags & LBF_ACTIVE_LB_LLC) &&
11064 	       READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu);
11065 }
11066 
11067 /*
11068  * Check if migrating task p from env->src_cpu to
11069  * env->dst_cpu breaks LLC localiy.
11070  */
11071 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
11072 {
11073 	if (!sched_cache_enabled())
11074 		return false;
11075 
11076 	if (task_has_sched_core(p))
11077 		return false;
11078 	/*
11079 	 * Skip over tasks that would degrade LLC locality;
11080 	 * only when nr_balanced_failed is sufficiently high do we
11081 	 * ignore this constraint.
11082 	 *
11083 	 * Threshold of cache_nice_tries is set to 1 higher
11084 	 * than nr_balance_failed to avoid excessive task
11085 	 * migration at the same time.
11086 	 */
11087 	if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
11088 		return false;
11089 
11090 	/*
11091 	 * We know the env->src_cpu has some tasks prefer to
11092 	 * run on env->dst_cpu, skip the tasks do not prefer
11093 	 * env->dst_cpu, and find the one that prefers.
11094 	 */
11095 	if (migrate_llc_task_wrong_dst(p, env))
11096 		return true;
11097 
11098 	if (can_migrate_llc_task(env, p) != mig_forbid)
11099 		return false;
11100 
11101 	return true;
11102 }
11103 
11104 #else
11105 static inline bool get_llc_stats(int cpu, unsigned long *util,
11106 				 unsigned long *cap)
11107 {
11108 	return false;
11109 }
11110 
11111 static inline bool
11112 alb_break_llc(struct lb_env *env)
11113 {
11114 	return false;
11115 }
11116 
11117 static inline bool
11118 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env)
11119 {
11120 	return false;
11121 }
11122 
11123 static inline bool
11124 migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
11125 {
11126 	return false;
11127 }
11128 #endif
11129 /*
11130  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
11131  */
11132 static
11133 int can_migrate_task(struct task_struct *p, struct lb_env *env)
11134 {
11135 	long degrades, hot;
11136 
11137 	lockdep_assert_rq_held(env->src_rq);
11138 	if (p->sched_task_hot)
11139 		p->sched_task_hot = 0;
11140 
11141 	/*
11142 	 * We do not migrate tasks that are:
11143 	 * 1) delayed dequeued unless we migrate load, or
11144 	 * 2) target cfs_rq is in throttled hierarchy, or
11145 	 * 3) cannot be migrated to this CPU due to cpus_ptr, or
11146 	 * 4) running (obviously), or
11147 	 * 5) are cache-hot on their current CPU, or
11148 	 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
11149 	 */
11150 	if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
11151 		return 0;
11152 
11153 	if (lb_throttled_hierarchy(p, env->dst_cpu))
11154 		return 0;
11155 
11156 	/*
11157 	 * We want to prioritize the migration of eligible tasks.
11158 	 * For ineligible tasks we soft-limit them and only allow
11159 	 * them to migrate when nr_balance_failed is non-zero to
11160 	 * avoid load-balancing trying very hard to balance the load.
11161 	 */
11162 	if (!env->sd->nr_balance_failed &&
11163 	    task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
11164 		return 0;
11165 
11166 	/* Disregard percpu kthreads; they are where they need to be. */
11167 	if (kthread_is_per_cpu(p))
11168 		return 0;
11169 
11170 	if (task_is_blocked(p))
11171 		return 0;
11172 
11173 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
11174 		int cpu;
11175 
11176 		schedstat_inc(p->stats.nr_failed_migrations_affine);
11177 
11178 		env->flags |= LBF_SOME_PINNED;
11179 
11180 		/*
11181 		 * Remember if this task can be migrated to any other CPU in
11182 		 * our sched_group. We may want to revisit it if we couldn't
11183 		 * meet load balance goals by pulling other tasks on src_cpu.
11184 		 *
11185 		 * Avoid computing new_dst_cpu
11186 		 * - for NEWLY_IDLE
11187 		 * - if we have already computed one in current iteration
11188 		 * - if it's an active balance
11189 		 */
11190 		if (env->idle == CPU_NEWLY_IDLE ||
11191 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
11192 			return 0;
11193 
11194 		/* Prevent to re-select dst_cpu via env's CPUs: */
11195 		cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
11196 
11197 		if (cpu < nr_cpu_ids) {
11198 			env->flags |= LBF_DST_PINNED;
11199 			env->new_dst_cpu = cpu;
11200 		}
11201 
11202 		return 0;
11203 	}
11204 
11205 	/* Record that we found at least one task that could run on dst_cpu */
11206 	env->flags &= ~LBF_ALL_PINNED;
11207 
11208 	if (task_on_cpu(env->src_rq, p) ||
11209 	    task_current_donor(env->src_rq, p)) {
11210 		schedstat_inc(p->stats.nr_failed_migrations_running);
11211 		return 0;
11212 	}
11213 
11214 	/*
11215 	 * Aggressive migration if:
11216 	 * 1) active balance
11217 	 * 2) destination numa is preferred
11218 	 * 3) task is cache cold, or
11219 	 * 4) too many balance attempts have failed.
11220 	 */
11221 	if (env->flags & LBF_ACTIVE_LB)
11222 		return !migrate_llc_task_wrong_dst(p, env);
11223 
11224 	degrades = migrate_degrades_locality(p, env);
11225 	if (!degrades) {
11226 		/*
11227 		 * If the NUMA locality is not broken,
11228 		 * further check if migration would hurt
11229 		 * LLC locality.
11230 		 */
11231 		if (migrate_degrades_llc(p, env)) {
11232 			/*
11233 			 * If regular load balancing fails to pull a task
11234 			 * due to LLC locality, this is expected behavior
11235 			 * and we set LBF_LLC_PINNED so we don't increase
11236 			 * nr_balance_failed unecessarily.
11237 			 */
11238 			if (env->migration_type != migrate_llc_task)
11239 				env->flags |= LBF_LLC_PINNED;
11240 
11241 			return 0;
11242 		}
11243 
11244 		hot = task_hot(p, env);
11245 	} else {
11246 		hot = degrades > 0;
11247 	}
11248 
11249 	if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
11250 		if (hot)
11251 			p->sched_task_hot = 1;
11252 		return 1;
11253 	}
11254 
11255 	schedstat_inc(p->stats.nr_failed_migrations_hot);
11256 	return 0;
11257 }
11258 
11259 /*
11260  * detach_task() -- detach the task for the migration specified in env
11261  */
11262 static void detach_task(struct task_struct *p, struct lb_env *env)
11263 {
11264 	lockdep_assert_rq_held(env->src_rq);
11265 
11266 	if (p->sched_task_hot) {
11267 		p->sched_task_hot = 0;
11268 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
11269 		schedstat_inc(p->stats.nr_forced_migrations);
11270 	}
11271 
11272 	WARN_ON(task_current(env->src_rq, p));
11273 	WARN_ON(task_current_donor(env->src_rq, p));
11274 
11275 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
11276 	set_task_cpu(p, env->dst_cpu);
11277 }
11278 
11279 /*
11280  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
11281  * part of active balancing operations within "domain".
11282  *
11283  * Returns a task if successful and NULL otherwise.
11284  */
11285 static struct task_struct *detach_one_task(struct lb_env *env)
11286 {
11287 	struct task_struct *p;
11288 
11289 	lockdep_assert_rq_held(env->src_rq);
11290 
11291 	list_for_each_entry_reverse(p,
11292 			&env->src_rq->cfs_tasks, se.group_node) {
11293 		if (!can_migrate_task(p, env))
11294 			continue;
11295 
11296 		detach_task(p, env);
11297 
11298 		/*
11299 		 * Right now, this is only the second place where
11300 		 * lb_gained[env->idle] is updated (other is detach_tasks)
11301 		 * so we can safely collect stats here rather than
11302 		 * inside detach_tasks().
11303 		 */
11304 		schedstat_inc(env->sd->lb_gained[env->idle]);
11305 		return p;
11306 	}
11307 	return NULL;
11308 }
11309 
11310 /*
11311  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
11312  * busiest_rq, as part of a balancing operation within domain "sd".
11313  *
11314  * Returns number of detached tasks if successful and 0 otherwise.
11315  */
11316 static int detach_tasks(struct lb_env *env)
11317 {
11318 	struct list_head *tasks = &env->src_rq->cfs_tasks;
11319 	unsigned long util, load;
11320 	struct task_struct *p;
11321 	int detached = 0;
11322 
11323 	lockdep_assert_rq_held(env->src_rq);
11324 
11325 	/*
11326 	 * Source run queue has been emptied by another CPU, clear
11327 	 * LBF_ALL_PINNED flag as we will not test any task.
11328 	 */
11329 	if (env->src_rq->nr_running <= 1) {
11330 		env->flags &= ~LBF_ALL_PINNED;
11331 		return 0;
11332 	}
11333 
11334 	if (env->imbalance <= 0)
11335 		return 0;
11336 
11337 	while (!list_empty(tasks)) {
11338 		/*
11339 		 * We don't want to steal all, otherwise we may be treated likewise,
11340 		 * which could at worst lead to a livelock crash.
11341 		 */
11342 		if (env->idle && env->src_rq->nr_running <= 1)
11343 			break;
11344 
11345 		env->loop++;
11346 		/* We've more or less seen every task there is, call it quits */
11347 		if (env->loop > env->loop_max)
11348 			break;
11349 
11350 		/* take a breather every nr_migrate tasks */
11351 		if (env->loop > env->loop_break) {
11352 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
11353 			env->flags |= LBF_NEED_BREAK;
11354 			break;
11355 		}
11356 
11357 		p = list_last_entry(tasks, struct task_struct, se.group_node);
11358 
11359 		if (!can_migrate_task(p, env))
11360 			goto next;
11361 
11362 		switch (env->migration_type) {
11363 		case migrate_load:
11364 			/*
11365 			 * Depending of the number of CPUs and tasks and the
11366 			 * cgroup hierarchy, task_h_load() can return a null
11367 			 * value. Make sure that env->imbalance decreases
11368 			 * otherwise detach_tasks() will stop only after
11369 			 * detaching up to loop_max tasks.
11370 			 */
11371 			load = max_t(unsigned long, task_h_load(p), 1);
11372 
11373 			if (sched_feat(LB_MIN) &&
11374 			    load < 16 && !env->sd->nr_balance_failed)
11375 				goto next;
11376 
11377 			/*
11378 			 * Make sure that we don't migrate too much load.
11379 			 * Nevertheless, let relax the constraint if
11380 			 * scheduler fails to find a good waiting task to
11381 			 * migrate.
11382 			 */
11383 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
11384 				goto next;
11385 
11386 			env->imbalance -= load;
11387 			break;
11388 
11389 		case migrate_util:
11390 			util = task_util_est(p);
11391 
11392 			if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
11393 				goto next;
11394 
11395 			env->imbalance -= util;
11396 			break;
11397 
11398 		case migrate_task:
11399 			env->imbalance--;
11400 			break;
11401 
11402 		case migrate_misfit:
11403 			/* This is not a misfit task */
11404 			if (task_fits_cpu(p, env->src_cpu))
11405 				goto next;
11406 
11407 			env->imbalance = 0;
11408 			break;
11409 
11410 		case migrate_llc_task:
11411 			env->imbalance--;
11412 			break;
11413 		}
11414 
11415 		detach_task(p, env);
11416 		list_add(&p->se.group_node, &env->tasks);
11417 
11418 		detached++;
11419 
11420 #ifdef CONFIG_PREEMPTION
11421 		/*
11422 		 * NEWIDLE balancing is a source of latency, so preemptible
11423 		 * kernels will stop after the first task is detached to minimize
11424 		 * the critical section.
11425 		 */
11426 		if (env->idle == CPU_NEWLY_IDLE)
11427 			break;
11428 #endif
11429 
11430 		/*
11431 		 * We only want to steal up to the prescribed amount of
11432 		 * load/util/tasks.
11433 		 */
11434 		if (env->imbalance <= 0)
11435 			break;
11436 
11437 		continue;
11438 next:
11439 		if (p->sched_task_hot)
11440 			schedstat_inc(p->stats.nr_failed_migrations_hot);
11441 
11442 		list_move(&p->se.group_node, tasks);
11443 	}
11444 
11445 	/*
11446 	 * Right now, this is one of only two places we collect this stat
11447 	 * so we can safely collect detach_one_task() stats here rather
11448 	 * than inside detach_one_task().
11449 	 */
11450 	schedstat_add(env->sd->lb_gained[env->idle], detached);
11451 
11452 	return detached;
11453 }
11454 
11455 /*
11456  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
11457  * new rq.
11458  */
11459 static void attach_tasks(struct lb_env *env)
11460 {
11461 	__attach_tasks(env->dst_rq, &env->tasks);
11462 }
11463 
11464 #ifdef CONFIG_NO_HZ_COMMON
11465 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq)
11466 {
11467 	if (cfs_rq->avg.load_avg)
11468 		return true;
11469 
11470 	if (cfs_rq->avg.util_avg)
11471 		return true;
11472 
11473 	return false;
11474 }
11475 
11476 static inline bool others_have_blocked(struct rq *rq)
11477 {
11478 	if (cpu_util_rt(rq))
11479 		return true;
11480 
11481 	if (cpu_util_dl(rq))
11482 		return true;
11483 
11484 	if (hw_load_avg(rq))
11485 		return true;
11486 
11487 	if (cpu_util_irq(rq))
11488 		return true;
11489 
11490 	return false;
11491 }
11492 
11493 static inline void update_blocked_load_tick(struct rq *rq)
11494 {
11495 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
11496 }
11497 
11498 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load)
11499 {
11500 	if (!has_blocked_load)
11501 		rq->has_blocked_load = 0;
11502 }
11503 #else /* !CONFIG_NO_HZ_COMMON: */
11504 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; }
11505 static inline bool others_have_blocked(struct rq *rq) { return false; }
11506 static inline void update_blocked_load_tick(struct rq *rq) {}
11507 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {}
11508 #endif /* !CONFIG_NO_HZ_COMMON */
11509 
11510 static bool __update_blocked_others(struct rq *rq, bool *done)
11511 {
11512 	bool updated;
11513 
11514 	/*
11515 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
11516 	 * DL and IRQ signals have been updated before updating CFS.
11517 	 */
11518 	updated = update_other_load_avgs(rq);
11519 
11520 	if (others_have_blocked(rq))
11521 		*done = false;
11522 
11523 	return updated;
11524 }
11525 
11526 #ifdef CONFIG_FAIR_GROUP_SCHED
11527 
11528 static bool __update_blocked_fair(struct rq *rq, bool *done)
11529 {
11530 	struct cfs_rq *cfs_rq, *pos;
11531 	bool decayed = false;
11532 
11533 	/*
11534 	 * Iterates the task_group tree in a bottom up fashion, see
11535 	 * list_add_leaf_cfs_rq() for details.
11536 	 */
11537 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
11538 		struct sched_entity *se;
11539 
11540 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
11541 			update_tg_load_avg(cfs_rq);
11542 
11543 			if (cfs_rq->nr_queued == 0)
11544 				update_idle_cfs_rq_clock_pelt(cfs_rq);
11545 
11546 			if (cfs_rq == &rq->cfs)
11547 				decayed = true;
11548 		}
11549 
11550 		/* Propagate pending load changes to the parent, if any: */
11551 		se = cfs_rq_se(cfs_rq);
11552 		if (se && !skip_blocked_update(se))
11553 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11554 
11555 		/*
11556 		 * There can be a lot of idle CPU cgroups.  Don't let fully
11557 		 * decayed cfs_rqs linger on the list.
11558 		 */
11559 		if (cfs_rq_is_decayed(cfs_rq))
11560 			list_del_leaf_cfs_rq(cfs_rq);
11561 
11562 		/* Don't need periodic decay once load/util_avg are null */
11563 		if (cfs_rq_has_blocked_load(cfs_rq))
11564 			*done = false;
11565 	}
11566 
11567 	return decayed;
11568 }
11569 
11570 /*
11571  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
11572  * This needs to be done in a top-down fashion because the load of a child
11573  * group is a fraction of its parents load.
11574  */
11575 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
11576 {
11577 	struct sched_entity *se = cfs_rq_se(cfs_rq);
11578 	unsigned long now = jiffies;
11579 	unsigned long load;
11580 
11581 	if (cfs_rq->last_h_load_update == now)
11582 		return;
11583 
11584 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
11585 	for_each_sched_entity(se) {
11586 		cfs_rq = cfs_rq_of(se);
11587 		WRITE_ONCE(cfs_rq->h_load_next, se);
11588 		if (cfs_rq->last_h_load_update == now)
11589 			break;
11590 	}
11591 
11592 	if (!se) {
11593 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
11594 		cfs_rq->last_h_load_update = now;
11595 	}
11596 
11597 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
11598 		load = cfs_rq->h_load;
11599 		load = div64_ul(load * se->avg.load_avg,
11600 				cfs_rq_load_avg(cfs_rq) + 1);
11601 		cfs_rq = group_cfs_rq(se);
11602 		cfs_rq->h_load = load;
11603 		cfs_rq->last_h_load_update = now;
11604 	}
11605 }
11606 
11607 static unsigned long task_h_load(struct task_struct *p)
11608 {
11609 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
11610 
11611 	update_cfs_rq_h_load(cfs_rq);
11612 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
11613 			cfs_rq_load_avg(cfs_rq) + 1);
11614 }
11615 #else /* !CONFIG_FAIR_GROUP_SCHED: */
11616 static bool __update_blocked_fair(struct rq *rq, bool *done)
11617 {
11618 	struct cfs_rq *cfs_rq = &rq->cfs;
11619 	bool decayed;
11620 
11621 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
11622 	if (cfs_rq_has_blocked_load(cfs_rq))
11623 		*done = false;
11624 
11625 	return decayed;
11626 }
11627 
11628 static unsigned long task_h_load(struct task_struct *p)
11629 {
11630 	return p->se.avg.load_avg;
11631 }
11632 #endif /* !CONFIG_FAIR_GROUP_SCHED */
11633 
11634 static void __sched_balance_update_blocked_averages(struct rq *rq)
11635 {
11636 	bool decayed = false, done = true;
11637 
11638 	update_blocked_load_tick(rq);
11639 
11640 	decayed |= __update_blocked_others(rq, &done);
11641 	decayed |= __update_blocked_fair(rq, &done);
11642 
11643 	update_has_blocked_load_status(rq, !done);
11644 	if (decayed)
11645 		cpufreq_update_util(rq, 0);
11646 }
11647 
11648 static void sched_balance_update_blocked_averages(int cpu)
11649 {
11650 	struct rq *rq = cpu_rq(cpu);
11651 
11652 	guard(rq_lock_irqsave)(rq);
11653 	update_rq_clock(rq);
11654 	__sched_balance_update_blocked_averages(rq);
11655 }
11656 
11657 /********** Helpers for sched_balance_find_src_group ************************/
11658 
11659 /*
11660  * sg_lb_stats - stats of a sched_group required for load-balancing:
11661  */
11662 struct sg_lb_stats {
11663 	unsigned long avg_load;			/* Avg load            over the CPUs of the group */
11664 	unsigned long group_load;		/* Total load          over the CPUs of the group */
11665 	unsigned long group_capacity;		/* Capacity            over the CPUs of the group */
11666 	unsigned long group_util;		/* Total utilization   over the CPUs of the group */
11667 	unsigned long group_runnable;		/* Total runnable time over the CPUs of the group */
11668 	unsigned int sum_nr_running;		/* Nr of all tasks running in the group */
11669 	unsigned int sum_h_nr_running;		/* Nr of CFS tasks running in the group */
11670 	unsigned int idle_cpus;                 /* Nr of idle CPUs         in the group */
11671 	unsigned int group_weight;
11672 	enum group_type group_type;
11673 	unsigned int group_asym_packing;	/* Tasks should be moved to preferred CPU */
11674 	unsigned int group_smt_balance;		/* Task on busy SMT be moved */
11675 	unsigned int group_llc_balance;		/* Tasks should be moved to preferred LLC */
11676 	unsigned long group_misfit_task_load;	/* A CPU has a task too big for its capacity */
11677 	unsigned int group_overutilized;	/* At least one CPU is overutilized in the group */
11678 #ifdef CONFIG_NUMA_BALANCING
11679 	unsigned int nr_numa_running;
11680 	unsigned int nr_preferred_running;
11681 #endif
11682 #ifdef CONFIG_SCHED_CACHE
11683 	unsigned int nr_pref_dst_llc;
11684 #endif
11685 };
11686 
11687 /*
11688  * sd_lb_stats - stats of a sched_domain required for load-balancing:
11689  */
11690 struct sd_lb_stats {
11691 	struct sched_group *busiest;		/* Busiest group in this sd */
11692 	struct sched_group *local;		/* Local group in this sd */
11693 	unsigned long total_load;		/* Total load of all groups in sd */
11694 	unsigned long total_capacity;		/* Total capacity of all groups in sd */
11695 	unsigned long avg_load;			/* Average load across all groups in sd */
11696 	unsigned int prefer_sibling;		/* Tasks should go to sibling first */
11697 
11698 	struct sg_lb_stats busiest_stat;	/* Statistics of the busiest group */
11699 	struct sg_lb_stats local_stat;		/* Statistics of the local group */
11700 };
11701 
11702 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
11703 {
11704 	/*
11705 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
11706 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
11707 	 * We must however set busiest_stat::group_type and
11708 	 * busiest_stat::idle_cpus to the worst busiest group because
11709 	 * update_sd_pick_busiest() reads these before assignment.
11710 	 */
11711 	*sds = (struct sd_lb_stats){
11712 		.busiest = NULL,
11713 		.local = NULL,
11714 		.total_load = 0UL,
11715 		.total_capacity = 0UL,
11716 		.busiest_stat = {
11717 			.idle_cpus = UINT_MAX,
11718 			.group_type = group_has_spare,
11719 		},
11720 	};
11721 }
11722 
11723 static unsigned long scale_rt_capacity(int cpu)
11724 {
11725 	unsigned long max = get_actual_cpu_capacity(cpu);
11726 	struct rq *rq = cpu_rq(cpu);
11727 	unsigned long used, free;
11728 	unsigned long irq;
11729 
11730 	irq = cpu_util_irq(rq);
11731 
11732 	if (unlikely(irq >= max))
11733 		return 1;
11734 
11735 	/*
11736 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
11737 	 * (running and not running) with weights 0 and 1024 respectively.
11738 	 */
11739 	used = cpu_util_rt(rq);
11740 	used += cpu_util_dl(rq);
11741 
11742 	if (unlikely(used >= max))
11743 		return 1;
11744 
11745 	free = max - used;
11746 
11747 	return scale_irq_capacity(free, irq, max);
11748 }
11749 
11750 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
11751 {
11752 	unsigned long capacity = scale_rt_capacity(cpu);
11753 	struct sched_group *sdg = sd->groups;
11754 
11755 	if (!capacity)
11756 		capacity = 1;
11757 
11758 	cpu_rq(cpu)->cpu_capacity = capacity;
11759 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
11760 
11761 	sdg->sgc->capacity = capacity;
11762 	sdg->sgc->min_capacity = capacity;
11763 	sdg->sgc->max_capacity = capacity;
11764 }
11765 
11766 void update_group_capacity(struct sched_domain *sd, int cpu)
11767 {
11768 	struct sched_domain *child = sd->child;
11769 	struct sched_group *group, *sdg = sd->groups;
11770 	unsigned long capacity, min_capacity, max_capacity;
11771 	unsigned long interval;
11772 
11773 	interval = msecs_to_jiffies(sd->balance_interval);
11774 	interval = clamp(interval, 1UL, max_load_balance_interval);
11775 	sdg->sgc->next_update = jiffies + interval;
11776 
11777 	if (!child) {
11778 		update_cpu_capacity(sd, cpu);
11779 		return;
11780 	}
11781 
11782 	capacity = 0;
11783 	min_capacity = ULONG_MAX;
11784 	max_capacity = 0;
11785 
11786 	if (child->flags & SD_NUMA) {
11787 		/*
11788 		 * SD_NUMA domains cannot assume that child groups
11789 		 * span the current group.
11790 		 */
11791 
11792 		for_each_cpu(cpu, sched_group_span(sdg)) {
11793 			unsigned long cpu_cap = capacity_of(cpu);
11794 
11795 			capacity += cpu_cap;
11796 			min_capacity = min(cpu_cap, min_capacity);
11797 			max_capacity = max(cpu_cap, max_capacity);
11798 		}
11799 	} else  {
11800 		/*
11801 		 * !SD_NUMA domains can assume that child groups
11802 		 * span the current group.
11803 		 */
11804 
11805 		group = child->groups;
11806 		do {
11807 			struct sched_group_capacity *sgc = group->sgc;
11808 
11809 			capacity += sgc->capacity;
11810 			min_capacity = min(sgc->min_capacity, min_capacity);
11811 			max_capacity = max(sgc->max_capacity, max_capacity);
11812 			group = group->next;
11813 		} while (group != child->groups);
11814 	}
11815 
11816 	sdg->sgc->capacity = capacity;
11817 	sdg->sgc->min_capacity = min_capacity;
11818 	sdg->sgc->max_capacity = max_capacity;
11819 }
11820 
11821 /*
11822  * Check whether the capacity of the rq has been noticeably reduced by side
11823  * activity. The imbalance_pct is used for the threshold.
11824  * Return true is the capacity is reduced
11825  */
11826 static inline int
11827 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
11828 {
11829 	return ((rq->cpu_capacity * sd->imbalance_pct) <
11830 				(arch_scale_cpu_capacity(cpu_of(rq)) * 100));
11831 }
11832 
11833 /* Check if the rq has a misfit task */
11834 static inline bool check_misfit_status(struct rq *rq)
11835 {
11836 	return rq->misfit_task_load;
11837 }
11838 
11839 /*
11840  * Group imbalance indicates (and tries to solve) the problem where balancing
11841  * groups is inadequate due to ->cpus_ptr constraints.
11842  *
11843  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
11844  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
11845  * Something like:
11846  *
11847  *	{ 0 1 2 3 } { 4 5 6 7 }
11848  *	        *     * * *
11849  *
11850  * If we were to balance group-wise we'd place two tasks in the first group and
11851  * two tasks in the second group. Clearly this is undesired as it will overload
11852  * cpu 3 and leave one of the CPUs in the second group unused.
11853  *
11854  * The current solution to this issue is detecting the skew in the first group
11855  * by noticing the lower domain failed to reach balance and had difficulty
11856  * moving tasks due to affinity constraints.
11857  *
11858  * When this is so detected; this group becomes a candidate for busiest; see
11859  * update_sd_pick_busiest(). And calculate_imbalance() and
11860  * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
11861  * to create an effective group imbalance.
11862  *
11863  * This is a somewhat tricky proposition since the next run might not find the
11864  * group imbalance and decide the groups need to be balanced again. A most
11865  * subtle and fragile situation.
11866  */
11867 
11868 static inline int sg_imbalanced(struct sched_group *group)
11869 {
11870 	return group->sgc->imbalance;
11871 }
11872 
11873 /*
11874  * group_has_capacity returns true if the group has spare capacity that could
11875  * be used by some tasks.
11876  * We consider that a group has spare capacity if the number of task is
11877  * smaller than the number of CPUs or if the utilization is lower than the
11878  * available capacity for CFS tasks.
11879  * For the latter, we use a threshold to stabilize the state, to take into
11880  * account the variance of the tasks' load and to return true if the available
11881  * capacity in meaningful for the load balancer.
11882  * As an example, an available capacity of 1% can appear but it doesn't make
11883  * any benefit for the load balance.
11884  */
11885 static inline bool
11886 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11887 {
11888 	if (sgs->sum_nr_running < sgs->group_weight)
11889 		return true;
11890 
11891 	if ((sgs->group_capacity * imbalance_pct) <
11892 			(sgs->group_runnable * 100))
11893 		return false;
11894 
11895 	if ((sgs->group_capacity * 100) >
11896 			(sgs->group_util * imbalance_pct))
11897 		return true;
11898 
11899 	return false;
11900 }
11901 
11902 /*
11903  *  group_is_overloaded returns true if the group has more tasks than it can
11904  *  handle.
11905  *  group_is_overloaded is not equals to !group_has_capacity because a group
11906  *  with the exact right number of tasks, has no more spare capacity but is not
11907  *  overloaded so both group_has_capacity and group_is_overloaded return
11908  *  false.
11909  */
11910 static inline bool
11911 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11912 {
11913 	/*
11914 	 * With EAS and uclamp, 1 CPU in the group must be overutilized to
11915 	 * consider the group overloaded.
11916 	 */
11917 	if (sched_energy_enabled() && !sgs->group_overutilized)
11918 		return false;
11919 
11920 	if (sgs->sum_nr_running <= sgs->group_weight)
11921 		return false;
11922 
11923 	if ((sgs->group_capacity * 100) <
11924 			(sgs->group_util * imbalance_pct))
11925 		return true;
11926 
11927 	if ((sgs->group_capacity * imbalance_pct) <
11928 			(sgs->group_runnable * 100))
11929 		return true;
11930 
11931 	return false;
11932 }
11933 
11934 static inline enum
11935 group_type group_classify(unsigned int imbalance_pct,
11936 			  struct sched_group *group,
11937 			  struct sg_lb_stats *sgs)
11938 {
11939 	if (group_is_overloaded(imbalance_pct, sgs))
11940 		return group_overloaded;
11941 
11942 	if (sgs->group_llc_balance)
11943 		return group_llc_balance;
11944 
11945 	if (sg_imbalanced(group))
11946 		return group_imbalanced;
11947 
11948 	if (sgs->group_asym_packing)
11949 		return group_asym_packing;
11950 
11951 	if (sgs->group_smt_balance)
11952 		return group_smt_balance;
11953 
11954 	if (sgs->group_misfit_task_load)
11955 		return group_misfit_task;
11956 
11957 	if (!group_has_capacity(imbalance_pct, sgs))
11958 		return group_fully_busy;
11959 
11960 	return group_has_spare;
11961 }
11962 
11963 /**
11964  * sched_use_asym_prio - Check whether asym_packing priority must be used
11965  * @sd:		The scheduling domain of the load balancing
11966  * @cpu:	A CPU
11967  *
11968  * Always use CPU priority when balancing load between SMT siblings. When
11969  * balancing load between cores, it is not sufficient that @cpu is idle. Only
11970  * use CPU priority if the whole core is idle.
11971  *
11972  * Returns: True if the priority of @cpu must be followed. False otherwise.
11973  */
11974 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
11975 {
11976 	if (!(sd->flags & SD_ASYM_PACKING))
11977 		return false;
11978 
11979 	if (!sched_smt_active())
11980 		return true;
11981 
11982 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
11983 }
11984 
11985 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
11986 {
11987 	/*
11988 	 * First check if @dst_cpu can do asym_packing load balance. Only do it
11989 	 * if it has higher priority than @src_cpu.
11990 	 */
11991 	return sched_use_asym_prio(sd, dst_cpu) &&
11992 		sched_asym_prefer(dst_cpu, src_cpu);
11993 }
11994 
11995 /**
11996  * sched_group_asym - Check if the destination CPU can do asym_packing balance
11997  * @env:	The load balancing environment
11998  * @sgs:	Load-balancing statistics of the candidate busiest group
11999  * @group:	The candidate busiest group
12000  *
12001  * @env::dst_cpu can do asym_packing if it has higher priority than the
12002  * preferred CPU of @group.
12003  *
12004  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
12005  * otherwise.
12006  */
12007 static inline bool
12008 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
12009 {
12010 	/*
12011 	 * CPU priorities do not make sense for SMT cores with more than one
12012 	 * busy sibling.
12013 	 */
12014 	if ((group->flags & SD_SHARE_CPUCAPACITY) &&
12015 	    (sgs->group_weight - sgs->idle_cpus != 1))
12016 		return false;
12017 
12018 	return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
12019 }
12020 
12021 /* One group has more than one SMT CPU while the other group does not */
12022 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
12023 				    struct sched_group *sg2)
12024 {
12025 	if (!sg1 || !sg2)
12026 		return false;
12027 
12028 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
12029 		(sg2->flags & SD_SHARE_CPUCAPACITY);
12030 }
12031 
12032 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12033 			       struct sched_group *group)
12034 {
12035 	if (!env->idle)
12036 		return false;
12037 
12038 	/*
12039 	 * For SMT source group, it is better to move a task
12040 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
12041 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
12042 	 * will not be on.
12043 	 */
12044 	if (group->flags & SD_SHARE_CPUCAPACITY &&
12045 	    sgs->sum_h_nr_running > 1)
12046 		return true;
12047 
12048 	return false;
12049 }
12050 
12051 static inline long sibling_imbalance(struct lb_env *env,
12052 				    struct sd_lb_stats *sds,
12053 				    struct sg_lb_stats *busiest,
12054 				    struct sg_lb_stats *local)
12055 {
12056 	int ncores_busiest, ncores_local;
12057 	long imbalance;
12058 
12059 	if (!env->idle || !busiest->sum_nr_running)
12060 		return 0;
12061 
12062 	ncores_busiest = sds->busiest->cores;
12063 	ncores_local = sds->local->cores;
12064 
12065 	if (ncores_busiest == ncores_local) {
12066 		imbalance = busiest->sum_nr_running;
12067 		lsub_positive(&imbalance, local->sum_nr_running);
12068 		return imbalance;
12069 	}
12070 
12071 	/* Balance such that nr_running/ncores ratio are same on both groups */
12072 	imbalance = ncores_local * busiest->sum_nr_running;
12073 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
12074 	/* Normalize imbalance and do rounding on normalization */
12075 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
12076 	imbalance /= ncores_local + ncores_busiest;
12077 
12078 	/* Take advantage of resource in an empty sched group */
12079 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
12080 	    busiest->sum_nr_running > 1)
12081 		imbalance = 2;
12082 
12083 	return imbalance;
12084 }
12085 
12086 static inline bool
12087 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
12088 {
12089 	/*
12090 	 * When there is more than 1 task, the group_overloaded case already
12091 	 * takes care of cpu with reduced capacity
12092 	 */
12093 	if (rq->cfs.h_nr_runnable != 1)
12094 		return false;
12095 
12096 	return check_cpu_capacity(rq, sd);
12097 }
12098 
12099 #ifdef CONFIG_SCHED_CACHE
12100 /*
12101  * Record the statistics for this scheduler group for later
12102  * use. These values guide load balancing on aggregating tasks
12103  * to a LLC.
12104  */
12105 static void record_sg_llc_stats(struct lb_env *env,
12106 				struct sg_lb_stats *sgs,
12107 				struct sched_group *group)
12108 {
12109 	struct sched_domain_shared *sd_share;
12110 	int cpu;
12111 
12112 	if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE)
12113 		return;
12114 
12115 	/* Only care about sched domain spanning multiple LLCs */
12116 	if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu)))
12117 		return;
12118 
12119 	/*
12120 	 * A redo repeats stats published on the first pass. Hotplug can
12121 	 * still leave env->cpus partial, so util would not match capacity.
12122 	 */
12123 	if ((env->flags & LBF_ALL_PINNED) ||
12124 	    !cpumask_subset(sched_group_span(group), env->cpus))
12125 		return;
12126 
12127 	/*
12128 	 * At this point we know this group spans a LLC domain.
12129 	 * Record the statistic of this group in its corresponding
12130 	 * shared LLC domain.
12131 	 * Note: sd_share cannot be obtained via sd->child->shared,
12132 	 * because the latter refers to the domain that covers the
12133 	 * local group. Instead, sd_share should be located using
12134 	 * the first CPU of the LLC group.
12135 	 */
12136 	cpu = cpumask_first(sched_group_span(group));
12137 	sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
12138 	if (!sd_share)
12139 		return;
12140 
12141 	if (READ_ONCE(sd_share->util_avg) != sgs->group_util)
12142 		WRITE_ONCE(sd_share->util_avg, sgs->group_util);
12143 
12144 	if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity))
12145 		WRITE_ONCE(sd_share->capacity, sgs->group_capacity);
12146 }
12147 
12148 /*
12149  * Do LLC balance on sched group that contains LLC, and have tasks preferring
12150  * to run on LLC in idle dst_cpu.
12151  */
12152 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12153 			       struct sched_group *group)
12154 {
12155 	if (!sched_cache_enabled())
12156 		return false;
12157 
12158 	if (env->sd->flags & SD_SHARE_LLC)
12159 		return false;
12160 
12161 	/*
12162 	 * On asymmetric domains, group_misfit_task_load
12163 	 * should be prioritized to move tasks to CPU that fit them
12164 	 * over aggregating tasks to their preferred LLC.
12165 	 */
12166 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12167 	    sgs->group_misfit_task_load)
12168 		return false;
12169 
12170 	/*
12171 	 * On asym packing domains, if the destination CPU
12172 	 * has higher priority than all CPUs in the source group,
12173 	 * prioritize asym packing.
12174 	 */
12175 	if (sgs->group_asym_packing)
12176 		return false;
12177 
12178 	/*
12179 	 * Skip cache aware tagging if nr_balanced_failed is sufficiently high.
12180 	 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed
12181 	 * to avoid excessive task migration at the same time.
12182 	 */
12183 	if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
12184 		return false;
12185 
12186 	if (sgs->nr_pref_dst_llc &&
12187 	    can_migrate_llc(cpumask_first(sched_group_span(group)),
12188 			    env->dst_cpu, 0, true) == mig_llc)
12189 		return true;
12190 
12191 	return false;
12192 }
12193 
12194 static bool update_llc_busiest(struct lb_env *env,
12195 			       struct sg_lb_stats *busiest,
12196 			       struct sg_lb_stats *sgs)
12197 {
12198 	/*
12199 	 * There are more tasks that want to run on dst_cpu's LLC.
12200 	 */
12201 	return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc;
12202 }
12203 #else
12204 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs,
12205 				       struct sched_group *group)
12206 {
12207 }
12208 
12209 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12210 			       struct sched_group *group)
12211 {
12212 	return false;
12213 }
12214 
12215 static bool update_llc_busiest(struct lb_env *env,
12216 			       struct sg_lb_stats *busiest,
12217 			       struct sg_lb_stats *sgs)
12218 {
12219 	return false;
12220 }
12221 #endif
12222 
12223 /**
12224  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
12225  * @env: The load balancing environment.
12226  * @sds: Load-balancing data with statistics of the local group.
12227  * @group: sched_group whose statistics are to be updated.
12228  * @sgs: variable to hold the statistics for this group.
12229  * @sg_overloaded: sched_group is overloaded
12230  */
12231 static inline void update_sg_lb_stats(struct lb_env *env,
12232 				      struct sd_lb_stats *sds,
12233 				      struct sched_group *group,
12234 				      struct sg_lb_stats *sgs,
12235 				      bool *sg_overloaded)
12236 {
12237 	int i, nr_running, local_group, sd_flags = env->sd->flags;
12238 	bool balancing_at_rd = !env->sd->parent;
12239 
12240 	memset(sgs, 0, sizeof(*sgs));
12241 
12242 	local_group = group == sds->local;
12243 
12244 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
12245 		struct rq *rq = cpu_rq(i);
12246 		unsigned long load = cpu_load(rq);
12247 
12248 		sgs->group_load += load;
12249 		sgs->group_util += cpu_util_cfs(i);
12250 		sgs->group_runnable += cpu_runnable(rq);
12251 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
12252 
12253 		nr_running = rq->nr_running;
12254 		sgs->sum_nr_running += nr_running;
12255 
12256 		if (cpu_overutilized(i))
12257 			sgs->group_overutilized = 1;
12258 
12259 #ifdef CONFIG_SCHED_CACHE
12260 		if (sched_cache_enabled()) {
12261 			struct sched_domain *sd_tmp;
12262 			int dst_llc;
12263 
12264 			dst_llc = llc_id(env->dst_cpu);
12265 			if (llc_id(i) != dst_llc) {
12266 				sd_tmp = rcu_dereference_all(rq->sd);
12267 				if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max)
12268 					sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc];
12269 			}
12270 		}
12271 #endif
12272 
12273 		/*
12274 		 * No need to call idle_cpu() if nr_running is not 0
12275 		 */
12276 		if (!nr_running && idle_cpu(i)) {
12277 			sgs->idle_cpus++;
12278 			/* Idle cpu can't have misfit task */
12279 			continue;
12280 		}
12281 
12282 		/* Overload indicator is only updated at root domain */
12283 		if (balancing_at_rd && nr_running > 1)
12284 			*sg_overloaded = 1;
12285 
12286 #ifdef CONFIG_NUMA_BALANCING
12287 		/* Only fbq_classify_group() uses this to classify NUMA groups */
12288 		if (sd_flags & SD_NUMA) {
12289 			sgs->nr_numa_running += rq->nr_numa_running;
12290 			sgs->nr_preferred_running += rq->nr_preferred_running;
12291 		}
12292 #endif
12293 		if (local_group)
12294 			continue;
12295 
12296 		if (sd_flags & SD_ASYM_CPUCAPACITY) {
12297 			if (rq->misfit_task_load) {
12298 				/*
12299 				 * Always mark the root domain overloaded so big
12300 				 * CPUs can pick up misfit tasks via newly idle
12301 				 * balance.
12302 				 */
12303 				if (balancing_at_rd)
12304 					*sg_overloaded = 1;
12305 
12306 				/*
12307 				 * Only account misfit load if @dst_cpu can
12308 				 * help; otherwise, the group may be classified
12309 				 * as misfit_task and update_sd_pick_busiest()
12310 				 * will skip it.
12311 				 */
12312 				if (capacity_greater(capacity_of(env->dst_cpu),
12313 						     group->sgc->max_capacity) &&
12314 				    (sgs->group_misfit_task_load < rq->misfit_task_load))
12315 					sgs->group_misfit_task_load = rq->misfit_task_load;
12316 			}
12317 		} else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
12318 			/* Check for a task running on a CPU with reduced capacity */
12319 			if (sgs->group_misfit_task_load < load)
12320 				sgs->group_misfit_task_load = load;
12321 		}
12322 	}
12323 
12324 	sgs->group_capacity = group->sgc->capacity;
12325 
12326 	sgs->group_weight = group->group_weight;
12327 
12328 	if (!local_group) {
12329 		/* Check if dst CPU is idle and preferred to this group */
12330 		if (env->idle && sgs->sum_h_nr_running &&
12331 		    sched_group_asym(env, sgs, group))
12332 			sgs->group_asym_packing = 1;
12333 
12334 		/* Check for loaded SMT group to be balanced to dst CPU */
12335 		if (smt_balance(env, sgs, group))
12336 			sgs->group_smt_balance = 1;
12337 
12338 		/* Check for tasks in this group can be moved to their preferred LLC */
12339 		if (llc_balance(env, sgs, group))
12340 			sgs->group_llc_balance = 1;
12341 	}
12342 
12343 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
12344 
12345 	record_sg_llc_stats(env, sgs, group);
12346 	/* Computing avg_load makes sense only when group is overloaded */
12347 	if (sgs->group_type == group_overloaded)
12348 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12349 				sgs->group_capacity;
12350 }
12351 
12352 /**
12353  * update_sd_pick_busiest - return 1 on busiest group
12354  * @env: The load balancing environment.
12355  * @sds: sched_domain statistics
12356  * @sg: sched_group candidate to be checked for being the busiest
12357  * @sgs: sched_group statistics
12358  *
12359  * Determine if @sg is a busier group than the previously selected
12360  * busiest group.
12361  *
12362  * Return: %true if @sg is a busier group than the previously selected
12363  * busiest group. %false otherwise.
12364  */
12365 static bool update_sd_pick_busiest(struct lb_env *env,
12366 				   struct sd_lb_stats *sds,
12367 				   struct sched_group *sg,
12368 				   struct sg_lb_stats *sgs)
12369 {
12370 	struct sg_lb_stats *busiest = &sds->busiest_stat;
12371 
12372 	/* Make sure that there is at least one task to pull */
12373 	if (!sgs->sum_h_nr_running)
12374 		return false;
12375 
12376 	/*
12377 	 * Don't try to pull misfit tasks we can't help.
12378 	 * We can use max_capacity here as reduction in capacity on some
12379 	 * CPUs in the group should either be possible to resolve
12380 	 * internally or be covered by avg_load imbalance (eventually).
12381 	 *
12382 	 * When SMT is active, only pull a misfit to dst_cpu if it is on a
12383 	 * fully idle core; otherwise the effective capacity of the core is
12384 	 * reduced and we may not actually provide more capacity than the
12385 	 * source.
12386 	 */
12387 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12388 	    (sgs->group_type == group_misfit_task) &&
12389 	    (!env->dst_core_idle ||
12390 	     !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
12391 	     sds->local_stat.group_type != group_has_spare))
12392 		return false;
12393 
12394 	/*
12395 	 * Candidate sg has no more than one task per CPU and has higher
12396 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
12397 	 * throughput. Maximize throughput, power/energy consequences are not
12398 	 * considered.
12399 	 */
12400 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12401 	    (sgs->group_type <= group_fully_busy) &&
12402 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
12403 		return false;
12404 
12405 	if (sgs->group_type > busiest->group_type)
12406 		return true;
12407 
12408 	if (sgs->group_type < busiest->group_type)
12409 		return false;
12410 
12411 	/*
12412 	 * The candidate and the current busiest group are the same type of
12413 	 * group. Let check which one is the busiest according to the type.
12414 	 */
12415 
12416 	switch (sgs->group_type) {
12417 	case group_overloaded:
12418 		/* Select the overloaded group with highest avg_load. */
12419 		return sgs->avg_load > busiest->avg_load;
12420 
12421 	case group_llc_balance:
12422 		/* Select the group with most tasks preferring dst LLC */
12423 		return update_llc_busiest(env, busiest, sgs);
12424 
12425 	case group_imbalanced:
12426 		/*
12427 		 * Select the 1st imbalanced group as we don't have any way to
12428 		 * choose one more than another.
12429 		 */
12430 		return false;
12431 
12432 	case group_asym_packing:
12433 		/* Prefer to move from lowest priority CPU's work */
12434 		return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
12435 					 READ_ONCE(sg->asym_prefer_cpu));
12436 
12437 	case group_misfit_task:
12438 		/*
12439 		 * If we have more than one misfit sg go with the biggest
12440 		 * misfit.
12441 		 */
12442 		return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
12443 
12444 	case group_smt_balance:
12445 		/*
12446 		 * Check if we have spare CPUs on either SMT group to
12447 		 * choose has spare or fully busy handling.
12448 		 */
12449 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
12450 			goto has_spare;
12451 
12452 		fallthrough;
12453 
12454 	case group_fully_busy:
12455 		/*
12456 		 * Select the fully busy group with highest avg_load. In
12457 		 * theory, there is no need to pull task from such kind of
12458 		 * group because tasks have all compute capacity that they need
12459 		 * but we can still improve the overall throughput by reducing
12460 		 * contention when accessing shared HW resources.
12461 		 *
12462 		 * XXX for now avg_load is not computed and always 0 so we
12463 		 * select the 1st one, except if @sg is composed of SMT
12464 		 * siblings.
12465 		 */
12466 
12467 		if (sgs->avg_load < busiest->avg_load)
12468 			return false;
12469 
12470 		if (sgs->avg_load == busiest->avg_load) {
12471 			/*
12472 			 * SMT sched groups need more help than non-SMT groups.
12473 			 * If @sg happens to also be SMT, either choice is good.
12474 			 */
12475 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
12476 				return false;
12477 		}
12478 
12479 		break;
12480 
12481 	case group_has_spare:
12482 		/*
12483 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
12484 		 * as we do not want to pull task off SMT core with one task
12485 		 * and make the core idle.
12486 		 */
12487 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
12488 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
12489 				return false;
12490 			else
12491 				return true;
12492 		}
12493 has_spare:
12494 
12495 		/*
12496 		 * Select not overloaded group with lowest number of idle CPUs
12497 		 * and highest number of running tasks. We could also compare
12498 		 * the spare capacity which is more stable but it can end up
12499 		 * that the group has less spare capacity but finally more idle
12500 		 * CPUs which means less opportunity to pull tasks.
12501 		 */
12502 		if (sgs->idle_cpus > busiest->idle_cpus)
12503 			return false;
12504 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
12505 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
12506 			return false;
12507 
12508 		break;
12509 	}
12510 
12511 	return true;
12512 }
12513 
12514 #ifdef CONFIG_NUMA_BALANCING
12515 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12516 {
12517 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
12518 		return regular;
12519 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
12520 		return remote;
12521 	return all;
12522 }
12523 
12524 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12525 {
12526 	if (rq->nr_running > rq->nr_numa_running)
12527 		return regular;
12528 	if (rq->nr_running > rq->nr_preferred_running)
12529 		return remote;
12530 	return all;
12531 }
12532 #else /* !CONFIG_NUMA_BALANCING: */
12533 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12534 {
12535 	return all;
12536 }
12537 
12538 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12539 {
12540 	return regular;
12541 }
12542 #endif /* !CONFIG_NUMA_BALANCING */
12543 
12544 
12545 struct sg_lb_stats;
12546 
12547 /*
12548  * task_running_on_cpu - return 1 if @p is running on @cpu.
12549  */
12550 
12551 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
12552 {
12553 	/* Task has no contribution or is new */
12554 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
12555 		return 0;
12556 
12557 	if (task_on_rq_queued(p))
12558 		return 1;
12559 
12560 	return 0;
12561 }
12562 
12563 /**
12564  * idle_cpu_without - would a given CPU be idle without p ?
12565  * @cpu: the processor on which idleness is tested.
12566  * @p: task which should be ignored.
12567  *
12568  * Return: 1 if the CPU would be idle. 0 otherwise.
12569  */
12570 static int idle_cpu_without(int cpu, struct task_struct *p)
12571 {
12572 	struct rq *rq = cpu_rq(cpu);
12573 
12574 	if (rq->curr != rq->idle && rq->curr != p)
12575 		return 0;
12576 
12577 	/*
12578 	 * rq->nr_running can't be used but an updated version without the
12579 	 * impact of p on cpu must be used instead. The updated nr_running
12580 	 * be computed and tested before calling idle_cpu_without().
12581 	 */
12582 
12583 	if (rq->ttwu_pending)
12584 		return 0;
12585 
12586 	return 1;
12587 }
12588 
12589 /*
12590  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
12591  * @sd: The sched_domain level to look for idlest group.
12592  * @group: sched_group whose statistics are to be updated.
12593  * @sgs: variable to hold the statistics for this group.
12594  * @p: The task for which we look for the idlest group/CPU.
12595  */
12596 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
12597 					  struct sched_group *group,
12598 					  struct sg_lb_stats *sgs,
12599 					  struct task_struct *p)
12600 {
12601 	int i, nr_running;
12602 
12603 	memset(sgs, 0, sizeof(*sgs));
12604 
12605 	/* Assume that task can't fit any CPU of the group */
12606 	if (sd->flags & SD_ASYM_CPUCAPACITY)
12607 		sgs->group_misfit_task_load = 1;
12608 
12609 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
12610 		struct rq *rq = cpu_rq(i);
12611 		unsigned int local;
12612 
12613 		sgs->group_load += cpu_load_without(rq, p);
12614 		sgs->group_util += cpu_util_without(i, p);
12615 		sgs->group_runnable += cpu_runnable_without(rq, p);
12616 		local = task_running_on_cpu(i, p);
12617 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
12618 
12619 		nr_running = rq->nr_running - local;
12620 		sgs->sum_nr_running += nr_running;
12621 
12622 		/*
12623 		 * No need to call idle_cpu_without() if nr_running is not 0
12624 		 */
12625 		if (!nr_running && idle_cpu_without(i, p))
12626 			sgs->idle_cpus++;
12627 
12628 		/* Check if task fits in the CPU */
12629 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
12630 		    sgs->group_misfit_task_load &&
12631 		    task_fits_cpu(p, i))
12632 			sgs->group_misfit_task_load = 0;
12633 
12634 	}
12635 
12636 	sgs->group_capacity = group->sgc->capacity;
12637 
12638 	sgs->group_weight = group->group_weight;
12639 
12640 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
12641 
12642 	/*
12643 	 * Computing avg_load makes sense only when group is fully busy or
12644 	 * overloaded
12645 	 */
12646 	if (sgs->group_type == group_fully_busy ||
12647 		sgs->group_type == group_overloaded)
12648 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12649 				sgs->group_capacity;
12650 }
12651 
12652 static bool update_pick_idlest(struct sched_group *idlest,
12653 			       struct sg_lb_stats *idlest_sgs,
12654 			       struct sched_group *group,
12655 			       struct sg_lb_stats *sgs)
12656 {
12657 	if (sgs->group_type < idlest_sgs->group_type)
12658 		return true;
12659 
12660 	if (sgs->group_type > idlest_sgs->group_type)
12661 		return false;
12662 
12663 	/*
12664 	 * The candidate and the current idlest group are the same type of
12665 	 * group. Let check which one is the idlest according to the type.
12666 	 */
12667 
12668 	switch (sgs->group_type) {
12669 	case group_overloaded:
12670 	case group_fully_busy:
12671 		/* Select the group with lowest avg_load. */
12672 		if (idlest_sgs->avg_load <= sgs->avg_load)
12673 			return false;
12674 		break;
12675 
12676 	case group_llc_balance:
12677 	case group_imbalanced:
12678 	case group_asym_packing:
12679 	case group_smt_balance:
12680 		/* Those types are not used in the slow wakeup path */
12681 		return false;
12682 
12683 	case group_misfit_task:
12684 		/* Select group with the highest max capacity */
12685 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
12686 			return false;
12687 		break;
12688 
12689 	case group_has_spare:
12690 		/* Select group with most idle CPUs */
12691 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
12692 			return false;
12693 
12694 		/* Select group with lowest group_util */
12695 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
12696 			idlest_sgs->group_util <= sgs->group_util)
12697 			return false;
12698 
12699 		break;
12700 	}
12701 
12702 	return true;
12703 }
12704 
12705 /*
12706  * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
12707  * domain.
12708  *
12709  * Assumes p is allowed on at least one CPU in sd.
12710  */
12711 static struct sched_group *
12712 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
12713 {
12714 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
12715 	struct sg_lb_stats local_sgs, tmp_sgs;
12716 	struct sg_lb_stats *sgs;
12717 	unsigned long imbalance;
12718 	struct sg_lb_stats idlest_sgs = {
12719 			.avg_load = UINT_MAX,
12720 			.group_type = group_overloaded,
12721 	};
12722 
12723 	do {
12724 		int local_group;
12725 
12726 		/* Skip over this group if it has no CPUs allowed */
12727 		if (!cpumask_intersects(sched_group_span(group),
12728 					p->cpus_ptr))
12729 			continue;
12730 
12731 		/* Skip over this group if no cookie matched */
12732 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
12733 			continue;
12734 
12735 		local_group = cpumask_test_cpu(this_cpu,
12736 					       sched_group_span(group));
12737 
12738 		if (local_group) {
12739 			sgs = &local_sgs;
12740 			local = group;
12741 		} else {
12742 			sgs = &tmp_sgs;
12743 		}
12744 
12745 		update_sg_wakeup_stats(sd, group, sgs, p);
12746 
12747 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
12748 			idlest = group;
12749 			idlest_sgs = *sgs;
12750 		}
12751 
12752 	} while (group = group->next, group != sd->groups);
12753 
12754 
12755 	/* There is no idlest group to push tasks to */
12756 	if (!idlest)
12757 		return NULL;
12758 
12759 	/* The local group has been skipped because of CPU affinity */
12760 	if (!local)
12761 		return idlest;
12762 
12763 	/*
12764 	 * If the local group is idler than the selected idlest group
12765 	 * don't try and push the task.
12766 	 */
12767 	if (local_sgs.group_type < idlest_sgs.group_type)
12768 		return NULL;
12769 
12770 	/*
12771 	 * If the local group is busier than the selected idlest group
12772 	 * try and push the task.
12773 	 */
12774 	if (local_sgs.group_type > idlest_sgs.group_type)
12775 		return idlest;
12776 
12777 	switch (local_sgs.group_type) {
12778 	case group_overloaded:
12779 	case group_fully_busy:
12780 
12781 		/* Calculate allowed imbalance based on load */
12782 		imbalance = scale_load_down(NICE_0_LOAD) *
12783 				(sd->imbalance_pct-100) / 100;
12784 
12785 		/*
12786 		 * When comparing groups across NUMA domains, it's possible for
12787 		 * the local domain to be very lightly loaded relative to the
12788 		 * remote domains but "imbalance" skews the comparison making
12789 		 * remote CPUs look much more favourable. When considering
12790 		 * cross-domain, add imbalance to the load on the remote node
12791 		 * and consider staying local.
12792 		 */
12793 
12794 		if ((sd->flags & SD_NUMA) &&
12795 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
12796 			return NULL;
12797 
12798 		/*
12799 		 * If the local group is less loaded than the selected
12800 		 * idlest group don't try and push any tasks.
12801 		 */
12802 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
12803 			return NULL;
12804 
12805 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
12806 			return NULL;
12807 		break;
12808 
12809 	case group_llc_balance:
12810 	case group_imbalanced:
12811 	case group_asym_packing:
12812 	case group_smt_balance:
12813 		/* Those type are not used in the slow wakeup path */
12814 		return NULL;
12815 
12816 	case group_misfit_task:
12817 		/* Select group with the highest max capacity */
12818 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
12819 			return NULL;
12820 		break;
12821 
12822 	case group_has_spare:
12823 #ifdef CONFIG_NUMA
12824 		if (sd->flags & SD_NUMA) {
12825 			int imb_numa_nr = sd->imb_numa_nr;
12826 #ifdef CONFIG_NUMA_BALANCING
12827 			int idlest_cpu;
12828 			/*
12829 			 * If there is spare capacity at NUMA, try to select
12830 			 * the preferred node
12831 			 */
12832 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
12833 				return NULL;
12834 
12835 			idlest_cpu = cpumask_first(sched_group_span(idlest));
12836 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
12837 				return idlest;
12838 #endif /* CONFIG_NUMA_BALANCING */
12839 			/*
12840 			 * Otherwise, keep the task close to the wakeup source
12841 			 * and improve locality if the number of running tasks
12842 			 * would remain below threshold where an imbalance is
12843 			 * allowed while accounting for the possibility the
12844 			 * task is pinned to a subset of CPUs. If there is a
12845 			 * real need of migration, periodic load balance will
12846 			 * take care of it.
12847 			 */
12848 			if (p->nr_cpus_allowed != NR_CPUS) {
12849 				unsigned int w = cpumask_weight_and(p->cpus_ptr,
12850 								sched_group_span(local));
12851 				imb_numa_nr = min(w, sd->imb_numa_nr);
12852 			}
12853 
12854 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
12855 			if (!adjust_numa_imbalance(imbalance,
12856 						   local_sgs.sum_nr_running + 1,
12857 						   imb_numa_nr)) {
12858 				return NULL;
12859 			}
12860 		}
12861 #endif /* CONFIG_NUMA */
12862 
12863 		/*
12864 		 * Select group with highest number of idle CPUs. We could also
12865 		 * compare the utilization which is more stable but it can end
12866 		 * up that the group has less spare capacity but finally more
12867 		 * idle CPUs which means more opportunity to run task.
12868 		 */
12869 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
12870 			return NULL;
12871 		break;
12872 	}
12873 
12874 	return idlest;
12875 }
12876 
12877 static void update_idle_cpu_scan(struct lb_env *env,
12878 				 unsigned long sum_util)
12879 {
12880 	struct sched_domain_shared *sd_share;
12881 	struct sched_domain *sd = env->sd;
12882 	int llc_weight, pct;
12883 	u64 x, y, tmp;
12884 	/*
12885 	 * Update the number of CPUs to scan in LLC domain, which could
12886 	 * be used as a hint in select_idle_cpu(). The update of sd_share
12887 	 * could be expensive because it is within a shared cache line.
12888 	 * So the write of this hint only occurs during periodic load
12889 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
12890 	 * can fire way more frequently than the former.
12891 	 */
12892 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
12893 		return;
12894 
12895 	sd_share = sd->shared;
12896 	if (!sd_share)
12897 		return;
12898 
12899 	/*
12900 	 * The number of CPUs to search drops as sum_util increases, when
12901 	 * sum_util hits 85% or above, the scan stops.
12902 	 * The reason to choose 85% as the threshold is because this is the
12903 	 * imbalance_pct(117) when a LLC sched group is overloaded.
12904 	 *
12905 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
12906 	 * and y'= y / SCHED_CAPACITY_SCALE
12907 	 *
12908 	 * x is the ratio of sum_util compared to the CPU capacity:
12909 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
12910 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
12911 	 * and the number of CPUs to scan is calculated by:
12912 	 *
12913 	 * nr_scan = llc_weight * y'                                    [2]
12914 	 *
12915 	 * When x hits the threshold of overloaded, AKA, when
12916 	 * x = 100 / pct, y drops to 0. According to [1],
12917 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
12918 	 *
12919 	 * Scale x by SCHED_CAPACITY_SCALE:
12920 	 * x' = sum_util / llc_weight;                                  [3]
12921 	 *
12922 	 * and finally [1] becomes:
12923 	 * y = SCHED_CAPACITY_SCALE -
12924 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
12925 	 *
12926 	 */
12927 	/* equation [3] */
12928 	x = sum_util;
12929 	llc_weight = sd->span_weight;
12930 	do_div(x, llc_weight);
12931 
12932 	/* equation [4] */
12933 	pct = sd->imbalance_pct;
12934 	tmp = x * x * pct * pct;
12935 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
12936 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
12937 	y = SCHED_CAPACITY_SCALE - tmp;
12938 
12939 	/* equation [2] */
12940 	y *= llc_weight;
12941 	do_div(y, SCHED_CAPACITY_SCALE);
12942 	if ((int)y != sd_share->nr_idle_scan)
12943 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
12944 }
12945 
12946 /**
12947  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
12948  * @env: The load balancing environment.
12949  * @sds: variable to hold the statistics for this sched_domain.
12950  */
12951 
12952 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
12953 {
12954 	struct sched_group *sg = env->sd->groups;
12955 	struct sg_lb_stats *local = &sds->local_stat;
12956 	struct sg_lb_stats tmp_sgs;
12957 	unsigned long sum_util = 0;
12958 	bool sg_overloaded = 0, sg_overutilized = 0;
12959 
12960 	env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu);
12961 
12962 	do {
12963 		struct sg_lb_stats *sgs = &tmp_sgs;
12964 		int local_group;
12965 
12966 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
12967 		if (local_group) {
12968 			sds->local = sg;
12969 			sgs = local;
12970 
12971 			if (env->idle != CPU_NEWLY_IDLE ||
12972 			    time_after_eq(jiffies, sg->sgc->next_update))
12973 				update_group_capacity(env->sd, env->dst_cpu);
12974 		}
12975 
12976 		update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded);
12977 
12978 		if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
12979 			sds->busiest = sg;
12980 			sds->busiest_stat = *sgs;
12981 		}
12982 
12983 		sg_overutilized |= sgs->group_overutilized;
12984 
12985 		/* Now, start updating sd_lb_stats */
12986 		sds->total_load += sgs->group_load;
12987 		sds->total_capacity += sgs->group_capacity;
12988 
12989 		sum_util += sgs->group_util;
12990 		sg = sg->next;
12991 	} while (sg != env->sd->groups);
12992 
12993 	/*
12994 	 * Indicate that the child domain of the busiest group prefers tasks
12995 	 * go to a child's sibling domains first. NB the flags of a sched group
12996 	 * are those of the child domain.
12997 	 */
12998 	if (sds->busiest)
12999 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
13000 
13001 
13002 	if (env->sd->flags & SD_NUMA)
13003 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
13004 
13005 	if (!env->sd->parent) {
13006 		/* update overload indicator if we are at root domain */
13007 		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
13008 
13009 		/* Update over-utilization (tipping point, U >= 0) indicator */
13010 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
13011 	} else if (sg_overutilized) {
13012 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
13013 	}
13014 
13015 	update_idle_cpu_scan(env, sum_util);
13016 }
13017 
13018 /**
13019  * calculate_imbalance - Calculate the amount of imbalance present within the
13020  *			 groups of a given sched_domain during load balance.
13021  * @env: load balance environment
13022  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
13023  */
13024 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
13025 {
13026 	struct sg_lb_stats *local, *busiest;
13027 
13028 	local = &sds->local_stat;
13029 	busiest = &sds->busiest_stat;
13030 
13031 	if (busiest->group_type == group_misfit_task) {
13032 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
13033 			/* Set imbalance to allow misfit tasks to be balanced. */
13034 			env->migration_type = migrate_misfit;
13035 			env->imbalance = 1;
13036 		} else {
13037 			/*
13038 			 * Set load imbalance to allow moving task from cpu
13039 			 * with reduced capacity.
13040 			 */
13041 			env->migration_type = migrate_load;
13042 			env->imbalance = busiest->group_misfit_task_load;
13043 		}
13044 		return;
13045 	}
13046 
13047 	if (busiest->group_type == group_asym_packing) {
13048 		/*
13049 		 * In case of asym capacity, we will try to migrate all load to
13050 		 * the preferred CPU.
13051 		 */
13052 		env->migration_type = migrate_task;
13053 		env->imbalance = busiest->sum_h_nr_running;
13054 		return;
13055 	}
13056 
13057 	if (busiest->group_type == group_smt_balance) {
13058 		/* Reduce number of tasks sharing CPU capacity */
13059 		env->migration_type = migrate_task;
13060 		env->imbalance = 1;
13061 		return;
13062 	}
13063 
13064 #ifdef CONFIG_SCHED_CACHE
13065 	if (busiest->group_type == group_llc_balance) {
13066 		/* Move a task that prefer local LLC */
13067 		env->migration_type = migrate_llc_task;
13068 		env->imbalance = 1;
13069 		return;
13070 	}
13071 #endif
13072 
13073 	if (busiest->group_type == group_imbalanced) {
13074 		/*
13075 		 * In the group_imb case we cannot rely on group-wide averages
13076 		 * to ensure CPU-load equilibrium, try to move any task to fix
13077 		 * the imbalance. The next load balance will take care of
13078 		 * balancing back the system.
13079 		 */
13080 		env->migration_type = migrate_task;
13081 		env->imbalance = 1;
13082 		return;
13083 	}
13084 
13085 	/*
13086 	 * Try to use spare capacity of local group without overloading it or
13087 	 * emptying busiest.
13088 	 */
13089 	if (local->group_type == group_has_spare) {
13090 		if ((busiest->group_type > group_fully_busy) &&
13091 		    !(env->sd->flags & SD_SHARE_LLC)) {
13092 			/*
13093 			 * If busiest is overloaded, try to fill spare
13094 			 * capacity. This might end up creating spare capacity
13095 			 * in busiest or busiest still being overloaded but
13096 			 * there is no simple way to directly compute the
13097 			 * amount of load to migrate in order to balance the
13098 			 * system.
13099 			 */
13100 			env->migration_type = migrate_util;
13101 			env->imbalance = max(local->group_capacity, local->group_util) -
13102 					 local->group_util;
13103 
13104 			/*
13105 			 * In some cases, the group's utilization is max or even
13106 			 * higher than capacity because of migrations but the
13107 			 * local CPU is (newly) idle. There is at least one
13108 			 * waiting task in this overloaded busiest group. Let's
13109 			 * try to pull it.
13110 			 */
13111 			if (env->idle && env->imbalance == 0) {
13112 				env->migration_type = migrate_task;
13113 				env->imbalance = 1;
13114 			}
13115 
13116 			return;
13117 		}
13118 
13119 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
13120 			/*
13121 			 * When prefer sibling, evenly spread running tasks on
13122 			 * groups.
13123 			 */
13124 			env->migration_type = migrate_task;
13125 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
13126 		} else {
13127 
13128 			/*
13129 			 * If there is no overload, we just want to even the number of
13130 			 * idle CPUs.
13131 			 */
13132 			env->migration_type = migrate_task;
13133 			env->imbalance = max_t(long, 0,
13134 					       (local->idle_cpus - busiest->idle_cpus));
13135 		}
13136 
13137 #ifdef CONFIG_NUMA
13138 		/* Consider allowing a small imbalance between NUMA groups */
13139 		if (env->sd->flags & SD_NUMA) {
13140 			env->imbalance = adjust_numa_imbalance(env->imbalance,
13141 							       local->sum_nr_running + 1,
13142 							       env->sd->imb_numa_nr);
13143 		}
13144 #endif
13145 
13146 		/* Number of tasks to move to restore balance */
13147 		env->imbalance >>= 1;
13148 
13149 		return;
13150 	}
13151 
13152 	/*
13153 	 * Local is fully busy but has to take more load to relieve the
13154 	 * busiest group
13155 	 */
13156 	if (local->group_type < group_overloaded) {
13157 		/*
13158 		 * Local will become overloaded so the avg_load metrics are
13159 		 * finally needed.
13160 		 */
13161 
13162 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
13163 				  local->group_capacity;
13164 
13165 		/*
13166 		 * If the local group is more loaded than the selected
13167 		 * busiest group don't try to pull any tasks.
13168 		 */
13169 		if (local->avg_load >= busiest->avg_load) {
13170 			env->imbalance = 0;
13171 			return;
13172 		}
13173 
13174 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
13175 				sds->total_capacity;
13176 
13177 		/*
13178 		 * If the local group is more loaded than the average system
13179 		 * load, don't try to pull any tasks.
13180 		 */
13181 		if (local->avg_load >= sds->avg_load) {
13182 			env->imbalance = 0;
13183 			return;
13184 		}
13185 
13186 	}
13187 
13188 	/*
13189 	 * Both group are or will become overloaded and we're trying to get all
13190 	 * the CPUs to the average_load, so we don't want to push ourselves
13191 	 * above the average load, nor do we wish to reduce the max loaded CPU
13192 	 * below the average load. At the same time, we also don't want to
13193 	 * reduce the group load below the group capacity. Thus we look for
13194 	 * the minimum possible imbalance.
13195 	 */
13196 	env->migration_type = migrate_load;
13197 	env->imbalance = min(
13198 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
13199 		(sds->avg_load - local->avg_load) * local->group_capacity
13200 	) / SCHED_CAPACITY_SCALE;
13201 }
13202 
13203 /******* sched_balance_find_src_group() helpers end here *********************/
13204 
13205 /*
13206  * Decision matrix according to the local and busiest group type:
13207  *
13208  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
13209  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
13210  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
13211  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
13212  * asym_packing     force     force      N/A    N/A  force      force
13213  * imbalanced       force     force      N/A    N/A  force      force
13214  * overloaded       force     force      N/A    N/A  force      avg_load
13215  *
13216  * N/A :      Not Applicable because already filtered while updating
13217  *            statistics.
13218  * balanced : The system is balanced for these 2 groups.
13219  * force :    Calculate the imbalance as load migration is probably needed.
13220  * avg_load : Only if imbalance is significant enough.
13221  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
13222  *            different in groups.
13223  */
13224 
13225 /**
13226  * sched_balance_find_src_group - Returns the busiest group within the sched_domain
13227  * if there is an imbalance.
13228  * @env: The load balancing environment.
13229  *
13230  * Also calculates the amount of runnable load which should be moved
13231  * to restore balance.
13232  *
13233  * Return:	- The busiest group if imbalance exists.
13234  */
13235 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
13236 {
13237 	struct sg_lb_stats *local, *busiest;
13238 	struct sd_lb_stats sds;
13239 
13240 	init_sd_lb_stats(&sds);
13241 
13242 	/*
13243 	 * Compute the various statistics relevant for load balancing at
13244 	 * this level.
13245 	 */
13246 	update_sd_lb_stats(env, &sds);
13247 
13248 	/* There is no busy sibling group to pull tasks from */
13249 	if (!sds.busiest)
13250 		goto out_balanced;
13251 
13252 	busiest = &sds.busiest_stat;
13253 
13254 	/* Misfit tasks should be dealt with regardless of the avg load */
13255 	if (busiest->group_type == group_misfit_task)
13256 		goto force_balance;
13257 
13258 	if (!is_rd_overutilized(env->dst_rq->rd) &&
13259 	    rcu_dereference_all(env->dst_rq->rd->pd))
13260 		goto out_balanced;
13261 
13262 	/* ASYM feature bypasses nice load balance check */
13263 	if (busiest->group_type == group_asym_packing)
13264 		goto force_balance;
13265 
13266 	/*
13267 	 * If the busiest group is imbalanced the below checks don't
13268 	 * work because they assume all things are equal, which typically
13269 	 * isn't true due to cpus_ptr constraints and the like.
13270 	 */
13271 	if (busiest->group_type == group_imbalanced)
13272 		goto force_balance;
13273 
13274 	local = &sds.local_stat;
13275 	/*
13276 	 * If the local group is busier than the selected busiest group
13277 	 * don't try and pull any tasks.
13278 	 */
13279 	if (local->group_type > busiest->group_type)
13280 		goto out_balanced;
13281 
13282 	/*
13283 	 * When groups are overloaded, use the avg_load to ensure fairness
13284 	 * between tasks.
13285 	 */
13286 	if (local->group_type == group_overloaded) {
13287 		/*
13288 		 * If the local group is more loaded than the selected
13289 		 * busiest group don't try to pull any tasks.
13290 		 */
13291 		if (local->avg_load >= busiest->avg_load)
13292 			goto out_balanced;
13293 
13294 		/* XXX broken for overlapping NUMA groups */
13295 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
13296 				sds.total_capacity;
13297 
13298 		/*
13299 		 * Don't pull any tasks if this group is already above the
13300 		 * domain average load.
13301 		 */
13302 		if (local->avg_load >= sds.avg_load)
13303 			goto out_balanced;
13304 
13305 		/*
13306 		 * If the busiest group is more loaded, use imbalance_pct to be
13307 		 * conservative.
13308 		 */
13309 		if (100 * busiest->avg_load <=
13310 				env->sd->imbalance_pct * local->avg_load)
13311 			goto out_balanced;
13312 	}
13313 
13314 	/*
13315 	 * Try to move all excess tasks to a sibling domain of the busiest
13316 	 * group's child domain.
13317 	 */
13318 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
13319 	    (busiest->group_type == group_llc_balance ||
13320 	    sibling_imbalance(env, &sds, busiest, local) > 1))
13321 		goto force_balance;
13322 
13323 	if (busiest->group_type != group_overloaded) {
13324 		if (!env->idle) {
13325 			/*
13326 			 * If the busiest group is not overloaded (and as a
13327 			 * result the local one too) but this CPU is already
13328 			 * busy, let another idle CPU try to pull task.
13329 			 */
13330 			goto out_balanced;
13331 		}
13332 
13333 		if (busiest->group_type == group_smt_balance &&
13334 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
13335 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
13336 			goto force_balance;
13337 		}
13338 
13339 		if (busiest->group_weight > 1 &&
13340 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
13341 			/*
13342 			 * If the busiest group is not overloaded
13343 			 * and there is no imbalance between this and busiest
13344 			 * group wrt idle CPUs, it is balanced. The imbalance
13345 			 * becomes significant if the diff is greater than 1
13346 			 * otherwise we might end up to just move the imbalance
13347 			 * on another group. Of course this applies only if
13348 			 * there is more than 1 CPU per group.
13349 			 */
13350 			goto out_balanced;
13351 		}
13352 
13353 		if (busiest->sum_h_nr_running == 1) {
13354 			/*
13355 			 * busiest doesn't have any tasks waiting to run
13356 			 */
13357 			goto out_balanced;
13358 		}
13359 	}
13360 
13361 force_balance:
13362 	/* Looks like there is an imbalance. Compute it */
13363 	calculate_imbalance(env, &sds);
13364 	return env->imbalance ? sds.busiest : NULL;
13365 
13366 out_balanced:
13367 	env->imbalance = 0;
13368 	return NULL;
13369 }
13370 
13371 /*
13372  * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
13373  */
13374 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
13375 				     struct sched_group *group)
13376 {
13377 	struct rq *busiest = NULL, *rq;
13378 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
13379 	unsigned int __maybe_unused busiest_pref_llc = 0;
13380 	struct sched_domain __maybe_unused *sd_tmp;
13381 	unsigned int busiest_nr = 0;
13382 	int __maybe_unused dst_llc;
13383 	int i;
13384 
13385 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
13386 		unsigned long capacity, load, util;
13387 		unsigned int nr_running;
13388 		enum fbq_type rt;
13389 
13390 		rq = cpu_rq(i);
13391 		rt = fbq_classify_rq(rq);
13392 
13393 		/*
13394 		 * We classify groups/runqueues into three groups:
13395 		 *  - regular: there are !numa tasks
13396 		 *  - remote:  there are numa tasks that run on the 'wrong' node
13397 		 *  - all:     there is no distinction
13398 		 *
13399 		 * In order to avoid migrating ideally placed numa tasks,
13400 		 * ignore those when there's better options.
13401 		 *
13402 		 * If we ignore the actual busiest queue to migrate another
13403 		 * task, the next balance pass can still reduce the busiest
13404 		 * queue by moving tasks around inside the node.
13405 		 *
13406 		 * If we cannot move enough load due to this classification
13407 		 * the next pass will adjust the group classification and
13408 		 * allow migration of more tasks.
13409 		 *
13410 		 * Both cases only affect the total convergence complexity.
13411 		 */
13412 		if (rt > env->fbq_type)
13413 			continue;
13414 
13415 		nr_running = rq->cfs.h_nr_runnable;
13416 		if (!nr_running)
13417 			continue;
13418 
13419 		capacity = capacity_of(i);
13420 
13421 		/*
13422 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
13423 		 * eventually lead to active_balancing high->low capacity.
13424 		 * Higher per-CPU capacity is considered better than balancing
13425 		 * average load.
13426 		 */
13427 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
13428 		    nr_running == 1) {
13429 			bool cluster_equal_cap = static_branch_unlikely(&sched_cluster_active) &&
13430 						 (get_actual_cpu_capacity(env->dst_cpu) ==
13431 						  get_actual_cpu_capacity(i));
13432 			bool smt_degraded_cap = sched_smt_active() && !is_core_idle(i);
13433 
13434 			/*
13435 			 * Busy SMT siblings reduce the capacity of CPU @i. Do
13436 			 * not skip it in this case.
13437 			 *
13438 			 * CONFIG_SCHED_CLUSTER requires balancing load across
13439 			 * clusters of identical capacity, accounting for
13440 			 * hardware and cpufreq pressure.
13441 			 */
13442 			if (!smt_degraded_cap && !cluster_equal_cap &&
13443 			    !capacity_greater(capacity_of(env->dst_cpu), capacity))
13444 				continue;
13445 		}
13446 
13447 		/*
13448 		 * Make sure we only pull tasks from a CPU of lower priority
13449 		 * when balancing between SMT siblings.
13450 		 *
13451 		 * If balancing between cores, let lower priority CPUs help
13452 		 * SMT cores with more than one busy sibling.
13453 		 */
13454 		if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
13455 			continue;
13456 
13457 		switch (env->migration_type) {
13458 		case migrate_load:
13459 			/*
13460 			 * When comparing with load imbalance, use cpu_load()
13461 			 * which is not scaled with the CPU capacity.
13462 			 */
13463 			load = cpu_load(rq);
13464 
13465 			if (nr_running == 1 && load > env->imbalance &&
13466 			    !check_cpu_capacity(rq, env->sd))
13467 				break;
13468 
13469 			/*
13470 			 * For the load comparisons with the other CPUs,
13471 			 * consider the cpu_load() scaled with the CPU
13472 			 * capacity, so that the load can be moved away
13473 			 * from the CPU that is potentially running at a
13474 			 * lower capacity.
13475 			 *
13476 			 * Thus we're looking for max(load_i / capacity_i),
13477 			 * crosswise multiplication to rid ourselves of the
13478 			 * division works out to:
13479 			 * load_i * capacity_j > load_j * capacity_i;
13480 			 * where j is our previous maximum.
13481 			 */
13482 			if (load * busiest_capacity > busiest_load * capacity) {
13483 				busiest_load = load;
13484 				busiest_capacity = capacity;
13485 				busiest = rq;
13486 			}
13487 			break;
13488 
13489 		case migrate_util:
13490 			util = cpu_util_cfs_boost(i);
13491 
13492 			/*
13493 			 * Don't try to pull utilization from a CPU with one
13494 			 * running task. Whatever its utilization, we will fail
13495 			 * detach the task.
13496 			 */
13497 			if (nr_running <= 1)
13498 				continue;
13499 
13500 			if (busiest_util < util) {
13501 				busiest_util = util;
13502 				busiest = rq;
13503 			}
13504 			break;
13505 
13506 		case migrate_task:
13507 			if (busiest_nr < nr_running) {
13508 				busiest_nr = nr_running;
13509 				busiest = rq;
13510 			}
13511 			break;
13512 
13513 		case migrate_misfit:
13514 			/*
13515 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
13516 			 * simply seek the "biggest" misfit task.
13517 			 */
13518 			if (rq->misfit_task_load > busiest_load) {
13519 				busiest_load = rq->misfit_task_load;
13520 				busiest = rq;
13521 			}
13522 
13523 			break;
13524 
13525 		case migrate_llc_task:
13526 #ifdef CONFIG_SCHED_CACHE
13527 			sd_tmp = rcu_dereference_all(rq->sd);
13528 			dst_llc = llc_id(env->dst_cpu);
13529 
13530 			if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) {
13531 				unsigned int this_pref_llc =
13532 					sd_tmp->llc_counts[dst_llc];
13533 
13534 				if (busiest_pref_llc < this_pref_llc) {
13535 					busiest_pref_llc = this_pref_llc;
13536 					busiest = rq;
13537 				}
13538 			}
13539 #endif
13540 			break;
13541 
13542 		}
13543 	}
13544 
13545 	return busiest;
13546 }
13547 
13548 /*
13549  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
13550  * so long as it is large enough.
13551  */
13552 #define MAX_PINNED_INTERVAL	512
13553 
13554 static inline bool
13555 asym_active_balance(struct lb_env *env)
13556 {
13557 	/*
13558 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
13559 	 * priority CPUs in order to pack all tasks in the highest priority
13560 	 * CPUs. When done between cores, do it only if the whole core if the
13561 	 * whole core is idle.
13562 	 *
13563 	 * If @env::src_cpu is an SMT core with busy siblings, let
13564 	 * the lower priority @env::dst_cpu help it. Do not follow
13565 	 * CPU priority.
13566 	 */
13567 	return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
13568 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
13569 		!sched_use_asym_prio(env->sd, env->src_cpu));
13570 }
13571 
13572 static inline bool
13573 imbalanced_active_balance(struct lb_env *env)
13574 {
13575 	struct sched_domain *sd = env->sd;
13576 
13577 	/*
13578 	 * The imbalanced case includes the case of pinned tasks preventing a fair
13579 	 * distribution of the load on the system but also the even distribution of the
13580 	 * threads on a system with spare capacity
13581 	 */
13582 	if ((env->migration_type == migrate_task) &&
13583 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
13584 		return 1;
13585 
13586 	return 0;
13587 }
13588 
13589 static int need_active_balance(struct lb_env *env)
13590 {
13591 	struct sched_domain *sd = env->sd;
13592 
13593 	if (asym_active_balance(env))
13594 		return 1;
13595 
13596 	if (alb_break_llc(env))
13597 		return 0;
13598 
13599 	if (imbalanced_active_balance(env))
13600 		return 1;
13601 
13602 	/*
13603 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
13604 	 * It's worth migrating the task if the src_cpu's capacity is reduced
13605 	 * because of other sched_class or IRQs if more capacity stays
13606 	 * available on dst_cpu.
13607 	 */
13608 	if (env->idle &&
13609 	    (env->src_rq->cfs.h_nr_runnable == 1)) {
13610 		if ((check_cpu_capacity(env->src_rq, sd)) &&
13611 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
13612 			return 1;
13613 	}
13614 
13615 	if (env->migration_type == migrate_misfit ||
13616 	    env->migration_type == migrate_llc_task)
13617 		return 1;
13618 
13619 	return 0;
13620 }
13621 
13622 static int active_load_balance_cpu_stop(void *data);
13623 static int active_load_balance_llc_cpu_stop(void *data);
13624 
13625 /*
13626  * migration_type is checked elsewhere to decide migration policy, so
13627  * it shouldn't be repurposed just to flag an LLC-directed active
13628  * balance across the stopper. Pick the callback here instead.
13629  */
13630 static inline cpu_stop_fn_t alb_stop_fn(struct lb_env *env)
13631 {
13632 	if (env->migration_type == migrate_llc_task)
13633 		return active_load_balance_llc_cpu_stop;
13634 
13635 	return active_load_balance_cpu_stop;
13636 }
13637 
13638 static int should_we_balance(struct lb_env *env)
13639 {
13640 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
13641 	struct sched_group *sg = env->sd->groups;
13642 	int cpu, idle_smt = -1;
13643 
13644 	/*
13645 	 * Ensure the balancing environment is consistent; can happen
13646 	 * when the softirq triggers 'during' hotplug.
13647 	 */
13648 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
13649 		return 0;
13650 
13651 	/*
13652 	 * In the newly idle case, we will allow all the CPUs
13653 	 * to do the newly idle load balance.
13654 	 *
13655 	 * However, we bail out if we already have tasks or a wakeup pending,
13656 	 * to optimize wakeup latency.
13657 	 */
13658 	if (env->idle == CPU_NEWLY_IDLE) {
13659 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
13660 			return 0;
13661 		return 1;
13662 	}
13663 
13664 	cpumask_copy(swb_cpus, group_balance_mask(sg));
13665 	/* Try to find first idle CPU */
13666 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
13667 		if (!idle_cpu(cpu))
13668 			continue;
13669 
13670 		/*
13671 		 * Don't balance to idle SMT in busy core right away when
13672 		 * balancing cores, but remember the first idle SMT CPU for
13673 		 * later consideration.  Find CPU on an idle core first.
13674 		 */
13675 		if (sched_smt_active() &&
13676 		    !(env->sd->flags & SD_SHARE_CPUCAPACITY) &&
13677 		    !is_core_idle(cpu)) {
13678 			if (idle_smt == -1)
13679 				idle_smt = cpu;
13680 			/*
13681 			 * If the core is not idle, and first SMT sibling which is
13682 			 * idle has been found, then its not needed to check other
13683 			 * SMT siblings for idleness:
13684 			 */
13685 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
13686 			continue;
13687 		}
13688 
13689 		/*
13690 		 * Are we the first idle core in a non-SMT domain or higher,
13691 		 * or the first idle CPU in a SMT domain?
13692 		 */
13693 		return cpu == env->dst_cpu;
13694 	}
13695 
13696 	/* Are we the first idle CPU with busy siblings? */
13697 	if (idle_smt != -1)
13698 		return idle_smt == env->dst_cpu;
13699 
13700 	/* Are we the first CPU of this group ? */
13701 	return group_balance_cpu(sg) == env->dst_cpu;
13702 }
13703 
13704 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
13705 				     enum cpu_idle_type idle)
13706 {
13707 	if (!schedstat_enabled())
13708 		return;
13709 
13710 	switch (env->migration_type) {
13711 	case migrate_load:
13712 		__schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
13713 		break;
13714 	case migrate_util:
13715 		__schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
13716 		break;
13717 	case migrate_task:
13718 		__schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
13719 		break;
13720 	case migrate_misfit:
13721 		__schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
13722 		break;
13723 	case migrate_llc_task:
13724 		break;
13725 	}
13726 }
13727 
13728 /*
13729  * This flag serializes load-balancing passes over large domains
13730  * (above the NODE topology level) - only one load-balancing instance
13731  * may run at a time, to reduce overhead on very large systems with
13732  * lots of CPUs and large NUMA distances.
13733  *
13734  * - Note that load-balancing passes triggered while another one
13735  *   is executing are skipped and not re-tried.
13736  *
13737  * - Also note that this does not serialize rebalance_domains()
13738  *   execution, as non-SD_SERIALIZE domains will still be
13739  *   load-balanced in parallel.
13740  */
13741 static atomic_t sched_balance_running = ATOMIC_INIT(0);
13742 
13743 /*
13744  * Check this_cpu to ensure it is balanced within domain. Attempt to move
13745  * tasks if there is an imbalance.
13746  */
13747 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
13748 			struct sched_domain *sd, enum cpu_idle_type idle,
13749 			int *continue_balancing)
13750 {
13751 	int ld_moved, cur_ld_moved, active_balance = 0;
13752 	struct sched_domain *sd_parent = sd->parent;
13753 	struct sched_group *group;
13754 	struct rq *busiest;
13755 	struct rq_flags rf;
13756 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
13757 	struct lb_env env = {
13758 		.sd		= sd,
13759 		.dst_cpu	= this_cpu,
13760 		.dst_rq		= this_rq,
13761 		.dst_grpmask    = group_balance_mask(sd->groups),
13762 		.idle		= idle,
13763 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
13764 		.cpus		= cpus,
13765 		.fbq_type	= all,
13766 		.tasks		= LIST_HEAD_INIT(env.tasks),
13767 	};
13768 	bool need_unlock = false;
13769 
13770 	cpumask_and(cpus, sched_domain_span(sd), cpu_preferred_mask);
13771 
13772 	schedstat_inc(sd->lb_count[idle]);
13773 
13774 redo:
13775 	if (!should_we_balance(&env)) {
13776 		*continue_balancing = 0;
13777 		goto out_balanced;
13778 	}
13779 
13780 	if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
13781 		int zero = 0;
13782 		if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
13783 			goto out_balanced;
13784 
13785 		need_unlock = true;
13786 	}
13787 
13788 	group = sched_balance_find_src_group(&env);
13789 	if (!group) {
13790 		schedstat_inc(sd->lb_nobusyg[idle]);
13791 		goto out_balanced;
13792 	}
13793 
13794 	busiest = sched_balance_find_src_rq(&env, group);
13795 	if (!busiest) {
13796 		schedstat_inc(sd->lb_nobusyq[idle]);
13797 		goto out_balanced;
13798 	}
13799 
13800 	WARN_ON_ONCE(busiest == env.dst_rq);
13801 
13802 	update_lb_imbalance_stat(&env, sd, idle);
13803 
13804 	env.src_cpu = busiest->cpu;
13805 	env.src_rq = busiest;
13806 
13807 	ld_moved = 0;
13808 	/* Clear this flag as soon as we find a pullable task */
13809 	env.flags |= LBF_ALL_PINNED;
13810 	if (busiest->nr_running > 1) {
13811 		/*
13812 		 * Attempt to move tasks. If sched_balance_find_src_group has found
13813 		 * an imbalance but busiest->nr_running <= 1, the group is
13814 		 * still unbalanced. ld_moved simply stays zero, so it is
13815 		 * correctly treated as an imbalance.
13816 		 */
13817 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
13818 
13819 more_balance:
13820 		rq_lock_irqsave(busiest, &rf);
13821 		update_rq_clock(busiest);
13822 
13823 		/*
13824 		 * cur_ld_moved - load moved in current iteration
13825 		 * ld_moved     - cumulative load moved across iterations
13826 		 */
13827 		cur_ld_moved = detach_tasks(&env);
13828 
13829 		/*
13830 		 * We've detached some tasks from busiest_rq. Every
13831 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
13832 		 * unlock busiest->lock, and we are able to be sure
13833 		 * that nobody can manipulate the tasks in parallel.
13834 		 * See task_rq_lock() family for the details.
13835 		 */
13836 
13837 		rq_unlock(busiest, &rf);
13838 
13839 		if (cur_ld_moved) {
13840 			attach_tasks(&env);
13841 			ld_moved += cur_ld_moved;
13842 		}
13843 
13844 		local_irq_restore(rf.flags);
13845 
13846 		if (env.flags & LBF_NEED_BREAK) {
13847 			env.flags &= ~LBF_NEED_BREAK;
13848 			goto more_balance;
13849 		}
13850 
13851 		/*
13852 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
13853 		 * us and move them to an alternate dst_cpu in our sched_group
13854 		 * where they can run. The upper limit on how many times we
13855 		 * iterate on same src_cpu is dependent on number of CPUs in our
13856 		 * sched_group.
13857 		 *
13858 		 * This changes load balance semantics a bit on who can move
13859 		 * load to a given_cpu. In addition to the given_cpu itself
13860 		 * (or a ilb_cpu acting on its behalf where given_cpu is
13861 		 * nohz-idle), we now have balance_cpu in a position to move
13862 		 * load to given_cpu. In rare situations, this may cause
13863 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
13864 		 * _independently_ and at _same_ time to move some load to
13865 		 * given_cpu) causing excess load to be moved to given_cpu.
13866 		 * This however should not happen so much in practice and
13867 		 * moreover subsequent load balance cycles should correct the
13868 		 * excess load moved.
13869 		 */
13870 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
13871 
13872 			/* Prevent to re-select dst_cpu via env's CPUs */
13873 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
13874 
13875 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
13876 			env.dst_cpu	 = env.new_dst_cpu;
13877 			env.flags	&= ~LBF_DST_PINNED;
13878 			env.loop	 = 0;
13879 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
13880 
13881 			/*
13882 			 * Go back to "more_balance" rather than "redo" since we
13883 			 * need to continue with same src_cpu.
13884 			 */
13885 			goto more_balance;
13886 		}
13887 
13888 		/*
13889 		 * We failed to reach balance because of affinity.
13890 		 */
13891 		if (sd_parent) {
13892 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
13893 
13894 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
13895 				*group_imbalance = 1;
13896 		}
13897 
13898 		/* All tasks on this runqueue were pinned by CPU affinity */
13899 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
13900 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
13901 			/*
13902 			 * Attempting to continue load balancing at the current
13903 			 * sched_domain level only makes sense if there are
13904 			 * active CPUs remaining as possible busiest CPUs to
13905 			 * pull load from which are not contained within the
13906 			 * destination group that is receiving any migrated
13907 			 * load.
13908 			 */
13909 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
13910 				env.loop = 0;
13911 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
13912 				goto redo;
13913 			}
13914 			goto out_all_pinned;
13915 		}
13916 	}
13917 
13918 	if (ld_moved) {
13919 		sd->nr_balance_failed = 0;
13920 		goto out_unbalanced;
13921 	}
13922 
13923 	schedstat_inc(sd->lb_failed[idle]);
13924 	/*
13925 	 * Increment the failure counter only on periodic balance.
13926 	 * We do not want newidle balance, which can be very
13927 	 * frequent, pollute the failure counter causing
13928 	 * excessive cache_hot migrations and active balances.
13929 	 *
13930 	 * Similarly for migration_misfit which is not related to
13931 	 * load/util migration, don't pollute nr_balance_failed.
13932 	 *
13933 	 * The same for cache aware scheduling's allowance for
13934 	 * load imbalance. If regular load balance does not
13935 	 * migrate task due to LLC locality, it is a expected
13936 	 * behavior and don't pollute nr_balance_failed.
13937 	 * See can_migrate_task().
13938 	 */
13939 	if (idle != CPU_NEWLY_IDLE &&
13940 	    env.migration_type != migrate_misfit &&
13941 	    !(env.flags & LBF_LLC_PINNED))
13942 		sd->nr_balance_failed++;
13943 
13944 	if (!need_active_balance(&env))
13945 		goto out_unbalanced;
13946 
13947 	scoped_guard (raw_spin_rq_lock_irqsave, busiest) {
13948 		/*
13949 		 * Don't kick the active_load_balance_cpu_stop,
13950 		 * if the curr task on busiest CPU can't be
13951 		 * moved to this_cpu:
13952 		 */
13953 		if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr))
13954 			goto out_one_pinned;
13955 
13956 		/* Record that we found at least one task that could run on this_cpu */
13957 		env.flags &= ~LBF_ALL_PINNED;
13958 
13959 		/*
13960 		 * ->active_balance synchronizes accesses to
13961 		 * ->active_balance_work.  Once set, it's cleared
13962 		 * only after active load balance is finished.
13963 		 */
13964 		if (busiest->active_balance)
13965 			goto out_unbalanced;
13966 
13967 		/*
13968 		 * @busiest dropped its rq_lock in the middle of
13969 		 * scheduling out its ->curr task (->on_rq := 0), no
13970 		 * need to forcefully punt it away with active balance.
13971 		 */
13972 		if (!busiest->curr->on_rq)
13973 			goto out_unbalanced;
13974 
13975 		busiest->active_balance = 1;
13976 		busiest->push_cpu = this_cpu;
13977 		active_balance = 1;
13978 		preempt_disable();
13979 	}
13980 	if (active_balance) {
13981 		stop_one_cpu_nowait(cpu_of(busiest),
13982 				    alb_stop_fn(&env), busiest,
13983 				    &busiest->active_balance_work);
13984 	}
13985 	preempt_enable();
13986 
13987 out_unbalanced:
13988 	/* We were unbalanced, so reset the balancing interval */
13989 	sd->balance_interval = sd->min_interval;
13990 	goto out;
13991 
13992 out_balanced:
13993 	/*
13994 	 * We reach balance although we may have faced some affinity
13995 	 * constraints. Clear the imbalance flag only if other tasks got
13996 	 * a chance to move and fix the imbalance.
13997 	 */
13998 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
13999 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
14000 
14001 		if (*group_imbalance)
14002 			*group_imbalance = 0;
14003 	}
14004 
14005 out_all_pinned:
14006 	/*
14007 	 * We reach balance because all tasks are pinned at this level so
14008 	 * we can't migrate them. Let the imbalance flag set so parent level
14009 	 * can try to migrate them.
14010 	 */
14011 	schedstat_inc(sd->lb_balanced[idle]);
14012 
14013 	sd->nr_balance_failed = 0;
14014 
14015 out_one_pinned:
14016 	ld_moved = 0;
14017 
14018 	/*
14019 	 * sched_balance_newidle() disregards balance intervals, so we could
14020 	 * repeatedly reach this code, which would lead to balance_interval
14021 	 * skyrocketing in a short amount of time. Skip the balance_interval
14022 	 * increase logic to avoid that.
14023 	 *
14024 	 * Similarly misfit migration which is not necessarily an indication of
14025 	 * the system being busy and requires lb to backoff to let it settle
14026 	 * down.
14027 	 */
14028 	if (env.idle == CPU_NEWLY_IDLE ||
14029 	    env.migration_type == migrate_misfit)
14030 		goto out;
14031 
14032 	/* tune up the balancing interval */
14033 	if ((env.flags & LBF_ALL_PINNED &&
14034 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
14035 	    sd->balance_interval < sd->max_interval)
14036 		sd->balance_interval *= 2;
14037 out:
14038 	if (need_unlock)
14039 		atomic_set_release(&sched_balance_running, 0);
14040 
14041 	return ld_moved;
14042 }
14043 
14044 static inline unsigned long
14045 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
14046 {
14047 	unsigned long interval = sd->balance_interval;
14048 
14049 	if (cpu_busy)
14050 		interval *= sd->busy_factor;
14051 
14052 	/* scale ms to jiffies */
14053 	interval = msecs_to_jiffies(interval);
14054 
14055 	/*
14056 	 * Reduce likelihood of busy balancing at higher domains racing with
14057 	 * balancing at lower domains by preventing their balancing periods
14058 	 * from being multiples of each other.
14059 	 */
14060 	if (cpu_busy)
14061 		interval -= 1;
14062 
14063 	interval = clamp(interval, 1UL, max_load_balance_interval);
14064 
14065 	return interval;
14066 }
14067 
14068 static inline void
14069 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
14070 {
14071 	unsigned long interval, next;
14072 
14073 	/* used by idle balance, so cpu_busy = 0 */
14074 	interval = get_sd_balance_interval(sd, 0);
14075 	next = sd->last_balance + interval;
14076 
14077 	if (time_after(*next_balance, next))
14078 		*next_balance = next;
14079 }
14080 
14081 /*
14082  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
14083  * running tasks off the busiest CPU onto idle CPUs. It requires at
14084  * least 1 task to be running on each physical CPU where possible, and
14085  * avoids physical / logical imbalances.
14086  */
14087 static int __active_load_balance_cpu_stop(void *data, unsigned int lb_flags)
14088 {
14089 	struct rq *busiest_rq = data;
14090 	int busiest_cpu = cpu_of(busiest_rq);
14091 	int target_cpu = busiest_rq->push_cpu;
14092 	struct rq *target_rq = cpu_rq(target_cpu);
14093 	struct sched_domain *sd;
14094 	struct task_struct *p = NULL;
14095 	struct rq_flags rf;
14096 
14097 	rq_lock_irq(busiest_rq, &rf);
14098 	/*
14099 	 * Between queueing the stop-work and running it is a hole in which
14100 	 * CPUs can become inactive. We should not move tasks from or to
14101 	 * inactive CPUs.
14102 	 */
14103 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
14104 		goto out_unlock;
14105 
14106 	/* Make sure the requested CPU hasn't gone down in the meantime: */
14107 	if (unlikely(busiest_cpu != smp_processor_id() ||
14108 		     !busiest_rq->active_balance))
14109 		goto out_unlock;
14110 
14111 	/* Is there any task to move? */
14112 	if (busiest_rq->nr_running <= 1)
14113 		goto out_unlock;
14114 
14115 	/*
14116 	 * This condition is "impossible", if it occurs
14117 	 * we need to fix it. Originally reported by
14118 	 * Bjorn Helgaas on a 128-CPU setup.
14119 	 */
14120 	WARN_ON_ONCE(busiest_rq == target_rq);
14121 
14122 	/* Search for an sd spanning us and the target CPU. */
14123 	rcu_read_lock();
14124 	for_each_domain(target_cpu, sd) {
14125 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
14126 			break;
14127 	}
14128 
14129 	if (likely(sd)) {
14130 		struct lb_env env = {
14131 			.sd		= sd,
14132 			.dst_cpu	= target_cpu,
14133 			.dst_rq		= target_rq,
14134 			.src_cpu	= busiest_rq->cpu,
14135 			.src_rq		= busiest_rq,
14136 			.idle		= CPU_IDLE,
14137 			.flags		= LBF_ACTIVE_LB | lb_flags,
14138 		};
14139 
14140 		schedstat_inc(sd->alb_count);
14141 		update_rq_clock(busiest_rq);
14142 
14143 		p = detach_one_task(&env);
14144 		if (p) {
14145 			schedstat_inc(sd->alb_pushed);
14146 			/* Active balancing done, reset the failure counter. */
14147 			sd->nr_balance_failed = 0;
14148 		} else {
14149 			schedstat_inc(sd->alb_failed);
14150 		}
14151 	}
14152 	rcu_read_unlock();
14153 out_unlock:
14154 	busiest_rq->active_balance = 0;
14155 	rq_unlock(busiest_rq, &rf);
14156 
14157 	if (p)
14158 		attach_one_task(target_rq, p);
14159 
14160 	local_irq_enable();
14161 
14162 	return 0;
14163 }
14164 
14165 static int active_load_balance_cpu_stop(void *data)
14166 {
14167 	return __active_load_balance_cpu_stop(data, 0);
14168 }
14169 
14170 static int active_load_balance_llc_cpu_stop(void *data)
14171 {
14172 	return __active_load_balance_cpu_stop(data, LBF_ACTIVE_LB_LLC);
14173 }
14174 
14175 /*
14176  * Scale the max sched_balance_rq interval with the number of CPUs in the system.
14177  * This trades load-balance latency on larger machines for less cross talk.
14178  */
14179 void update_max_interval(void)
14180 {
14181 	max_load_balance_interval = HZ*num_online_cpus()/10;
14182 }
14183 
14184 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
14185 {
14186 	sd->newidle_call++;
14187 	sd->newidle_success += success;
14188 
14189 	if (sd->newidle_call >= 1024) {
14190 		u64 now = sched_clock();
14191 		s64 delta = now - sd->newidle_stamp;
14192 		sd->newidle_stamp = now;
14193 		int ratio = 0;
14194 
14195 		if (delta < 0)
14196 			delta = 0;
14197 
14198 		if (sched_feat(NI_RATE)) {
14199 			/*
14200 			 * ratio  delta   freq
14201 			 *
14202 			 * 1024 -  4  s -  128 Hz
14203 			 *  512 -  2  s -  256 Hz
14204 			 *  256 -  1  s -  512 Hz
14205 			 *  128 - .5  s - 1024 Hz
14206 			 *   64 - .25 s - 2048 Hz
14207 			 */
14208 			ratio = delta >> 22;
14209 		}
14210 
14211 		ratio += sd->newidle_success;
14212 
14213 		sd->newidle_ratio = min(1024, ratio);
14214 		sd->newidle_call /= 2;
14215 		sd->newidle_success /= 2;
14216 	}
14217 }
14218 
14219 static inline bool
14220 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
14221 {
14222 	unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
14223 	unsigned long now = jiffies;
14224 
14225 	if (cost)
14226 		update_newidle_stats(sd, success);
14227 
14228 	if (cost > sd->max_newidle_lb_cost) {
14229 		/*
14230 		 * Track max cost of a domain to make sure to not delay the
14231 		 * next wakeup on the CPU.
14232 		 */
14233 		sd->max_newidle_lb_cost = cost;
14234 		sd->last_decay_max_lb_cost = now;
14235 
14236 	} else if (time_after(now, next_decay)) {
14237 		/*
14238 		 * Decay the newidle max times by ~1% per second to ensure that
14239 		 * it is not outdated and the current max cost is actually
14240 		 * shorter.
14241 		 */
14242 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
14243 		sd->last_decay_max_lb_cost = now;
14244 		return true;
14245 	}
14246 
14247 	return false;
14248 }
14249 
14250 /*
14251  * It checks each scheduling domain to see if it is due to be balanced,
14252  * and initiates a balancing operation if so.
14253  *
14254  * Balancing parameters are set up in init_sched_domains.
14255  */
14256 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
14257 {
14258 	int continue_balancing = 1;
14259 	int cpu = rq->cpu;
14260 	int busy = idle != CPU_IDLE && !sched_idle_rq(rq);
14261 	unsigned long interval;
14262 	struct sched_domain *sd;
14263 	/* Earliest time when we have to do rebalance again */
14264 	unsigned long next_balance = jiffies + 60*HZ;
14265 	int update_next_balance = 0;
14266 	int need_decay = 0;
14267 	u64 max_cost = 0;
14268 
14269 	rcu_read_lock();
14270 	for_each_domain(cpu, sd) {
14271 		/*
14272 		 * Decay the newidle max times here because this is a regular
14273 		 * visit to all the domains.
14274 		 */
14275 		need_decay = update_newidle_cost(sd, 0, 0);
14276 		max_cost += sd->max_newidle_lb_cost;
14277 
14278 		/*
14279 		 * Stop the load balance at this level. There is another
14280 		 * CPU in our sched group which is doing load balancing more
14281 		 * actively.
14282 		 */
14283 		if (!continue_balancing) {
14284 			if (need_decay)
14285 				continue;
14286 			break;
14287 		}
14288 
14289 		interval = get_sd_balance_interval(sd, busy);
14290 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
14291 			if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
14292 				/*
14293 				 * The LBF_DST_PINNED logic could have changed
14294 				 * env->dst_cpu, so we can't know our idle
14295 				 * state even if we migrated tasks. Update it.
14296 				 */
14297 				idle = idle_cpu(cpu);
14298 				busy = !idle && !sched_idle_rq(rq);
14299 			}
14300 			sd->last_balance = jiffies;
14301 			interval = get_sd_balance_interval(sd, busy);
14302 		}
14303 		if (time_after(next_balance, sd->last_balance + interval)) {
14304 			next_balance = sd->last_balance + interval;
14305 			update_next_balance = 1;
14306 		}
14307 	}
14308 	if (need_decay) {
14309 		/*
14310 		 * Ensure the rq-wide value also decays but keep it at a
14311 		 * reasonable floor to avoid funnies with rq->avg_idle.
14312 		 */
14313 		rq->max_idle_balance_cost =
14314 			max((u64)sysctl_sched_migration_cost, max_cost);
14315 	}
14316 	rcu_read_unlock();
14317 
14318 	/*
14319 	 * next_balance will be updated only when there is a need.
14320 	 * When the cpu is attached to null domain for ex, it will not be
14321 	 * updated.
14322 	 */
14323 	if (likely(update_next_balance))
14324 		rq->next_balance = next_balance;
14325 
14326 }
14327 
14328 static inline int on_null_domain(struct rq *rq)
14329 {
14330 	return unlikely(!rcu_dereference_sched(rq->sd));
14331 }
14332 
14333 #ifdef CONFIG_NO_HZ_COMMON
14334 /*
14335  * NOHZ idle load balancing (ILB) details:
14336  *
14337  * - When one of the busy CPUs notices that there may be an idle rebalancing
14338  *   needed, they will kick the idle load balancer, which then does idle
14339  *   load balancing for all the idle CPUs.
14340  */
14341 static inline int find_new_ilb(void)
14342 {
14343 	struct cpumask *ilb_cpus;
14344 	int ilb_cpu, fallback = -1;
14345 
14346 	lockdep_assert_irqs_disabled();
14347 
14348 	/*
14349 	 * Reuse the per-CPU select_rq_mask, which is protected from concurrent
14350 	 * use on this CPU by having interrupts disabled.
14351 	 */
14352 	ilb_cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
14353 	cpumask_and(ilb_cpus, nohz.idle_cpus_mask,
14354 		    housekeeping_cpumask(HK_TYPE_KERNEL_NOISE));
14355 
14356 	for_each_cpu(ilb_cpu, ilb_cpus) {
14357 		if (!idle_cpu(ilb_cpu)) {
14358 			/*
14359 			 * Once an idle fallback exists, a busy CPU proves that
14360 			 * this core cannot be fully idle. Skip its siblings.
14361 			 */
14362 			if (sched_smt_active() && fallback >= 0)
14363 				cpumask_andnot(ilb_cpus, ilb_cpus, cpu_smt_mask(ilb_cpu));
14364 			continue;
14365 		}
14366 
14367 		/*
14368 		 * Running the idle load balancer on an idle sibling of a busy
14369 		 * SMT core can reduce the capacity available to its sibling. Prefer
14370 		 * a CPU whose entire core is idle, but retain the first idle CPU as
14371 		 * a fallback so idle balancing can still make progress when no fully
14372 		 * idle core exists.
14373 		 */
14374 		if (sched_smt_active() && !is_core_idle(ilb_cpu)) {
14375 			if (fallback < 0)
14376 				fallback = ilb_cpu;
14377 
14378 			/*
14379 			 * The core is not idle, so there is no need to check
14380 			 * any of its other SMT siblings.
14381 			 */
14382 			cpumask_andnot(ilb_cpus, ilb_cpus,
14383 				       cpu_smt_mask(ilb_cpu));
14384 			continue;
14385 		}
14386 
14387 		return ilb_cpu;
14388 	}
14389 
14390 	return fallback;
14391 }
14392 
14393 /*
14394  * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
14395  * SMP function call (IPI).
14396  *
14397  * Prefer a CPU on a fully idle core in the HK_TYPE_KERNEL_NOISE housekeeping
14398  * set. Fall back to the first idle CPU when no fully idle core exists.
14399  */
14400 static void kick_ilb(unsigned int flags)
14401 {
14402 	int ilb_cpu;
14403 
14404 	/*
14405 	 * Increase nohz.next_balance only when if full ilb is triggered but
14406 	 * not if we only update stats.
14407 	 */
14408 	if (flags & NOHZ_BALANCE_KICK)
14409 		nohz.next_balance = jiffies+1;
14410 
14411 	ilb_cpu = find_new_ilb();
14412 	if (ilb_cpu < 0)
14413 		return;
14414 
14415 	/*
14416 	 * Don't bother if no new NOHZ balance work items for ilb_cpu,
14417 	 * i.e. all bits in flags are already set in ilb_cpu.
14418 	 */
14419 	if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
14420 		return;
14421 
14422 	/*
14423 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
14424 	 * the first flag owns it; cleared by nohz_csd_func().
14425 	 */
14426 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
14427 	if (flags & NOHZ_KICK_MASK)
14428 		return;
14429 
14430 	/*
14431 	 * This way we generate an IPI on the target CPU which
14432 	 * is idle, and the softirq performing NOHZ idle load balancing
14433 	 * will be run before returning from the IPI.
14434 	 */
14435 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
14436 }
14437 
14438 /*
14439  * Current decision point for kicking the idle load balancer in the presence
14440  * of idle CPUs in the system.
14441  */
14442 static void nohz_balancer_kick(struct rq *rq)
14443 {
14444 	unsigned long now = jiffies;
14445 	struct sched_domain_shared *sds;
14446 	struct sched_domain *sd;
14447 	int nr_busy, i, cpu = rq->cpu;
14448 	unsigned int flags = 0;
14449 
14450 	if (unlikely(rq->idle_balance))
14451 		return;
14452 
14453 	/*
14454 	 * We may be recently in ticked or tickless idle mode. At the first
14455 	 * busy tick after returning from idle, we will update the busy stats.
14456 	 */
14457 	nohz_balance_exit_idle(rq);
14458 
14459 	if (READ_ONCE(nohz.has_blocked_load) &&
14460 	    time_after(now, READ_ONCE(nohz.next_blocked)))
14461 		flags = NOHZ_STATS_KICK;
14462 
14463 	/*
14464 	 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0
14465 	 * Skip the read if time is not due.
14466 	 *
14467 	 * If none are in tickless mode, there maybe a narrow window
14468 	 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called.
14469 	 * But idle load balancing is not done as find_new_ilb fails.
14470 	 * That's very rare. So read nohz.nr_cpus only if time is due.
14471 	 */
14472 	if (time_before(now, nohz.next_balance))
14473 		goto out;
14474 
14475 	/*
14476 	 * None are in tickless mode and hence no need for NOHZ idle load
14477 	 * balancing
14478 	 */
14479 	if (unlikely(cpumask_empty(nohz.idle_cpus_mask)))
14480 		return;
14481 
14482 	if (rq->nr_running >= 2) {
14483 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14484 		goto out;
14485 	}
14486 
14487 	sd = rcu_dereference_all(rq->sd);
14488 	if (sd) {
14489 		/*
14490 		 * If there's a runnable CFS task and the current CPU has reduced
14491 		 * capacity, kick the ILB to see if there's a better CPU to run on:
14492 		 */
14493 		if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
14494 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14495 			goto out;
14496 		}
14497 	}
14498 
14499 	sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu));
14500 	if (sd) {
14501 		/*
14502 		 * When ASYM_PACKING; see if there's a more preferred CPU
14503 		 * currently idle; in which case, kick the ILB to move tasks
14504 		 * around.
14505 		 *
14506 		 * When balancing between cores, all the SMT siblings of the
14507 		 * preferred CPU must be idle.
14508 		 */
14509 		for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
14510 			if (sched_asym(sd, i, cpu)) {
14511 				flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14512 				goto out;
14513 			}
14514 		}
14515 	}
14516 
14517 	sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu));
14518 	if (sd) {
14519 		/*
14520 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
14521 		 * to run the misfit task on.
14522 		 */
14523 		if (check_misfit_status(rq))
14524 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14525 
14526 		/*
14527 		 * For asymmetric systems, we do not want to nicely balance
14528 		 * cache use, instead we want to embrace asymmetry and only
14529 		 * ensure tasks have enough CPU capacity.
14530 		 *
14531 		 * Skip the LLC logic because it's not relevant in that case.
14532 		 */
14533 		goto out;
14534 	}
14535 
14536 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
14537 	if (sds) {
14538 		/*
14539 		 * If there is an imbalance between LLC domains (IOW we could
14540 		 * increase the overall cache utilization), we need a less-loaded LLC
14541 		 * domain to pull some load from. Likewise, we may need to spread
14542 		 * load within the current LLC domain (e.g. packed SMT cores but
14543 		 * other CPUs are idle). We can't really know from here how busy
14544 		 * the others are - so just get a NOHZ balance going if it looks
14545 		 * like this LLC domain has tasks we could move.
14546 		 */
14547 		nr_busy = atomic_read(&sds->nr_busy_cpus);
14548 		if (nr_busy > 1)
14549 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14550 	}
14551 out:
14552 	if (READ_ONCE(nohz.needs_update))
14553 		flags |= NOHZ_NEXT_KICK;
14554 
14555 	if (flags)
14556 		kick_ilb(flags);
14557 }
14558 
14559 static void set_cpu_sd_state_busy(int cpu)
14560 {
14561 	struct sched_domain *sd;
14562 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14563 
14564 	/*
14565 	 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this
14566 	 * domain has no shared object there is nothing to clear or account.
14567 	 */
14568 	if (!sd || !sd->shared || !sd->nohz_idle)
14569 		return;
14570 	sd->nohz_idle = 0;
14571 
14572 	atomic_inc(&sd->shared->nr_busy_cpus);
14573 }
14574 
14575 void nohz_balance_exit_idle(struct rq *rq)
14576 {
14577 	WARN_ON_ONCE(rq != this_rq());
14578 
14579 	if (likely(!rq->nohz_tick_stopped))
14580 		return;
14581 
14582 	rq->nohz_tick_stopped = 0;
14583 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
14584 
14585 	set_cpu_sd_state_busy(rq->cpu);
14586 }
14587 
14588 static void set_cpu_sd_state_idle(int cpu)
14589 {
14590 	struct sched_domain *sd;
14591 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14592 
14593 	/* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */
14594 	if (!sd || !sd->shared || sd->nohz_idle)
14595 		return;
14596 	sd->nohz_idle = 1;
14597 
14598 	atomic_dec(&sd->shared->nr_busy_cpus);
14599 }
14600 
14601 /*
14602  * This routine will record that the CPU is going idle with tick stopped.
14603  * This info will be used in performing idle load balancing in the future.
14604  */
14605 void nohz_balance_enter_idle(int cpu)
14606 {
14607 	struct rq *rq = cpu_rq(cpu);
14608 
14609 	WARN_ON_ONCE(cpu != smp_processor_id());
14610 
14611 	/* If this CPU is going down, then nothing needs to be done: */
14612 	if (!cpu_active(cpu))
14613 		return;
14614 
14615 	/*
14616 	 * Can be set safely without rq->lock held
14617 	 * If a clear happens, it will have evaluated last additions because
14618 	 * rq->lock is held during the check and the clear
14619 	 */
14620 	rq->has_blocked_load = 1;
14621 
14622 	/*
14623 	 * The tick is still stopped but load could have been added in the
14624 	 * meantime. We set the nohz.has_blocked_load flag to trig a check of the
14625 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
14626 	 * of nohz.has_blocked_load can only happen after checking the new load
14627 	 */
14628 	if (rq->nohz_tick_stopped)
14629 		goto out;
14630 
14631 	/* If we're a completely isolated CPU, we don't play: */
14632 	if (on_null_domain(rq))
14633 		return;
14634 
14635 	rq->nohz_tick_stopped = 1;
14636 
14637 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
14638 
14639 	/*
14640 	 * Ensures that if nohz_idle_balance() fails to observe our
14641 	 * @idle_cpus_mask store, it must observe the @has_blocked_load
14642 	 * and @needs_update stores.
14643 	 */
14644 	smp_mb__after_atomic();
14645 
14646 	set_cpu_sd_state_idle(cpu);
14647 
14648 	WRITE_ONCE(nohz.needs_update, 1);
14649 out:
14650 	/*
14651 	 * Each time a cpu enter idle, we assume that it has blocked load and
14652 	 * enable the periodic update of the load of idle CPUs
14653 	 */
14654 	WRITE_ONCE(nohz.has_blocked_load, 1);
14655 }
14656 
14657 static bool update_nohz_stats(struct rq *rq)
14658 {
14659 	unsigned int cpu = rq->cpu;
14660 
14661 	if (!rq->has_blocked_load)
14662 		return false;
14663 
14664 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
14665 		return false;
14666 
14667 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
14668 		return true;
14669 
14670 	sched_balance_update_blocked_averages(cpu);
14671 
14672 	return rq->has_blocked_load;
14673 }
14674 
14675 /*
14676  * Internal function that runs load balance for all idle CPUs. The load balance
14677  * can be a simple update of blocked load or a complete load balance with
14678  * tasks movement depending of flags.
14679  */
14680 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
14681 {
14682 	/* Earliest time when we have to do rebalance again */
14683 	unsigned long now = jiffies;
14684 	unsigned long next_balance = now + 60*HZ;
14685 	bool has_blocked_load = false;
14686 	int update_next_balance = 0;
14687 	int this_cpu = this_rq->cpu;
14688 	int balance_cpu;
14689 	struct rq *rq;
14690 
14691 	WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
14692 
14693 	/*
14694 	 * We assume there will be no idle load after this update and clear
14695 	 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will
14696 	 * set the has_blocked_load flag and trigger another update of idle load.
14697 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
14698 	 * setting the flag, we are sure to not clear the state and not
14699 	 * check the load of an idle cpu.
14700 	 *
14701 	 * Same applies to idle_cpus_mask vs needs_update.
14702 	 */
14703 	if (flags & NOHZ_STATS_KICK)
14704 		WRITE_ONCE(nohz.has_blocked_load, 0);
14705 	if (flags & NOHZ_NEXT_KICK)
14706 		WRITE_ONCE(nohz.needs_update, 0);
14707 
14708 	/*
14709 	 * Ensures that if we miss the CPU, we must see the has_blocked_load
14710 	 * store from nohz_balance_enter_idle().
14711 	 */
14712 	smp_mb();
14713 
14714 	/*
14715 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
14716 	 * chance for other idle cpu to pull load.
14717 	 */
14718 	for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
14719 		if (!idle_cpu(balance_cpu))
14720 			continue;
14721 
14722 		/*
14723 		 * If this CPU gets work to do, stop the load balancing
14724 		 * work being done for other CPUs. Next load
14725 		 * balancing owner will pick it up.
14726 		 */
14727 		if (!idle_cpu(this_cpu) && need_resched()) {
14728 			if (flags & NOHZ_STATS_KICK)
14729 				has_blocked_load = true;
14730 			if (flags & NOHZ_NEXT_KICK)
14731 				WRITE_ONCE(nohz.needs_update, 1);
14732 			goto abort;
14733 		}
14734 
14735 		rq = cpu_rq(balance_cpu);
14736 
14737 		if (flags & NOHZ_STATS_KICK)
14738 			has_blocked_load |= update_nohz_stats(rq);
14739 
14740 		/*
14741 		 * If time for next balance is due,
14742 		 * do the balance.
14743 		 */
14744 		if (time_after_eq(jiffies, rq->next_balance)) {
14745 			struct rq_flags rf;
14746 
14747 			rq_lock_irqsave(rq, &rf);
14748 			update_rq_clock(rq);
14749 			rq_unlock_irqrestore(rq, &rf);
14750 
14751 			if (flags & NOHZ_BALANCE_KICK)
14752 				sched_balance_domains(rq, CPU_IDLE);
14753 		}
14754 
14755 		if (time_after(next_balance, rq->next_balance)) {
14756 			next_balance = rq->next_balance;
14757 			update_next_balance = 1;
14758 		}
14759 	}
14760 
14761 	/*
14762 	 * next_balance will be updated only when there is a need.
14763 	 * When the CPU is attached to null domain for ex, it will not be
14764 	 * updated.
14765 	 */
14766 	if (likely(update_next_balance))
14767 		nohz.next_balance = next_balance;
14768 
14769 	if (flags & NOHZ_STATS_KICK)
14770 		WRITE_ONCE(nohz.next_blocked,
14771 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
14772 
14773 abort:
14774 	/* There is still blocked load, enable periodic update */
14775 	if (has_blocked_load)
14776 		WRITE_ONCE(nohz.has_blocked_load, 1);
14777 }
14778 
14779 /*
14780  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
14781  * rebalancing for all the CPUs for whom scheduler ticks are stopped.
14782  */
14783 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14784 {
14785 	unsigned int flags = this_rq->nohz_idle_balance;
14786 
14787 	if (!flags)
14788 		return false;
14789 
14790 	this_rq->nohz_idle_balance = 0;
14791 
14792 	if (idle != CPU_IDLE)
14793 		return false;
14794 
14795 	_nohz_idle_balance(this_rq, flags);
14796 
14797 	return true;
14798 }
14799 
14800 /*
14801  * Check if we need to directly run the ILB for updating blocked load before
14802  * entering idle state. Here we run ILB directly without issuing IPIs.
14803  *
14804  * Note that when this function is called, the tick may not yet be stopped on
14805  * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
14806  * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
14807  * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
14808  * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
14809  * called from this function on (this) CPU that's not yet in the mask. That's
14810  * OK because the goal of nohz_run_idle_balance() is to run ILB only for
14811  * updating the blocked load of already idle CPUs without waking up one of
14812  * those idle CPUs and outside the preempt disable / IRQ off phase of the local
14813  * cpu about to enter idle, because it can take a long time.
14814  */
14815 void nohz_run_idle_balance(int cpu)
14816 {
14817 	unsigned int flags;
14818 
14819 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
14820 
14821 	/*
14822 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
14823 	 * (i.e. NOHZ_STATS_KICK set) and will do the same.
14824 	 */
14825 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
14826 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
14827 }
14828 
14829 static void nohz_newidle_balance(struct rq *this_rq)
14830 {
14831 	int this_cpu = this_rq->cpu;
14832 
14833 	/* Will wake up very soon. No time for doing anything else*/
14834 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
14835 		return;
14836 
14837 	/* Don't need to update blocked load of idle CPUs*/
14838 	if (!READ_ONCE(nohz.has_blocked_load) ||
14839 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
14840 		return;
14841 
14842 	/*
14843 	 * Set the need to trigger ILB in order to update blocked load
14844 	 * before entering idle state.
14845 	 */
14846 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
14847 }
14848 
14849 #else /* !CONFIG_NO_HZ_COMMON: */
14850 static inline void nohz_balancer_kick(struct rq *rq) { }
14851 
14852 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14853 {
14854 	return false;
14855 }
14856 
14857 static inline void nohz_newidle_balance(struct rq *this_rq) { }
14858 #endif /* !CONFIG_NO_HZ_COMMON */
14859 
14860 /*
14861  * sched_balance_newidle is called by schedule() if this_cpu is about to become
14862  * idle. Attempts to pull tasks from other CPUs.
14863  *
14864  * Returns:
14865  *   < 0 - we released the lock and there are !fair tasks present
14866  *     0 - failed, no new tasks
14867  *   > 0 - success, new (fair) tasks present
14868  */
14869 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
14870 	__must_hold(__rq_lockp(this_rq))
14871 {
14872 	unsigned long next_balance = jiffies + HZ;
14873 	int this_cpu = this_rq->cpu;
14874 	int continue_balancing = 1;
14875 	u64 t0, t1, curr_cost = 0;
14876 	struct sched_domain *sd;
14877 	int pulled_task = 0;
14878 
14879 	update_misfit_status(NULL, this_rq);
14880 
14881 	/*
14882 	 * There is a task waiting to run. No need to search for one.
14883 	 * Return 0; the task will be enqueued when switching to idle.
14884 	 */
14885 	if (this_rq->ttwu_pending)
14886 		return 0;
14887 
14888 	/*
14889 	 * We must set idle_stamp _before_ calling sched_balance_rq()
14890 	 * for CPU_NEWLY_IDLE, such that we measure the this duration
14891 	 * as idle time.
14892 	 */
14893 	this_rq->idle_stamp = rq_clock(this_rq);
14894 
14895 	/* Do not pull tasks towards !preferred CPUs */
14896 	if (!cpu_preferred(this_cpu))
14897 		return 0;
14898 
14899 	/*
14900 	 * This is OK, because current is on_cpu, which avoids it being picked
14901 	 * for load-balance and preemption/IRQs are still disabled avoiding
14902 	 * further scheduler activity on it and we're being very careful to
14903 	 * re-start the picking loop.
14904 	 */
14905 	rq_unpin_lock(this_rq, rf);
14906 
14907 	sd = rcu_dereference_sched_domain(this_rq->sd);
14908 	if (!sd)
14909 		goto out;
14910 
14911 	if (!get_rd_overloaded(this_rq->rd) ||
14912 	    this_rq->avg_idle < sd->max_newidle_lb_cost) {
14913 
14914 		update_next_balance(sd, &next_balance);
14915 		goto out;
14916 	}
14917 
14918 	/*
14919 	 * Include sched_balance_update_blocked_averages() in the cost
14920 	 * calculation because it can be quite costly -- this ensures we skip
14921 	 * it when avg_idle gets to be very low.
14922 	 */
14923 	t0 = sched_clock_cpu(this_cpu);
14924 	__sched_balance_update_blocked_averages(this_rq);
14925 
14926 	rq_modified_begin(this_rq, &fair_sched_class);
14927 	raw_spin_rq_unlock(this_rq);
14928 
14929 	for_each_domain(this_cpu, sd) {
14930 		u64 domain_cost;
14931 
14932 		update_next_balance(sd, &next_balance);
14933 
14934 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
14935 			break;
14936 
14937 		if (sd->flags & SD_BALANCE_NEWIDLE) {
14938 			unsigned int weight = 1;
14939 
14940 			if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) {
14941 				/*
14942 				 * Throw a 1k sided dice; and only run
14943 				 * newidle_balance according to the success
14944 				 * rate.
14945 				 */
14946 				u32 d1k = sched_rng() % 1024;
14947 				weight = 1 + sd->newidle_ratio;
14948 				if (d1k > weight) {
14949 					update_newidle_stats(sd, 0);
14950 					continue;
14951 				}
14952 				weight = (1024 + weight/2) / weight;
14953 			}
14954 
14955 			pulled_task = sched_balance_rq(this_cpu, this_rq,
14956 						   sd, CPU_NEWLY_IDLE,
14957 						   &continue_balancing);
14958 
14959 			t1 = sched_clock_cpu(this_cpu);
14960 			domain_cost = t1 - t0;
14961 			curr_cost += domain_cost;
14962 			t0 = t1;
14963 
14964 			/*
14965 			 * Track max cost of a domain to make sure to not delay the
14966 			 * next wakeup on the CPU.
14967 			 */
14968 			update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
14969 		}
14970 
14971 		/*
14972 		 * Stop searching for tasks to pull if there are
14973 		 * now runnable tasks on this rq.
14974 		 */
14975 		if (pulled_task || !continue_balancing)
14976 			break;
14977 	}
14978 
14979 	raw_spin_rq_lock(this_rq);
14980 
14981 	if (curr_cost > this_rq->max_idle_balance_cost)
14982 		this_rq->max_idle_balance_cost = curr_cost;
14983 
14984 	/*
14985 	 * While browsing the domains, we released the rq lock, a task could
14986 	 * have been enqueued in the meantime. Since we're not going idle,
14987 	 * pretend we pulled a task.
14988 	 */
14989 	if (this_rq->cfs.h_nr_queued && !pulled_task)
14990 		pulled_task = 1;
14991 
14992 	/* If a higher prio class was modified, restart the pick */
14993 	if (rq_modified_above(this_rq, &fair_sched_class))
14994 		pulled_task = -1;
14995 
14996 out:
14997 	/* Move the next balance forward */
14998 	if (time_after(this_rq->next_balance, next_balance))
14999 		this_rq->next_balance = next_balance;
15000 
15001 	if (pulled_task)
15002 		this_rq->idle_stamp = 0;
15003 	else
15004 		nohz_newidle_balance(this_rq);
15005 
15006 	rq_repin_lock(this_rq, rf);
15007 
15008 	return pulled_task;
15009 }
15010 
15011 /*
15012  * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
15013  *
15014  * - directly from the local sched_tick() for periodic load balancing
15015  *
15016  * - indirectly from a remote sched_tick() for NOHZ idle balancing
15017  *   through the SMP cross-call nohz_csd_func()
15018  */
15019 static __latent_entropy void sched_balance_softirq(void)
15020 {
15021 	struct rq *this_rq = this_rq();
15022 	enum cpu_idle_type idle = this_rq->idle_balance;
15023 	/*
15024 	 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
15025 	 * balancing on behalf of the other idle CPUs whose ticks are
15026 	 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
15027 	 * give the idle CPUs a chance to load balance. Else we may
15028 	 * load balance only within the local sched_domain hierarchy
15029 	 * and abort nohz_idle_balance altogether if we pull some load.
15030 	 */
15031 	if (nohz_idle_balance(this_rq, idle))
15032 		return;
15033 
15034 	/* normal load balance */
15035 	sched_balance_update_blocked_averages(this_rq->cpu);
15036 	sched_balance_domains(this_rq, idle);
15037 }
15038 
15039 /*
15040  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
15041  */
15042 void sched_balance_trigger(struct rq *rq)
15043 {
15044 	/*
15045 	 * Don't need to rebalance while attached to NULL domain or
15046 	 * runqueue CPU is not active
15047 	 */
15048 	if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
15049 		return;
15050 
15051 	if (time_after_eq(jiffies, rq->next_balance))
15052 		raise_softirq(SCHED_SOFTIRQ);
15053 
15054 	nohz_balancer_kick(rq);
15055 }
15056 
15057 static void rq_online_fair(struct rq *rq)
15058 {
15059 	update_sysctl();
15060 
15061 	update_runtime_enabled(rq);
15062 }
15063 
15064 static void rq_offline_fair(struct rq *rq)
15065 {
15066 	update_sysctl();
15067 
15068 	/* Ensure any throttled groups are reachable by pick_next_task */
15069 	unthrottle_offline_cfs_rqs(rq);
15070 
15071 	/* Ensure that we remove rq contribution to group share: */
15072 	clear_tg_offline_cfs_rqs(rq);
15073 }
15074 
15075 #ifdef CONFIG_SCHED_CORE
15076 static inline bool
15077 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
15078 {
15079 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
15080 	u64 slice = se->slice;
15081 
15082 	return (rtime * min_nr_tasks > slice);
15083 }
15084 
15085 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
15086 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
15087 {
15088 	if (!sched_core_enabled(rq))
15089 		return;
15090 
15091 	/*
15092 	 * If runqueue has only one task which used up its slice and
15093 	 * if the sibling is forced idle, then trigger schedule to
15094 	 * give forced idle task a chance.
15095 	 *
15096 	 * __entity_slice_used() considers only this active rq and it gets the
15097 	 * whole slice. But during force idle, we have siblings acting
15098 	 * like a single runqueue and hence we need to consider runnable
15099 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
15100 	 * go through the forced idle rq, but that would be a perf hit.
15101 	 * We can assume that the forced idle CPU has at least
15102 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
15103 	 * if we need to give up the CPU.
15104 	 */
15105 	if (rq->core->core_forceidle_count && rq->cfs.h_nr_queued == 1 &&
15106 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
15107 		resched_curr(rq);
15108 }
15109 
15110 /*
15111  * Consider any infeasible weight scenario. Take for instance two tasks,
15112  * each bound to their respective sibling, one with weight 1 and one with
15113  * weight 2. Then the lower weight task will run ahead of the higher weight
15114  * task without bound.
15115  *
15116  * This utterly destroys the concept of a shared time base.
15117  *
15118  * Remember; all this is about a proportionally fair scheduling, where each
15119  * tasks receives:
15120  *
15121  *              w_i
15122  *   dt_i = ---------- dt                                     (1)
15123  *          \Sum_j w_j
15124  *
15125  * which we do by tracking a virtual time, s_i:
15126  *
15127  *          1
15128  *   s_i = --- d[t]_i                                         (2)
15129  *         w_i
15130  *
15131  * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
15132  * The immediate corollary is that the ideal schedule S, where (2) to use
15133  * an infinitesimal delta, is:
15134  *
15135  *           1
15136  *   S = ---------- dt                                        (3)
15137  *       \Sum_i w_i
15138  *
15139  * From which we can define the lag, or deviation from the ideal, as:
15140  *
15141  *   lag(i) = S - s_i                                         (4)
15142  *
15143  * And since the one and only purpose is to approximate S, we get that:
15144  *
15145  *   \Sum_i w_i lag(i) := 0                                   (5)
15146  *
15147  * If this were not so, we no longer converge to S, and we can no longer
15148  * claim our scheduler has any of the properties we derive from S. This is
15149  * exactly what you did above, you broke it!
15150  *
15151  *
15152  * Let's continue for a while though; to see if there is anything useful to
15153  * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
15154  *
15155  *       \Sum_i w_i s_i
15156  *   S = --------------                                       (6)
15157  *         \Sum_i w_i
15158  *
15159  * Which gives us a way to compute S, given our s_i. Now, if you've read
15160  * our code, you know that we do not in fact do this, the reason for this
15161  * is two-fold. Firstly, computing S in that way requires a 64bit division
15162  * for every time we'd use it (see 12), and secondly, this only describes
15163  * the steady-state, it doesn't handle dynamics.
15164  *
15165  * Anyway, in (6):  s_i -> x + (s_i - x), to get:
15166  *
15167  *           \Sum_i w_i (s_i - x)
15168  *   S - x = --------------------                             (7)
15169  *              \Sum_i w_i
15170  *
15171  * Which shows that S and s_i transform alike (which makes perfect sense
15172  * given that S is basically the (weighted) average of s_i).
15173  *
15174  * So the thing to remember is that the above is strictly UP. It is
15175  * possible to generalize to multiple runqueues -- however it gets really
15176  * yuck when you have to add affinity support, as illustrated by our very
15177  * first counter-example.
15178  *
15179  * Luckily I think we can avoid needing a full multi-queue variant for
15180  * core-scheduling (or load-balancing). The crucial observation is that we
15181  * only actually need this comparison in the presence of forced-idle; only
15182  * then do we need to tell if the stalled rq has higher priority over the
15183  * other.
15184  *
15185  * [XXX assumes SMT2; better consider the more general case, I suspect
15186  * it'll work out because our comparison is always between 2 rqs and the
15187  * answer is only interesting if one of them is forced-idle]
15188  *
15189  * And (under assumption of SMT2) when there is forced-idle, there is only
15190  * a single queue, so everything works like normal.
15191  *
15192  * Let, for our runqueue 'k':
15193  *
15194  *   T_k = \Sum_i w_i s_i
15195  *   W_k = \Sum_i w_i      ; for all i of k                  (8)
15196  *
15197  * Then we can write (6) like:
15198  *
15199  *         T_k
15200  *   S_k = ---                                               (9)
15201  *         W_k
15202  *
15203  * From which immediately follows that:
15204  *
15205  *           T_k + T_l
15206  *   S_k+l = ---------                                       (10)
15207  *           W_k + W_l
15208  *
15209  * On which we can define a combined lag:
15210  *
15211  *   lag_k+l(i) := S_k+l - s_i                               (11)
15212  *
15213  * And that gives us the tools to compare tasks across a combined runqueue.
15214  *
15215  *
15216  * Combined this gives the following:
15217  *
15218  *  a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
15219  *     using (7); this only requires storing single 'time'-stamps.
15220  *
15221  *  b) when comparing tasks between 2 runqueues of which one is forced-idle,
15222  *     compare the combined lag, per (11).
15223  *
15224  * Now, of course cgroups (I so hate them) make this more interesting in
15225  * that a) seems to suggest we need to iterate all cgroup on a CPU at such
15226  * boundaries, but I think we can avoid that. The force-idle is for the
15227  * whole CPU, all it's rqs. So we can mark it in the root and lazily
15228  * propagate downward on demand.
15229  */
15230 
15231 /*
15232  * So this sync is basically a relative reset of S to 0.
15233  *
15234  * So with 2 queues, when one goes idle, we drop them both to 0 and one
15235  * then increases due to not being idle, and the idle one builds up lag to
15236  * get re-elected. So far so simple, right?
15237  *
15238  * When there's 3, we can have the situation where 2 run and one is idle,
15239  * we sync to 0 and let the idle one build up lag to get re-election. Now
15240  * suppose another one also drops idle. At this point dropping all to 0
15241  * again would destroy the built-up lag from the queue that was already
15242  * idle, not good.
15243  *
15244  * So instead of syncing everything, we can:
15245  *
15246  *   less := !((s64)(s_a - s_b) <= 0)
15247  *
15248  *   (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
15249  *                             == v_a - (v_b - S_a + S_b)
15250  *
15251  * IOW, we can recast the (lag) comparison to a one-sided difference.
15252  * So if then, instead of syncing the whole queue, sync the idle queue
15253  * against the active queue with S_a + S_b at the point where we sync.
15254  *
15255  * (XXX consider the implication of living in a cyclic group: N / 2^n N)
15256  *
15257  * This gives us means of syncing single queues against the active queue,
15258  * and for already idle queues to preserve their build-up lag.
15259  *
15260  * Of course, then we get the situation where there's 2 active and one
15261  * going idle, who do we pick to sync against? Theory would have us sync
15262  * against the combined S, but as we've already demonstrated, there is no
15263  * such thing in infeasible weight scenarios.
15264  *
15265  * One thing I've considered; and this is where that core_active rudiment
15266  * came from, is having active queues sync up between themselves after
15267  * every tick. This limits the observed divergence due to the work
15268  * conservancy.
15269  *
15270  * On top of that, we can improve upon things by employing (10) here.
15271  */
15272 
15273 /*
15274  * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
15275  */
15276 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
15277 			 bool forceidle)
15278 {
15279 	for_each_sched_entity(se) {
15280 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
15281 
15282 		if (forceidle) {
15283 			if (cfs_rq->forceidle_seq == fi_seq)
15284 				break;
15285 			cfs_rq->forceidle_seq = fi_seq;
15286 		}
15287 
15288 		cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
15289 	}
15290 }
15291 
15292 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
15293 {
15294 	struct sched_entity *se = &p->se;
15295 
15296 	if (p->sched_class != &fair_sched_class)
15297 		return;
15298 
15299 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
15300 }
15301 
15302 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
15303 			bool in_fi)
15304 {
15305 	struct rq *rq = task_rq(a);
15306 	const struct sched_entity *sea = &a->se;
15307 	const struct sched_entity *seb = &b->se;
15308 	struct cfs_rq *cfs_rqa;
15309 	struct cfs_rq *cfs_rqb;
15310 	s64 delta;
15311 
15312 	WARN_ON_ONCE(task_rq(b)->core != rq->core);
15313 
15314 	cfs_rqa = &task_rq(a)->cfs;
15315 	cfs_rqb = &task_rq(b)->cfs;
15316 
15317 	/*
15318 	 * Find delta after normalizing se's vruntime with its cfs_rq's
15319 	 * zero_vruntime_fi, which would have been updated in prior calls
15320 	 * to se_fi_update().
15321 	 */
15322 	delta = vruntime_op(sea->vruntime, "-", seb->vruntime) +
15323 		vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi);
15324 
15325 	return delta > 0;
15326 }
15327 
15328 static int task_is_throttled_fair(struct task_struct *p, int cpu)
15329 {
15330 	struct cfs_rq *cfs_rq;
15331 
15332 #ifdef CONFIG_FAIR_GROUP_SCHED
15333 	cfs_rq = tg_cfs_rq(task_group(p), cpu);
15334 #else
15335 	cfs_rq = &cpu_rq(cpu)->cfs;
15336 #endif
15337 	return throttled_hierarchy(cfs_rq);
15338 }
15339 #else /* !CONFIG_SCHED_CORE: */
15340 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
15341 #endif /* !CONFIG_SCHED_CORE */
15342 
15343 /*
15344  * scheduler tick hitting a task of our scheduling class.
15345  *
15346  * NOTE: This function can be called remotely by the tick offload that
15347  * goes along full dynticks. Therefore no local assumption can be made
15348  * and everything must be accessed through the @rq and @curr passed in
15349  * parameters.
15350  */
15351 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
15352 {
15353 	struct sched_entity *se = &curr->se;
15354 
15355 	if (se->on_rq) {
15356 		unsigned long weight = NICE_0_LOAD;
15357 		struct cfs_rq *cfs_rq;
15358 
15359 		for_each_sched_entity(se) {
15360 			cfs_rq = cfs_rq_of(se);
15361 			entity_tick(cfs_rq, se, queued);
15362 
15363 			weight = __calc_prop_weight(cfs_rq, se, weight);
15364 		}
15365 
15366 		se = &curr->se;
15367 		reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15368 	}
15369 
15370 	if (queued)
15371 		return;
15372 
15373 	if (static_branch_unlikely(&sched_numa_balancing))
15374 		task_tick_numa(rq, curr);
15375 
15376 	task_tick_cache(rq, curr);
15377 
15378 	update_misfit_status(curr, rq);
15379 	check_update_overutilized_status(task_rq(curr));
15380 
15381 	task_tick_core(rq, curr);
15382 }
15383 
15384 /*
15385  * called on fork with the child task as argument from the parent's context
15386  *  - child not yet on the tasklist
15387  *  - preemption disabled
15388  */
15389 static void task_fork_fair(struct task_struct *p)
15390 {
15391 	set_task_max_allowed_capacity(p);
15392 }
15393 
15394 /*
15395  * Priority of the task has changed. Check to see if we preempt
15396  * the current task.
15397  */
15398 static void
15399 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
15400 {
15401 	if (!task_on_rq_queued(p))
15402 		return;
15403 
15404 	if (p->prio == oldprio)
15405 		return;
15406 
15407 	if (rq->cfs.h_nr_queued == 1)
15408 		return;
15409 
15410 	/*
15411 	 * Reschedule if we are currently running on this runqueue and
15412 	 * our priority decreased, or if we are not currently running on
15413 	 * this runqueue and our priority is higher than the current's
15414 	 */
15415 	if (task_current_donor(rq, p)) {
15416 		if (p->prio > oldprio)
15417 			resched_curr(rq);
15418 	} else {
15419 		wakeup_preempt(rq, p, 0);
15420 	}
15421 }
15422 
15423 #ifdef CONFIG_FAIR_GROUP_SCHED
15424 /*
15425  * Propagate the changes of the sched_entity across the tg tree to make it
15426  * visible to the root
15427  */
15428 static void propagate_entity_cfs_rq(struct sched_entity *se)
15429 {
15430 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15431 
15432 	/*
15433 	 * If a task gets attached to this cfs_rq and before being queued,
15434 	 * it gets migrated to another CPU due to reasons like affinity
15435 	 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
15436 	 * that removed load decayed or it can cause faireness problem.
15437 	 */
15438 	if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15439 		list_add_leaf_cfs_rq(cfs_rq);
15440 
15441 	/* Start to propagate at parent */
15442 	se = se->parent;
15443 
15444 	for_each_sched_entity(se) {
15445 		cfs_rq = cfs_rq_of(se);
15446 
15447 		update_load_avg(cfs_rq, se, UPDATE_TG);
15448 
15449 		if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15450 			list_add_leaf_cfs_rq(cfs_rq);
15451 	}
15452 
15453 	assert_list_leaf_cfs_rq(rq_of(cfs_rq));
15454 }
15455 #else /* !CONFIG_FAIR_GROUP_SCHED: */
15456 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
15457 #endif /* !CONFIG_FAIR_GROUP_SCHED */
15458 
15459 static void detach_entity_cfs_rq(struct sched_entity *se)
15460 {
15461 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15462 
15463 	/*
15464 	 * In case the task sched_avg hasn't been attached:
15465 	 * - A forked task which hasn't been woken up by wake_up_new_task().
15466 	 * - A task which has been woken up by try_to_wake_up() but is
15467 	 *   waiting for actually being woken up by sched_ttwu_pending().
15468 	 */
15469 	if (!se->avg.last_update_time)
15470 		return;
15471 
15472 	/* Catch up with the cfs_rq and remove our load when we leave */
15473 	update_load_avg(cfs_rq, se, 0);
15474 	detach_entity_load_avg(cfs_rq, se);
15475 	update_tg_load_avg(cfs_rq);
15476 	propagate_entity_cfs_rq(se);
15477 }
15478 
15479 static void attach_entity_cfs_rq(struct sched_entity *se)
15480 {
15481 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15482 
15483 	/* Synchronize entity with its cfs_rq */
15484 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
15485 	attach_entity_load_avg(cfs_rq, se);
15486 	update_tg_load_avg(cfs_rq);
15487 	propagate_entity_cfs_rq(se);
15488 }
15489 
15490 static void detach_task_cfs_rq(struct task_struct *p)
15491 {
15492 	struct sched_entity *se = &p->se;
15493 
15494 	detach_entity_cfs_rq(se);
15495 }
15496 
15497 static void attach_task_cfs_rq(struct task_struct *p)
15498 {
15499 	struct sched_entity *se = &p->se;
15500 
15501 	attach_entity_cfs_rq(se);
15502 }
15503 
15504 static void switching_from_fair(struct rq *rq, struct task_struct *p)
15505 {
15506 	if (p->se.sched_delayed)
15507 		dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
15508 }
15509 
15510 static void switched_from_fair(struct rq *rq, struct task_struct *p)
15511 {
15512 	detach_task_cfs_rq(p);
15513 }
15514 
15515 static void switched_to_fair(struct rq *rq, struct task_struct *p)
15516 {
15517 	WARN_ON_ONCE(p->se.sched_delayed);
15518 
15519 	attach_task_cfs_rq(p);
15520 
15521 	set_task_max_allowed_capacity(p);
15522 
15523 	if (task_on_rq_queued(p)) {
15524 		/*
15525 		 * We were most likely switched from sched_rt, so
15526 		 * kick off the schedule if running, otherwise just see
15527 		 * if we can still preempt the current task.
15528 		 */
15529 		if (task_current_donor(rq, p))
15530 			resched_curr(rq);
15531 		else
15532 			wakeup_preempt(rq, p, 0);
15533 	}
15534 }
15535 
15536 static void set_next_task_fair(struct rq *rq, struct task_struct *p, enum snt_e type)
15537 {
15538 	struct sched_entity *se = &p->se;
15539 	struct cfs_rq *cfs_rq = &rq->cfs;
15540 	unsigned long weight = NICE_0_LOAD;
15541 	bool first = type == SNT_PICK;
15542 	bool throttled = false;
15543 	bool on_rq = se->on_rq;
15544 
15545 	if (type == SNT_REPICK)
15546 		goto repick;
15547 
15548 	clear_buddies(cfs_rq, se);
15549 
15550 	if (on_rq)
15551 		__dequeue_entity(cfs_rq, se);
15552 
15553 	for_each_sched_entity(se) {
15554 		cfs_rq = cfs_rq_of(se);
15555 
15556 		if (!IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) ||
15557 		    !first || !cfs_rq->h_curr)
15558 			set_next_entity(cfs_rq, se);
15559 
15560 		/* ensure bandwidth has been allocated on our new cfs_rq */
15561 		throttled |= account_cfs_rq_runtime(cfs_rq, 0);
15562 
15563 		if (on_rq)
15564 			weight = __calc_prop_weight(cfs_rq, se, weight);
15565 	}
15566 
15567 	if (throttled)
15568 		task_throttle_setup_work(p);
15569 
15570 	se = &p->se;
15571 	cfs_rq->curr = se;
15572 
15573 	if (on_rq) {
15574 		reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15575 		if (first)
15576 			set_protect_slice(cfs_rq, se);
15577 	}
15578 
15579 	if (task_on_rq_queued(p)) {
15580 		/*
15581 		 * Move the next running task to the front of the list, so our
15582 		 * cfs_tasks list becomes MRU one.
15583 		 */
15584 		list_move(&se->group_node, &rq->cfs_tasks);
15585 	}
15586 	if (!first)
15587 		return;
15588 
15589 	WARN_ON_ONCE(se->sched_delayed);
15590 
15591 	update_misfit_status(p, rq);
15592 	sched_fair_update_stop_tick(rq, p);
15593 
15594 repick:
15595 	/*
15596 	 * A same-task repick skips put_prev_task_fair(), but
15597 	 * pick_task_fair() refreshed the entity hrtick_start_fair() reads
15598 	 * before selecting it again. rq->cfs.curr identifies that entity,
15599 	 * including with group scheduling.
15600 	 */
15601 	if (hrtick_enabled_fair(rq))
15602 		hrtick_start_fair(rq, p);
15603 }
15604 
15605 void init_cfs_rq(struct cfs_rq *cfs_rq)
15606 {
15607 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
15608 	cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
15609 	raw_spin_lock_init(&cfs_rq->removed.lock);
15610 }
15611 
15612 #ifdef CONFIG_FAIR_GROUP_SCHED
15613 static void task_change_group_fair(struct task_struct *p)
15614 {
15615 	/*
15616 	 * We couldn't detach or attach a forked task which
15617 	 * hasn't been woken up by wake_up_new_task().
15618 	 */
15619 	if (READ_ONCE(p->__state) == TASK_NEW)
15620 		return;
15621 
15622 	detach_task_cfs_rq(p);
15623 
15624 	/* Tell se's cfs_rq has been changed -- migrated */
15625 	p->se.avg.last_update_time = 0;
15626 	set_task_rq(p, task_cpu(p));
15627 	attach_task_cfs_rq(p);
15628 }
15629 
15630 void free_fair_sched_group(struct task_group *tg)
15631 {
15632 	free_percpu(tg->cfs_rq);
15633 }
15634 
15635 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
15636 {
15637 	struct cfs_tg_state __percpu *state;
15638 	struct sched_entity *se;
15639 	struct cfs_rq *cfs_rq;
15640 	int i;
15641 
15642 	state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL);
15643 	if (!state)
15644 		goto err;
15645 
15646 	tg->cfs_rq = &state->cfs_rq;
15647 	tg->shares = NICE_0_LOAD;
15648 
15649 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
15650 
15651 	for_each_possible_cpu(i) {
15652 		cfs_rq = tg_cfs_rq(tg, i);
15653 		if (!cfs_rq)
15654 			goto err;
15655 
15656 		se = tg_se(tg, i);
15657 		init_cfs_rq(cfs_rq);
15658 		init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i));
15659 		init_entity_runnable_average(se);
15660 	}
15661 
15662 	return 1;
15663 
15664 err:
15665 	return 0;
15666 }
15667 
15668 void online_fair_sched_group(struct task_group *tg)
15669 {
15670 	int i;
15671 
15672 	for_each_possible_cpu(i) {
15673 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, i);
15674 		struct sched_entity *se = tg_se(tg, i);
15675 		struct rq *rq = cpu_rq(i);
15676 
15677 		guard(rq_lock_irq)(rq);
15678 
15679 		update_rq_clock(rq);
15680 		attach_entity_cfs_rq(se);
15681 		sync_throttle(tg, i);
15682 
15683 		cfs_rq->idle = tg_cfs_rq(tg->parent, i)->idle;
15684 	}
15685 }
15686 
15687 void unregister_fair_sched_group(struct task_group *tg)
15688 {
15689 	int cpu;
15690 
15691 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
15692 
15693 	for_each_possible_cpu(cpu) {
15694 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);
15695 		struct sched_entity *se = tg_se(tg, cpu);
15696 		struct rq *rq = cpu_rq(cpu);
15697 
15698 		if (se)
15699 			remove_entity_load_avg(se);
15700 
15701 		/*
15702 		 * Only empty task groups can be destroyed; so we can speculatively
15703 		 * check on_list without danger of it being re-added.
15704 		 */
15705 		if (cfs_rq->on_list) {
15706 			guard(rq_lock_irqsave)(rq);
15707 			list_del_leaf_cfs_rq(cfs_rq);
15708 		}
15709 	}
15710 }
15711 
15712 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
15713 			struct sched_entity *se, int cpu,
15714 			struct sched_entity *parent)
15715 {
15716 	struct rq *rq = cpu_rq(cpu);
15717 
15718 	cfs_rq->tg = tg;
15719 	cfs_rq->rq = rq;
15720 	init_cfs_rq_runtime(cfs_rq);
15721 
15722 	/* se could be NULL for root_task_group */
15723 	if (!se)
15724 		return;
15725 
15726 	if (!parent) {
15727 		se->cfs_rq = &rq->cfs;
15728 		se->depth = 0;
15729 	} else {
15730 		se->cfs_rq = parent->my_q;
15731 		se->depth = parent->depth + 1;
15732 	}
15733 
15734 	se->my_q = cfs_rq;
15735 	/* guarantee group entities always have weight */
15736 	update_load_set(&se->load, NICE_0_LOAD);
15737 	se->parent = parent;
15738 }
15739 
15740 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
15741 {
15742 	int i;
15743 
15744 	lockdep_assert_held(&cpu_weight_mutex);
15745 
15746 	/*
15747 	 * We can't change the weight of the root cgroup.
15748 	 */
15749 	if (is_root_task_group(tg))
15750 		return -EINVAL;
15751 
15752 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
15753 
15754 	if (tg->shares == shares)
15755 		return 0;
15756 
15757 	tg->shares = shares;
15758 	for_each_possible_cpu(i) {
15759 		struct rq *rq = cpu_rq(i);
15760 		struct sched_entity *se = tg_se(tg, i);
15761 		struct rq_flags rf;
15762 
15763 		/* Propagate contribution to hierarchy */
15764 		rq_lock_irqsave(rq, &rf);
15765 		update_rq_clock(rq);
15766 		for_each_sched_entity(se) {
15767 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
15768 			update_cfs_group(se);
15769 		}
15770 		rq_unlock_irqrestore(rq, &rf);
15771 	}
15772 
15773 	return 0;
15774 }
15775 
15776 int sched_group_set_shares_locked(struct task_group *tg, unsigned long shares)
15777 {
15778 	int ret;
15779 
15780 	lockdep_assert_held(&cpu_weight_mutex);
15781 
15782 	if (tg_is_idle(tg))
15783 		ret = -EINVAL;
15784 	else
15785 		ret = __sched_group_set_shares(tg, shares);
15786 
15787 	return ret;
15788 }
15789 
15790 struct tg_set_idle_struct {
15791 	long idle;
15792 	int cpu;
15793 };
15794 
15795 static int tg_set_idle_up(struct task_group *tg, void *data)
15796 {
15797 	struct tg_set_idle_struct *tsi = data;
15798 	struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, tsi->cpu);
15799 	struct sched_entity *se = tg_se(tg, tsi->cpu);
15800 	int old_idle = grp_cfs_rq->idle;
15801 	int task_delta;
15802 
15803 	grp_cfs_rq->idle += tsi->idle;
15804 
15805 	if (!!old_idle == !!grp_cfs_rq->idle)
15806 		return 0;
15807 
15808 	task_delta = grp_cfs_rq->h_nr_queued - grp_cfs_rq->h_nr_idle;
15809 	if (!task_delta)
15810 		return 0;
15811 
15812 	task_delta *= tsi->idle;
15813 	for_each_sched_entity(se) {
15814 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
15815 
15816 		if (!se->on_rq)
15817 			break;
15818 
15819 		cfs_rq->h_nr_idle += task_delta;
15820 
15821 		if (cfs_rq_is_idle(cfs_rq))
15822 			break;
15823 	}
15824 	return 0;
15825 }
15826 
15827 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
15828 {
15829 	guard(mutex)(&cpu_weight_mutex);
15830 	return sched_group_set_shares_locked(tg, shares);
15831 }
15832 
15833 int sched_group_set_idle(struct task_group *tg, long idle)
15834 {
15835 	int i;
15836 
15837 	lockdep_assert_held(&cpu_weight_mutex);
15838 
15839 	if (tg == &root_task_group)
15840 		return -EINVAL;
15841 
15842 	if (idle < 0 || idle > 1)
15843 		return -EINVAL;
15844 
15845 	if (tg->idle == idle)
15846 		return 0;
15847 
15848 	tg->idle = idle;
15849 
15850 	for_each_possible_cpu(i) {
15851 		struct rq *rq = cpu_rq(i);
15852 
15853 		guard(rq_lock_irqsave)(rq);
15854 
15855 		struct tg_set_idle_struct tsi = {
15856 			.idle = idle ? 1 : -1,
15857 			.cpu = i,
15858 		};
15859 		walk_tg_tree_from(tg, tg_nop, tg_set_idle_up, &tsi);
15860 	}
15861 
15862 	/* Idle groups have minimum weight. */
15863 	if (tg_is_idle(tg))
15864 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
15865 	else
15866 		__sched_group_set_shares(tg, NICE_0_LOAD);
15867 
15868 	return 0;
15869 }
15870 
15871 #endif /* CONFIG_FAIR_GROUP_SCHED */
15872 
15873 
15874 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
15875 {
15876 	struct sched_entity *se = &task->se;
15877 	unsigned int rr_interval = 0;
15878 
15879 	/*
15880 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
15881 	 * idle runqueue:
15882 	 */
15883 	if (rq->cfs.load.weight)
15884 		rr_interval = NS_TO_JIFFIES(se->slice);
15885 
15886 	return rr_interval;
15887 }
15888 
15889 /*
15890  * All the scheduling class methods:
15891  */
15892 DEFINE_SCHED_CLASS(fair) = {
15893 	.enqueue_task		= enqueue_task_fair,
15894 	.dequeue_task		= dequeue_task_fair,
15895 	.yield_task		= yield_task_fair,
15896 	.yield_to_task		= yield_to_task_fair,
15897 
15898 	.wakeup_preempt		= wakeup_preempt_fair,
15899 
15900 	.pick_task		= pick_task_fair,
15901 	.put_prev_task		= put_prev_task_fair,
15902 	.set_next_task          = set_next_task_fair,
15903 
15904 	.select_task_rq		= select_task_rq_fair,
15905 	.migrate_task_rq	= migrate_task_rq_fair,
15906 
15907 	.rq_online		= rq_online_fair,
15908 	.rq_offline		= rq_offline_fair,
15909 
15910 	.task_dead		= task_dead_fair,
15911 	.set_cpus_allowed	= set_cpus_allowed_fair,
15912 
15913 	.task_tick		= task_tick_fair,
15914 	.task_fork		= task_fork_fair,
15915 
15916 	.reweight_task		= reweight_task_fair,
15917 	.prio_changed		= prio_changed_fair,
15918 	.switching_from		= switching_from_fair,
15919 	.switched_from		= switched_from_fair,
15920 	.switched_to		= switched_to_fair,
15921 
15922 	.get_rr_interval	= get_rr_interval_fair,
15923 
15924 	.update_curr		= update_curr_fair,
15925 
15926 #ifdef CONFIG_FAIR_GROUP_SCHED
15927 	.task_change_group	= task_change_group_fair,
15928 #endif
15929 
15930 #ifdef CONFIG_SCHED_CORE
15931 	.task_is_throttled	= task_is_throttled_fair,
15932 #endif
15933 
15934 #ifdef CONFIG_UCLAMP_TASK
15935 	.uclamp_enabled		= 1,
15936 #endif
15937 };
15938 
15939 void print_cfs_stats(struct seq_file *m, int cpu)
15940 {
15941 	struct cfs_rq *cfs_rq, *pos;
15942 
15943 	rcu_read_lock();
15944 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
15945 		print_cfs_rq(m, cpu, cfs_rq);
15946 	rcu_read_unlock();
15947 }
15948 
15949 #ifdef CONFIG_NUMA_BALANCING
15950 void show_numa_stats(struct task_struct *p, struct seq_file *m)
15951 {
15952 	int node;
15953 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
15954 	struct numa_group *ng;
15955 
15956 	rcu_read_lock();
15957 	ng = rcu_dereference_all(p->numa_group);
15958 	for_each_online_node(node) {
15959 		if (p->numa_faults) {
15960 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
15961 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
15962 		}
15963 		if (ng) {
15964 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
15965 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
15966 		}
15967 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
15968 	}
15969 	rcu_read_unlock();
15970 }
15971 #endif /* CONFIG_NUMA_BALANCING */
15972 
15973 __init void init_sched_fair_class(void)
15974 {
15975 	int i;
15976 
15977 	for_each_possible_cpu(i) {
15978 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
15979 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
15980 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
15981 					GFP_KERNEL, cpu_to_node(i));
15982 
15983 #ifdef CONFIG_CFS_BANDWIDTH
15984 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
15985 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
15986 #endif
15987 	}
15988 
15989 	open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
15990 
15991 #ifdef CONFIG_NO_HZ_COMMON
15992 	nohz.next_balance = jiffies;
15993 	nohz.next_blocked = jiffies;
15994 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
15995 #endif
15996 }
15997