xref: /linux/kernel/sched/fair.c (revision 8a36f53fd5ec3eff01f1b637d42cbdc3821d0493)
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 	return cfs_rq_is_idle(group_cfs_rq(se));
451 }
452 
453 #else /* !CONFIG_FAIR_GROUP_SCHED: */
454 
455 #define for_each_sched_entity(se) \
456 		for (; se; se = NULL)
457 
458 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
459 {
460 	return true;
461 }
462 
463 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
464 {
465 }
466 
467 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
468 {
469 }
470 
471 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
472 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
473 
474 static inline struct sched_entity *parent_entity(struct sched_entity *se)
475 {
476 	return NULL;
477 }
478 
479 static inline int tg_is_idle(struct task_group *tg)
480 {
481 	return 0;
482 }
483 
484 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
485 {
486 	return 0;
487 }
488 
489 static int se_is_idle(struct sched_entity *se)
490 {
491 	return task_has_idle_policy(task_of(se));
492 }
493 
494 #endif /* !CONFIG_FAIR_GROUP_SCHED */
495 
496 static __always_inline
497 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
498 
499 /**************************************************************
500  * Scheduling class tree data structure manipulation methods:
501  */
502 
503 extern void __BUILD_BUG_vruntime_cmp(void);
504 
505 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */
506 
507 #define vruntime_cmp(A, CMP_STR, B) ({				\
508 	int __res = 0;						\
509 								\
510 	if (!__builtin_strcmp(CMP_STR, "<")) {			\
511 		__res = ((s64)((A)-(B)) < 0);			\
512 	} else 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 {						\
519 		/* Unknown operator throws linker error: */	\
520 		__BUILD_BUG_vruntime_cmp();			\
521 	}							\
522 								\
523 	__res;							\
524 })
525 
526 extern void __BUILD_BUG_vruntime_op(void);
527 
528 #define vruntime_op(A, OP_STR, B) ({				\
529 	s64 __res = 0;						\
530 								\
531 	if (!__builtin_strcmp(OP_STR, "-")) {			\
532 		__res = (s64)((A)-(B));				\
533 	} else {						\
534 		/* Unknown operator throws linker error: */	\
535 		__BUILD_BUG_vruntime_op();			\
536 	}							\
537 								\
538 	__res;						\
539 })
540 
541 
542 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
543 {
544 	if (vruntime_cmp(vruntime, ">", max_vruntime))
545 		max_vruntime = vruntime;
546 
547 	return max_vruntime;
548 }
549 
550 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
551 {
552 	if (vruntime_cmp(vruntime, "<", min_vruntime))
553 		min_vruntime = vruntime;
554 
555 	return min_vruntime;
556 }
557 
558 static inline bool entity_before(const struct sched_entity *a,
559 				 const struct sched_entity *b)
560 {
561 	/*
562 	 * Tiebreak on vruntime seems unnecessary since it can
563 	 * hardly happen.
564 	 */
565 	return vruntime_cmp(a->deadline, "<", b->deadline);
566 }
567 
568 /*
569  * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale
570  * and this value should be no more than two lag bounds. Which puts it in the
571  * general order of:
572  *
573  *	(slice + TICK_NSEC) << NICE_0_LOAD_SHIFT
574  *
575  * which is around 44 bits in size (on 64bit); that is 20 for
576  * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for
577  * however many msec the actual slice+tick ends up begin.
578  *
579  * (disregarding the actual divide-by-weight part makes for the worst case
580  * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually
581  * being the zero-lag point).
582  */
583 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
584 {
585 	return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime);
586 }
587 
588 #define __node_2_se(node) \
589 	rb_entry((node), struct sched_entity, run_node)
590 
591 /*
592  * Compute virtual time from the per-task service numbers:
593  *
594  * Fair schedulers conserve lag:
595  *
596  *   \Sum lag_i = 0
597  *
598  * Where lag_i is given by:
599  *
600  *   lag_i = S - s_i = w_i * (V - v_i)
601  *
602  * Where S is the ideal service time and V is it's virtual time counterpart.
603  * Therefore:
604  *
605  *   \Sum lag_i = 0
606  *   \Sum w_i * (V - v_i) = 0
607  *   \Sum (w_i * V - w_i * v_i) = 0
608  *
609  * From which we can solve an expression for V in v_i (which we have in
610  * se->vruntime):
611  *
612  *       \Sum v_i * w_i   \Sum v_i * w_i
613  *   V = -------------- = --------------
614  *          \Sum w_i            W
615  *
616  * Specifically, this is the weighted average of all entity virtual runtimes.
617  *
618  * [[ NOTE: this is only equal to the ideal scheduler under the condition
619  *          that join/leave operations happen at lag_i = 0, otherwise the
620  *          virtual time has non-contiguous motion equivalent to:
621  *
622  *	      V +-= lag_i / W
623  *
624  *	    Also see the comment in place_entity() that deals with this. ]]
625  *
626  * However, since v_i is u64, and the multiplication could easily overflow
627  * transform it into a relative form that uses smaller quantities:
628  *
629  * Substitute: v_i == (v_i - v0) + v0
630  *
631  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
632  * V = ---------------------------- = --------------------- + v0
633  *                  W                            W
634  *
635  * Which we track using:
636  *
637  *                    v0 := cfs_rq->zero_vruntime
638  * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime
639  *              \Sum w_i := cfs_rq->sum_weight
640  *
641  * Since zero_vruntime closely tracks the per-task service, these
642  * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag
643  * induced in the system due to quantisation.
644  */
645 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w)
646 {
647 #ifdef CONFIG_64BIT
648 	if (cfs_rq->sum_shift)
649 		w = max(2UL, w >> cfs_rq->sum_shift);
650 #endif
651 	return w;
652 }
653 
654 static inline void
655 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
656 {
657 	unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
658 	s64 w_vruntime, key = entity_key(cfs_rq, se);
659 
660 	w_vruntime = key * weight;
661 	WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62));
662 
663 	cfs_rq->sum_w_vruntime += w_vruntime;
664 	cfs_rq->sum_weight += weight;
665 }
666 
667 static void
668 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se)
669 {
670 	unsigned long weight;
671 	s64 key, tmp;
672 
673 again:
674 	weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
675 	key = entity_key(cfs_rq, se);
676 
677 	if (check_mul_overflow(key, weight, &key))
678 		goto overflow;
679 
680 	if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp))
681 		goto overflow;
682 
683 	cfs_rq->sum_w_vruntime = tmp;
684 	cfs_rq->sum_weight += weight;
685 	return;
686 
687 overflow:
688 	/*
689 	 * There's gotta be a limit -- if we're still failing at this point
690 	 * there's really nothing much to be done about things.
691 	 */
692 	BUG_ON(cfs_rq->sum_shift >= 10);
693 	cfs_rq->sum_shift++;
694 
695 	/*
696 	 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1
697 	 */
698 	cfs_rq->sum_w_vruntime = 0;
699 	cfs_rq->sum_weight = 0;
700 
701 	for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost;
702 	     node; node = rb_next(node))
703 		__sum_w_vruntime_add(cfs_rq, __node_2_se(node));
704 
705 	goto again;
706 }
707 
708 static void
709 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
710 {
711 	if (sched_feat(PARANOID_AVG))
712 		return sum_w_vruntime_add_paranoid(cfs_rq, se);
713 
714 	__sum_w_vruntime_add(cfs_rq, se);
715 }
716 
717 static void
718 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
719 {
720 	unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
721 	s64 key = entity_key(cfs_rq, se);
722 
723 	cfs_rq->sum_w_vruntime -= key * weight;
724 	cfs_rq->sum_weight -= weight;
725 }
726 
727 static inline
728 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta)
729 {
730 	/*
731 	 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight
732 	 */
733 	cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta;
734 	cfs_rq->zero_vruntime += delta;
735 }
736 
737 /*
738  * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true
739  * For this to be so, the result of this function must have a left bias.
740  *
741  * Called in:
742  *  - place_entity()      -- before enqueue
743  *  - update_entity_lag() -- before dequeue
744  *  - update_deadline()   -- slice expiration
745  *
746  * This means it is one entry 'behind' but that puts it close enough to where
747  * the bound on entity_key() is at most two lag bounds.
748  */
749 u64 avg_vruntime(struct cfs_rq *cfs_rq)
750 {
751 	struct sched_entity *curr = cfs_rq->curr;
752 	long weight = cfs_rq->sum_weight;
753 	s64 delta = 0;
754 
755 	if (curr && !curr->on_rq)
756 		curr = NULL;
757 
758 	if (weight) {
759 		s64 runtime = cfs_rq->sum_w_vruntime;
760 
761 		if (curr) {
762 			unsigned long w = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
763 
764 			runtime += entity_key(cfs_rq, curr) * w;
765 			weight += w;
766 		}
767 
768 		/* sign flips effective floor / ceiling */
769 		if (runtime < 0)
770 			runtime -= (weight - 1);
771 
772 		delta = div64_long(runtime, weight);
773 	} else if (curr) {
774 		/*
775 		 * When there is but one element, it is the average.
776 		 */
777 		delta = curr->vruntime - cfs_rq->zero_vruntime;
778 	}
779 
780 	update_zero_vruntime(cfs_rq, delta);
781 
782 	return cfs_rq->zero_vruntime;
783 }
784 
785 /*
786  *     \Sum (v_i - v0)*w_i
787  * V = ------------------- + v0
788  *          \Sum w_i
789  *
790  * Let W = \Sum w_i, and move v_j such that 'v_j == V', thus:
791  *
792  * V = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0
793  *
794  * v_j = 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 + 1/W * \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*W - (v_j - v0)*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
801  *
802  * v_j*(W - w_j) + v0*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
803  *
804  * v_j*(W - w_j) = \Sum_i!=j (v_i - v0)*w_i + v0*(W - w_j)
805  *
806  *       \Sum_i!=j (v_i - v0)*w_i
807  * v_j = ------------------------ + v0
808  *               W - w_j
809  *
810  * When v_j happens to be curr, then '\Sum_i!=j (v_i - v0)*w_i'
811  * is cfs_rq->sum_w_runtime, and 'W - w_j' is cfs_rq->sum_weight, since curr
812  * is not included in the sum.
813  */
814 static u64 ineligible_vruntime(struct cfs_rq *cfs_rq)
815 {
816 	struct sched_entity *curr = cfs_rq->curr;
817 	long weight = cfs_rq->sum_weight;
818 	s64 delta = 0;
819 
820 	if (curr && !curr->on_rq)
821 		curr = NULL;
822 
823 	if (weight) {
824 		s64 runtime = cfs_rq->sum_w_vruntime;
825 
826 		/*
827 		 * Do not add @curr to obtain the effective '- w_j' terms.
828 		 */
829 
830 		/* sign flips effective floor / ceiling */
831 		if (runtime < 0)
832 			runtime -= (weight - 1);
833 
834 		delta = div64_long(runtime, weight);
835 	}
836 
837 	return cfs_rq->zero_vruntime + delta + 1;
838 }
839 
840 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq);
841 
842 /*
843  * lag_i = S - s_i = w_i * (V - v_i)
844  *
845  * However, since V is approximated by the weighted average of all entities it
846  * is possible -- by addition/removal/reweight to the tree -- to move V around
847  * and end up with a larger lag than we started with.
848  *
849  * Limit this to either double the slice length with a minimum of TICK_NSEC
850  * since that is the timing granularity.
851  *
852  * EEVDF gives the following limit for a steady state system:
853  *
854  *   -r_max < lag < max(r_max, q)
855  */
856 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime)
857 {
858 	u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC;
859 	s64 vlag, limit;
860 
861 	vlag = avruntime - se->vruntime;
862 	limit = calc_delta_fair(max_slice, se);
863 
864 	return clamp(vlag, -limit, limit);
865 }
866 
867 /*
868  * Delayed dequeue aims to reduce the negative lag of a dequeued task. While
869  * updating the lag of an entity, check that negative lag didn't increase
870  * during the delayed dequeue period which would be unfair.
871  * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO
872  * is set.
873  *
874  * Return true if the vlag has been modified. Specifically:
875  *
876  *   se->vlag != avg_vruntime() - se->vruntime
877  *
878  * This can be due to clamping in entity_lag() or clamping due to
879  * sched_delayed. Either way, when vlag is modified and the entity is
880  * retained, the tree needs to be adjusted.
881  */
882 static __always_inline
883 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
884 {
885 	u64 avruntime = avg_vruntime(cfs_rq);
886 	s64 vlag = entity_lag(cfs_rq, se, avruntime);
887 
888 	if (se->sched_delayed) {
889 		/* previous vlag < 0 otherwise se would not be delayed */
890 		vlag = max(vlag, se->vlag);
891 		if (sched_feat(DELAY_ZERO))
892 			vlag = min(vlag, 0);
893 	}
894 	se->vlag = vlag;
895 
896 	return avruntime - vlag != se->vruntime;
897 }
898 
899 /*
900  * Entity is eligible once it received less service than it ought to have,
901  * eg. lag >= 0.
902  *
903  * lag_i = S - s_i = w_i*(V - v_i)
904  *
905  * lag_i >= 0 -> V >= v_i
906  *
907  *     \Sum (v_i - v0)*w_i
908  * V = ------------------- + v0
909  *          \Sum w_i
910  *
911  * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i)
912  *
913  * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
914  *       to the loss in precision caused by the division.
915  */
916 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
917 {
918 	struct sched_entity *curr = cfs_rq->curr;
919 	s64 key, avg = cfs_rq->sum_w_vruntime;
920 	long load = cfs_rq->sum_weight;
921 
922 	if (curr && curr->on_rq) {
923 		unsigned long weight = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
924 
925 		avg += entity_key(cfs_rq, curr) * weight;
926 		load += weight;
927 	}
928 
929 	key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime);
930 
931 	/*
932 	 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD'
933 	 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24
934 	 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise.
935 	 *
936 	 * This gives that on 64bit the product will be at least 64bit which
937 	 * overflows s64, while on 32bit it will only be 44bits and should fit
938 	 * comfortably.
939 	 */
940 #ifdef CONFIG_64BIT
941 #ifdef CONFIG_ARCH_SUPPORTS_INT128
942 	/* This often results in simpler code than __builtin_mul_overflow(). */
943 	return avg >= (__int128)key * load;
944 #else
945 	s64 rhs;
946 	/*
947 	 * On overflow, the sign of key tells us the correct answer: a large
948 	 * positive key means vruntime >> V, so not eligible; a large negative
949 	 * key means vruntime << V, so eligible.
950 	 */
951 	if (check_mul_overflow(key, load, &rhs))
952 		return key <= 0;
953 
954 	return avg >= rhs;
955 #endif
956 #else /* 32bit */
957 	return avg >= key * load;
958 #endif
959 }
960 
961 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
962 {
963 	return vruntime_eligible(cfs_rq, se->vruntime);
964 }
965 
966 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
967 {
968 	struct sched_entity *root = __pick_root_entity(cfs_rq);
969 	struct sched_entity *curr = cfs_rq->curr;
970 	u64 min_slice = ~0ULL;
971 
972 	if (curr && curr->on_rq)
973 		min_slice = curr->slice;
974 
975 	if (root)
976 		min_slice = min(min_slice, root->min_slice);
977 
978 	return min_slice;
979 }
980 
981 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq)
982 {
983 	struct sched_entity *root = __pick_root_entity(cfs_rq);
984 	struct sched_entity *curr = cfs_rq->curr;
985 	u64 max_slice = 0ULL;
986 
987 	if (curr && curr->on_rq)
988 		max_slice = curr->slice;
989 
990 	if (root)
991 		max_slice = max(max_slice, root->max_slice);
992 
993 	return max_slice;
994 }
995 
996 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
997 {
998 	return entity_before(__node_2_se(a), __node_2_se(b));
999 }
1000 
1001 /* min() for wrapping vruntimes */
1002 static inline u64 __min_vruntime(u64 a, u64 b)
1003 {
1004 	return vruntime_cmp(a, "<", b) ? a : b;
1005 }
1006 
1007 RB_DECLARE_CALLBACKS(static, min_vruntime_cb,
1008 		     struct sched_entity, run_node,
1009 		     RB_AUG(vruntime, min_vruntime, __min_vruntime),
1010 		     RB_AUG(slice, min_slice, min),
1011 		     RB_AUG(slice, max_slice, max));
1012 
1013 /*
1014  * Enqueue an entity into the rb-tree:
1015  */
1016 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1017 {
1018 	WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1019 	WARN_ON_ONCE(!entity_is_task(se));
1020 
1021 	sum_w_vruntime_add(cfs_rq, se);
1022 	se->min_vruntime = se->vruntime;
1023 	se->min_slice = se->slice;
1024 	se->max_slice = se->slice;
1025 
1026 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1027 				__entity_less, &min_vruntime_cb);
1028 }
1029 
1030 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1031 {
1032 	WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1033 	WARN_ON_ONCE(!entity_is_task(se));
1034 
1035 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1036 				  &min_vruntime_cb);
1037 	sum_w_vruntime_sub(cfs_rq, se);
1038 }
1039 
1040 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
1041 {
1042 	struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
1043 
1044 	if (!root)
1045 		return NULL;
1046 
1047 	return __node_2_se(root);
1048 }
1049 
1050 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
1051 {
1052 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
1053 
1054 	if (!left)
1055 		return NULL;
1056 
1057 	return __node_2_se(left);
1058 }
1059 
1060 /*
1061  * Set the vruntime up to which an entity can run before looking
1062  * for another entity to pick.
1063  * In case of run to parity, we use the shortest slice of the enqueued
1064  * entities to set the protected period.
1065  * When run to parity is disabled, we give a minimum quantum to the running
1066  * entity to ensure progress.
1067  */
1068 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1069 {
1070 	u64 slice = normalized_sysctl_sched_base_slice;
1071 	u64 vprot = se->deadline;
1072 
1073 	if (sched_feat(RUN_TO_PARITY))
1074 		slice = cfs_rq_min_slice(cfs_rq);
1075 
1076 	slice = min(slice, se->slice);
1077 
1078 	/* If there are shorter slices than se's one */
1079 	if (slice != se->slice) {
1080 		vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
1081 		if (sched_feat(PREEMPT_SHORT))
1082 			vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq));
1083 	}
1084 
1085 	se->vprot = vprot;
1086 }
1087 
1088 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1089 {
1090 	u64 vruntime = min_vruntime(se->vruntime, avg_vruntime(cfs_rq));
1091 	u64 slice = cfs_rq_min_slice(cfs_rq);
1092 	u64 vprot = min_vruntime(se->vprot, vruntime + calc_delta_fair(slice, se));
1093 
1094 	if (sched_feat(PREEMPT_SHORT) && slice != se->slice)
1095 		vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq));
1096 
1097 	se->vprot = vprot;
1098 }
1099 
1100 static inline bool protect_slice(struct sched_entity *se)
1101 {
1102 	return vruntime_cmp(se->vruntime, "<", se->vprot);
1103 }
1104 
1105 static inline void cancel_protect_slice(struct sched_entity *se)
1106 {
1107 	if (protect_slice(se))
1108 		se->vprot = se->vruntime;
1109 }
1110 
1111 /*
1112  * Earliest Eligible Virtual Deadline First
1113  *
1114  * In order to provide latency guarantees for different request sizes
1115  * EEVDF selects the best runnable task from two criteria:
1116  *
1117  *  1) the task must be eligible (must be owed service)
1118  *
1119  *  2) from those tasks that meet 1), we select the one
1120  *     with the earliest virtual deadline.
1121  *
1122  * We can do this in O(log n) time due to an augmented RB-tree. The
1123  * tree keeps the entries sorted on deadline, but also functions as a
1124  * heap based on the vruntime by keeping:
1125  *
1126  *  se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
1127  *
1128  * Which allows tree pruning through eligibility.
1129  */
1130 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
1131 {
1132 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
1133 	struct sched_entity *se = __pick_first_entity(cfs_rq);
1134 	struct sched_entity *curr = cfs_rq->curr;
1135 	struct sched_entity *best = NULL;
1136 
1137 	/*
1138 	 * We can safely skip eligibility check if there is only one entity
1139 	 * in this cfs_rq, saving some cycles.
1140 	 */
1141 	if (cfs_rq->h_nr_queued == 1)
1142 		return curr && curr->on_rq ? curr : se;
1143 
1144 	/*
1145 	 * Picking the ->next buddy will affect latency but not fairness.
1146 	 */
1147 	if (sched_feat(PICK_BUDDY) && protect &&
1148 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
1149 		/* ->next will never be delayed */
1150 		WARN_ON_ONCE(cfs_rq->next->sched_delayed);
1151 		return cfs_rq->next;
1152 	}
1153 
1154 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
1155 		curr = NULL;
1156 
1157 	if (curr && protect && protect_slice(curr))
1158 		return curr;
1159 
1160 	/* Pick the leftmost entity if it's eligible */
1161 	if (se && entity_eligible(cfs_rq, se)) {
1162 		best = se;
1163 		goto found;
1164 	}
1165 
1166 	/* Heap search for the EEVD entity */
1167 	while (node) {
1168 		struct rb_node *left = node->rb_left;
1169 
1170 		/*
1171 		 * Eligible entities in left subtree are always better
1172 		 * choices, since they have earlier deadlines.
1173 		 */
1174 		if (left && vruntime_eligible(cfs_rq,
1175 					__node_2_se(left)->min_vruntime)) {
1176 			node = left;
1177 			continue;
1178 		}
1179 
1180 		se = __node_2_se(node);
1181 
1182 		/*
1183 		 * The left subtree either is empty or has no eligible
1184 		 * entity, so check the current node since it is the one
1185 		 * with earliest deadline that might be eligible.
1186 		 */
1187 		if (entity_eligible(cfs_rq, se)) {
1188 			best = se;
1189 			break;
1190 		}
1191 
1192 		node = node->rb_right;
1193 	}
1194 found:
1195 	if (!best || (curr && entity_before(curr, best)))
1196 		best = curr;
1197 
1198 	return best;
1199 }
1200 
1201 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1202 {
1203 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1204 
1205 	if (!last)
1206 		return NULL;
1207 
1208 	return __node_2_se(last);
1209 }
1210 
1211 /**************************************************************
1212  * Scheduling class statistics methods:
1213  */
1214 int sched_update_scaling(void)
1215 {
1216 	unsigned int factor = get_update_sysctl_factor();
1217 
1218 #define WRT_SYSCTL(name) \
1219 	(normalized_sysctl_##name = sysctl_##name / (factor))
1220 	WRT_SYSCTL(sched_base_slice);
1221 #undef WRT_SYSCTL
1222 
1223 	return 0;
1224 }
1225 
1226 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1227 
1228 /*
1229  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1230  * this is probably good enough.
1231  */
1232 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1233 {
1234 	if (vruntime_cmp(se->vruntime, "<", se->deadline))
1235 		return false;
1236 
1237 	/*
1238 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1239 	 * nice) while the request time r_i is determined by
1240 	 * sysctl_sched_base_slice.
1241 	 */
1242 	if (!se->custom_slice)
1243 		se->slice = sysctl_sched_base_slice;
1244 
1245 	/*
1246 	 * EEVDF: vd_i = ve_i + r_i / w_i
1247 	 */
1248 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1249 	avg_vruntime(cfs_rq);
1250 
1251 	/*
1252 	 * The task has consumed its request, reschedule.
1253 	 */
1254 	return true;
1255 }
1256 
1257 #include "pelt.h"
1258 
1259 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1260 static unsigned long task_h_load(struct task_struct *p);
1261 static unsigned long capacity_of(int cpu);
1262 
1263 /* Give new sched_entity start runnable values to heavy its load in infant time */
1264 void init_entity_runnable_average(struct sched_entity *se)
1265 {
1266 	struct sched_avg *sa = &se->avg;
1267 
1268 	memset(sa, 0, sizeof(*sa));
1269 
1270 	/*
1271 	 * Tasks are initialized with full load to be seen as heavy tasks until
1272 	 * they get a chance to stabilize to their real load level.
1273 	 * Group entities are initialized with zero load to reflect the fact that
1274 	 * nothing has been attached to the task group yet.
1275 	 */
1276 	if (entity_is_task(se))
1277 		sa->load_avg = scale_load_down(se->load.weight);
1278 
1279 	/* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1280 }
1281 
1282 /*
1283  * With new tasks being created, their initial util_avgs are extrapolated
1284  * based on the cfs_rq's current util_avg:
1285  *
1286  *   util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1287  *		* se_weight(se)
1288  *
1289  * However, in many cases, the above util_avg does not give a desired
1290  * value. Moreover, the sum of the util_avgs may be divergent, such
1291  * as when the series is a harmonic series.
1292  *
1293  * To solve this problem, we also cap the util_avg of successive tasks to
1294  * only 1/2 of the left utilization budget:
1295  *
1296  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1297  *
1298  * where n denotes the nth task and cpu_scale the CPU capacity.
1299  *
1300  * For example, for a CPU with 1024 of capacity, a simplest series from
1301  * the beginning would be like:
1302  *
1303  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1304  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1305  *
1306  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1307  * if util_avg > util_avg_cap.
1308  */
1309 void post_init_entity_util_avg(struct task_struct *p)
1310 {
1311 	struct sched_entity *se = &p->se;
1312 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1313 	struct sched_avg *sa = &se->avg;
1314 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1315 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1316 
1317 	if (p->sched_class != &fair_sched_class) {
1318 		/*
1319 		 * For !fair tasks do:
1320 		 *
1321 		update_cfs_rq_load_avg(now, cfs_rq);
1322 		attach_entity_load_avg(cfs_rq, se);
1323 		switched_from_fair(rq, p);
1324 		 *
1325 		 * such that the next switched_to_fair() has the
1326 		 * expected state.
1327 		 */
1328 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1329 		return;
1330 	}
1331 
1332 	if (cap > 0) {
1333 		if (cfs_rq->avg.util_avg != 0) {
1334 			sa->util_avg  = cfs_rq->avg.util_avg * se_weight(se);
1335 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1336 
1337 			if (sa->util_avg > cap)
1338 				sa->util_avg = cap;
1339 		} else {
1340 			sa->util_avg = cap;
1341 		}
1342 	}
1343 
1344 	sa->runnable_avg = sa->util_avg;
1345 }
1346 
1347 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec);
1348 
1349 static s64 update_se(struct rq *rq, struct sched_entity *se)
1350 {
1351 	u64 now = rq_clock_task(rq);
1352 	s64 delta_exec;
1353 
1354 	delta_exec = now - se->exec_start;
1355 	if (unlikely(delta_exec <= 0))
1356 		return delta_exec;
1357 
1358 	se->exec_start = now;
1359 	if (entity_is_task(se)) {
1360 		struct task_struct *running = rq->curr;
1361 		/*
1362 		 * If se is a task, we account the time against the running
1363 		 * task, as w/ proxy-exec they may not be the same.
1364 		 */
1365 		running->se.exec_start = now;
1366 		running->se.sum_exec_runtime += delta_exec;
1367 
1368 		trace_sched_stat_runtime(running, delta_exec);
1369 		account_group_exec_runtime(running, delta_exec);
1370 		account_mm_sched(rq, running, delta_exec);
1371 
1372 		cgroup_account_cputime(running, delta_exec);
1373 	} else {
1374 		/* If not task, account the time against donor se  */
1375 		se->sum_exec_runtime += delta_exec;
1376 	}
1377 
1378 	if (schedstat_enabled()) {
1379 		struct sched_statistics *stats;
1380 
1381 		stats = __schedstats_from_se(se);
1382 		__schedstat_set(stats->exec_max,
1383 				max(delta_exec, stats->exec_max));
1384 	}
1385 
1386 	return delta_exec;
1387 }
1388 
1389 #ifdef CONFIG_SCHED_CACHE
1390 
1391 /*
1392  * XXX numbers come from a place the sun don't shine -- probably wants to be SD
1393  * tunable or so.
1394  */
1395 #define EPOCH_PERIOD	(HZ / 100)	/* 10 ms */
1396 #define EPOCH_LLC_AFFINITY_TIMEOUT	5	/* 50 ms */
1397 __read_mostly unsigned int llc_aggr_tolerance	= 1;
1398 __read_mostly unsigned int llc_epoch_period	= EPOCH_PERIOD;
1399 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT;
1400 __read_mostly unsigned int llc_imb_pct		= 20;
1401 __read_mostly unsigned int llc_overaggr_pct	= 50;
1402 
1403 static int llc_id(int cpu)
1404 {
1405 	if (cpu < 0)
1406 		return -1;
1407 
1408 	return per_cpu(sd_llc_id, cpu);
1409 }
1410 
1411 static inline int get_sched_cache_scale(int mul)
1412 {
1413 	unsigned int tol = READ_ONCE(llc_aggr_tolerance);
1414 
1415 	if (!tol)
1416 		return 0;
1417 
1418 	if (tol >= 100)
1419 		return INT_MAX;
1420 
1421 	return (1 + (tol - 1) * mul);
1422 }
1423 
1424 static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu)
1425 {
1426 #ifdef CONFIG_NUMA_BALANCING
1427 	unsigned long llc, footprint;
1428 	struct sched_domain *sd;
1429 	int scale;
1430 
1431 	guard(rcu)();
1432 
1433 	sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd);
1434 	if (!sd)
1435 		return true;
1436 
1437 	if (static_branch_likely(&sched_numa_balancing)) {
1438 		/*
1439 		 * TBD: RDT exclusive LLC ways reserved should be
1440 		 * excluded.
1441 		 */
1442 		llc = sd->llc_bytes;
1443 		footprint = READ_ONCE(grp->footprint);
1444 
1445 		/*
1446 		 * Scale the LLC size by 256*llc_aggr_tolerance
1447 		 * and compare it to the task's footprint.
1448 		 *
1449 		 * Suppose the L3 size is 32MB. If the
1450 		 * llc_aggr_tolerance is 1:
1451 		 * When the footprint is larger than 32MB, the
1452 		 * process is regarded as exceeding the LLC
1453 		 * capacity. If the llc_aggr_tolerance is 99:
1454 		 * When the footprint is larger than 784GB, the
1455 		 * process is regarded as exceeding the LLC
1456 		 * capacity:
1457 		 * 784GB = (1 + (99 - 1) * 256) * 32MB
1458 		 * If the llc_aggr_tolerance is 100:
1459 		 * ignore the footprint and do the aggregation
1460 		 * anyway.
1461 		 */
1462 		scale = get_sched_cache_scale(256);
1463 		if (scale == INT_MAX)
1464 			return false;
1465 
1466 		return ((llc * (u64)scale) < (footprint * PAGE_SIZE));
1467 	}
1468 #endif
1469 	return false;
1470 }
1471 
1472 static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p,
1473 			   int cpu)
1474 {
1475 	int scale;
1476 
1477 	if (get_nr_threads(p) <= 1)
1478 		return true;
1479 
1480 	/*
1481 	 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance
1482 	 * and compare it to the task's active threads.
1483 	 */
1484 	scale = get_sched_cache_scale(1);
1485 	if (scale == INT_MAX)
1486 		return false;
1487 
1488 	return !fits_capacity((READ_ONCE(grp->nr_running_avg) * cpu_smt_num_threads),
1489 			(scale * per_cpu(sd_llc_size, cpu)));
1490 }
1491 
1492 /*
1493  * A task counts in nr_pref_llc_running while it is queued on its preferred
1494  * LLC (pref_llc_queued) and runnable (!sched_delayed), keeping the counter in
1495  * the runnable domain so alb_break_llc() can compare it with h_nr_runnable.
1496  */
1497 static bool task_pref_llc_runnable(struct task_struct *p)
1498 {
1499 	return p->pref_llc_queued && !p->se.sched_delayed;
1500 }
1501 
1502 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p)
1503 {
1504 	if (task_pref_llc_runnable(p))
1505 		rq->nr_pref_llc_running++;
1506 }
1507 
1508 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p)
1509 {
1510 	if (task_pref_llc_runnable(p))
1511 		rq->nr_pref_llc_running--;
1512 }
1513 
1514 static void account_llc_enqueue(struct rq *rq, struct task_struct *p)
1515 {
1516 	int pref_llc, pref_llc_queued;
1517 	struct sched_domain *sd;
1518 
1519 	pref_llc = p->preferred_llc;
1520 	if (pref_llc < 0)
1521 		return;
1522 
1523 	pref_llc_queued = (pref_llc == task_llc(p));
1524 	rq->nr_llc_running++;
1525 
1526 	/*
1527 	 * Record whether p is enqueued on its preferred
1528 	 * LLC, in order to pair with account_llc_dequeue()
1529 	 * to maintain a consistent nr_pref_llc_running per
1530 	 * runqueue.
1531 	 * This is necessary because a race condition exists:
1532 	 * after a task is enqueued on a runqueue, task_llc(p)
1533 	 * may change due to CPU hotplug. Therefore, checking
1534 	 * task_llc(p) to determine whether the task is being
1535 	 * dequeued from its preferred LLC is unreliable and
1536 	 * can cause inconsistent values - checking the
1537 	 * p->pref_llc_queued in account_llc_dequeue() would
1538 	 * be reliable.
1539 	 */
1540 	p->pref_llc_queued = pref_llc_queued;
1541 
1542 	/* Skipped while delayed; clear_delayed() adds it back on wake. */
1543 	pref_llc_running_inc(rq, p);
1544 
1545 	sd = rcu_dereference_all(rq->sd);
1546 	if (sd && (unsigned int)pref_llc < sd->llc_max)
1547 		sd->llc_counts[pref_llc]++;
1548 }
1549 
1550 static void account_llc_dequeue(struct rq *rq, struct task_struct *p)
1551 {
1552 	struct sched_domain *sd;
1553 	int pref_llc;
1554 
1555 	pref_llc = p->preferred_llc;
1556 	if (pref_llc < 0)
1557 		return;
1558 
1559 	rq->nr_llc_running--;
1560 	if (p->pref_llc_queued) {
1561 		/*
1562 		 * Skipped if still delayed (set_delayed() already removed it);
1563 		 * clearing pref_llc_queued below also stops clear_delayed()
1564 		 * from re-adding it.
1565 		 */
1566 		pref_llc_running_dec(rq, p);
1567 		/*
1568 		 * Update the status in case
1569 		 * other logic might query
1570 		 * this.
1571 		 */
1572 		p->pref_llc_queued = 0;
1573 	}
1574 
1575 	sd = rcu_dereference_all(rq->sd);
1576 	if (sd && (unsigned int)pref_llc < sd->llc_max) {
1577 		/*
1578 		 * There is a race condition between dequeue
1579 		 * and CPU hotplug. After a task has been enqueued
1580 		 * on CPUx, a CPU hotplug event occurs, and all online
1581 		 * CPUs (including CPUx) rebuild their sched_domains
1582 		 * and reset statistics to zero(including sd->llc_counts).
1583 		 * This can cause temporary undercount and we have to
1584 		 * check for such underflow in sd->llc_counts.
1585 		 *
1586 		 * This undercount is temporary and accurate accounting
1587 		 * will resume once the rq has a chance to be idle.
1588 		 */
1589 		if (sd->llc_counts[pref_llc])
1590 			sd->llc_counts[pref_llc]--;
1591 	}
1592 }
1593 
1594 int mm_init_sched(struct mm_struct *mm,
1595 		  struct sched_cache_time __percpu *_pcpu_sched)
1596 {
1597 	struct sched_cache_group *grp;
1598 	unsigned long epoch = 0;
1599 	int i;
1600 
1601 	grp = kzalloc_obj(*grp);
1602 	if (!grp) {
1603 		free_percpu(_pcpu_sched);
1604 		mm->sched_cache_grp = NULL;
1605 		return -ENOMEM;
1606 	}
1607 
1608 	for_each_possible_cpu(i) {
1609 		struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i);
1610 		struct rq *rq = cpu_rq(i);
1611 
1612 		pcpu_sched->runtime = 0;
1613 		/* a slightly stale cpu epoch is acceptible */
1614 		pcpu_sched->epoch = rq->cpu_epoch;
1615 		epoch = rq->cpu_epoch;
1616 	}
1617 
1618 	raw_spin_lock_init(&grp->lock);
1619 	grp->epoch = epoch;
1620 	grp->cpu = -1;
1621 	grp->next_scan = jiffies;
1622 	grp->nr_running_avg = 0;
1623 	grp->footprint = 0;
1624 	refcount_set(&grp->refcnt, 1);
1625 	/*
1626 	 * The update to grp->pcpu_sched should not be reordered
1627 	 * before initialization to grp's other fields, in case
1628 	 * the readers may get invalid mm_sched_epoch, etc.
1629 	 */
1630 	smp_store_release(&grp->pcpu_sched, _pcpu_sched);
1631 	/*
1632 	 * Publish the group last.  Not every reader qualifies it by
1633 	 * grp->pcpu_sched - can_migrate_llc_task() only checks that the
1634 	 * pointer is non-NULL before reading grp->footprint and
1635 	 * grp->nr_running_avg - so a reachable group must already be
1636 	 * fully initialized.
1637 	 */
1638 	smp_store_release(&mm->sched_cache_grp, grp);
1639 	return 0;
1640 }
1641 
1642 static void sched_cache_group_free_rcu(struct rcu_head *rcu)
1643 {
1644 	struct sched_cache_group *grp =
1645 		container_of(rcu, struct sched_cache_group, rcu);
1646 
1647 	free_percpu(grp->pcpu_sched);
1648 	kfree(grp);
1649 }
1650 
1651 static void sched_cache_group_put(struct sched_cache_group *grp)
1652 {
1653 	if (!grp || !refcount_dec_and_test(&grp->refcnt))
1654 		return;
1655 
1656 	call_rcu(&grp->rcu, sched_cache_group_free_rcu);
1657 }
1658 
1659 DEFINE_FREE(sched_cache_group_put, struct sched_cache_group *,
1660 	    sched_cache_group_put(_T));
1661 
1662 #define rcu_deref_sched_cache_grp(tsk) \
1663 	rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
1664 
1665 static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p,
1666 							 struct sched_cache_group *new)
1667 {
1668 	struct sched_cache_group *old;
1669 
1670 	old = rcu_deref_sched_cache_grp(p);
1671 	rcu_assign_pointer(p->sched_cache_grp, new);
1672 
1673 	return old;
1674 }
1675 
1676 struct sched_cache_group *sched_cache_group_get(struct sched_cache_group *grp)
1677 {
1678 	/*
1679 	 * refcount_inc_not_zero() is the acquire primitive for lockless
1680 	 * (RCU) lookups; plain refcount_inc() would scribble the count if
1681 	 * it already reached zero. Return NULL in that case.
1682 	 */
1683 	if (grp && !refcount_inc_not_zero(&grp->refcnt))
1684 		grp = NULL;
1685 
1686 	return grp;
1687 }
1688 
1689 struct sched_cache_group *task_cache_group_get(struct task_struct *p)
1690 {
1691 	guard(rcu)();
1692 	return sched_cache_group_get(rcu_dereference(p->sched_cache_grp));
1693 }
1694 
1695 void sched_cache_fork(struct task_struct *p)
1696 {
1697 	/*
1698 	 * The child takes its own reference on the mm's cache group, separate
1699 	 * from the reference held by the mm. @p is not yet visible to readers,
1700 	 * so a plain initializing store is enough.
1701 	 */
1702 	RCU_INIT_POINTER(p->sched_cache_grp,
1703 			 sched_cache_group_get(p->mm->sched_cache_grp));
1704 }
1705 
1706 void sched_cache_fork_cleanup(struct task_struct *p)
1707 {
1708 	/*
1709 	 * A fork that fails after sched_cache_fork() never reaches exit_mm(),
1710 	 * so drop the reference here. @p never became visible, so there are no
1711 	 * concurrent readers and the reference we hold keeps the group alive.
1712 	 */
1713 	sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp));
1714 	RCU_INIT_POINTER(p->sched_cache_grp, NULL);
1715 }
1716 
1717 void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
1718 {
1719 	struct sched_cache_group *old;
1720 
1721 	/*
1722 	 * Acquire the new reference before publishing the pointer, then drop
1723 	 * the old one. @p is current and the only writer of its own pointer.
1724 	 */
1725 	old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp));
1726 	sched_cache_group_put(old);
1727 }
1728 
1729 void sched_cache_exit_mm(struct task_struct *p)
1730 {
1731 	struct sched_cache_group *grp = sched_cache_replace_grp(p, NULL);
1732 
1733 #ifdef CONFIG_NUMA_BALANCING
1734 	/*
1735 	 * Subtract this task's footprint from the group before dropping the
1736 	 * reference, so the group footprint converges as its threads exit.
1737 	 * Unlocked for performance; clamp to avoid underflow.
1738 	 */
1739 	if (grp && p->total_numa_faults) {
1740 		unsigned long fp = READ_ONCE(grp->footprint);
1741 		unsigned long sub = min(fp, p->total_numa_faults);
1742 
1743 		WRITE_ONCE(grp->footprint, fp - sub);
1744 	}
1745 #endif
1746 	sched_cache_group_put(grp);
1747 }
1748 
1749 void mm_destroy_sched(struct mm_struct *mm)
1750 {
1751 	sched_cache_group_put(mm->sched_cache_grp);
1752 	mm->sched_cache_grp = NULL;
1753 }
1754 
1755 /* because why would C be fully specified */
1756 static __always_inline void __shr_u64(u64 *val, unsigned int n)
1757 {
1758 	if (n >= 64) {
1759 		*val = 0;
1760 		return;
1761 	}
1762 	*val >>= n;
1763 }
1764 
1765 static inline void __update_mm_sched(struct rq *rq,
1766 				     struct sched_cache_time *pcpu_sched)
1767 {
1768 	lockdep_assert_held(&rq->cpu_epoch_lock);
1769 
1770 	unsigned int period = max(READ_ONCE(llc_epoch_period), 1U);
1771 	unsigned long n, now = jiffies;
1772 	long delta = now - rq->cpu_epoch_next;
1773 
1774 	if (delta > 0) {
1775 		n = (delta + period - 1) / period;
1776 		rq->cpu_epoch += n;
1777 		rq->cpu_epoch_next += n * period;
1778 		__shr_u64(&rq->cpu_runtime, n);
1779 	}
1780 
1781 	n = rq->cpu_epoch - pcpu_sched->epoch;
1782 	if (n) {
1783 		pcpu_sched->epoch += n;
1784 		__shr_u64(&pcpu_sched->runtime, n);
1785 	}
1786 }
1787 
1788 static unsigned long fraction_mm_sched(struct rq *rq,
1789 				       struct sched_cache_time *pcpu_sched)
1790 {
1791 	guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock);
1792 
1793 	__update_mm_sched(rq, pcpu_sched);
1794 
1795 	/*
1796 	 * Runtime is a geometric series (r=0.5) and as such will sum to twice
1797 	 * the accumulation period, this means the multiplcation here should
1798 	 * not overflow.
1799 	 */
1800 	return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1);
1801 }
1802 
1803 static int get_pref_llc(struct task_struct *p, struct sched_cache_group *grp)
1804 {
1805 	int mm_sched_llc = -1, mm_sched_cpu;
1806 
1807 	if (!grp)
1808 		return -1;
1809 
1810 	mm_sched_cpu = READ_ONCE(grp->cpu);
1811 	if (mm_sched_cpu != -1) {
1812 		mm_sched_llc = llc_id(mm_sched_cpu);
1813 
1814 #ifdef CONFIG_NUMA_BALANCING
1815 		/*
1816 		 * Don't assign preferred LLC if it
1817 		 * conflicts with NUMA balancing.
1818 		 * This can happen when sched_setnuma() gets
1819 		 * called, however it is not much of an issue
1820 		 * because we expect account_mm_sched() to get
1821 		 * called fairly regularly -- at a higher rate
1822 		 * than sched_setnuma() at least -- and thus the
1823 		 * conflict only exists for a short period of time.
1824 		 */
1825 		if (static_branch_likely(&sched_numa_balancing) &&
1826 		    p->numa_preferred_nid >= 0 &&
1827 		    cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid)
1828 			mm_sched_llc = -1;
1829 #endif
1830 	}
1831 
1832 	return mm_sched_llc;
1833 }
1834 
1835 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p);
1836 
1837 static inline
1838 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
1839 {
1840 	struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp);
1841 	struct sched_cache_time *pcpu_sched;
1842 	int mm_sched_llc = -1;
1843 	unsigned long epoch;
1844 
1845 	if (!sched_cache_enabled())
1846 		return;
1847 
1848 	if (p->sched_class != &fair_sched_class)
1849 		return;
1850 	/*
1851 	 * init_task, kthreads and user thread created
1852 	 * by user_mode_thread() don't have a cache group.
1853 	 * In theory a kernel thread does not have any valid
1854 	 * cache group, because sched_cache_fork() is not
1855 	 * invoked for a kernel thread - !grp should gate the
1856 	 * kernel thread. Use the PF_KTHREAD check explicitly
1857 	 * here for safety reasons, to guard against future
1858 	 * modifications and to pair with task_tick_cache().
1859 	 */
1860 	if (p->flags & PF_KTHREAD || !grp || !grp->pcpu_sched)
1861 		return;
1862 
1863 	pcpu_sched = per_cpu_ptr(grp->pcpu_sched, cpu_of(rq));
1864 
1865 	scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) {
1866 		__update_mm_sched(rq, pcpu_sched);
1867 		pcpu_sched->runtime += delta_exec;
1868 		rq->cpu_runtime += delta_exec;
1869 		epoch = rq->cpu_epoch;
1870 	}
1871 
1872 	/*
1873 	 * If this process hasn't hit task_cache_work() for a while invalidate
1874 	 * its preferred state.
1875 	 */
1876 	if ((long)(epoch - READ_ONCE(grp->epoch)) > llc_epoch_affinity_timeout ||
1877 	    invalid_llc_nr(grp, p, cpu_of(rq)) ||
1878 	    exceed_llc_capacity(grp, cpu_of(rq))) {
1879 		if (READ_ONCE(grp->cpu) != -1)
1880 			WRITE_ONCE(grp->cpu, -1);
1881 	}
1882 
1883 	mm_sched_llc = get_pref_llc(p, grp);
1884 
1885 	/* task not on rq accounted later in account_entity_enqueue() */
1886 	if (task_running_on_cpu(rq->cpu, p) &&
1887 	    READ_ONCE(p->preferred_llc) != mm_sched_llc) {
1888 		account_llc_dequeue(rq, p);
1889 		WRITE_ONCE(p->preferred_llc, mm_sched_llc);
1890 		account_llc_enqueue(rq, p);
1891 	}
1892 }
1893 
1894 static void task_tick_cache(struct rq *rq, struct task_struct *p)
1895 {
1896 	struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp);
1897 	struct callback_head *work = &p->cache_work;
1898 	unsigned long epoch;
1899 
1900 	if (!sched_cache_enabled())
1901 		return;
1902 
1903 	if (!grp || p->flags & PF_KTHREAD ||
1904 	    !grp->pcpu_sched)
1905 		return;
1906 
1907 	epoch = rq->cpu_epoch;
1908 	/* avoid moving backwards */
1909 	if (time_after_eq(grp->epoch, epoch))
1910 		return;
1911 
1912 	guard(raw_spinlock)(&grp->lock);
1913 
1914 	if (work->next == work) {
1915 		task_work_add(p, work, TWA_RESUME);
1916 		WRITE_ONCE(grp->epoch, epoch);
1917 	}
1918 }
1919 
1920 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p,
1921 			      struct sched_cache_group *grp)
1922 {
1923 #ifdef CONFIG_NUMA_BALANCING
1924 	int cpu, curr_cpu, nid, pref_nid;
1925 
1926 	if (!static_branch_likely(&sched_numa_balancing))
1927 		goto out;
1928 
1929 	cpu = READ_ONCE(grp->cpu);
1930 	if (cpu != -1)
1931 		nid = cpu_to_node(cpu);
1932 	curr_cpu = task_cpu(p);
1933 
1934 	/*
1935 	 * Scanning in the preferred NUMA node is ideal. However, the NUMA
1936 	 * preferred node is per-task rather than per-process. It is possible
1937 	 * for different threads of the process to have distinct preferred
1938 	 * nodes; consequently, the process-wide preferred LLC may bounce
1939 	 * between different nodes. As a workaround, maintain the scan
1940 	 * CPU mask to also cover the process's current preferred LLC and the
1941 	 * current running node to mitigate the bouncing risk.
1942 	 * TBD: numa_group should be considered during task aggregation.
1943 	 */
1944 	pref_nid = p->numa_preferred_nid;
1945 	/* honor the task's preferred node */
1946 	if (pref_nid == NUMA_NO_NODE)
1947 		goto out;
1948 
1949 	cpumask_or(cpus, cpus, cpumask_of_node(pref_nid));
1950 
1951 	/* honor the task's preferred LLC CPU */
1952 	if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE)
1953 		cpumask_or(cpus, cpus, cpumask_of_node(nid));
1954 
1955 	/* make sure the task's current running node is included */
1956 	if (!cpumask_test_cpu(curr_cpu, cpus))
1957 		cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu)));
1958 
1959 	return;
1960 
1961 out:
1962 #endif
1963 	cpumask_copy(cpus, cpu_online_mask);
1964 }
1965 
1966 static inline void update_avg_scale(u64 *avg, u64 sample)
1967 {
1968 	int factor = per_cpu(sd_llc_size, raw_smp_processor_id());
1969 	s64 diff = sample - *avg;
1970 	u32 divisor;
1971 
1972 	/*
1973 	 * Scale the divisor based on the number of CPUs contained
1974 	 * in the LLC. This scaling ensures smaller LLC domains use
1975 	 * a smaller divisor to achieve more precise sensitivity to
1976 	 * changes in nr_running, while larger LLC domains are capped
1977 	 * at a maximum divisor of 8 which is the default smoothing
1978 	 * factor of EWMA in update_avg().
1979 	 */
1980 	divisor = clamp_t(u32, (factor >> 2), 2, 8);
1981 	*avg += div64_s64(diff, divisor);
1982 }
1983 
1984 static void task_cache_work(struct callback_head *work)
1985 {
1986 	struct sched_cache_group *grp __free(sched_cache_group_put) = NULL;
1987 	cpumask_var_t cpus __free(free_cpumask_var) = CPUMASK_VAR_NULL;
1988 	int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu;
1989 	unsigned long next_scan, now = jiffies;
1990 	struct task_struct *p = current, *cur;
1991 	unsigned long curr_m_a_occ = 0;
1992 	unsigned long m_a_occ = 0;
1993 
1994 	WARN_ON_ONCE(work != &p->cache_work);
1995 
1996 	work->next = work;
1997 
1998 	if (p->flags & PF_EXITING)
1999 		return;
2000 
2001 	/*
2002 	 * A reference makes sure grp is not released by others. The rcu
2003 	 * lock can not be held till after zalloc_cpumask_var() below,
2004 	 * because the latter might sleep.
2005 	 */
2006 	grp = task_cache_group_get(p);
2007 	if (!grp)
2008 		return;
2009 
2010 	next_scan = READ_ONCE(grp->next_scan);
2011 	if (time_before(now, next_scan))
2012 		return;
2013 
2014 	/* only 1 thread is allowed to scan */
2015 	if (!try_cmpxchg(&grp->next_scan, &next_scan,
2016 			 now + max_t(unsigned long,
2017 				     READ_ONCE(llc_epoch_period), 1)))
2018 		return;
2019 
2020 	curr_cpu = task_cpu(p);
2021 	if (invalid_llc_nr(grp, p, curr_cpu) ||
2022 	    exceed_llc_capacity(grp, curr_cpu)) {
2023 		if (READ_ONCE(grp->cpu) != -1)
2024 			WRITE_ONCE(grp->cpu, -1);
2025 
2026 		return;
2027 	}
2028 
2029 	if (!zalloc_cpumask_var(&cpus, GFP_KERNEL))
2030 		return;
2031 
2032 	scoped_guard (cpus_read_lock) {
2033 		guard(rcu)();
2034 
2035 		get_scan_cpumasks(cpus, p, grp);
2036 
2037 		for_each_cpu(cpu, cpus) {
2038 			/* XXX sched_cluster_active */
2039 			struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
2040 			unsigned long occ, m_occ = 0, a_occ = 0;
2041 			int m_cpu = -1, i;
2042 
2043 			if (!sd)
2044 				continue;
2045 
2046 			for_each_cpu(i, sched_domain_span(sd)) {
2047 				occ = fraction_mm_sched(cpu_rq(i),
2048 							per_cpu_ptr(grp->pcpu_sched, i));
2049 				a_occ += occ;
2050 				if (occ > m_occ) {
2051 					m_occ = occ;
2052 					m_cpu = i;
2053 				}
2054 
2055 				/*
2056 				 * rcu_access_pointer() is used because the
2057 				 * pointer is only compared, never dereferenced.
2058 				 */
2059 				cur = rcu_dereference_all(cpu_rq(i)->curr);
2060 				if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) &&
2061 				    rcu_access_pointer(cur->sched_cache_grp) == grp)
2062 					nr_running++;
2063 			}
2064 
2065 			/*
2066 			 * Compare the accumulated occupancy of each LLC. The
2067 			 * reason for using accumulated occupancy rather than average
2068 			 * per CPU occupancy is that it works better in asymmetric LLC
2069 			 * scenarios.
2070 			 * For example, if there are 2 threads in a 4CPU LLC and 3
2071 			 * threads in an 8CPU LLC, it might be better to choose the one
2072 			 * with 3 threads. However, this would not be the case if the
2073 			 * occupancy is divided by the number of CPUs in an LLC (i.e.,
2074 			 * if average per CPU occupancy is used).
2075 			 * Besides, NUMA balancing fault statistics behave similarly:
2076 			 * the total number of faults per node is compared rather than
2077 			 * the average number of faults per CPU. This strategy is also
2078 			 * followed here.
2079 			 */
2080 			if (a_occ > m_a_occ) {
2081 				m_a_occ = a_occ;
2082 				m_a_cpu = m_cpu;
2083 			}
2084 
2085 			if (llc_id(cpu) == llc_id(READ_ONCE(grp->cpu)))
2086 				curr_m_a_occ = a_occ;
2087 
2088 			cpumask_andnot(cpus, cpus, sched_domain_span(sd));
2089 		}
2090 	}
2091 
2092 	if (m_a_occ > (2 * curr_m_a_occ)) {
2093 		/*
2094 		 * Avoid switching sched_cache_grp->cpu too fast.
2095 		 * The reason to choose 2X is because:
2096 		 * 1. It is better to keep the preferred LLC stable,
2097 		 *    rather than changing it frequently and cause migrations
2098 		 * 2. 2X means the new preferred LLC has at least 1 more
2099 		 *    busy CPU than the old one(200% vs 100%, eg)
2100 		 * 3. 2X is chosen based on test results, as it delivers
2101 		 *    the optimal performance gain so far.
2102 		 */
2103 		WRITE_ONCE(grp->cpu, m_a_cpu);
2104 	}
2105 
2106 	update_avg_scale(&grp->nr_running_avg, nr_running);
2107 }
2108 
2109 void init_sched_mm(struct task_struct *p)
2110 {
2111 	struct callback_head *work = &p->cache_work;
2112 
2113 	init_task_work(work, task_cache_work);
2114 	work->next = work;
2115 	/*
2116 	 * dup_task_struct() copies the parent's task_struct, including its
2117 	 * sched_cache_grp, for which the child holds no reference.  Clear it
2118 	 * here - before copy_mm() runs - so the child never carries a
2119 	 * borrowed pointer that the fork error path would put.
2120 	 */
2121 	RCU_INIT_POINTER(p->sched_cache_grp, NULL);
2122 	/*
2123 	 * Reset new task's preference to avoid
2124 	 * polluting account_llc_enqueue().
2125 	 */
2126 	p->preferred_llc = -1;
2127 	p->pref_llc_queued = 0;
2128 }
2129 
2130 #else /* CONFIG_SCHED_CACHE */
2131 
2132 static inline void account_mm_sched(struct rq *rq, struct task_struct *p,
2133 				    s64 delta_exec) { }
2134 
2135 void init_sched_mm(struct task_struct *p) { }
2136 
2137 static void task_tick_cache(struct rq *rq, struct task_struct *p) { }
2138 
2139 static inline int get_pref_llc(struct task_struct *p,
2140 			       struct sched_cache_group *grp)
2141 {
2142 	return -1;
2143 }
2144 
2145 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {}
2146 
2147 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {}
2148 
2149 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p) {}
2150 
2151 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) {}
2152 
2153 #endif /* CONFIG_SCHED_CACHE */
2154 
2155 /*
2156  * Used by other classes to account runtime.
2157  */
2158 s64 update_curr_common(struct rq *rq)
2159 {
2160 	return update_se(rq, &rq->donor->se);
2161 }
2162 
2163 /*
2164  * Update the current task's runtime statistics.
2165  */
2166 static void update_curr(struct cfs_rq *cfs_rq)
2167 {
2168 	/*
2169 	 * Note: cfs_rq->curr corresponds to the task picked to
2170 	 * run (ie: rq->donor.se) which due to proxy-exec may
2171 	 * not necessarily be the actual task running
2172 	 * (rq->curr.se). This is easy to confuse!
2173 	 */
2174 	struct sched_entity *curr = cfs_rq->h_curr;
2175 	struct rq *rq = rq_of(cfs_rq);
2176 	s64 delta_exec;
2177 	bool resched;
2178 
2179 	if (unlikely(!curr))
2180 		return;
2181 
2182 	delta_exec = update_se(rq, curr);
2183 	if (unlikely(delta_exec <= 0))
2184 		return;
2185 
2186 	account_cfs_rq_runtime(cfs_rq, delta_exec);
2187 
2188 	if (!entity_is_task(curr))
2189 		return;
2190 
2191 	cfs_rq = &rq->cfs;
2192 
2193 	curr->vruntime += calc_delta_fair(delta_exec, curr);
2194 	resched = update_deadline(cfs_rq, curr);
2195 
2196 	/*
2197 	 * If the fair_server is active, we need to account for the
2198 	 * fair_server time whether or not the task is running on
2199 	 * behalf of fair_server or not:
2200 	 *  - If the task is running on behalf of fair_server, we need
2201 	 *    to limit its time based on the assigned runtime.
2202 	 *  - Fair task that runs outside of fair_server should account
2203 	 *    against fair_server such that it can account for this time
2204 	 *    and possibly avoid running this period.
2205 	 */
2206 	dl_server_update(&rq->fair_server, delta_exec);
2207 
2208 	if (cfs_rq->h_nr_queued == 1)
2209 		return;
2210 
2211 	if (resched || !protect_slice(curr)) {
2212 		resched_curr_lazy(rq);
2213 		clear_buddies(cfs_rq, curr);
2214 	}
2215 }
2216 
2217 static void update_curr_fair(struct rq *rq)
2218 {
2219 	struct sched_entity *se = &rq->donor->se;
2220 
2221 	for_each_sched_entity(se)
2222 		update_curr(cfs_rq_of(se));
2223 }
2224 
2225 static inline void
2226 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2227 {
2228 	struct sched_statistics *stats;
2229 	struct task_struct *p = NULL;
2230 
2231 	if (!schedstat_enabled())
2232 		return;
2233 
2234 	stats = __schedstats_from_se(se);
2235 
2236 	if (entity_is_task(se))
2237 		p = task_of(se);
2238 
2239 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
2240 }
2241 
2242 static inline void
2243 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2244 {
2245 	struct sched_statistics *stats;
2246 	struct task_struct *p = NULL;
2247 
2248 	if (!schedstat_enabled())
2249 		return;
2250 
2251 	stats = __schedstats_from_se(se);
2252 
2253 	/*
2254 	 * When the sched_schedstat changes from 0 to 1, some sched se
2255 	 * maybe already in the runqueue, the se->statistics.wait_start
2256 	 * will be 0.So it will let the delta wrong. We need to avoid this
2257 	 * scenario.
2258 	 */
2259 	if (unlikely(!schedstat_val(stats->wait_start)))
2260 		return;
2261 
2262 	if (entity_is_task(se))
2263 		p = task_of(se);
2264 
2265 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
2266 }
2267 
2268 static inline void
2269 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2270 {
2271 	struct sched_statistics *stats;
2272 	struct task_struct *tsk = NULL;
2273 
2274 	if (!schedstat_enabled())
2275 		return;
2276 
2277 	stats = __schedstats_from_se(se);
2278 
2279 	if (entity_is_task(se))
2280 		tsk = task_of(se);
2281 
2282 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
2283 }
2284 
2285 /*
2286  * Task is being enqueued - update stats:
2287  */
2288 static inline void
2289 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2290 {
2291 	if (!schedstat_enabled())
2292 		return;
2293 
2294 	/*
2295 	 * Are we enqueueing a waiting task? (for current tasks
2296 	 * a dequeue/enqueue event is a NOP)
2297 	 */
2298 	if (se != cfs_rq->h_curr)
2299 		update_stats_wait_start_fair(cfs_rq, se);
2300 
2301 	if (flags & ENQUEUE_WAKEUP)
2302 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
2303 }
2304 
2305 static inline void
2306 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2307 {
2308 
2309 	if (!schedstat_enabled())
2310 		return;
2311 
2312 	/*
2313 	 * Mark the end of the wait period if dequeueing a
2314 	 * waiting task:
2315 	 */
2316 	if (se != cfs_rq->h_curr)
2317 		update_stats_wait_end_fair(cfs_rq, se);
2318 
2319 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
2320 		struct task_struct *tsk = task_of(se);
2321 		unsigned int state;
2322 
2323 		/* XXX racy against TTWU */
2324 		state = READ_ONCE(tsk->__state);
2325 		if (state & TASK_INTERRUPTIBLE)
2326 			__schedstat_set(tsk->stats.sleep_start,
2327 				      rq_clock(rq_of(cfs_rq)));
2328 		if (state & TASK_UNINTERRUPTIBLE)
2329 			__schedstat_set(tsk->stats.block_start,
2330 				      rq_clock(rq_of(cfs_rq)));
2331 	}
2332 }
2333 
2334 /*
2335  * We are picking a new current task - update its stats:
2336  */
2337 static inline void
2338 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
2339 {
2340 	/*
2341 	 * We are starting a new run period:
2342 	 */
2343 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
2344 }
2345 
2346 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */
2347 static inline bool is_core_idle(int cpu)
2348 {
2349 	int sibling;
2350 
2351 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
2352 		if (cpu == sibling)
2353 			continue;
2354 
2355 		if (!idle_cpu(sibling))
2356 			return false;
2357 	}
2358 
2359 	return true;
2360 }
2361 
2362 #ifdef CONFIG_NUMA
2363 #define NUMA_IMBALANCE_MIN 2
2364 
2365 static inline long
2366 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
2367 {
2368 	/*
2369 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
2370 	 * threshold. Above this threshold, individual tasks may be contending
2371 	 * for both memory bandwidth and any shared HT resources.  This is an
2372 	 * approximation as the number of running tasks may not be related to
2373 	 * the number of busy CPUs due to sched_setaffinity.
2374 	 */
2375 	if (dst_running > imb_numa_nr)
2376 		return imbalance;
2377 
2378 	/*
2379 	 * Allow a small imbalance based on a simple pair of communicating
2380 	 * tasks that remain local when the destination is lightly loaded.
2381 	 */
2382 	if (imbalance <= NUMA_IMBALANCE_MIN)
2383 		return 0;
2384 
2385 	return imbalance;
2386 }
2387 #endif /* CONFIG_NUMA */
2388 
2389 #ifdef CONFIG_NUMA_BALANCING
2390 /*
2391  * Approximate time to scan a full NUMA task in ms. The task scan period is
2392  * calculated based on the tasks virtual memory size and
2393  * numa_balancing_scan_size.
2394  */
2395 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
2396 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
2397 
2398 /* Portion of address space to scan in MB */
2399 unsigned int sysctl_numa_balancing_scan_size = 256;
2400 
2401 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
2402 unsigned int sysctl_numa_balancing_scan_delay = 1000;
2403 
2404 /* The page with hint page fault latency < threshold in ms is considered hot */
2405 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
2406 
2407 struct numa_group {
2408 	refcount_t refcount;
2409 
2410 	spinlock_t lock; /* nr_tasks, tasks */
2411 	int nr_tasks;
2412 	pid_t gid;
2413 	int active_nodes;
2414 
2415 	struct rcu_head rcu;
2416 	unsigned long total_faults;
2417 	unsigned long max_faults_cpu;
2418 	/*
2419 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
2420 	 *
2421 	 * Faults_cpu is used to decide whether memory should move
2422 	 * towards the CPU. As a consequence, these stats are weighted
2423 	 * more by CPU use than by memory faults.
2424 	 */
2425 	unsigned long faults[];
2426 };
2427 
2428 /*
2429  * For functions that can be called in multiple contexts that permit reading
2430  * ->numa_group (see struct task_struct for locking rules).
2431  */
2432 static struct numa_group *deref_task_numa_group(struct task_struct *p)
2433 {
2434 	return rcu_dereference_check(p->numa_group, p == current ||
2435 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
2436 }
2437 
2438 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
2439 {
2440 	return rcu_dereference_protected(p->numa_group, p == current);
2441 }
2442 
2443 static inline unsigned long group_faults_priv(struct numa_group *ng);
2444 static inline unsigned long group_faults_shared(struct numa_group *ng);
2445 
2446 static unsigned int task_nr_scan_windows(struct task_struct *p)
2447 {
2448 	unsigned long rss = 0;
2449 	unsigned long nr_scan_pages;
2450 
2451 	/*
2452 	 * Calculations based on RSS as non-present and empty pages are skipped
2453 	 * by the PTE scanner and NUMA hinting faults should be trapped based
2454 	 * on resident pages
2455 	 */
2456 	nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
2457 	rss = get_mm_rss(p->mm);
2458 	if (!rss)
2459 		rss = nr_scan_pages;
2460 
2461 	rss = round_up(rss, nr_scan_pages);
2462 	return rss / nr_scan_pages;
2463 }
2464 
2465 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
2466 #define MAX_SCAN_WINDOW 2560
2467 
2468 static unsigned int task_scan_min(struct task_struct *p)
2469 {
2470 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
2471 	unsigned int scan, floor;
2472 	unsigned int windows = 1;
2473 
2474 	if (scan_size < MAX_SCAN_WINDOW)
2475 		windows = MAX_SCAN_WINDOW / scan_size;
2476 	floor = 1000 / windows;
2477 
2478 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
2479 	return max_t(unsigned int, floor, scan);
2480 }
2481 
2482 static unsigned int task_scan_start(struct task_struct *p)
2483 {
2484 	unsigned long smin = task_scan_min(p);
2485 	unsigned long period = smin;
2486 	struct numa_group *ng;
2487 
2488 	/* Scale the maximum scan period with the amount of shared memory. */
2489 	rcu_read_lock();
2490 	ng = rcu_dereference_all(p->numa_group);
2491 	if (ng) {
2492 		unsigned long shared = group_faults_shared(ng);
2493 		unsigned long private = group_faults_priv(ng);
2494 
2495 		period *= refcount_read(&ng->refcount);
2496 		period *= shared + 1;
2497 		period /= private + shared + 1;
2498 	}
2499 	rcu_read_unlock();
2500 
2501 	return max(smin, period);
2502 }
2503 
2504 static unsigned int task_scan_max(struct task_struct *p)
2505 {
2506 	unsigned long smin = task_scan_min(p);
2507 	unsigned long smax;
2508 	struct numa_group *ng;
2509 
2510 	/* Watch for min being lower than max due to floor calculations */
2511 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
2512 
2513 	/* Scale the maximum scan period with the amount of shared memory. */
2514 	ng = deref_curr_numa_group(p);
2515 	if (ng) {
2516 		unsigned long shared = group_faults_shared(ng);
2517 		unsigned long private = group_faults_priv(ng);
2518 		unsigned long period = smax;
2519 
2520 		period *= refcount_read(&ng->refcount);
2521 		period *= shared + 1;
2522 		period /= private + shared + 1;
2523 
2524 		smax = max(smax, period);
2525 	}
2526 
2527 	return max(smin, smax);
2528 }
2529 
2530 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2531 {
2532 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
2533 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
2534 }
2535 
2536 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2537 {
2538 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
2539 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
2540 }
2541 
2542 /* Shared or private faults. */
2543 #define NR_NUMA_HINT_FAULT_TYPES 2
2544 
2545 /* Memory and CPU locality */
2546 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
2547 
2548 /* Averaged statistics, and temporary buffers. */
2549 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
2550 
2551 pid_t task_numa_group_id(struct task_struct *p)
2552 {
2553 	struct numa_group *ng;
2554 	pid_t gid = 0;
2555 
2556 	rcu_read_lock();
2557 	ng = rcu_dereference_all(p->numa_group);
2558 	if (ng)
2559 		gid = ng->gid;
2560 	rcu_read_unlock();
2561 
2562 	return gid;
2563 }
2564 
2565 /*
2566  * The averaged statistics, shared & private, memory & CPU,
2567  * occupy the first half of the array. The second half of the
2568  * array is for current counters, which are averaged into the
2569  * first set by task_numa_placement.
2570  */
2571 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
2572 {
2573 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
2574 }
2575 
2576 static inline unsigned long task_faults(struct task_struct *p, int nid)
2577 {
2578 	if (!p->numa_faults)
2579 		return 0;
2580 
2581 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2582 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
2583 }
2584 
2585 static inline unsigned long group_faults(struct task_struct *p, int nid)
2586 {
2587 	struct numa_group *ng = deref_task_numa_group(p);
2588 
2589 	if (!ng)
2590 		return 0;
2591 
2592 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2593 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
2594 }
2595 
2596 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
2597 {
2598 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
2599 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
2600 }
2601 
2602 static inline unsigned long group_faults_priv(struct numa_group *ng)
2603 {
2604 	unsigned long faults = 0;
2605 	int node;
2606 
2607 	for_each_online_node(node) {
2608 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
2609 	}
2610 
2611 	return faults;
2612 }
2613 
2614 static inline unsigned long group_faults_shared(struct numa_group *ng)
2615 {
2616 	unsigned long faults = 0;
2617 	int node;
2618 
2619 	for_each_online_node(node) {
2620 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
2621 	}
2622 
2623 	return faults;
2624 }
2625 
2626 /*
2627  * A node triggering more than 1/3 as many NUMA faults as the maximum is
2628  * considered part of a numa group's pseudo-interleaving set. Migrations
2629  * between these nodes are slowed down, to allow things to settle down.
2630  */
2631 #define ACTIVE_NODE_FRACTION 3
2632 
2633 static bool numa_is_active_node(int nid, struct numa_group *ng)
2634 {
2635 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
2636 }
2637 
2638 /* Handle placement on systems where not all nodes are directly connected. */
2639 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
2640 					int lim_dist, bool task)
2641 {
2642 	unsigned long score = 0;
2643 	int node, max_dist;
2644 
2645 	/*
2646 	 * All nodes are directly connected, and the same distance
2647 	 * from each other. No need for fancy placement algorithms.
2648 	 */
2649 	if (sched_numa_topology_type == NUMA_DIRECT)
2650 		return 0;
2651 
2652 	/* sched_max_numa_distance may be changed in parallel. */
2653 	max_dist = READ_ONCE(sched_max_numa_distance);
2654 	/*
2655 	 * This code is called for each node, introducing N^2 complexity,
2656 	 * which should be OK given the number of nodes rarely exceeds 8.
2657 	 */
2658 	for_each_online_node(node) {
2659 		unsigned long faults;
2660 		int dist = node_distance(nid, node);
2661 
2662 		/*
2663 		 * The furthest away nodes in the system are not interesting
2664 		 * for placement; nid was already counted.
2665 		 */
2666 		if (dist >= max_dist || node == nid)
2667 			continue;
2668 
2669 		/*
2670 		 * On systems with a backplane NUMA topology, compare groups
2671 		 * of nodes, and move tasks towards the group with the most
2672 		 * memory accesses. When comparing two nodes at distance
2673 		 * "hoplimit", only nodes closer by than "hoplimit" are part
2674 		 * of each group. Skip other nodes.
2675 		 */
2676 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
2677 			continue;
2678 
2679 		/* Add up the faults from nearby nodes. */
2680 		if (task)
2681 			faults = task_faults(p, node);
2682 		else
2683 			faults = group_faults(p, node);
2684 
2685 		/*
2686 		 * On systems with a glueless mesh NUMA topology, there are
2687 		 * no fixed "groups of nodes". Instead, nodes that are not
2688 		 * directly connected bounce traffic through intermediate
2689 		 * nodes; a numa_group can occupy any set of nodes.
2690 		 * The further away a node is, the less the faults count.
2691 		 * This seems to result in good task placement.
2692 		 */
2693 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2694 			faults *= (max_dist - dist);
2695 			faults /= (max_dist - LOCAL_DISTANCE);
2696 		}
2697 
2698 		score += faults;
2699 	}
2700 
2701 	return score;
2702 }
2703 
2704 /*
2705  * These return the fraction of accesses done by a particular task, or
2706  * task group, on a particular numa node.  The group weight is given a
2707  * larger multiplier, in order to group tasks together that are almost
2708  * evenly spread out between numa nodes.
2709  */
2710 static inline unsigned long task_weight(struct task_struct *p, int nid,
2711 					int dist)
2712 {
2713 	unsigned long faults, total_faults;
2714 
2715 	if (!p->numa_faults)
2716 		return 0;
2717 
2718 	total_faults = p->total_numa_faults;
2719 
2720 	if (!total_faults)
2721 		return 0;
2722 
2723 	faults = task_faults(p, nid);
2724 	faults += score_nearby_nodes(p, nid, dist, true);
2725 
2726 	return 1000 * faults / total_faults;
2727 }
2728 
2729 static inline unsigned long group_weight(struct task_struct *p, int nid,
2730 					 int dist)
2731 {
2732 	struct numa_group *ng = deref_task_numa_group(p);
2733 	unsigned long faults, total_faults;
2734 
2735 	if (!ng)
2736 		return 0;
2737 
2738 	total_faults = ng->total_faults;
2739 
2740 	if (!total_faults)
2741 		return 0;
2742 
2743 	faults = group_faults(p, nid);
2744 	faults += score_nearby_nodes(p, nid, dist, false);
2745 
2746 	return 1000 * faults / total_faults;
2747 }
2748 
2749 /*
2750  * If memory tiering mode is enabled, cpupid of slow memory page is
2751  * used to record scan time instead of CPU and PID.  When tiering mode
2752  * is disabled at run time, the scan time (in cpupid) will be
2753  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
2754  * access out of array bound.
2755  */
2756 static inline bool cpupid_valid(int cpupid)
2757 {
2758 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
2759 }
2760 
2761 /*
2762  * For memory tiering mode, if there are enough free pages (more than
2763  * enough watermark defined here) in fast memory node, to take full
2764  * advantage of fast memory capacity, all recently accessed slow
2765  * memory pages will be migrated to fast memory node without
2766  * considering hot threshold.
2767  */
2768 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
2769 {
2770 	int z;
2771 	unsigned long enough_wmark;
2772 
2773 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
2774 			   pgdat->node_present_pages >> 4);
2775 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2776 		struct zone *zone = pgdat->node_zones + z;
2777 
2778 		if (!populated_zone(zone))
2779 			continue;
2780 
2781 		if (zone_watermark_ok(zone, 0,
2782 				      promo_wmark_pages(zone) + enough_wmark,
2783 				      ZONE_MOVABLE, 0))
2784 			return true;
2785 	}
2786 	return false;
2787 }
2788 
2789 /*
2790  * For memory tiering mode, when page tables are scanned, the scan
2791  * time will be recorded in struct page in addition to make page
2792  * PROT_NONE for slow memory page.  So when the page is accessed, in
2793  * hint page fault handler, the hint page fault latency is calculated
2794  * via,
2795  *
2796  *	hint page fault latency = hint page fault time - scan time
2797  *
2798  * The smaller the hint page fault latency, the higher the possibility
2799  * for the page to be hot.
2800  */
2801 static int numa_hint_fault_latency(struct folio *folio)
2802 {
2803 	int last_time, time;
2804 
2805 	time = jiffies_to_msecs(jiffies);
2806 	last_time = folio_xchg_access_time(folio, time);
2807 
2808 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
2809 }
2810 
2811 /*
2812  * For memory tiering mode, too high promotion/demotion throughput may
2813  * hurt application latency.  So we provide a mechanism to rate limit
2814  * the number of pages that are tried to be promoted.
2815  */
2816 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
2817 				      unsigned long rate_limit, int nr)
2818 {
2819 	unsigned long nr_cand;
2820 	unsigned int now, start;
2821 
2822 	now = jiffies_to_msecs(jiffies);
2823 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
2824 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2825 	start = pgdat->nbp_rl_start;
2826 	if (now - start > MSEC_PER_SEC &&
2827 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
2828 		pgdat->nbp_rl_nr_cand = nr_cand;
2829 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
2830 		return true;
2831 	return false;
2832 }
2833 
2834 #define NUMA_MIGRATION_ADJUST_STEPS	16
2835 
2836 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
2837 					    unsigned long rate_limit,
2838 					    unsigned int ref_th)
2839 {
2840 	unsigned int now, start, th_period, unit_th, th;
2841 	unsigned long nr_cand, ref_cand, diff_cand;
2842 
2843 	now = jiffies_to_msecs(jiffies);
2844 	th_period = sysctl_numa_balancing_scan_period_max;
2845 	start = pgdat->nbp_th_start;
2846 	if (now - start > th_period &&
2847 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
2848 		ref_cand = rate_limit *
2849 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
2850 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2851 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
2852 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
2853 		th = pgdat->nbp_threshold ? : ref_th;
2854 		if (diff_cand > ref_cand * 11 / 10)
2855 			th = max(th - unit_th, unit_th);
2856 		else if (diff_cand < ref_cand * 9 / 10)
2857 			th = min(th + unit_th, ref_th * 2);
2858 		pgdat->nbp_th_nr_cand = nr_cand;
2859 		pgdat->nbp_threshold = th;
2860 	}
2861 }
2862 
2863 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
2864 				int src_nid, int dst_cpu)
2865 {
2866 	struct numa_group *ng = deref_curr_numa_group(p);
2867 	int dst_nid = cpu_to_node(dst_cpu);
2868 	int last_cpupid, this_cpupid;
2869 
2870 	/*
2871 	 * Cannot migrate to memoryless nodes.
2872 	 */
2873 	if (!node_state(dst_nid, N_MEMORY))
2874 		return false;
2875 
2876 	/*
2877 	 * The pages in slow memory node should be migrated according
2878 	 * to hot/cold instead of private/shared.
2879 	 */
2880 	if (folio_use_access_time(folio)) {
2881 		struct pglist_data *pgdat;
2882 		unsigned long rate_limit;
2883 		unsigned int latency, th, def_th;
2884 		long nr = folio_nr_pages(folio);
2885 
2886 		pgdat = NODE_DATA(dst_nid);
2887 		if (pgdat_free_space_enough(pgdat)) {
2888 			/* workload changed, reset hot threshold */
2889 			pgdat->nbp_threshold = 0;
2890 			mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
2891 			return true;
2892 		}
2893 
2894 		def_th = sysctl_numa_balancing_hot_threshold;
2895 		rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
2896 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
2897 
2898 		th = pgdat->nbp_threshold ? : def_th;
2899 		latency = numa_hint_fault_latency(folio);
2900 		if (latency >= th)
2901 			return false;
2902 
2903 		return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
2904 	}
2905 
2906 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
2907 	last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
2908 
2909 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
2910 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
2911 		return false;
2912 
2913 	/*
2914 	 * Allow first faults or private faults to migrate immediately early in
2915 	 * the lifetime of a task. The magic number 4 is based on waiting for
2916 	 * two full passes of the "multi-stage node selection" test that is
2917 	 * executed below.
2918 	 */
2919 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
2920 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
2921 		return true;
2922 
2923 	/*
2924 	 * Multi-stage node selection is used in conjunction with a periodic
2925 	 * migration fault to build a temporal task<->page relation. By using
2926 	 * a two-stage filter we remove short/unlikely relations.
2927 	 *
2928 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2929 	 * a task's usage of a particular page (n_p) per total usage of this
2930 	 * page (n_t) (in a given time-span) to a probability.
2931 	 *
2932 	 * Our periodic faults will sample this probability and getting the
2933 	 * same result twice in a row, given these samples are fully
2934 	 * independent, is then given by P(n)^2, provided our sample period
2935 	 * is sufficiently short compared to the usage pattern.
2936 	 *
2937 	 * This quadric squishes small probabilities, making it less likely we
2938 	 * act on an unlikely task<->page relation.
2939 	 */
2940 	if (!cpupid_pid_unset(last_cpupid) &&
2941 				cpupid_to_nid(last_cpupid) != dst_nid)
2942 		return false;
2943 
2944 	/* Always allow migrate on private faults */
2945 	if (cpupid_match_pid(p, last_cpupid))
2946 		return true;
2947 
2948 	/* A shared fault, but p->numa_group has not been set up yet. */
2949 	if (!ng)
2950 		return true;
2951 
2952 	/*
2953 	 * Destination node is much more heavily used than the source
2954 	 * node? Allow migration.
2955 	 */
2956 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2957 					ACTIVE_NODE_FRACTION)
2958 		return true;
2959 
2960 	/*
2961 	 * Distribute memory according to CPU & memory use on each node,
2962 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2963 	 *
2964 	 * faults_cpu(dst)   3   faults_cpu(src)
2965 	 * --------------- * - > ---------------
2966 	 * faults_mem(dst)   4   faults_mem(src)
2967 	 */
2968 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2969 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2970 }
2971 
2972 /*
2973  * 'numa_type' describes the node at the moment of load balancing.
2974  */
2975 enum numa_type {
2976 	/* The node has spare capacity that can be used to run more tasks.  */
2977 	node_has_spare = 0,
2978 	/*
2979 	 * The node is fully used and the tasks don't compete for more CPU
2980 	 * cycles. Nevertheless, some tasks might wait before running.
2981 	 */
2982 	node_fully_busy,
2983 	/*
2984 	 * The node is overloaded and can't provide expected CPU cycles to all
2985 	 * tasks.
2986 	 */
2987 	node_overloaded
2988 };
2989 
2990 /* Cached statistics for all CPUs within a node */
2991 struct numa_stats {
2992 	unsigned long load;
2993 	unsigned long runnable;
2994 	unsigned long util;
2995 	/* Total compute capacity of CPUs on a node */
2996 	unsigned long compute_capacity;
2997 	unsigned int nr_running;
2998 	unsigned int weight;
2999 	enum numa_type node_type;
3000 	int idle_cpu;
3001 };
3002 
3003 struct task_numa_env {
3004 	struct task_struct *p;
3005 
3006 	int src_cpu, src_nid;
3007 	int dst_cpu, dst_nid;
3008 	int imb_numa_nr;
3009 
3010 	struct numa_stats src_stats, dst_stats;
3011 
3012 	int imbalance_pct;
3013 	int dist;
3014 
3015 	struct task_struct *best_task;
3016 	long best_imp;
3017 	int best_cpu;
3018 };
3019 
3020 static unsigned long cpu_load(struct rq *rq);
3021 static unsigned long cpu_runnable(struct rq *rq);
3022 
3023 static inline enum
3024 numa_type numa_classify(unsigned int imbalance_pct,
3025 			 struct numa_stats *ns)
3026 {
3027 	if ((ns->nr_running > ns->weight) &&
3028 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
3029 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
3030 		return node_overloaded;
3031 
3032 	if ((ns->nr_running < ns->weight) ||
3033 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
3034 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
3035 		return node_has_spare;
3036 
3037 	return node_fully_busy;
3038 }
3039 
3040 /* Forward declarations of select_idle_sibling helpers */
3041 static inline bool test_idle_cores(int cpu);
3042 static inline int numa_idle_core(int idle_core, int cpu)
3043 {
3044 	if (!sched_smt_active() ||
3045 	    idle_core >= 0 || !test_idle_cores(cpu))
3046 		return idle_core;
3047 
3048 	/*
3049 	 * Prefer cores instead of packing HT siblings
3050 	 * and triggering future load balancing.
3051 	 */
3052 	if (is_core_idle(cpu))
3053 		idle_core = cpu;
3054 
3055 	return idle_core;
3056 }
3057 
3058 /*
3059  * Gather all necessary information to make NUMA balancing placement
3060  * decisions that are compatible with standard load balancer. This
3061  * borrows code and logic from update_sg_lb_stats but sharing a
3062  * common implementation is impractical.
3063  */
3064 static void update_numa_stats(struct task_numa_env *env,
3065 			      struct numa_stats *ns, int nid,
3066 			      bool find_idle)
3067 {
3068 	int cpu, idle_core = -1;
3069 
3070 	memset(ns, 0, sizeof(*ns));
3071 	ns->idle_cpu = -1;
3072 
3073 	rcu_read_lock();
3074 	for_each_cpu(cpu, cpumask_of_node(nid)) {
3075 		struct rq *rq = cpu_rq(cpu);
3076 
3077 		ns->load += cpu_load(rq);
3078 		ns->runnable += cpu_runnable(rq);
3079 		ns->util += cpu_util_cfs(cpu);
3080 		ns->nr_running += rq->cfs.h_nr_runnable;
3081 		ns->compute_capacity += capacity_of(cpu);
3082 
3083 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
3084 			if (READ_ONCE(rq->numa_migrate_on) ||
3085 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
3086 				continue;
3087 
3088 			if (ns->idle_cpu == -1)
3089 				ns->idle_cpu = cpu;
3090 
3091 			idle_core = numa_idle_core(idle_core, cpu);
3092 		}
3093 	}
3094 	rcu_read_unlock();
3095 
3096 	ns->weight = cpumask_weight(cpumask_of_node(nid));
3097 
3098 	ns->node_type = numa_classify(env->imbalance_pct, ns);
3099 
3100 	if (idle_core >= 0)
3101 		ns->idle_cpu = idle_core;
3102 }
3103 
3104 static void task_numa_assign(struct task_numa_env *env,
3105 			     struct task_struct *p, long imp)
3106 {
3107 	struct rq *rq = cpu_rq(env->dst_cpu);
3108 
3109 	/* Check if run-queue part of active NUMA balance. */
3110 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
3111 		int cpu;
3112 		int start = env->dst_cpu;
3113 
3114 		/* Find alternative idle CPU. */
3115 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
3116 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
3117 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
3118 				continue;
3119 			}
3120 
3121 			env->dst_cpu = cpu;
3122 			rq = cpu_rq(env->dst_cpu);
3123 			if (!xchg(&rq->numa_migrate_on, 1))
3124 				goto assign;
3125 		}
3126 
3127 		/* Failed to find an alternative idle CPU */
3128 		return;
3129 	}
3130 
3131 assign:
3132 	/*
3133 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
3134 	 * found a better CPU to move/swap.
3135 	 */
3136 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
3137 		rq = cpu_rq(env->best_cpu);
3138 		WRITE_ONCE(rq->numa_migrate_on, 0);
3139 	}
3140 
3141 	if (env->best_task)
3142 		put_task_struct(env->best_task);
3143 	if (p)
3144 		get_task_struct(p);
3145 
3146 	env->best_task = p;
3147 	env->best_imp = imp;
3148 	env->best_cpu = env->dst_cpu;
3149 }
3150 
3151 static bool load_too_imbalanced(long src_load, long dst_load,
3152 				struct task_numa_env *env)
3153 {
3154 	long imb, old_imb;
3155 	long orig_src_load, orig_dst_load;
3156 	long src_capacity, dst_capacity;
3157 
3158 	/*
3159 	 * The load is corrected for the CPU capacity available on each node.
3160 	 *
3161 	 * src_load        dst_load
3162 	 * ------------ vs ---------
3163 	 * src_capacity    dst_capacity
3164 	 */
3165 	src_capacity = env->src_stats.compute_capacity;
3166 	dst_capacity = env->dst_stats.compute_capacity;
3167 
3168 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
3169 
3170 	orig_src_load = env->src_stats.load;
3171 	orig_dst_load = env->dst_stats.load;
3172 
3173 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
3174 
3175 	/* Would this change make things worse? */
3176 	return (imb > old_imb);
3177 }
3178 
3179 /*
3180  * Maximum NUMA importance can be 1998 (2*999);
3181  * SMALLIMP @ 30 would be close to 1998/64.
3182  * Used to deter task migration.
3183  */
3184 #define SMALLIMP	30
3185 
3186 /*
3187  * This checks if the overall compute and NUMA accesses of the system would
3188  * be improved if the source tasks was migrated to the target dst_cpu taking
3189  * into account that it might be best if task running on the dst_cpu should
3190  * be exchanged with the source task
3191  */
3192 static bool task_numa_compare(struct task_numa_env *env,
3193 			      long taskimp, long groupimp, bool maymove)
3194 {
3195 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
3196 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
3197 	long imp = p_ng ? groupimp : taskimp;
3198 	struct task_struct *cur;
3199 	long src_load, dst_load;
3200 	int dist = env->dist;
3201 	long moveimp = imp;
3202 	long load;
3203 	bool stopsearch = false;
3204 
3205 	if (READ_ONCE(dst_rq->numa_migrate_on))
3206 		return false;
3207 
3208 	rcu_read_lock();
3209 	cur = rcu_dereference_all(dst_rq->curr);
3210 	if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
3211 		    !cur->mm))
3212 		cur = NULL;
3213 
3214 	/*
3215 	 * Because we have preemption enabled we can get migrated around and
3216 	 * end try selecting ourselves (current == env->p) as a swap candidate.
3217 	 */
3218 	if (cur == env->p) {
3219 		stopsearch = true;
3220 		goto unlock;
3221 	}
3222 
3223 	if (!cur) {
3224 		if (maymove && moveimp >= env->best_imp)
3225 			goto assign;
3226 		else
3227 			goto unlock;
3228 	}
3229 
3230 	/* Skip this swap candidate if cannot move to the source cpu. */
3231 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
3232 		goto unlock;
3233 
3234 	/*
3235 	 * Skip this swap candidate if it is not moving to its preferred
3236 	 * node and the best task is.
3237 	 */
3238 	if (env->best_task &&
3239 	    env->best_task->numa_preferred_nid == env->src_nid &&
3240 	    cur->numa_preferred_nid != env->src_nid) {
3241 		goto unlock;
3242 	}
3243 
3244 	/*
3245 	 * "imp" is the fault differential for the source task between the
3246 	 * source and destination node. Calculate the total differential for
3247 	 * the source task and potential destination task. The more negative
3248 	 * the value is, the more remote accesses that would be expected to
3249 	 * be incurred if the tasks were swapped.
3250 	 *
3251 	 * If dst and source tasks are in the same NUMA group, or not
3252 	 * in any group then look only at task weights.
3253 	 */
3254 	cur_ng = rcu_dereference_all(cur->numa_group);
3255 	if (cur_ng == p_ng) {
3256 		/*
3257 		 * Do not swap within a group or between tasks that have
3258 		 * no group if there is spare capacity. Swapping does
3259 		 * not address the load imbalance and helps one task at
3260 		 * the cost of punishing another.
3261 		 */
3262 		if (env->dst_stats.node_type == node_has_spare)
3263 			goto unlock;
3264 
3265 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
3266 		      task_weight(cur, env->dst_nid, dist);
3267 		/*
3268 		 * Add some hysteresis to prevent swapping the
3269 		 * tasks within a group over tiny differences.
3270 		 */
3271 		if (cur_ng)
3272 			imp -= imp / 16;
3273 	} else {
3274 		/*
3275 		 * Compare the group weights. If a task is all by itself
3276 		 * (not part of a group), use the task weight instead.
3277 		 */
3278 		if (cur_ng && p_ng)
3279 			imp += group_weight(cur, env->src_nid, dist) -
3280 			       group_weight(cur, env->dst_nid, dist);
3281 		else
3282 			imp += task_weight(cur, env->src_nid, dist) -
3283 			       task_weight(cur, env->dst_nid, dist);
3284 	}
3285 
3286 	/* Discourage picking a task already on its preferred node */
3287 	if (cur->numa_preferred_nid == env->dst_nid)
3288 		imp -= imp / 16;
3289 
3290 	/*
3291 	 * Encourage picking a task that moves to its preferred node.
3292 	 * This potentially makes imp larger than it's maximum of
3293 	 * 1998 (see SMALLIMP and task_weight for why) but in this
3294 	 * case, it does not matter.
3295 	 */
3296 	if (cur->numa_preferred_nid == env->src_nid)
3297 		imp += imp / 8;
3298 
3299 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
3300 		imp = moveimp;
3301 		cur = NULL;
3302 		goto assign;
3303 	}
3304 
3305 	/*
3306 	 * Prefer swapping with a task moving to its preferred node over a
3307 	 * task that is not.
3308 	 */
3309 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
3310 	    env->best_task->numa_preferred_nid != env->src_nid) {
3311 		goto assign;
3312 	}
3313 
3314 	/*
3315 	 * If the NUMA importance is less than SMALLIMP,
3316 	 * task migration might only result in ping pong
3317 	 * of tasks and also hurt performance due to cache
3318 	 * misses.
3319 	 */
3320 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
3321 		goto unlock;
3322 
3323 	/*
3324 	 * In the overloaded case, try and keep the load balanced.
3325 	 */
3326 	load = task_h_load(env->p) - task_h_load(cur);
3327 	if (!load)
3328 		goto assign;
3329 
3330 	dst_load = env->dst_stats.load + load;
3331 	src_load = env->src_stats.load - load;
3332 
3333 	if (load_too_imbalanced(src_load, dst_load, env))
3334 		goto unlock;
3335 
3336 assign:
3337 	/* Evaluate an idle CPU for a task numa move. */
3338 	if (!cur) {
3339 		int cpu = env->dst_stats.idle_cpu;
3340 
3341 		/* Nothing cached so current CPU went idle since the search. */
3342 		if (cpu < 0)
3343 			cpu = env->dst_cpu;
3344 
3345 		/*
3346 		 * If the CPU is no longer truly idle and the previous best CPU
3347 		 * is, keep using it.
3348 		 */
3349 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
3350 		    idle_cpu(env->best_cpu)) {
3351 			cpu = env->best_cpu;
3352 		}
3353 
3354 		env->dst_cpu = cpu;
3355 	}
3356 
3357 	task_numa_assign(env, cur, imp);
3358 
3359 	/*
3360 	 * If a move to idle is allowed because there is capacity or load
3361 	 * balance improves then stop the search. While a better swap
3362 	 * candidate may exist, a search is not free.
3363 	 */
3364 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
3365 		stopsearch = true;
3366 
3367 	/*
3368 	 * If a swap candidate must be identified and the current best task
3369 	 * moves its preferred node then stop the search.
3370 	 */
3371 	if (!maymove && env->best_task &&
3372 	    env->best_task->numa_preferred_nid == env->src_nid) {
3373 		stopsearch = true;
3374 	}
3375 unlock:
3376 	rcu_read_unlock();
3377 
3378 	return stopsearch;
3379 }
3380 
3381 static void task_numa_find_cpu(struct task_numa_env *env,
3382 				long taskimp, long groupimp)
3383 {
3384 	bool maymove = false;
3385 	int cpu;
3386 
3387 	/*
3388 	 * If dst node has spare capacity, then check if there is an
3389 	 * imbalance that would be overruled by the load balancer.
3390 	 */
3391 	if (env->dst_stats.node_type == node_has_spare) {
3392 		unsigned int imbalance;
3393 		int src_running, dst_running;
3394 
3395 		/*
3396 		 * Would movement cause an imbalance? Note that if src has
3397 		 * more running tasks that the imbalance is ignored as the
3398 		 * move improves the imbalance from the perspective of the
3399 		 * CPU load balancer.
3400 		 * */
3401 		src_running = env->src_stats.nr_running - 1;
3402 		dst_running = env->dst_stats.nr_running + 1;
3403 		imbalance = max(0, dst_running - src_running);
3404 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
3405 						  env->imb_numa_nr);
3406 
3407 		/* Use idle CPU if there is no imbalance */
3408 		if (!imbalance) {
3409 			maymove = true;
3410 			if (env->dst_stats.idle_cpu >= 0) {
3411 				env->dst_cpu = env->dst_stats.idle_cpu;
3412 				task_numa_assign(env, NULL, 0);
3413 				return;
3414 			}
3415 		}
3416 	} else {
3417 		long src_load, dst_load, load;
3418 		/*
3419 		 * If the improvement from just moving env->p direction is better
3420 		 * than swapping tasks around, check if a move is possible.
3421 		 */
3422 		load = task_h_load(env->p);
3423 		dst_load = env->dst_stats.load + load;
3424 		src_load = env->src_stats.load - load;
3425 		maymove = !load_too_imbalanced(src_load, dst_load, env);
3426 	}
3427 
3428 	/* Skip CPUs if the source task cannot migrate */
3429 	for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) {
3430 		env->dst_cpu = cpu;
3431 		if (task_numa_compare(env, taskimp, groupimp, maymove))
3432 			break;
3433 	}
3434 }
3435 
3436 static int task_numa_migrate(struct task_struct *p)
3437 {
3438 	struct task_numa_env env = {
3439 		.p = p,
3440 
3441 		.src_cpu = task_cpu(p),
3442 		.src_nid = task_node(p),
3443 
3444 		.imbalance_pct = 112,
3445 
3446 		.best_task = NULL,
3447 		.best_imp = 0,
3448 		.best_cpu = -1,
3449 	};
3450 	unsigned long taskweight, groupweight;
3451 	struct sched_domain *sd;
3452 	long taskimp, groupimp;
3453 	struct numa_group *ng;
3454 	struct rq *best_rq;
3455 	int nid, ret, dist;
3456 
3457 	/*
3458 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
3459 	 * imbalance and would be the first to start moving tasks about.
3460 	 *
3461 	 * And we want to avoid any moving of tasks about, as that would create
3462 	 * random movement of tasks -- counter the numa conditions we're trying
3463 	 * to satisfy here.
3464 	 */
3465 	rcu_read_lock();
3466 	sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu));
3467 	if (sd) {
3468 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
3469 		env.imb_numa_nr = sd->imb_numa_nr;
3470 	}
3471 	rcu_read_unlock();
3472 
3473 	/*
3474 	 * Cpusets can break the scheduler domain tree into smaller
3475 	 * balance domains, some of which do not cross NUMA boundaries.
3476 	 * Tasks that are "trapped" in such domains cannot be migrated
3477 	 * elsewhere, so there is no point in (re)trying.
3478 	 */
3479 	if (unlikely(!sd)) {
3480 		sched_setnuma(p, task_node(p));
3481 		return -EINVAL;
3482 	}
3483 
3484 	env.dst_nid = p->numa_preferred_nid;
3485 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
3486 	taskweight = task_weight(p, env.src_nid, dist);
3487 	groupweight = group_weight(p, env.src_nid, dist);
3488 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
3489 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
3490 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
3491 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3492 
3493 	/* Try to find a spot on the preferred nid. */
3494 	task_numa_find_cpu(&env, taskimp, groupimp);
3495 
3496 	/*
3497 	 * Look at other nodes in these cases:
3498 	 * - there is no space available on the preferred_nid
3499 	 * - the task is part of a numa_group that is interleaved across
3500 	 *   multiple NUMA nodes; in order to better consolidate the group,
3501 	 *   we need to check other locations.
3502 	 */
3503 	ng = deref_curr_numa_group(p);
3504 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
3505 		for_each_node_state(nid, N_CPU) {
3506 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
3507 				continue;
3508 
3509 			dist = node_distance(env.src_nid, env.dst_nid);
3510 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
3511 						dist != env.dist) {
3512 				taskweight = task_weight(p, env.src_nid, dist);
3513 				groupweight = group_weight(p, env.src_nid, dist);
3514 			}
3515 
3516 			/* Only consider nodes where both task and groups benefit */
3517 			taskimp = task_weight(p, nid, dist) - taskweight;
3518 			groupimp = group_weight(p, nid, dist) - groupweight;
3519 			if (taskimp < 0 && groupimp < 0)
3520 				continue;
3521 
3522 			env.dist = dist;
3523 			env.dst_nid = nid;
3524 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3525 			task_numa_find_cpu(&env, taskimp, groupimp);
3526 		}
3527 	}
3528 
3529 	/*
3530 	 * If the task is part of a workload that spans multiple NUMA nodes,
3531 	 * and is migrating into one of the workload's active nodes, remember
3532 	 * this node as the task's preferred numa node, so the workload can
3533 	 * settle down.
3534 	 * A task that migrated to a second choice node will be better off
3535 	 * trying for a better one later. Do not set the preferred node here.
3536 	 */
3537 	if (ng) {
3538 		if (env.best_cpu == -1)
3539 			nid = env.src_nid;
3540 		else
3541 			nid = cpu_to_node(env.best_cpu);
3542 
3543 		if (nid != p->numa_preferred_nid)
3544 			sched_setnuma(p, nid);
3545 	}
3546 
3547 	/* No better CPU than the current one was found. */
3548 	if (env.best_cpu == -1) {
3549 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
3550 		return -EAGAIN;
3551 	}
3552 
3553 	best_rq = cpu_rq(env.best_cpu);
3554 	if (env.best_task == NULL) {
3555 		ret = migrate_task_to(p, env.best_cpu);
3556 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
3557 		if (ret != 0)
3558 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
3559 		return ret;
3560 	}
3561 
3562 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
3563 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
3564 
3565 	if (ret != 0)
3566 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
3567 	put_task_struct(env.best_task);
3568 	return ret;
3569 }
3570 
3571 /* Attempt to migrate a task to a CPU on the preferred node. */
3572 static void numa_migrate_preferred(struct task_struct *p)
3573 {
3574 	unsigned long interval = HZ;
3575 
3576 	/* This task has no NUMA fault statistics yet */
3577 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
3578 		return;
3579 
3580 	/* Periodically retry migrating the task to the preferred node */
3581 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
3582 	p->numa_migrate_retry = jiffies + interval;
3583 
3584 	/* Success if task is already running on preferred CPU */
3585 	if (task_node(p) == p->numa_preferred_nid)
3586 		return;
3587 
3588 	/* Otherwise, try migrate to a CPU on the preferred node */
3589 	task_numa_migrate(p);
3590 }
3591 
3592 /*
3593  * Find out how many nodes the workload is actively running on. Do this by
3594  * tracking the nodes from which NUMA hinting faults are triggered. This can
3595  * be different from the set of nodes where the workload's memory is currently
3596  * located.
3597  */
3598 static void numa_group_count_active_nodes(struct numa_group *numa_group)
3599 {
3600 	unsigned long faults, max_faults = 0;
3601 	int nid, active_nodes = 0;
3602 
3603 	for_each_node_state(nid, N_CPU) {
3604 		faults = group_faults_cpu(numa_group, nid);
3605 		if (faults > max_faults)
3606 			max_faults = faults;
3607 	}
3608 
3609 	for_each_node_state(nid, N_CPU) {
3610 		faults = group_faults_cpu(numa_group, nid);
3611 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
3612 			active_nodes++;
3613 	}
3614 
3615 	numa_group->max_faults_cpu = max_faults;
3616 	numa_group->active_nodes = active_nodes;
3617 }
3618 
3619 /*
3620  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
3621  * increments. The more local the fault statistics are, the higher the scan
3622  * period will be for the next scan window. If local/(local+remote) ratio is
3623  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
3624  * the scan period will decrease. Aim for 70% local accesses.
3625  */
3626 #define NUMA_PERIOD_SLOTS 10
3627 #define NUMA_PERIOD_THRESHOLD 7
3628 
3629 /*
3630  * Increase the scan period (slow down scanning) if the majority of
3631  * our memory is already on our local node, or if the majority of
3632  * the page accesses are shared with other processes.
3633  * Otherwise, decrease the scan period.
3634  */
3635 static void update_task_scan_period(struct task_struct *p,
3636 			unsigned long shared, unsigned long private)
3637 {
3638 	unsigned int period_slot;
3639 	int lr_ratio, ps_ratio;
3640 	int diff;
3641 
3642 	unsigned long remote = p->numa_faults_locality[0];
3643 	unsigned long local = p->numa_faults_locality[1];
3644 
3645 	/*
3646 	 * If there were no record hinting faults then either the task is
3647 	 * completely idle or all activity is in areas that are not of interest
3648 	 * to automatic numa balancing. Related to that, if there were failed
3649 	 * migration then it implies we are migrating too quickly or the local
3650 	 * node is overloaded. In either case, scan slower
3651 	 */
3652 	if (local + shared == 0 || p->numa_faults_locality[2]) {
3653 		p->numa_scan_period = min(p->numa_scan_period_max,
3654 			p->numa_scan_period << 1);
3655 
3656 		p->mm->numa_next_scan = jiffies +
3657 			msecs_to_jiffies(p->numa_scan_period);
3658 
3659 		goto out;
3660 	}
3661 
3662 	/*
3663 	 * Prepare to scale scan period relative to the current period.
3664 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
3665 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
3666 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
3667 	 */
3668 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
3669 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
3670 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
3671 
3672 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
3673 		/*
3674 		 * Most memory accesses are local. There is no need to
3675 		 * do fast NUMA scanning, since memory is already local.
3676 		 */
3677 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
3678 		if (!slot)
3679 			slot = 1;
3680 		diff = slot * period_slot;
3681 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
3682 		/*
3683 		 * Most memory accesses are shared with other tasks.
3684 		 * There is no point in continuing fast NUMA scanning,
3685 		 * since other tasks may just move the memory elsewhere.
3686 		 */
3687 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
3688 		if (!slot)
3689 			slot = 1;
3690 		diff = slot * period_slot;
3691 	} else {
3692 		/*
3693 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
3694 		 * yet they are not on the local NUMA node. Speed up
3695 		 * NUMA scanning to get the memory moved over.
3696 		 */
3697 		int ratio = max(lr_ratio, ps_ratio);
3698 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
3699 	}
3700 
3701 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
3702 			task_scan_min(p), task_scan_max(p));
3703 
3704 out:
3705 	memset(p->numa_faults_locality, 0,
3706 	       sizeof(p->numa_faults_locality));
3707 }
3708 
3709 /*
3710  * Get the fraction of time the task has been running since the last
3711  * NUMA placement cycle. The scheduler keeps similar statistics, but
3712  * decays those on a 32ms period, which is orders of magnitude off
3713  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
3714  * stats only if the task is so new there are no NUMA statistics yet.
3715  */
3716 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
3717 {
3718 	u64 runtime, delta, now;
3719 	/* Use the start of this time slice to avoid calculations. */
3720 	now = p->se.exec_start;
3721 	runtime = p->se.sum_exec_runtime;
3722 
3723 	if (p->last_task_numa_placement) {
3724 		delta = runtime - p->last_sum_exec_runtime;
3725 		*period = now - p->last_task_numa_placement;
3726 
3727 		/* Avoid time going backwards, prevent potential divide error: */
3728 		if (unlikely((s64)*period < 0))
3729 			*period = 0;
3730 	} else {
3731 		delta = p->se.avg.load_sum;
3732 		*period = LOAD_AVG_MAX;
3733 	}
3734 
3735 	p->last_sum_exec_runtime = runtime;
3736 	p->last_task_numa_placement = now;
3737 
3738 	return delta;
3739 }
3740 
3741 /*
3742  * Determine the preferred nid for a task in a numa_group. This needs to
3743  * be done in a way that produces consistent results with group_weight,
3744  * otherwise workloads might not converge.
3745  */
3746 static int preferred_group_nid(struct task_struct *p, int nid)
3747 {
3748 	nodemask_t nodes;
3749 	int dist;
3750 
3751 	/* Direct connections between all NUMA nodes. */
3752 	if (sched_numa_topology_type == NUMA_DIRECT)
3753 		return nid;
3754 
3755 	/*
3756 	 * On a system with glueless mesh NUMA topology, group_weight
3757 	 * scores nodes according to the number of NUMA hinting faults on
3758 	 * both the node itself, and on nearby nodes.
3759 	 */
3760 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
3761 		unsigned long score, max_score = 0;
3762 		int node, max_node = nid;
3763 
3764 		dist = sched_max_numa_distance;
3765 
3766 		for_each_node_state(node, N_CPU) {
3767 			score = group_weight(p, node, dist);
3768 			if (score > max_score) {
3769 				max_score = score;
3770 				max_node = node;
3771 			}
3772 		}
3773 		return max_node;
3774 	}
3775 
3776 	/*
3777 	 * Finding the preferred nid in a system with NUMA backplane
3778 	 * interconnect topology is more involved. The goal is to locate
3779 	 * tasks from numa_groups near each other in the system, and
3780 	 * untangle workloads from different sides of the system. This requires
3781 	 * searching down the hierarchy of node groups, recursively searching
3782 	 * inside the highest scoring group of nodes. The nodemask tricks
3783 	 * keep the complexity of the search down.
3784 	 */
3785 	nodes = node_states[N_CPU];
3786 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
3787 		unsigned long max_faults = 0;
3788 		nodemask_t max_group = NODE_MASK_NONE;
3789 		int a, b;
3790 
3791 		/* Are there nodes at this distance from each other? */
3792 		if (!find_numa_distance(dist))
3793 			continue;
3794 
3795 		for_each_node_mask(a, nodes) {
3796 			unsigned long faults = 0;
3797 			nodemask_t this_group;
3798 			nodes_clear(this_group);
3799 
3800 			/* Sum group's NUMA faults; includes a==b case. */
3801 			for_each_node_mask(b, nodes) {
3802 				if (node_distance(a, b) < dist) {
3803 					faults += group_faults(p, b);
3804 					node_set(b, this_group);
3805 					node_clear(b, nodes);
3806 				}
3807 			}
3808 
3809 			/* Remember the top group. */
3810 			if (faults > max_faults) {
3811 				max_faults = faults;
3812 				max_group = this_group;
3813 				/*
3814 				 * subtle: at the smallest distance there is
3815 				 * just one node left in each "group", the
3816 				 * winner is the preferred nid.
3817 				 */
3818 				nid = a;
3819 			}
3820 		}
3821 		/* Next round, evaluate the nodes within max_group. */
3822 		if (!max_faults)
3823 			break;
3824 		nodes = max_group;
3825 	}
3826 	return nid;
3827 }
3828 
3829 static void task_numa_placement(struct task_struct *p)
3830 	__context_unsafe(/* conditional locking */)
3831 {
3832 	struct sched_cache_group __maybe_unused *grp;
3833 	int seq, nid, max_nid = NUMA_NO_NODE;
3834 	unsigned long max_faults = 0;
3835 	unsigned long fault_types[2] = { 0, 0 };
3836 	unsigned long total_faults;
3837 	u64 runtime, period;
3838 	spinlock_t *group_lock = NULL;
3839 	long __maybe_unused new_fp;
3840 	struct numa_group *ng;
3841 
3842 	/*
3843 	 * The p->mm->numa_scan_seq field gets updated without
3844 	 * exclusive access. Use READ_ONCE() here to ensure
3845 	 * that the field is read in a single access:
3846 	 */
3847 	seq = READ_ONCE(p->mm->numa_scan_seq);
3848 	if (p->numa_scan_seq == seq)
3849 		return;
3850 	p->numa_scan_seq = seq;
3851 	p->numa_scan_period_max = task_scan_max(p);
3852 
3853 	total_faults = p->numa_faults_locality[0] +
3854 		       p->numa_faults_locality[1];
3855 	runtime = numa_get_avg_runtime(p, &period);
3856 
3857 	/* If the task is part of a group prevent parallel updates to group stats */
3858 	ng = deref_curr_numa_group(p);
3859 	if (ng) {
3860 		group_lock = &ng->lock;
3861 		spin_lock_irq(group_lock);
3862 	}
3863 
3864 	/* Find the node with the highest number of faults */
3865 	for_each_online_node(nid) {
3866 		/* Keep track of the offsets in numa_faults array */
3867 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
3868 		unsigned long faults = 0, group_faults = 0;
3869 		int priv;
3870 
3871 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
3872 			long diff, f_diff, f_weight;
3873 
3874 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
3875 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
3876 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
3877 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
3878 
3879 			/* Decay existing window, copy faults since last scan */
3880 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
3881 			fault_types[priv] += p->numa_faults[membuf_idx];
3882 			p->numa_faults[membuf_idx] = 0;
3883 
3884 			/*
3885 			 * Normalize the faults_from, so all tasks in a group
3886 			 * count according to CPU use, instead of by the raw
3887 			 * number of faults. Tasks with little runtime have
3888 			 * little over-all impact on throughput, and thus their
3889 			 * faults are less important.
3890 			 */
3891 			f_weight = div64_u64(runtime << 16, period + 1);
3892 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
3893 				   (total_faults + 1);
3894 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
3895 			p->numa_faults[cpubuf_idx] = 0;
3896 
3897 			p->numa_faults[mem_idx] += diff;
3898 			p->numa_faults[cpu_idx] += f_diff;
3899 			faults += p->numa_faults[mem_idx];
3900 			p->total_numa_faults += diff;
3901 			if (ng) {
3902 				/*
3903 				 * safe because we can only change our own group
3904 				 *
3905 				 * mem_idx represents the offset for a given
3906 				 * nid and priv in a specific region because it
3907 				 * is at the beginning of the numa_faults array.
3908 				 */
3909 				ng->faults[mem_idx] += diff;
3910 				ng->faults[cpu_idx] += f_diff;
3911 				ng->total_faults += diff;
3912 				group_faults += ng->faults[mem_idx];
3913 			}
3914 #ifdef CONFIG_SCHED_CACHE
3915 			/*
3916 			 * Per task p->numa_faults[mem_idx] converges,
3917 			 * so the accumulation of each task's faults
3918 			 * converges too - Given the number of threads,
3919 			 * it cannot overflow an unsigned long.
3920 			 * Racy with concurrent updates from other threads
3921 			 * sharing this mm. Acceptable since footprint is a
3922 			 * heuristic and occasional lost updates are tolerable.
3923 			 *
3924 			 * If a task exits, its corresponding footprint must
3925 			 * be subtracted from p->sched_cache_grp->footprint,
3926 			 * otherwise the footprint will not converge: the
3927 			 * exiting thread's footprint remains unchanged/undecayed.
3928 			 * See exit_mm().
3929 			 *
3930 			 * Lost updates and unsynchronized subtraction
3931 			 * in exit_mm() can cause footprint + diff to
3932 			 * go negative. Clamp to zero to prevent the
3933 			 * unsigned footprint from wrapping.
3934 			 */
3935 			scoped_guard(rcu) {
3936 				grp = rcu_dereference(p->sched_cache_grp);
3937 
3938 				if (grp) {
3939 					new_fp = (long)READ_ONCE(grp->footprint) + diff;
3940 					WRITE_ONCE(grp->footprint, max(new_fp, 0L));
3941 				}
3942 			}
3943 #endif
3944 		}
3945 
3946 		if (!ng) {
3947 			if (faults > max_faults) {
3948 				max_faults = faults;
3949 				max_nid = nid;
3950 			}
3951 		} else if (group_faults > max_faults) {
3952 			max_faults = group_faults;
3953 			max_nid = nid;
3954 		}
3955 	}
3956 
3957 	/* Cannot migrate task to CPU-less node */
3958 	max_nid = numa_nearest_node(max_nid, N_CPU);
3959 
3960 	if (ng) {
3961 		numa_group_count_active_nodes(ng);
3962 		spin_unlock_irq(group_lock);
3963 		max_nid = preferred_group_nid(p, max_nid);
3964 	}
3965 
3966 	if (max_faults) {
3967 		/* Set the new preferred node */
3968 		if (max_nid != p->numa_preferred_nid)
3969 			sched_setnuma(p, max_nid);
3970 	}
3971 
3972 	update_task_scan_period(p, fault_types[0], fault_types[1]);
3973 }
3974 
3975 static inline int get_numa_group(struct numa_group *grp)
3976 {
3977 	return refcount_inc_not_zero(&grp->refcount);
3978 }
3979 
3980 static inline void put_numa_group(struct numa_group *grp)
3981 {
3982 	if (refcount_dec_and_test(&grp->refcount))
3983 		kfree_rcu(grp, rcu);
3984 }
3985 
3986 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3987 			int *priv)
3988 {
3989 	struct numa_group *grp, *my_grp;
3990 	struct task_struct *tsk;
3991 	bool join = false;
3992 	int cpu = cpupid_to_cpu(cpupid);
3993 	int i;
3994 
3995 	if (unlikely(!deref_curr_numa_group(p))) {
3996 		unsigned int size = sizeof(struct numa_group) +
3997 				    NR_NUMA_HINT_FAULT_STATS *
3998 				    nr_node_ids * sizeof(unsigned long);
3999 
4000 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
4001 		if (!grp)
4002 			return;
4003 
4004 		refcount_set(&grp->refcount, 1);
4005 		grp->active_nodes = 1;
4006 		grp->max_faults_cpu = 0;
4007 		spin_lock_init(&grp->lock);
4008 		grp->gid = p->pid;
4009 
4010 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4011 			grp->faults[i] = p->numa_faults[i];
4012 
4013 		grp->total_faults = p->total_numa_faults;
4014 
4015 		grp->nr_tasks++;
4016 		rcu_assign_pointer(p->numa_group, grp);
4017 	}
4018 
4019 	rcu_read_lock();
4020 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
4021 
4022 	if (!cpupid_match_pid(tsk, cpupid))
4023 		goto no_join;
4024 
4025 	grp = rcu_dereference_all(tsk->numa_group);
4026 	if (!grp)
4027 		goto no_join;
4028 
4029 	my_grp = deref_curr_numa_group(p);
4030 	if (grp == my_grp)
4031 		goto no_join;
4032 
4033 	/*
4034 	 * Only join the other group if its bigger; if we're the bigger group,
4035 	 * the other task will join us.
4036 	 */
4037 	if (my_grp->nr_tasks > grp->nr_tasks)
4038 		goto no_join;
4039 
4040 	/*
4041 	 * Tie-break on the grp address.
4042 	 */
4043 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
4044 		goto no_join;
4045 
4046 	/* Always join threads in the same process. */
4047 	if (tsk->mm == current->mm)
4048 		join = true;
4049 
4050 	/* Simple filter to avoid false positives due to PID collisions */
4051 	if (flags & TNF_SHARED)
4052 		join = true;
4053 
4054 	/* Update priv based on whether false sharing was detected */
4055 	*priv = !join;
4056 
4057 	if (join && !get_numa_group(grp))
4058 		goto no_join;
4059 
4060 	rcu_read_unlock();
4061 
4062 	if (!join)
4063 		return;
4064 
4065 	WARN_ON_ONCE(irqs_disabled());
4066 	double_lock_irq(&my_grp->lock, &grp->lock);
4067 
4068 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
4069 		my_grp->faults[i] -= p->numa_faults[i];
4070 		grp->faults[i] += p->numa_faults[i];
4071 	}
4072 	my_grp->total_faults -= p->total_numa_faults;
4073 	grp->total_faults += p->total_numa_faults;
4074 
4075 	my_grp->nr_tasks--;
4076 	grp->nr_tasks++;
4077 
4078 	spin_unlock(&my_grp->lock);
4079 	spin_unlock_irq(&grp->lock);
4080 
4081 	rcu_assign_pointer(p->numa_group, grp);
4082 
4083 	put_numa_group(my_grp);
4084 	return;
4085 
4086 no_join:
4087 	rcu_read_unlock();
4088 	return;
4089 }
4090 
4091 /*
4092  * Get rid of NUMA statistics associated with a task (either current or dead).
4093  * If @final is set, the task is dead and has reached refcount zero, so we can
4094  * safely free all relevant data structures. Otherwise, there might be
4095  * concurrent reads from places like load balancing and procfs, and we should
4096  * reset the data back to default state without freeing ->numa_faults.
4097  */
4098 void task_numa_free(struct task_struct *p, bool final)
4099 {
4100 	/* safe: p either is current or is being freed by current */
4101 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
4102 	unsigned long *numa_faults = p->numa_faults;
4103 	unsigned long flags;
4104 	int i;
4105 
4106 	if (!numa_faults)
4107 		return;
4108 
4109 	if (grp) {
4110 		spin_lock_irqsave(&grp->lock, flags);
4111 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4112 			grp->faults[i] -= p->numa_faults[i];
4113 		grp->total_faults -= p->total_numa_faults;
4114 
4115 		grp->nr_tasks--;
4116 		spin_unlock_irqrestore(&grp->lock, flags);
4117 		RCU_INIT_POINTER(p->numa_group, NULL);
4118 		put_numa_group(grp);
4119 	}
4120 
4121 	if (final) {
4122 		p->numa_faults = NULL;
4123 		kfree(numa_faults);
4124 	} else {
4125 		p->total_numa_faults = 0;
4126 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
4127 			numa_faults[i] = 0;
4128 	}
4129 }
4130 
4131 /*
4132  * Got a PROT_NONE fault for a page on @node.
4133  */
4134 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
4135 {
4136 	struct task_struct *p = current;
4137 	bool migrated = flags & TNF_MIGRATED;
4138 	int cpu_node = task_node(current);
4139 	int local = !!(flags & TNF_FAULT_LOCAL);
4140 	struct numa_group *ng;
4141 	int priv;
4142 
4143 	if (!static_branch_likely(&sched_numa_balancing))
4144 		return;
4145 
4146 	/* for example, ksmd faulting in a user's mm */
4147 	if (!p->mm)
4148 		return;
4149 
4150 	/*
4151 	 * NUMA faults statistics are unnecessary for the slow memory
4152 	 * node for memory tiering mode.
4153 	 */
4154 	if (!node_is_toptier(mem_node) &&
4155 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
4156 	     !cpupid_valid(last_cpupid)))
4157 		return;
4158 
4159 	/* Allocate buffer to track faults on a per-node basis */
4160 	if (unlikely(!p->numa_faults)) {
4161 		int size = sizeof(*p->numa_faults) *
4162 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
4163 
4164 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
4165 		if (!p->numa_faults)
4166 			return;
4167 
4168 		p->total_numa_faults = 0;
4169 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
4170 	}
4171 
4172 	/*
4173 	 * First accesses are treated as private, otherwise consider accesses
4174 	 * to be private if the accessing pid has not changed
4175 	 */
4176 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
4177 		priv = 1;
4178 	} else {
4179 		priv = cpupid_match_pid(p, last_cpupid);
4180 		if (!priv && !(flags & TNF_NO_GROUP))
4181 			task_numa_group(p, last_cpupid, flags, &priv);
4182 	}
4183 
4184 	/*
4185 	 * If a workload spans multiple NUMA nodes, a shared fault that
4186 	 * occurs wholly within the set of nodes that the workload is
4187 	 * actively using should be counted as local. This allows the
4188 	 * scan rate to slow down when a workload has settled down.
4189 	 */
4190 	ng = deref_curr_numa_group(p);
4191 	if (!priv && !local && ng && ng->active_nodes > 1 &&
4192 				numa_is_active_node(cpu_node, ng) &&
4193 				numa_is_active_node(mem_node, ng))
4194 		local = 1;
4195 
4196 	/*
4197 	 * Retry to migrate task to preferred node periodically, in case it
4198 	 * previously failed, or the scheduler moved us.
4199 	 */
4200 	if (time_after(jiffies, p->numa_migrate_retry)) {
4201 		task_numa_placement(p);
4202 		numa_migrate_preferred(p);
4203 	}
4204 
4205 	if (migrated)
4206 		p->numa_pages_migrated += pages;
4207 	if (flags & TNF_MIGRATE_FAIL)
4208 		p->numa_faults_locality[2] += pages;
4209 
4210 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
4211 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
4212 	p->numa_faults_locality[local] += pages;
4213 }
4214 
4215 static void reset_ptenuma_scan(struct task_struct *p)
4216 {
4217 	/*
4218 	 * We only did a read acquisition of the mmap sem, so
4219 	 * p->mm->numa_scan_seq is written to without exclusive access
4220 	 * and the update is not guaranteed to be atomic. That's not
4221 	 * much of an issue though, since this is just used for
4222 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
4223 	 * expensive, to avoid any form of compiler optimizations:
4224 	 */
4225 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
4226 	p->mm->numa_scan_offset = 0;
4227 }
4228 
4229 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
4230 {
4231 	unsigned long pids;
4232 	/*
4233 	 * Allow unconditional access first two times, so that all the (pages)
4234 	 * of VMAs get prot_none fault introduced irrespective of accesses.
4235 	 * This is also done to avoid any side effect of task scanning
4236 	 * amplifying the unfairness of disjoint set of VMAs' access.
4237 	 */
4238 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
4239 		return true;
4240 
4241 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
4242 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
4243 		return true;
4244 
4245 	/*
4246 	 * Complete a scan that has already started regardless of PID access, or
4247 	 * some VMAs may never be scanned in multi-threaded applications:
4248 	 */
4249 	if (mm->numa_scan_offset > vma->vm_start) {
4250 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
4251 		return true;
4252 	}
4253 
4254 	/*
4255 	 * This vma has not been accessed for a while, and if the number
4256 	 * the threads in the same process is low, which means no other
4257 	 * threads can help scan this vma, force a vma scan.
4258 	 */
4259 	if (READ_ONCE(mm->numa_scan_seq) >
4260 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
4261 		return true;
4262 
4263 	return false;
4264 }
4265 
4266 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
4267 
4268 /*
4269  * The expensive part of numa migration is done from task_work context.
4270  * Triggered from task_tick_numa().
4271  */
4272 static void task_numa_work(struct callback_head *work)
4273 {
4274 	unsigned long migrate, next_scan, now = jiffies;
4275 	struct task_struct *p = current;
4276 	struct mm_struct *mm = p->mm;
4277 	u64 runtime = p->se.sum_exec_runtime;
4278 	struct vm_area_struct *vma;
4279 	unsigned long start, end;
4280 	unsigned long nr_pte_updates = 0;
4281 	long pages, virtpages;
4282 	struct vma_iterator vmi;
4283 	bool vma_pids_skipped;
4284 	bool vma_pids_forced = false;
4285 
4286 	WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
4287 
4288 	work->next = work;
4289 	/*
4290 	 * Who cares about NUMA placement when they're dying.
4291 	 *
4292 	 * NOTE: make sure not to dereference p->mm before this check,
4293 	 * exit_task_work() happens _after_ exit_mm() so we could be called
4294 	 * without p->mm even though we still had it when we enqueued this
4295 	 * work.
4296 	 */
4297 	if (p->flags & PF_EXITING)
4298 		return;
4299 
4300 	/*
4301 	 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
4302 	 * no page can be migrated.
4303 	 */
4304 	if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
4305 		trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
4306 		return;
4307 	}
4308 
4309 	if (!mm->numa_next_scan) {
4310 		mm->numa_next_scan = now +
4311 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4312 	}
4313 
4314 	/*
4315 	 * Enforce maximal scan/migration frequency..
4316 	 */
4317 	migrate = mm->numa_next_scan;
4318 	if (time_before(now, migrate))
4319 		return;
4320 
4321 	if (p->numa_scan_period == 0) {
4322 		p->numa_scan_period_max = task_scan_max(p);
4323 		p->numa_scan_period = task_scan_start(p);
4324 	}
4325 
4326 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
4327 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
4328 		return;
4329 
4330 	/*
4331 	 * Delay this task enough that another task of this mm will likely win
4332 	 * the next time around.
4333 	 */
4334 	p->node_stamp += 2 * TICK_NSEC;
4335 
4336 	pages = sysctl_numa_balancing_scan_size;
4337 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
4338 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
4339 	if (!pages)
4340 		return;
4341 
4342 
4343 	if (!mmap_read_trylock(mm))
4344 		return;
4345 
4346 	/*
4347 	 * VMAs are skipped if the current PID has not trapped a fault within
4348 	 * the VMA recently. Allow scanning to be forced if there is no
4349 	 * suitable VMA remaining.
4350 	 */
4351 	vma_pids_skipped = false;
4352 
4353 retry_pids:
4354 	start = mm->numa_scan_offset;
4355 	vma_iter_init(&vmi, mm, start);
4356 	vma = vma_next(&vmi);
4357 	if (!vma) {
4358 		reset_ptenuma_scan(p);
4359 		start = 0;
4360 		vma_iter_set(&vmi, start);
4361 		vma = vma_next(&vmi);
4362 	}
4363 
4364 	for (; vma; vma = vma_next(&vmi)) {
4365 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
4366 			vma_is_hugetlb(vma) || !vma_is_mm_managed(vma)) {
4367 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
4368 			continue;
4369 		}
4370 
4371 		/*
4372 		 * Shared library pages mapped by multiple processes are not
4373 		 * migrated as it is expected they are cache replicated. Avoid
4374 		 * hinting faults in read-only file-backed mappings or the vDSO
4375 		 * as migrating the pages will be of marginal benefit.
4376 		 */
4377 		if (!vma->vm_mm ||
4378 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
4379 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
4380 			continue;
4381 		}
4382 
4383 		/*
4384 		 * Skip inaccessible VMAs to avoid any confusion between
4385 		 * PROT_NONE and NUMA hinting PTEs
4386 		 */
4387 		if (!vma_is_accessible(vma)) {
4388 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
4389 			continue;
4390 		}
4391 
4392 		/* Initialise new per-VMA NUMAB state. */
4393 		if (!vma->numab_state) {
4394 			struct vma_numab_state *ptr;
4395 
4396 			ptr = kzalloc_obj(*ptr);
4397 			if (!ptr)
4398 				continue;
4399 
4400 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
4401 				kfree(ptr);
4402 				continue;
4403 			}
4404 
4405 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
4406 
4407 			vma->numab_state->next_scan = now +
4408 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4409 
4410 			/* Reset happens after 4 times scan delay of scan start */
4411 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
4412 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4413 
4414 			/*
4415 			 * Ensure prev_scan_seq does not match numa_scan_seq,
4416 			 * to prevent VMAs being skipped prematurely on the
4417 			 * first scan:
4418 			 */
4419 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
4420 		}
4421 
4422 		/*
4423 		 * Scanning the VMAs of short lived tasks add more overhead. So
4424 		 * delay the scan for new VMAs.
4425 		 */
4426 		if (mm->numa_scan_seq && time_before(jiffies,
4427 						vma->numab_state->next_scan)) {
4428 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
4429 			continue;
4430 		}
4431 
4432 		/* RESET access PIDs regularly for old VMAs. */
4433 		if (mm->numa_scan_seq &&
4434 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
4435 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
4436 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4437 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
4438 			vma->numab_state->pids_active[1] = 0;
4439 		}
4440 
4441 		/* Do not rescan VMAs twice within the same sequence. */
4442 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
4443 			mm->numa_scan_offset = vma->vm_end;
4444 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
4445 			continue;
4446 		}
4447 
4448 		/*
4449 		 * Do not scan the VMA if task has not accessed it, unless no other
4450 		 * VMA candidate exists.
4451 		 */
4452 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
4453 			vma_pids_skipped = true;
4454 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
4455 			continue;
4456 		}
4457 
4458 		do {
4459 			start = max(start, vma->vm_start);
4460 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
4461 			end = min(end, vma->vm_end);
4462 			nr_pte_updates = change_prot_numa(vma, start, end);
4463 
4464 			/*
4465 			 * Try to scan sysctl_numa_balancing_size worth of
4466 			 * hpages that have at least one present PTE that
4467 			 * is not already PTE-numa. If the VMA contains
4468 			 * areas that are unused or already full of prot_numa
4469 			 * PTEs, scan up to virtpages, to skip through those
4470 			 * areas faster.
4471 			 */
4472 			if (nr_pte_updates)
4473 				pages -= (end - start) >> PAGE_SHIFT;
4474 			virtpages -= (end - start) >> PAGE_SHIFT;
4475 
4476 			start = end;
4477 			if (pages <= 0 || virtpages <= 0)
4478 				goto out;
4479 
4480 			cond_resched();
4481 		} while (end != vma->vm_end);
4482 
4483 		/* VMA scan is complete, do not scan until next sequence. */
4484 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
4485 
4486 		/*
4487 		 * Only force scan within one VMA at a time, to limit the
4488 		 * cost of scanning a potentially uninteresting VMA.
4489 		 */
4490 		if (vma_pids_forced)
4491 			break;
4492 	}
4493 
4494 	/*
4495 	 * If no VMAs are remaining and VMAs were skipped due to the PID
4496 	 * not accessing the VMA previously, then force a scan to ensure
4497 	 * forward progress:
4498 	 */
4499 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
4500 		vma_pids_forced = true;
4501 		goto retry_pids;
4502 	}
4503 
4504 out:
4505 	/*
4506 	 * It is possible to reach the end of the VMA list but the last few
4507 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
4508 	 * would find the !migratable VMA on the next scan but not reset the
4509 	 * scanner to the start so check it now.
4510 	 */
4511 	if (vma)
4512 		mm->numa_scan_offset = start;
4513 	else
4514 		reset_ptenuma_scan(p);
4515 	mmap_read_unlock(mm);
4516 
4517 	/*
4518 	 * Make sure tasks use at least 32x as much time to run other code
4519 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
4520 	 * Usually update_task_scan_period slows down scanning enough; on an
4521 	 * overloaded system we need to limit overhead on a per task basis.
4522 	 */
4523 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
4524 		u64 diff = p->se.sum_exec_runtime - runtime;
4525 		p->node_stamp += 32 * diff;
4526 	}
4527 }
4528 
4529 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
4530 {
4531 	int mm_users = 0;
4532 	struct mm_struct *mm = p->mm;
4533 
4534 	if (mm) {
4535 		mm_users = atomic_read(&mm->mm_users);
4536 		if (mm_users == 1) {
4537 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4538 			mm->numa_scan_seq = 0;
4539 		}
4540 	}
4541 	p->node_stamp			= 0;
4542 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
4543 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
4544 	p->numa_migrate_retry		= 0;
4545 	/* Protect against double add, see task_tick_numa and task_numa_work */
4546 	p->numa_work.next		= &p->numa_work;
4547 	p->numa_faults			= NULL;
4548 	p->numa_pages_migrated		= 0;
4549 	p->total_numa_faults		= 0;
4550 	RCU_INIT_POINTER(p->numa_group, NULL);
4551 	p->last_task_numa_placement	= 0;
4552 	p->last_sum_exec_runtime	= 0;
4553 
4554 	init_task_work(&p->numa_work, task_numa_work);
4555 
4556 	/* New address space, reset the preferred nid */
4557 	if (!(clone_flags & CLONE_VM)) {
4558 		p->numa_preferred_nid = NUMA_NO_NODE;
4559 		return;
4560 	}
4561 
4562 	/*
4563 	 * New thread, keep existing numa_preferred_nid which should be copied
4564 	 * already by arch_dup_task_struct but stagger when scans start.
4565 	 */
4566 	if (mm) {
4567 		unsigned int delay;
4568 
4569 		delay = min_t(unsigned int, task_scan_max(current),
4570 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
4571 		delay += 2 * TICK_NSEC;
4572 		p->node_stamp = delay;
4573 	}
4574 }
4575 
4576 /*
4577  * Drive the periodic memory faults..
4578  */
4579 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4580 {
4581 	struct callback_head *work = &curr->numa_work;
4582 	u64 period, now;
4583 
4584 	/*
4585 	 * We don't care about NUMA placement if we don't have memory.
4586 	 */
4587 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
4588 		return;
4589 
4590 	/*
4591 	 * Using runtime rather than walltime has the dual advantage that
4592 	 * we (mostly) drive the selection from busy threads and that the
4593 	 * task needs to have done some actual work before we bother with
4594 	 * NUMA placement.
4595 	 */
4596 	now = curr->se.sum_exec_runtime;
4597 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
4598 
4599 	if (now > curr->node_stamp + period) {
4600 		if (!curr->node_stamp)
4601 			curr->numa_scan_period = task_scan_start(curr);
4602 		curr->node_stamp += period;
4603 
4604 		if (!time_before(jiffies, curr->mm->numa_next_scan))
4605 			task_work_add(curr, work, TWA_RESUME);
4606 	}
4607 }
4608 
4609 static void update_scan_period(struct task_struct *p, int new_cpu)
4610 {
4611 	int src_nid = cpu_to_node(task_cpu(p));
4612 	int dst_nid = cpu_to_node(new_cpu);
4613 
4614 	if (!static_branch_likely(&sched_numa_balancing))
4615 		return;
4616 
4617 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
4618 		return;
4619 
4620 	if (src_nid == dst_nid)
4621 		return;
4622 
4623 	/*
4624 	 * Allow resets if faults have been trapped before one scan
4625 	 * has completed. This is most likely due to a new task that
4626 	 * is pulled cross-node due to wakeups or load balancing.
4627 	 */
4628 	if (p->numa_scan_seq) {
4629 		/*
4630 		 * Avoid scan adjustments if moving to the preferred
4631 		 * node or if the task was not previously running on
4632 		 * the preferred node.
4633 		 */
4634 		if (dst_nid == p->numa_preferred_nid ||
4635 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
4636 			src_nid != p->numa_preferred_nid))
4637 			return;
4638 	}
4639 
4640 	p->numa_scan_period = task_scan_start(p);
4641 }
4642 
4643 #else /* !CONFIG_NUMA_BALANCING: */
4644 
4645 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4646 {
4647 }
4648 
4649 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
4650 {
4651 }
4652 
4653 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
4654 {
4655 }
4656 
4657 static inline void update_scan_period(struct task_struct *p, int new_cpu)
4658 {
4659 }
4660 
4661 #endif /* !CONFIG_NUMA_BALANCING */
4662 
4663 static void
4664 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4665 {
4666 	WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4667 	update_load_add(&cfs_rq->load, se->load.weight);
4668 	if (entity_is_task(se)) {
4669 		struct task_struct *p = task_of(se);
4670 		struct rq *rq = rq_of(cfs_rq);
4671 
4672 		account_numa_enqueue(rq, p);
4673 		account_llc_enqueue(rq, p);
4674 		list_add(&se->group_node, &rq->cfs_tasks);
4675 	}
4676 	cfs_rq->nr_queued++;
4677 }
4678 
4679 static void
4680 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4681 {
4682 	WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4683 	update_load_sub(&cfs_rq->load, se->load.weight);
4684 	if (entity_is_task(se)) {
4685 		struct task_struct *p = task_of(se);
4686 		struct rq *rq = rq_of(cfs_rq);
4687 
4688 		account_numa_dequeue(rq, p);
4689 		account_llc_dequeue(rq, p);
4690 		list_del_init(&se->group_node);
4691 	}
4692 	cfs_rq->nr_queued--;
4693 }
4694 
4695 /*
4696  * Signed add and clamp on underflow.
4697  *
4698  * Explicitly do a load-store to ensure the intermediate value never hits
4699  * memory. This allows lockless observations without ever seeing the negative
4700  * values.
4701  */
4702 #define add_positive(_ptr, _val) do {                           \
4703 	typeof(_ptr) ptr = (_ptr);                              \
4704 	__signed_scalar_typeof(*ptr) val = (_val);              \
4705 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
4706 								\
4707 	res = var + val;                                        \
4708 								\
4709 	if (val < 0 && res > var)                               \
4710 		res = 0;                                        \
4711 								\
4712 	WRITE_ONCE(*ptr, res);                                  \
4713 } while (0)
4714 
4715 /*
4716  * Remove and clamp on negative, from a local variable.
4717  *
4718  * A variant of sub_positive(), which does not use explicit load-store
4719  * and is thus optimized for local variable updates.
4720  */
4721 #define lsub_positive(_ptr, _val) do {				\
4722 	typeof(_ptr) ptr = (_ptr);				\
4723 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
4724 } while (0)
4725 
4726 
4727 /*
4728  * Because of rounding, se->util_sum might ends up being +1 more than
4729  * cfs->util_sum. Although this is not a problem by itself, detaching
4730  * a lot of tasks with the rounding problem between 2 updates of
4731  * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4732  * cfs_util_avg is not.
4733  *
4734  * Check that util_sum is still above its lower bound for the new
4735  * util_avg. Given that period_contrib might have moved since the last
4736  * sync, we are only sure that util_sum must be above or equal to
4737  *    util_avg * minimum possible divider
4738  */
4739 #define __update_sa(sa, name, delta_avg, delta_sum) do {	\
4740 	add_positive(&(sa)->name##_avg, delta_avg);		\
4741 	add_positive(&(sa)->name##_sum, delta_sum);		\
4742 	(sa)->name##_sum = max_t(typeof((sa)->name##_sum),	\
4743 			       (sa)->name##_sum,		\
4744 			       (sa)->name##_avg * PELT_MIN_DIVIDER); \
4745 } while (0)
4746 
4747 static inline void
4748 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4749 {
4750 	__update_sa(&cfs_rq->avg, load, se->avg.load_avg,
4751 		    se_weight(se) * se->avg.load_sum);
4752 }
4753 
4754 static inline void
4755 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4756 {
4757 	__update_sa(&cfs_rq->avg, load, -se->avg.load_avg,
4758 		    se_weight(se) * -se->avg.load_sum);
4759 }
4760 
4761 static void
4762 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot)
4763 {
4764 	long old_weight = se->h_load.weight;
4765 
4766 	/*
4767 	 * VRUNTIME
4768 	 * --------
4769 	 *
4770 	 * COROLLARY #1: The virtual runtime of the entity needs to be
4771 	 * adjusted if re-weight at !0-lag point.
4772 	 *
4773 	 * Proof: For contradiction assume this is not true, so we can
4774 	 * re-weight without changing vruntime at !0-lag point.
4775 	 *
4776 	 *             Weight	VRuntime   Avg-VRuntime
4777 	 *     before    w          v            V
4778 	 *      after    w'         v'           V'
4779 	 *
4780 	 * Since lag needs to be preserved through re-weight:
4781 	 *
4782 	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
4783 	 *	==>	V' = (V - v)*w/w' + v		(1)
4784 	 *
4785 	 * Let W be the total weight of the entities before reweight,
4786 	 * since V' is the new weighted average of entities:
4787 	 *
4788 	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
4789 	 *
4790 	 * by using (1) & (2) we obtain:
4791 	 *
4792 	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
4793 	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
4794 	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
4795 	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
4796 	 *
4797 	 * Since we are doing at !0-lag point which means V != v, we
4798 	 * can simplify (3):
4799 	 *
4800 	 *	==>	W / (W + w' - w) = w / w'
4801 	 *	==>	Ww' = Ww + ww' - ww
4802 	 *	==>	W * (w' - w) = w * (w' - w)
4803 	 *	==>	W = w	(re-weight indicates w' != w)
4804 	 *
4805 	 * So the cfs_rq contains only one entity, hence vruntime of
4806 	 * the entity @v should always equal to the cfs_rq's weighted
4807 	 * average vruntime @V, which means we will always re-weight
4808 	 * at 0-lag point, thus breach assumption. Proof completed.
4809 	 *
4810 	 *
4811 	 * COROLLARY #2: Re-weight does NOT affect weighted average
4812 	 * vruntime of all the entities.
4813 	 *
4814 	 * Proof: According to corollary #1, Eq. (1) should be:
4815 	 *
4816 	 *	(V - v)*w = (V' - v')*w'
4817 	 *	==>    v' = V' - (V - v)*w/w'		(4)
4818 	 *
4819 	 * According to the weighted average formula, we have:
4820 	 *
4821 	 *	V' = (WV - wv + w'v') / (W - w + w')
4822 	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
4823 	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
4824 	 *	   = (WV + w'V' - Vw) / (W - w + w')
4825 	 *
4826 	 *	==>  V'*(W - w + w') = WV + w'V' - Vw
4827 	 *	==>	V' * (W - w) = (W - w) * V	(5)
4828 	 *
4829 	 * If the entity is the only one in the cfs_rq, then reweight
4830 	 * always occurs at 0-lag point, so V won't change. Or else
4831 	 * there are other entities, hence W != w, then Eq. (5) turns
4832 	 * into V' = V. So V won't change in either case, proof done.
4833 	 *
4834 	 *
4835 	 * So according to corollary #1 & #2, the effect of re-weight
4836 	 * on vruntime should be:
4837 	 *
4838 	 *	v' = V' - (V - v) * w / w'		(4)
4839 	 *	   = V  - (V - v) * w / w'
4840 	 *	   = V  - vl * w / w'
4841 	 *	   = V  - vl'
4842 	 */
4843 	se->vlag = div64_long(se->vlag * old_weight, weight);
4844 
4845 	/*
4846 	 * DEADLINE
4847 	 * --------
4848 	 *
4849 	 * When the weight changes, the virtual time slope changes and
4850 	 * we should adjust the relative virtual deadline accordingly.
4851 	 *
4852 	 *	d' = v' + (d - v)*w/w'
4853 	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
4854 	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
4855 	 *	   = V  + (d - V)*w/w'
4856 	 */
4857 	if (se->rel_deadline)
4858 		se->deadline = div64_long(se->deadline * old_weight, weight);
4859 
4860 	if (rel_vprot)
4861 		se->vprot = div64_long(se->vprot * old_weight, weight);
4862 }
4863 
4864 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se,
4865 			   unsigned long weight, bool on_rq)
4866 {
4867 	bool curr = cfs_rq->curr == se;
4868 	bool rel_vprot = false;
4869 	u64 avruntime = 0;
4870 
4871 	if (se->h_load.weight == weight)
4872 		return;
4873 
4874 	if (on_rq) {
4875 		avruntime = avg_vruntime(cfs_rq);
4876 		se->vlag = entity_lag(cfs_rq, se, avruntime);
4877 		se->deadline -= avruntime;
4878 		se->rel_deadline = 1;
4879 		if (curr && protect_slice(se)) {
4880 			se->vprot -= avruntime;
4881 			rel_vprot = true;
4882 		}
4883 
4884 		cfs_rq->h_nr_queued--;
4885 		if (!curr)
4886 			__dequeue_entity(cfs_rq, se);
4887 	}
4888 
4889 	rescale_entity(se, weight, rel_vprot);
4890 
4891 	update_load_set(&se->h_load, weight);
4892 
4893 	if (on_rq) {
4894 		if (rel_vprot)
4895 			se->vprot += avruntime;
4896 		se->deadline += avruntime;
4897 		se->rel_deadline = 0;
4898 		se->vruntime = avruntime - se->vlag;
4899 
4900 		if (!curr)
4901 			__enqueue_entity(cfs_rq, se);
4902 		cfs_rq->h_nr_queued++;
4903 	}
4904 }
4905 
4906 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
4907 			    unsigned long weight)
4908 {
4909 	if (se->load.weight == weight)
4910 		return;
4911 
4912 	if (se->on_rq) {
4913 		WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4914 		update_load_sub(&cfs_rq->load, se->load.weight);
4915 	}
4916 	dequeue_load_avg(cfs_rq, se);
4917 
4918 	update_load_set(&se->load, weight);
4919 
4920 	do {
4921 		u32 divider = get_pelt_divider(&se->avg);
4922 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
4923 	} while (0);
4924 
4925 	enqueue_load_avg(cfs_rq, se);
4926 
4927 	if (se->on_rq)
4928 		update_load_add(&cfs_rq->load, se->load.weight);
4929 }
4930 
4931 /*
4932  * weight = NICE_0_LOAD;
4933  * for_each_entity_se(se)
4934  *   weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4935  */
4936 static __always_inline
4937 unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se,
4938 				 unsigned long weight)
4939 {
4940 	weight *= se->load.weight;
4941 	if (parent_entity(se))
4942 		weight /= cfs_rq->load.weight;
4943 	else
4944 		weight /= NICE_0_LOAD;
4945 
4946 	return max(weight, MIN_SHARES);
4947 }
4948 
4949 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
4950 			       const struct load_weight *lw)
4951 {
4952 	struct sched_entity *se = &p->se;
4953 	unsigned long weight = NICE_0_LOAD;
4954 
4955 	if (se->on_rq)
4956 		update_curr_fair(rq);
4957 
4958 	reweight_entity(cfs_rq_of(se), se, lw->weight);
4959 	se->load.inv_weight = lw->inv_weight;
4960 
4961 	if (!se->on_rq)
4962 		return;
4963 
4964 	for_each_sched_entity(se)
4965 		weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4966 
4967 	reweight_eevdf(&rq->cfs, &p->se, weight, p->se.on_rq);
4968 }
4969 
4970 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
4971 
4972 #ifdef CONFIG_FAIR_GROUP_SCHED
4973 /*
4974  * All this does is approximate the hierarchical proportion which includes that
4975  * global sum we all love to hate.
4976  *
4977  * That is, the weight of a group entity, is the proportional share of the
4978  * group weight based on the group runqueue weights. That is:
4979  *
4980  *                     tg->weight * grq->load.weight
4981  *   ge->load.weight = -----------------------------               (1)
4982  *                       \Sum grq->load.weight
4983  *
4984  * Now, because computing that sum is prohibitively expensive to compute (been
4985  * there, done that) we approximate it with this average stuff. The average
4986  * moves slower and therefore the approximation is cheaper and more stable.
4987  *
4988  * So instead of the above, we substitute:
4989  *
4990  *   grq->load.weight -> grq->avg.load_avg                         (2)
4991  *
4992  * which yields the following:
4993  *
4994  *                     tg->weight * grq->avg.load_avg
4995  *   ge->load.weight = ------------------------------              (3)
4996  *                             tg->load_avg
4997  *
4998  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
4999  *
5000  * That is shares_avg, and it is right (given the approximation (2)).
5001  *
5002  * The problem with it is that because the average is slow -- it was designed
5003  * to be exactly that of course -- this leads to transients in boundary
5004  * conditions. In specific, the case where the group was idle and we start the
5005  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
5006  * yielding bad latency etc..
5007  *
5008  * Now, in that special case (1) reduces to:
5009  *
5010  *                     tg->weight * grq->load.weight
5011  *   ge->load.weight = ----------------------------- = tg->weight   (4)
5012  *                         grp->load.weight
5013  *
5014  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
5015  *
5016  * So what we do is modify our approximation (3) to approach (4) in the (near)
5017  * UP case, like:
5018  *
5019  *   ge->load.weight =
5020  *
5021  *              tg->weight * grq->load.weight
5022  *     ---------------------------------------------------         (5)
5023  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
5024  *
5025  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
5026  * we need to use grq->avg.load_avg as its lower bound, which then gives:
5027  *
5028  *
5029  *                     tg->weight * grq->load.weight
5030  *   ge->load.weight = -----------------------------		   (6)
5031  *                             tg_load_avg'
5032  *
5033  * Where:
5034  *
5035  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
5036  *                  max(grq->load.weight, grq->avg.load_avg)
5037  *
5038  * And that is shares_weight and is icky. In the (near) UP case it approaches
5039  * (4) while in the normal case it approaches (3). It consistently
5040  * overestimates the ge->load.weight and therefore:
5041  *
5042  *   \Sum ge->load.weight >= tg->weight
5043  *
5044  * hence icky!
5045  */
5046 static long __calc_smp_shares(struct cfs_rq *cfs_rq, long tg_shares, long shares_max)
5047 {
5048 	struct task_group *tg = cfs_rq->tg;
5049 	long tg_weight, load, shares;
5050 
5051 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
5052 
5053 	tg_weight = atomic_long_read(&tg->load_avg);
5054 
5055 	/* Ensure tg_weight >= load */
5056 	tg_weight -= cfs_rq->tg_load_avg_contrib;
5057 	tg_weight += load;
5058 
5059 	shares = (tg_shares * load);
5060 	if (tg_weight)
5061 		shares /= tg_weight;
5062 
5063 	/*
5064 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
5065 	 * of a group with small tg->shares value. It is a floor value which is
5066 	 * assigned as a minimum load.weight to the sched_entity representing
5067 	 * the group on a CPU.
5068 	 *
5069 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
5070 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
5071 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
5072 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
5073 	 * instead of 0.
5074 	 */
5075 	return clamp_t(long, shares, MIN_SHARES, shares_max);
5076 }
5077 
5078 static int tg_cpus(struct task_group *tg)
5079 {
5080 	int nr = num_online_cpus();
5081 
5082 	if (cpusets_enabled()) {
5083 		struct cgroup *cgrp = tg->css.cgroup;
5084 		if (cgrp)
5085 			nr = cpuset_num_cpus(cgrp);
5086 	}
5087 
5088 	/*
5089 	 * An empty cpuset would propagate a 0 shares_max into
5090 	 * __calc_smp_shares(), where clamp() yields hi when hi < lo and so
5091 	 * defeats the MIN_SHARES floor. Match tg_tasks(), which floors at 1.
5092 	 */
5093 	return max(nr, 1);
5094 }
5095 
5096 static inline int tg_tasks(struct task_group *tg)
5097 {
5098 	return max(1, atomic_long_read(&tg->runnable_avg) >> SCHED_CAPACITY_SHIFT);
5099 }
5100 
5101 /*
5102  * Func: fraction(nr_tasks * tg->shares)
5103  *
5104  * Scale tg->shares by the number of tasks.
5105  */
5106 static long calc_tasks_shares(struct cfs_rq *cfs_rq)
5107 {
5108 	struct task_group *tg = cfs_rq->tg;
5109 	int nr = tg_tasks(tg);
5110 	long tg_shares = READ_ONCE(tg->shares);
5111 	return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
5112 }
5113 
5114 /*
5115  * Func: min(fraction(nr_cpus * tg->shares), nice -20)
5116  *
5117  * Scale tg->shares by the maximal number of CPUs; but clip the max shares at
5118  * nice -20, otherwise a single spinner on a 512 CPU machine would result in
5119  * 512*NICE_0_LOAD, which is also crazy.
5120  */
5121 static long calc_max_shares(struct cfs_rq *cfs_rq)
5122 {
5123 	struct task_group *tg = cfs_rq->tg;
5124 	int nr = tg_cpus(tg);
5125 	long tg_shares = READ_ONCE(tg->shares);
5126 	long max_shares = scale_load(sched_prio_to_weight[0]);
5127 	return __calc_smp_shares(cfs_rq, tg_shares * nr, max_shares);
5128 }
5129 
5130 /*
5131  * Func: fraction(nr * tg->shares); nr = min(nr_tasks, nr_cpus)
5132  *
5133  * Scales between "smp" and "max" in a natural way. No longer needs clipping
5134  * since there are no unnatural inflations like with "max".
5135  */
5136 static long calc_concur_shares(struct cfs_rq *cfs_rq)
5137 {
5138 	struct task_group *tg = cfs_rq->tg;
5139 	int nr = min(tg_tasks(tg), tg_cpus(tg));
5140 	long tg_shares = READ_ONCE(tg->shares);
5141 	return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
5142 }
5143 
5144 /*
5145  * Func: fraction(tg->shares)
5146  *
5147  * This infamously results in tiny shares when you have many CPUs.
5148  */
5149 static long calc_smp_shares(struct cfs_rq *cfs_rq)
5150 {
5151 	struct task_group *tg = cfs_rq->tg;
5152 	long tg_shares = READ_ONCE(tg->shares);
5153 	return __calc_smp_shares(cfs_rq, tg_shares, tg_shares);
5154 }
5155 
5156 /*
5157  * Ignore this pesky SMP stuff, use (4).
5158  */
5159 static long calc_up_shares(struct cfs_rq *cfs_rq)
5160 {
5161 	struct task_group *tg = cfs_rq->tg;
5162 	return READ_ONCE(tg->shares);
5163 }
5164 
5165 DEFINE_STATIC_CALL(calc_group_shares, calc_concur_shares);
5166 
5167 void __sched_cgroup_mode_update(int mode)
5168 {
5169 	long (*func)(struct cfs_rq *);
5170 	switch (mode) {
5171 	case 0:
5172 		func = &calc_up_shares;
5173 		break;
5174 	case 1:
5175 		func = &calc_smp_shares;
5176 		break;
5177 	case 2:
5178 	default:
5179 		func = &calc_concur_shares;
5180 		break;
5181 	case 3:
5182 		func = &calc_max_shares;
5183 		break;
5184 	case 4:
5185 		func = &calc_tasks_shares;
5186 		break;
5187 	}
5188 	static_call_update(calc_group_shares, func);
5189 }
5190 
5191 /*
5192  * Recomputes the group entity based on the current state of its group
5193  * runqueue.
5194  */
5195 static void update_cfs_group(struct sched_entity *se)
5196 {
5197 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5198 	long shares;
5199 
5200 	/*
5201 	 * When a group becomes empty, preserve its weight. This matters for
5202 	 * DELAY_DEQUEUE.
5203 	 */
5204 	if (!gcfs_rq || !gcfs_rq->load.weight)
5205 		return;
5206 
5207 	shares = static_call(calc_group_shares)(gcfs_rq);
5208 	reweight_entity(cfs_rq_of(se), se, shares);
5209 }
5210 
5211 #else /* !CONFIG_FAIR_GROUP_SCHED: */
5212 static inline void update_cfs_group(struct sched_entity *se)
5213 {
5214 }
5215 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5216 
5217 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
5218 {
5219 	struct rq *rq = rq_of(cfs_rq);
5220 
5221 	if (&rq->cfs == cfs_rq) {
5222 		/*
5223 		 * There are a few boundary cases this might miss but it should
5224 		 * get called often enough that that should (hopefully) not be
5225 		 * a real problem.
5226 		 *
5227 		 * It will not get called when we go idle, because the idle
5228 		 * thread is a different class (!fair), nor will the utilization
5229 		 * number include things like RT tasks.
5230 		 *
5231 		 * As is, the util number is not freq-invariant (we'd have to
5232 		 * implement arch_scale_freq_capacity() for that).
5233 		 *
5234 		 * See cpu_util_cfs().
5235 		 */
5236 		cpufreq_update_util(rq, flags);
5237 	}
5238 }
5239 
5240 static inline bool load_avg_is_decayed(struct sched_avg *sa)
5241 {
5242 	if (sa->load_sum)
5243 		return false;
5244 
5245 	if (sa->util_sum)
5246 		return false;
5247 
5248 	if (sa->runnable_sum)
5249 		return false;
5250 
5251 	/*
5252 	 * _avg must be null when _sum are null because _avg = _sum / divider
5253 	 * Make sure that rounding and/or propagation of PELT values never
5254 	 * break this.
5255 	 */
5256 	WARN_ON_ONCE(sa->load_avg ||
5257 		      sa->util_avg ||
5258 		      sa->runnable_avg);
5259 
5260 	return true;
5261 }
5262 
5263 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
5264 {
5265 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
5266 				 cfs_rq->last_update_time_copy);
5267 }
5268 #ifdef CONFIG_FAIR_GROUP_SCHED
5269 /*
5270  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
5271  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
5272  * bottom-up, we only have to test whether the cfs_rq before us on the list
5273  * is our child.
5274  * If cfs_rq is not on the list, test whether a child needs its to be added to
5275  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
5276  */
5277 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
5278 {
5279 	struct cfs_rq *prev_cfs_rq;
5280 	struct list_head *prev;
5281 	struct rq *rq = rq_of(cfs_rq);
5282 
5283 	if (cfs_rq->on_list) {
5284 		prev = cfs_rq->leaf_cfs_rq_list.prev;
5285 	} else {
5286 		prev = rq->tmp_alone_branch;
5287 	}
5288 
5289 	if (prev == &rq->leaf_cfs_rq_list)
5290 		return false;
5291 
5292 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
5293 
5294 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
5295 }
5296 
5297 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5298 {
5299 	if (cfs_rq->load.weight)
5300 		return false;
5301 
5302 	if (!load_avg_is_decayed(&cfs_rq->avg))
5303 		return false;
5304 
5305 	if (child_cfs_rq_on_list(cfs_rq))
5306 		return false;
5307 
5308 	if (cfs_rq->tg_load_avg_contrib)
5309 		return false;
5310 
5311 	return true;
5312 }
5313 
5314 /**
5315  * update_tg_load_avg - update the tg's load avg
5316  * @cfs_rq: the cfs_rq whose avg changed
5317  *
5318  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
5319  * However, because tg->load_avg is a global value there are performance
5320  * considerations.
5321  *
5322  * In order to avoid having to look at the other cfs_rq's, we use a
5323  * differential update where we store the last value we propagated. This in
5324  * turn allows skipping updates if the differential is 'small'.
5325  *
5326  * Updating tg's load_avg is necessary before update_cfs_group().
5327  */
5328 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
5329 {
5330 	long dl, dr;
5331 	u64 now;
5332 
5333 	/*
5334 	 * No need to update load_avg for root_task_group as it is not used.
5335 	 */
5336 	if (cfs_rq->tg == &root_task_group)
5337 		return;
5338 
5339 	/* rq has been offline and doesn't contribute to the share anymore: */
5340 	if (!cpu_active(cpu_of(rq_of(cfs_rq))))
5341 		return;
5342 
5343 	/*
5344 	 * For migration heavy workloads, access to tg->load_avg can be
5345 	 * unbound. Limit the update rate to at most once per ms.
5346 	 */
5347 	now = rq_clock(rq_of(cfs_rq));
5348 	if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
5349 		return;
5350 
5351 	dl = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
5352 	dr = cfs_rq->avg.runnable_avg - cfs_rq->tg_runnable_avg_contrib;
5353 	if (abs(dl) > cfs_rq->tg_load_avg_contrib / 64 ||
5354 	    abs(dr) > cfs_rq->tg_runnable_avg_contrib / 64) {
5355 		atomic_long_add(dl, &cfs_rq->tg->load_avg);
5356 		atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5357 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
5358 		cfs_rq->tg_runnable_avg_contrib = cfs_rq->avg.runnable_avg;
5359 		cfs_rq->last_update_tg_load_avg = now;
5360 	}
5361 }
5362 
5363 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
5364 {
5365 	long dl, dr;
5366 	u64 now;
5367 
5368 	/*
5369 	 * No need to update load_avg for root_task_group, as it is not used.
5370 	 */
5371 	if (cfs_rq->tg == &root_task_group)
5372 		return;
5373 
5374 	now = rq_clock(rq_of(cfs_rq));
5375 	dl = 0 - cfs_rq->tg_load_avg_contrib;
5376 	dr = 0 - cfs_rq->tg_runnable_avg_contrib;
5377 	atomic_long_add(dl, &cfs_rq->tg->load_avg);
5378 	atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5379 	cfs_rq->tg_load_avg_contrib = 0;
5380 	cfs_rq->tg_runnable_avg_contrib = 0;
5381 	cfs_rq->last_update_tg_load_avg = now;
5382 }
5383 
5384 /* CPU offline callback: */
5385 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
5386 {
5387 	struct task_group *tg;
5388 
5389 	lockdep_assert_rq_held(rq);
5390 
5391 	/*
5392 	 * The rq clock has already been updated in
5393 	 * set_rq_offline(), so we should skip updating
5394 	 * the rq clock again in unthrottle_cfs_rq().
5395 	 */
5396 	rq_clock_start_loop_update(rq);
5397 
5398 	guard(rcu)();
5399 
5400 	list_for_each_entry_rcu(tg, &task_groups, list) {
5401 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
5402 
5403 		clear_tg_load_avg(cfs_rq);
5404 	}
5405 
5406 	rq_clock_stop_loop_update(rq);
5407 }
5408 
5409 /*
5410  * Called within set_task_rq() right before setting a task's CPU. The
5411  * caller only guarantees p->pi_lock is held; no other assumptions,
5412  * including the state of rq->lock, should be made.
5413  */
5414 void set_task_rq_fair(struct sched_entity *se,
5415 		      struct cfs_rq *prev, struct cfs_rq *next)
5416 {
5417 	u64 p_last_update_time;
5418 	u64 n_last_update_time;
5419 
5420 	if (!sched_feat(ATTACH_AGE_LOAD))
5421 		return;
5422 
5423 	/*
5424 	 * We are supposed to update the task to "current" time, then its up to
5425 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
5426 	 * getting what current time is, so simply throw away the out-of-date
5427 	 * time. This will result in the wakee task is less decayed, but giving
5428 	 * the wakee more load sounds not bad.
5429 	 */
5430 	if (!(se->avg.last_update_time && prev))
5431 		return;
5432 
5433 	p_last_update_time = cfs_rq_last_update_time(prev);
5434 	n_last_update_time = cfs_rq_last_update_time(next);
5435 
5436 	__update_load_avg_blocked_se(p_last_update_time, se);
5437 	se->avg.last_update_time = n_last_update_time;
5438 }
5439 
5440 /*
5441  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
5442  * propagate its contribution. The key to this propagation is the invariant
5443  * that for each group:
5444  *
5445  *   ge->avg == grq->avg						(1)
5446  *
5447  * _IFF_ we look at the pure running and runnable sums. Because they
5448  * represent the very same entity, just at different points in the hierarchy.
5449  *
5450  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
5451  * and simply copies the running/runnable sum over (but still wrong, because
5452  * the group entity and group rq do not have their PELT windows aligned).
5453  *
5454  * However, update_tg_cfs_load() is more complex. So we have:
5455  *
5456  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
5457  *
5458  * And since, like util, the runnable part should be directly transferable,
5459  * the following would _appear_ to be the straight forward approach:
5460  *
5461  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
5462  *
5463  * And per (1) we have:
5464  *
5465  *   ge->avg.runnable_avg == grq->avg.runnable_avg
5466  *
5467  * Which gives:
5468  *
5469  *                      ge->load.weight * grq->avg.load_avg
5470  *   ge->avg.load_avg = -----------------------------------		(4)
5471  *                               grq->load.weight
5472  *
5473  * Except that is wrong!
5474  *
5475  * Because while for entities historical weight is not important and we
5476  * really only care about our future and therefore can consider a pure
5477  * runnable sum, runqueues can NOT do this.
5478  *
5479  * We specifically want runqueues to have a load_avg that includes
5480  * historical weights. Those represent the blocked load, the load we expect
5481  * to (shortly) return to us. This only works by keeping the weights as
5482  * integral part of the sum. We therefore cannot decompose as per (3).
5483  *
5484  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
5485  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
5486  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
5487  * runnable section of these tasks overlap (or not). If they were to perfectly
5488  * align the rq as a whole would be runnable 2/3 of the time. If however we
5489  * always have at least 1 runnable task, the rq as a whole is always runnable.
5490  *
5491  * So we'll have to approximate.. :/
5492  *
5493  * Given the constraint:
5494  *
5495  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
5496  *
5497  * We can construct a rule that adds runnable to a rq by assuming minimal
5498  * overlap.
5499  *
5500  * On removal, we'll assume each task is equally runnable; which yields:
5501  *
5502  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
5503  *
5504  * XXX: only do this for the part of runnable > running ?
5505  *
5506  */
5507 static inline void
5508 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5509 {
5510 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
5511 	u32 new_sum, divider;
5512 
5513 	/* Nothing to update */
5514 	if (!delta_avg)
5515 		return;
5516 
5517 	/*
5518 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5519 	 * See ___update_load_avg() for details.
5520 	 */
5521 	divider = get_pelt_divider(&cfs_rq->avg);
5522 
5523 	/* Set new sched_entity's utilization */
5524 	se->avg.util_avg = gcfs_rq->avg.util_avg;
5525 	new_sum = se->avg.util_avg * divider;
5526 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
5527 	se->avg.util_sum = new_sum;
5528 
5529 	/* Update parent cfs_rq utilization */
5530 	__update_sa(&cfs_rq->avg, util, delta_avg, delta_sum);
5531 }
5532 
5533 static inline void
5534 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5535 {
5536 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
5537 	u64 new_sum;
5538 	u32 divider;
5539 
5540 	/* Nothing to update */
5541 	if (!delta_avg)
5542 		return;
5543 
5544 	/*
5545 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5546 	 * See ___update_load_avg() for details.
5547 	 */
5548 	divider = get_pelt_divider(&cfs_rq->avg);
5549 
5550 	/* Set new sched_entity's runnable */
5551 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
5552 	new_sum = (u64)se->avg.runnable_avg * divider;
5553 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
5554 	se->avg.runnable_sum = new_sum;
5555 
5556 	/* Update parent cfs_rq runnable */
5557 	__update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum);
5558 }
5559 
5560 static inline void
5561 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5562 {
5563 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
5564 	unsigned long load_avg;
5565 	u64 load_sum = 0;
5566 	s64 delta_sum;
5567 	u32 divider;
5568 
5569 	if (!runnable_sum)
5570 		return;
5571 
5572 	gcfs_rq->prop_runnable_sum = 0;
5573 
5574 	/*
5575 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5576 	 * See ___update_load_avg() for details.
5577 	 */
5578 	divider = get_pelt_divider(&cfs_rq->avg);
5579 
5580 	if (runnable_sum >= 0) {
5581 		/*
5582 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
5583 		 * the CPU is saturated running == runnable.
5584 		 */
5585 		runnable_sum += se->avg.load_sum;
5586 		runnable_sum = min_t(long, runnable_sum, divider);
5587 	} else {
5588 		/*
5589 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
5590 		 * assuming all tasks are equally runnable.
5591 		 */
5592 		if (scale_load_down(gcfs_rq->load.weight)) {
5593 			load_sum = div_u64(gcfs_rq->avg.load_sum,
5594 				scale_load_down(gcfs_rq->load.weight));
5595 		}
5596 
5597 		/* But make sure to not inflate se's runnable */
5598 		runnable_sum = min(se->avg.load_sum, load_sum);
5599 	}
5600 
5601 	/*
5602 	 * runnable_sum can't be lower than running_sum
5603 	 * Rescale running sum to be in the same range as runnable sum
5604 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
5605 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
5606 	 */
5607 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
5608 	runnable_sum = max(runnable_sum, running_sum);
5609 
5610 	load_sum = se_weight(se) * runnable_sum;
5611 	load_avg = div_u64(load_sum, divider);
5612 
5613 	delta_avg = load_avg - se->avg.load_avg;
5614 	if (!delta_avg)
5615 		return;
5616 
5617 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
5618 
5619 	se->avg.load_sum = runnable_sum;
5620 	se->avg.load_avg = load_avg;
5621 	__update_sa(&cfs_rq->avg, load, delta_avg, delta_sum);
5622 }
5623 
5624 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
5625 {
5626 	cfs_rq->propagate = 1;
5627 	cfs_rq->prop_runnable_sum += runnable_sum;
5628 }
5629 
5630 /* Update task and its cfs_rq load average */
5631 static inline int propagate_entity_load_avg(struct sched_entity *se)
5632 {
5633 	struct cfs_rq *cfs_rq, *gcfs_rq;
5634 
5635 	if (entity_is_task(se))
5636 		return 0;
5637 
5638 	gcfs_rq = group_cfs_rq(se);
5639 	if (!gcfs_rq->propagate)
5640 		return 0;
5641 
5642 	gcfs_rq->propagate = 0;
5643 
5644 	cfs_rq = cfs_rq_of(se);
5645 
5646 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
5647 
5648 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
5649 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
5650 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
5651 
5652 	trace_pelt_cfs_tp(cfs_rq);
5653 	trace_pelt_se_tp(se);
5654 
5655 	return 1;
5656 }
5657 
5658 /*
5659  * Check if we need to update the load and the utilization of a blocked
5660  * group_entity:
5661  */
5662 static inline bool skip_blocked_update(struct sched_entity *se)
5663 {
5664 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5665 
5666 	/*
5667 	 * If sched_entity still have not zero load or utilization, we have to
5668 	 * decay it:
5669 	 */
5670 	if (se->avg.load_avg || se->avg.util_avg)
5671 		return false;
5672 
5673 	/*
5674 	 * If there is a pending propagation, we have to update the load and
5675 	 * the utilization of the sched_entity:
5676 	 */
5677 	if (gcfs_rq->propagate)
5678 		return false;
5679 
5680 	/*
5681 	 * Otherwise, the load and the utilization of the sched_entity is
5682 	 * already zero and there is no pending propagation, so it will be a
5683 	 * waste of time to try to decay it:
5684 	 */
5685 	return true;
5686 }
5687 
5688 #else /* !CONFIG_FAIR_GROUP_SCHED: */
5689 
5690 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
5691 
5692 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
5693 
5694 static inline int propagate_entity_load_avg(struct sched_entity *se)
5695 {
5696 	return 0;
5697 }
5698 
5699 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
5700 
5701 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5702 
5703 #ifdef CONFIG_NO_HZ_COMMON
5704 static inline void migrate_se_pelt_lag(struct sched_entity *se)
5705 {
5706 	u64 throttled = 0, now, lut;
5707 	struct cfs_rq *cfs_rq;
5708 	struct rq *rq;
5709 	bool is_idle;
5710 
5711 	if (load_avg_is_decayed(&se->avg))
5712 		return;
5713 
5714 	cfs_rq = cfs_rq_of(se);
5715 	rq = rq_of(cfs_rq);
5716 
5717 	rcu_read_lock();
5718 	is_idle = is_idle_task(rcu_dereference_all(rq->curr));
5719 	rcu_read_unlock();
5720 
5721 	/*
5722 	 * The lag estimation comes with a cost we don't want to pay all the
5723 	 * time. Hence, limiting to the case where the source CPU is idle and
5724 	 * we know we are at the greatest risk to have an outdated clock.
5725 	 */
5726 	if (!is_idle)
5727 		return;
5728 
5729 	/*
5730 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
5731 	 *
5732 	 *   last_update_time (the cfs_rq's last_update_time)
5733 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
5734 	 *      = rq_clock_pelt()@cfs_rq_idle
5735 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
5736 	 *
5737 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
5738 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
5739 	 *
5740 	 *   rq_idle_lag (delta between now and rq's update)
5741 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
5742 	 *
5743 	 * We can then write:
5744 	 *
5745 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
5746 	 *          sched_clock_cpu() - rq_clock()@rq_idle
5747 	 * Where:
5748 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
5749 	 *      rq_clock()@rq_idle      is rq->clock_idle
5750 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
5751 	 *                              is cfs_rq->throttled_pelt_idle
5752 	 */
5753 
5754 #ifdef CONFIG_CFS_BANDWIDTH
5755 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
5756 	/* The clock has been stopped for throttling */
5757 	if (throttled == U64_MAX)
5758 		return;
5759 #endif
5760 	now = u64_u32_load(rq->clock_pelt_idle);
5761 	/*
5762 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
5763 	 * is observed the old clock_pelt_idle value and the new clock_idle,
5764 	 * which lead to an underestimation. The opposite would lead to an
5765 	 * overestimation.
5766 	 */
5767 	smp_rmb();
5768 	lut = cfs_rq_last_update_time(cfs_rq);
5769 
5770 	now -= throttled;
5771 	if (now < lut)
5772 		/*
5773 		 * cfs_rq->avg.last_update_time is more recent than our
5774 		 * estimation, let's use it.
5775 		 */
5776 		now = lut;
5777 	else
5778 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
5779 
5780 	__update_load_avg_blocked_se(now, se);
5781 }
5782 #else /* !CONFIG_NO_HZ_COMMON: */
5783 static void migrate_se_pelt_lag(struct sched_entity *se) {}
5784 #endif /* !CONFIG_NO_HZ_COMMON */
5785 
5786 /**
5787  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
5788  * @now: current time, as per cfs_rq_clock_pelt()
5789  * @cfs_rq: cfs_rq to update
5790  *
5791  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
5792  * avg. The immediate corollary is that all (fair) tasks must be attached.
5793  *
5794  * cfs_rq->avg is used for task_h_load() and update_cfs_group() for example.
5795  *
5796  * Return: true if the load decayed or we removed load.
5797  *
5798  * Since both these conditions indicate a changed cfs_rq->avg.load we should
5799  * call update_tg_load_avg() when this function returns true.
5800  */
5801 static inline int
5802 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
5803 {
5804 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
5805 	struct sched_avg *sa = &cfs_rq->avg;
5806 	int decayed = 0;
5807 
5808 	if (cfs_rq->removed.nr) {
5809 		unsigned long r;
5810 		u32 divider = get_pelt_divider(&cfs_rq->avg);
5811 
5812 		raw_spin_lock(&cfs_rq->removed.lock);
5813 		swap(cfs_rq->removed.util_avg, removed_util);
5814 		swap(cfs_rq->removed.load_avg, removed_load);
5815 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
5816 		cfs_rq->removed.nr = 0;
5817 		raw_spin_unlock(&cfs_rq->removed.lock);
5818 
5819 		r = removed_load;
5820 		__update_sa(sa, load, -r, -r*divider);
5821 
5822 		r = removed_util;
5823 		__update_sa(sa, util, -r, -r*divider);
5824 
5825 		r = removed_runnable;
5826 		__update_sa(sa, runnable, -r, -r*divider);
5827 
5828 		/*
5829 		 * removed_runnable is the unweighted version of removed_load so we
5830 		 * can use it to estimate removed_load_sum.
5831 		 */
5832 		add_tg_cfs_propagate(cfs_rq,
5833 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
5834 
5835 		decayed = 1;
5836 	}
5837 
5838 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
5839 	u64_u32_store_copy(sa->last_update_time,
5840 			   cfs_rq->last_update_time_copy,
5841 			   sa->last_update_time);
5842 	return decayed;
5843 }
5844 
5845 /**
5846  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
5847  * @cfs_rq: cfs_rq to attach to
5848  * @se: sched_entity to attach
5849  *
5850  * Must call update_cfs_rq_load_avg() before this, since we rely on
5851  * cfs_rq->avg.last_update_time being current.
5852  */
5853 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5854 {
5855 	/*
5856 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5857 	 * See ___update_load_avg() for details.
5858 	 */
5859 	u32 divider = get_pelt_divider(&cfs_rq->avg);
5860 
5861 	/*
5862 	 * When we attach the @se to the @cfs_rq, we must align the decay
5863 	 * window because without that, really weird and wonderful things can
5864 	 * happen.
5865 	 *
5866 	 * XXX illustrate
5867 	 */
5868 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
5869 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
5870 
5871 	/*
5872 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
5873 	 * period_contrib. This isn't strictly correct, but since we're
5874 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
5875 	 * _sum a little.
5876 	 */
5877 	se->avg.util_sum = se->avg.util_avg * divider;
5878 
5879 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
5880 
5881 	se->avg.load_sum = se->avg.load_avg * divider;
5882 	if (se_weight(se) < se->avg.load_sum)
5883 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
5884 	else
5885 		se->avg.load_sum = 1;
5886 
5887 	enqueue_load_avg(cfs_rq, se);
5888 	cfs_rq->avg.util_avg += se->avg.util_avg;
5889 	cfs_rq->avg.util_sum += se->avg.util_sum;
5890 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
5891 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
5892 
5893 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
5894 
5895 	cfs_rq_util_change(cfs_rq, 0);
5896 
5897 	trace_pelt_cfs_tp(cfs_rq);
5898 }
5899 
5900 /**
5901  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
5902  * @cfs_rq: cfs_rq to detach from
5903  * @se: sched_entity to detach
5904  *
5905  * Must call update_cfs_rq_load_avg() before this, since we rely on
5906  * cfs_rq->avg.last_update_time being current.
5907  */
5908 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5909 {
5910 	dequeue_load_avg(cfs_rq, se);
5911 	__update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum);
5912 	__update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum);
5913 
5914 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
5915 
5916 	cfs_rq_util_change(cfs_rq, 0);
5917 
5918 	trace_pelt_cfs_tp(cfs_rq);
5919 }
5920 
5921 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
5922 
5923 static inline void util_est_update(struct sched_entity *se)
5924 {
5925 	unsigned int ewma, dequeued, last_ewma_diff;
5926 
5927 	if (!sched_feat(UTIL_EST))
5928 		return;
5929 
5930 	/* Get current estimate of utilization */
5931 	ewma = READ_ONCE(se->avg.util_est);
5932 
5933 	/*
5934 	 * If the PELT values haven't changed since enqueue time,
5935 	 * skip the util_est update.
5936 	 */
5937 	if (ewma & UTIL_AVG_UNCHANGED)
5938 		return;
5939 
5940 	/* Get utilization at dequeue */
5941 	dequeued = READ_ONCE(se->avg.util_avg);
5942 
5943 	/*
5944 	 * Reset EWMA on utilization increases, the moving average is used only
5945 	 * to smooth utilization decreases.
5946 	 */
5947 	if (ewma <= dequeued) {
5948 		ewma = dequeued;
5949 		goto done;
5950 	}
5951 
5952 	/*
5953 	 * Skip update of task's estimated utilization when its members are
5954 	 * already ~1% close to its last activation value.
5955 	 */
5956 	last_ewma_diff = ewma - dequeued;
5957 	if (last_ewma_diff < UTIL_EST_MARGIN)
5958 		goto done;
5959 
5960 	/*
5961 	 * To avoid underestimate of task utilization, skip updates of EWMA if
5962 	 * we cannot grant that thread got all CPU time it wanted.
5963 	 */
5964 	if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg))
5965 		goto done;
5966 
5967 	/*
5968 	 * Update Task's estimated utilization
5969 	 *
5970 	 * When *p completes an activation we can consolidate another sample
5971 	 * of the task size. This is done by using this value to update the
5972 	 * Exponential Weighted Moving Average (EWMA):
5973 	 *
5974 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
5975 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
5976 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
5977 	 *          = w * (      -last_ewma_diff           ) +     ewma(t-1)
5978 	 *          = w * (-last_ewma_diff +  ewma(t-1) / w)
5979 	 *
5980 	 * Where 'w' is the weight of new samples, which is configured to be
5981 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5982 	 */
5983 	ewma <<= UTIL_EST_WEIGHT_SHIFT;
5984 	ewma  -= last_ewma_diff;
5985 	ewma >>= UTIL_EST_WEIGHT_SHIFT;
5986 done:
5987 	ewma |= UTIL_AVG_UNCHANGED;
5988 	WRITE_ONCE(se->avg.util_est, ewma);
5989 
5990 	trace_sched_util_est_se_tp(se);
5991 }
5992 
5993 /*
5994  * Optional action to be done while updating the load average
5995  */
5996 #define UPDATE_TG	0x01
5997 #define SKIP_AGE_LOAD	0x02
5998 #define DO_ATTACH	0x04
5999 #define DO_DETACH	0x08
6000 #define UPDATE_UTIL_EST	0x10
6001 
6002 /* Update task and its cfs_rq load average */
6003 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6004 {
6005 	u64 now = cfs_rq_clock_pelt(cfs_rq);
6006 	int decayed;
6007 
6008 	/*
6009 	 * Track task load average for carrying it to new CPU after migrated, and
6010 	 * track group sched_entity load average for task_h_load calculation in migration
6011 	 */
6012 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
6013 		__update_load_avg_se(now, cfs_rq, se);
6014 
6015 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
6016 	decayed |= propagate_entity_load_avg(se);
6017 
6018 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
6019 
6020 		/*
6021 		 * DO_ATTACH means we're here from enqueue_entity().
6022 		 * !last_update_time means we've passed through
6023 		 * migrate_task_rq_fair() indicating we migrated.
6024 		 *
6025 		 * IOW we're enqueueing a task on a new CPU.
6026 		 */
6027 		attach_entity_load_avg(cfs_rq, se);
6028 		update_tg_load_avg(cfs_rq);
6029 
6030 	} else if (flags & DO_DETACH) {
6031 		/*
6032 		 * DO_DETACH means we're here from dequeue_entity()
6033 		 * and we are migrating task out of the CPU.
6034 		 */
6035 		detach_entity_load_avg(cfs_rq, se);
6036 		update_tg_load_avg(cfs_rq);
6037 	} else if (decayed) {
6038 		cfs_rq_util_change(cfs_rq, 0);
6039 
6040 		if (flags & UPDATE_TG)
6041 			update_tg_load_avg(cfs_rq);
6042 	}
6043 
6044 	if (flags & UPDATE_UTIL_EST)
6045 		util_est_update(se);
6046 }
6047 
6048 /*
6049  * Synchronize entity load avg of dequeued entity without locking
6050  * the previous rq.
6051  */
6052 static void sync_entity_load_avg(struct sched_entity *se)
6053 {
6054 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6055 	u64 last_update_time;
6056 
6057 	last_update_time = cfs_rq_last_update_time(cfs_rq);
6058 	__update_load_avg_blocked_se(last_update_time, se);
6059 }
6060 
6061 /*
6062  * Task first catches up with cfs_rq, and then subtract
6063  * itself from the cfs_rq (task must be off the queue now).
6064  */
6065 static void remove_entity_load_avg(struct sched_entity *se)
6066 {
6067 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6068 	unsigned long flags;
6069 
6070 	/*
6071 	 * tasks cannot exit without having gone through wake_up_new_task() ->
6072 	 * enqueue_task_fair() which will have added things to the cfs_rq,
6073 	 * so we can remove unconditionally.
6074 	 */
6075 
6076 	sync_entity_load_avg(se);
6077 
6078 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
6079 	++cfs_rq->removed.nr;
6080 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
6081 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
6082 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
6083 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
6084 }
6085 
6086 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
6087 {
6088 	return cfs_rq->avg.runnable_avg;
6089 }
6090 
6091 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
6092 {
6093 	return cfs_rq->avg.load_avg;
6094 }
6095 
6096 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
6097 	__must_hold(__rq_lockp(this_rq));
6098 
6099 static inline unsigned long task_util(struct task_struct *p)
6100 {
6101 	return READ_ONCE(p->se.avg.util_avg);
6102 }
6103 
6104 static inline unsigned long _task_util_est(struct task_struct *p)
6105 {
6106 	return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
6107 }
6108 
6109 static inline unsigned long task_util_est(struct task_struct *p)
6110 {
6111 	return max(task_util(p), _task_util_est(p));
6112 }
6113 
6114 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
6115 				    struct task_struct *p)
6116 {
6117 	unsigned int enqueued;
6118 
6119 	if (!sched_feat(UTIL_EST))
6120 		return;
6121 
6122 	/* Update root cfs_rq's estimated utilization */
6123 	enqueued  = cfs_rq->avg.util_est;
6124 	enqueued += _task_util_est(p);
6125 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
6126 
6127 	trace_sched_util_est_cfs_tp(cfs_rq);
6128 }
6129 
6130 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
6131 				    struct task_struct *p)
6132 {
6133 	unsigned int enqueued;
6134 
6135 	if (!sched_feat(UTIL_EST))
6136 		return;
6137 
6138 	/* Update root cfs_rq's estimated utilization */
6139 	enqueued  = cfs_rq->avg.util_est;
6140 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
6141 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
6142 
6143 	trace_sched_util_est_cfs_tp(cfs_rq);
6144 }
6145 
6146 static inline unsigned long get_actual_cpu_capacity(int cpu)
6147 {
6148 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
6149 
6150 	capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
6151 
6152 	return capacity;
6153 }
6154 
6155 static inline int util_fits_cpu(unsigned long util,
6156 				unsigned long uclamp_min,
6157 				unsigned long uclamp_max,
6158 				int cpu)
6159 {
6160 	unsigned long capacity = capacity_of(cpu);
6161 	unsigned long capacity_orig;
6162 	bool fits, uclamp_max_fits;
6163 
6164 	/*
6165 	 * Check if the real util fits without any uclamp boost/cap applied.
6166 	 */
6167 	fits = fits_capacity(util, capacity);
6168 
6169 	if (!uclamp_is_used())
6170 		return fits;
6171 
6172 	/*
6173 	 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
6174 	 * uclamp_max. We only care about capacity pressure (by using
6175 	 * capacity_of()) for comparing against the real util.
6176 	 *
6177 	 * If a task is boosted to 1024 for example, we don't want a tiny
6178 	 * pressure to skew the check whether it fits a CPU or not.
6179 	 *
6180 	 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
6181 	 * should fit a little cpu even if there's some pressure.
6182 	 *
6183 	 * Only exception is for HW or cpufreq pressure since it has a direct impact
6184 	 * on available OPP of the system.
6185 	 *
6186 	 * We honour it for uclamp_min only as a drop in performance level
6187 	 * could result in not getting the requested minimum performance level.
6188 	 *
6189 	 * For uclamp_max, we can tolerate a drop in performance level as the
6190 	 * goal is to cap the task. So it's okay if it's getting less.
6191 	 */
6192 	capacity_orig = arch_scale_cpu_capacity(cpu);
6193 
6194 	/*
6195 	 * We want to force a task to fit a cpu as implied by uclamp_max.
6196 	 * But we do have some corner cases to cater for..
6197 	 *
6198 	 *
6199 	 *                                 C=z
6200 	 *   |                             ___
6201 	 *   |                  C=y       |   |
6202 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
6203 	 *   |      C=x        |   |      |   |
6204 	 *   |      ___        |   |      |   |
6205 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
6206 	 *   |     |   |       |   |      |   |
6207 	 *   |     |   |       |   |      |   |
6208 	 *   +----------------------------------------
6209 	 *         CPU0        CPU1       CPU2
6210 	 *
6211 	 *   In the above example if a task is capped to a specific performance
6212 	 *   point, y, then when:
6213 	 *
6214 	 *   * util = 80% of x then it does not fit on CPU0 and should migrate
6215 	 *     to CPU1
6216 	 *   * util = 80% of y then it is forced to fit on CPU1 to honour
6217 	 *     uclamp_max request.
6218 	 *
6219 	 *   which is what we're enforcing here. A task always fits if
6220 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
6221 	 *   the normal upmigration rules should withhold still.
6222 	 *
6223 	 *   Only exception is when we are on max capacity, then we need to be
6224 	 *   careful not to block overutilized state. This is so because:
6225 	 *
6226 	 *     1. There's no concept of capping at max_capacity! We can't go
6227 	 *        beyond this performance level anyway.
6228 	 *     2. The system is being saturated when we're operating near
6229 	 *        max capacity, it doesn't make sense to block overutilized.
6230 	 */
6231 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
6232 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
6233 	fits = fits || uclamp_max_fits;
6234 
6235 	/*
6236 	 *
6237 	 *                                 C=z
6238 	 *   |                             ___       (region a, capped, util >= uclamp_max)
6239 	 *   |                  C=y       |   |
6240 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
6241 	 *   |      C=x        |   |      |   |
6242 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
6243 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
6244 	 *   |     |   |       |   |      |   |
6245 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
6246 	 *   +----------------------------------------
6247 	 *         CPU0        CPU1       CPU2
6248 	 *
6249 	 * a) If util > uclamp_max, then we're capped, we don't care about
6250 	 *    actual fitness value here. We only care if uclamp_max fits
6251 	 *    capacity without taking margin/pressure into account.
6252 	 *    See comment above.
6253 	 *
6254 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
6255 	 *    fits_capacity() rules apply. Except we need to ensure that we
6256 	 *    enforce we remain within uclamp_max, see comment above.
6257 	 *
6258 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
6259 	 *    need to take into account the boosted value fits the CPU without
6260 	 *    taking margin/pressure into account.
6261 	 *
6262 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
6263 	 * just need to consider an extra check for case (c) after ensuring we
6264 	 * handle the case uclamp_min > uclamp_max.
6265 	 */
6266 	uclamp_min = min(uclamp_min, uclamp_max);
6267 	if (fits && (util < uclamp_min) &&
6268 	    (uclamp_min > get_actual_cpu_capacity(cpu)))
6269 		return -1;
6270 
6271 	return fits;
6272 }
6273 
6274 static inline int task_fits_cpu(struct task_struct *p, int cpu)
6275 {
6276 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
6277 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
6278 	unsigned long util = task_util_est(p);
6279 	/*
6280 	 * Return true only if the cpu fully fits the task requirements, which
6281 	 * include the utilization but also the performance hints.
6282 	 */
6283 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
6284 }
6285 
6286 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
6287 {
6288 	int cpu = cpu_of(rq);
6289 
6290 	if (!sched_asym_cpucap_active())
6291 		return;
6292 
6293 	/*
6294 	 * Affinity allows us to go somewhere higher?  Or are we on biggest
6295 	 * available CPU already? Or do we fit into this CPU ?
6296 	 */
6297 	if (!p || (p->nr_cpus_allowed == 1) ||
6298 	    (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
6299 	    task_fits_cpu(p, cpu)) {
6300 
6301 		rq->misfit_task_load = 0;
6302 		return;
6303 	}
6304 
6305 	/*
6306 	 * Make sure that misfit_task_load will not be null even if
6307 	 * task_h_load() returns 0.
6308 	 */
6309 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
6310 }
6311 
6312 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
6313 {
6314 	struct sched_entity *se = &p->se;
6315 
6316 	p->static_prio = NICE_TO_PRIO(attr->sched_nice);
6317 	if (attr->sched_runtime) {
6318 		se->custom_slice = 1;
6319 		se->slice = clamp_t(u64, attr->sched_runtime,
6320 				      NSEC_PER_MSEC/10,   /* HZ=1000 * 10 */
6321 				      NSEC_PER_MSEC*100); /* HZ=100  / 10 */
6322 	} else {
6323 		se->custom_slice = 0;
6324 		se->slice = sysctl_sched_base_slice;
6325 	}
6326 }
6327 
6328 static void
6329 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6330 {
6331 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
6332 	unsigned int nr_queued = cfs_rq->h_nr_queued;
6333 	bool update_zero = false;
6334 	s64 lag = 0;
6335 
6336 	if (!se->custom_slice)
6337 		se->slice = sysctl_sched_base_slice;
6338 	vslice = calc_delta_fair(se->slice, se);
6339 
6340 	if (flags & ENQUEUE_QUEUED)
6341 		nr_queued -= 1;
6342 
6343 	/*
6344 	 * Due to how V is constructed as the weighted average of entities,
6345 	 * adding tasks with positive lag, or removing tasks with negative lag
6346 	 * will move 'time' backwards, this can screw around with the lag of
6347 	 * other tasks.
6348 	 *
6349 	 * EEVDF: placement strategy #1 / #2
6350 	 */
6351 	if (sched_feat(PLACE_LAG) && nr_queued && se->vlag) {
6352 		struct sched_entity *curr = cfs_rq->curr;
6353 		long load, weight;
6354 
6355 		lag = se->vlag;
6356 
6357 		/*
6358 		 * If we want to place a task and preserve lag, we have to
6359 		 * consider the effect of the new entity on the weighted
6360 		 * average and compensate for this, otherwise lag can quickly
6361 		 * evaporate.
6362 		 *
6363 		 * Lag is defined as:
6364 		 *
6365 		 *   lag_i = S - s_i = w_i * (V - v_i)
6366 		 *
6367 		 * To avoid the 'w_i' term all over the place, we only track
6368 		 * the virtual lag:
6369 		 *
6370 		 *   vl_i = V - v_i <=> v_i = V - vl_i
6371 		 *
6372 		 * And we take V to be the weighted average of all v:
6373 		 *
6374 		 *   V = (\Sum w_j*v_j) / W
6375 		 *
6376 		 * Where W is: \Sum w_j
6377 		 *
6378 		 * Then, the weighted average after adding an entity with lag
6379 		 * vl_i is given by:
6380 		 *
6381 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
6382 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
6383 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
6384 		 *      = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
6385 		 *      = V - w_i*vl_i / (W + w_i)
6386 		 *
6387 		 * And the actual lag after adding an entity with vl_i is:
6388 		 *
6389 		 *   vl'_i = V' - v_i
6390 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
6391 		 *         = vl_i - w_i*vl_i / (W + w_i)
6392 		 *
6393 		 * Which is strictly less than vl_i. So in order to preserve lag
6394 		 * we should inflate the lag before placement such that the
6395 		 * effective lag after placement comes out right.
6396 		 *
6397 		 * As such, invert the above relation for vl'_i to get the vl_i
6398 		 * we need to use such that the lag after placement is the lag
6399 		 * we computed before dequeue.
6400 		 *
6401 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
6402 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
6403 		 *
6404 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
6405 		 *                   = W*vl_i
6406 		 *
6407 		 *   vl_i = (W + w_i)*vl'_i / W
6408 		 */
6409 		load = cfs_rq->sum_weight;
6410 		if (curr && curr->on_rq)
6411 			load += avg_vruntime_weight(cfs_rq, curr->h_load.weight);
6412 		if (WARN_ON_ONCE(!load))
6413 			load = 1;
6414 
6415 		weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
6416 
6417 		/*
6418 		 * Rewrite, because the product (W + w_i)*vl'_i might
6419 		 * overflow s64:
6420 		 *
6421 		 *   vl_i = (W + w_i)*vl'_i / W
6422 		 *        = (W*vl'_i + w_i*vl'_i) / W
6423 		 *        = vl'_i + w_i*vl'_i/W
6424 		 */
6425 		lag += div64_long(lag * weight, load);
6426 
6427 		/*
6428 		 * A heavy entity (relative to the tree) will pull the
6429 		 * avg_vruntime close to its vruntime position on enqueue. But
6430 		 * the zero_vruntime point is only updated at the next
6431 		 * update_deadline()/place_entity()/update_entity_lag().
6432 		 *
6433 		 * Specifically (see the comment near avg_vruntime_weight()):
6434 		 *
6435 		 *   sum_w_vruntime = \Sum (v_i - v0) * w_i
6436 		 *
6437 		 * Note that if v0 is near a light entity, both terms will be
6438 		 * small for the light entity, while in that case both terms
6439 		 * are large for the heavy entity, leading to risk of
6440 		 * overflow.
6441 		 *
6442 		 * OTOH if v0 is near the heavy entity, then the difference is
6443 		 * larger for the light entity, but the factor is small, while
6444 		 * for the heavy entity the difference is small but the factor
6445 		 * is large. Avoiding the multiplication overflow.
6446 		 */
6447 		if (weight > load)
6448 			update_zero = true;
6449 	}
6450 
6451 	se->vruntime = vruntime - lag;
6452 
6453 	if (update_zero)
6454 		update_zero_vruntime(cfs_rq, -lag);
6455 
6456 	if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
6457 		se->deadline += se->vruntime;
6458 		se->rel_deadline = 0;
6459 		return;
6460 	}
6461 
6462 	/*
6463 	 * When joining the competition; the existing tasks will be,
6464 	 * on average, halfway through their slice, as such start tasks
6465 	 * off with half a slice to ease into the competition.
6466 	 */
6467 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
6468 		vslice /= 2;
6469 
6470 	/*
6471 	 * EEVDF: vd_i = ve_i + r_i/w_i
6472 	 */
6473 	se->deadline = se->vruntime + vslice;
6474 }
6475 
6476 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
6477 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
6478 
6479 static void
6480 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6481 {
6482 	/*
6483 	 * When enqueuing a sched_entity, we must:
6484 	 *   - Update loads to have both entity and cfs_rq synced with now.
6485 	 *   - For group_entity, update its runnable_weight to reflect the new
6486 	 *     h_nr_runnable of its group cfs_rq.
6487 	 *   - For group_entity, update its weight to reflect the new share of
6488 	 *     its group cfs_rq
6489 	 *   - Add its new weight to cfs_rq->load.weight
6490 	 */
6491 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
6492 	se_update_runnable(se);
6493 	/*
6494 	 * XXX update_load_avg() above will have attached us to the pelt sum;
6495 	 * but update_cfs_group() here will re-adjust the weight and have to
6496 	 * undo/redo all that. Seems wasteful.
6497 	 */
6498 	update_cfs_group(se);
6499 
6500 	account_entity_enqueue(cfs_rq, se);
6501 
6502 	/* Entity has migrated, no longer consider this task hot */
6503 	if (flags & ENQUEUE_MIGRATED)
6504 		se->exec_start = 0;
6505 
6506 	check_schedstat_required();
6507 	update_stats_enqueue_fair(cfs_rq, se, flags);
6508 	se->on_rq = 1;
6509 
6510 	if (cfs_rq->nr_queued == 1) {
6511 		check_enqueue_throttle(cfs_rq);
6512 		list_add_leaf_cfs_rq(cfs_rq);
6513 #ifdef CONFIG_CFS_BANDWIDTH
6514 		if (cfs_rq->pelt_clock_throttled) {
6515 			struct rq *rq = rq_of(cfs_rq);
6516 
6517 			cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6518 				cfs_rq->throttled_clock_pelt;
6519 			cfs_rq->pelt_clock_throttled = 0;
6520 		}
6521 #endif
6522 	}
6523 }
6524 
6525 static void set_next_buddy(struct cfs_rq *cfs_rq, struct sched_entity *se)
6526 {
6527 	if (WARN_ON_ONCE(!se->on_rq || se->sched_delayed))
6528 		return;
6529 	if (se_is_idle(se))
6530 		return;
6531 	cfs_rq->next = se;
6532 }
6533 
6534 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
6535 {
6536 	if (cfs_rq->next == se)
6537 		cfs_rq->next = NULL;
6538 }
6539 
6540 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
6541 
6542 static void set_delayed(struct sched_entity *se)
6543 {
6544 	/*
6545 	 * Delayed se of cfs_rq have no tasks queued on them.
6546 	 * Do not adjust h_nr_runnable since __dequeue_task()
6547 	 * will account it for blocked tasks.
6548 	 *
6549 	 * This check can be removed because when flat pick
6550 	 * patches get merged as only task can get delayed,
6551 	 * same for clear_delayed().
6552 	 */
6553 	if (!entity_is_task(se)) {
6554 		se->sched_delayed = 1;
6555 		return;
6556 	}
6557 
6558 	/*
6559 	 * Drop a task leaving the runnable set.
6560 	 * Needs to be called before sched_delayed is set.
6561 	 * clear_delayed() mirrors this after clearing the flag.
6562 	 */
6563 	pref_llc_running_dec(rq_of(cfs_rq_of(se)), task_of(se));
6564 	se->sched_delayed = 1;
6565 
6566 	for_each_sched_entity(se) {
6567 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
6568 
6569 		cfs_rq->h_nr_runnable--;
6570 	}
6571 }
6572 
6573 static void clear_delayed(struct sched_entity *se)
6574 {
6575 	se->sched_delayed = 0;
6576 
6577 	/*
6578 	 * Delayed se of cfs_rq have no tasks queued on them.
6579 	 * Do not adjust h_nr_runnable since a dequeue has
6580 	 * already accounted for it or an enqueue of a task
6581 	 * below it will account for it in enqueue_task_fair().
6582 	 */
6583 	if (!entity_is_task(se))
6584 		return;
6585 
6586 	/*
6587 	 * Re-add on wake, after sched_delayed is cleared. On a final delayed
6588 	 * dequeue account_llc_dequeue() already cleared pref_llc_queued, so
6589 	 * this does nothing.
6590 	 */
6591 	pref_llc_running_inc(rq_of(cfs_rq_of(se)), task_of(se));
6592 
6593 	for_each_sched_entity(se) {
6594 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
6595 
6596 		cfs_rq->h_nr_runnable++;
6597 	}
6598 }
6599 
6600 static void
6601 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6602 {
6603 	int action = UPDATE_TG;
6604 
6605 	if (entity_is_task(se)) {
6606 		if (task_on_rq_migrating(task_of(se)))
6607 			action |= DO_DETACH;
6608 
6609 		if ((flags & DEQUEUE_SLEEP) && !(flags & DEQUEUE_DELAYED))
6610 			action |= UPDATE_UTIL_EST;
6611 	}
6612 
6613 	/*
6614 	 * When dequeuing a sched_entity, we must:
6615 	 *   - Update loads to have both entity and cfs_rq synced with now.
6616 	 *   - For group_entity, update its runnable_weight to reflect the new
6617 	 *     h_nr_runnable of its group cfs_rq.
6618 	 *   - Subtract its previous weight from cfs_rq->load.weight.
6619 	 *   - For group entity, update its weight to reflect the new share
6620 	 *     of its group cfs_rq.
6621 	 */
6622 	update_load_avg(cfs_rq, se, action);
6623 	se_update_runnable(se);
6624 
6625 	update_stats_dequeue_fair(cfs_rq, se, flags);
6626 
6627 	se->on_rq = 0;
6628 	account_entity_dequeue(cfs_rq, se);
6629 
6630 	/* return excess runtime on last dequeue */
6631 	return_cfs_rq_runtime(cfs_rq);
6632 
6633 	update_cfs_group(se);
6634 
6635 	if (cfs_rq->nr_queued == 0) {
6636 		update_idle_cfs_rq_clock_pelt(cfs_rq);
6637 #ifdef CONFIG_CFS_BANDWIDTH
6638 		if (throttled_hierarchy(cfs_rq)) {
6639 			struct rq *rq = rq_of(cfs_rq);
6640 
6641 			list_del_leaf_cfs_rq(cfs_rq);
6642 			cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6643 			cfs_rq->pelt_clock_throttled = 1;
6644 		}
6645 #endif
6646 	}
6647 }
6648 
6649 static void
6650 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
6651 {
6652 	/* 'current' is not kept within the tree. */
6653 	if (se->on_rq) {
6654 		/*
6655 		 * Any task has to be enqueued before it get to execute on
6656 		 * a CPU. So account for the time it spent waiting on the
6657 		 * runqueue.
6658 		 */
6659 		update_stats_wait_end_fair(cfs_rq, se);
6660 		update_load_avg(cfs_rq, se, UPDATE_TG);
6661 	}
6662 
6663 	update_stats_curr_start(cfs_rq, se);
6664 	WARN_ON_ONCE(cfs_rq->h_curr);
6665 	cfs_rq->h_curr = se;
6666 
6667 	/*
6668 	 * Track our maximum slice length, if the CPU's load is at
6669 	 * least twice that of our own weight (i.e. don't track it
6670 	 * when there are only lesser-weight tasks around):
6671 	 */
6672 	if (schedstat_enabled() &&
6673 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
6674 		struct sched_statistics *stats;
6675 
6676 		stats = __schedstats_from_se(se);
6677 		__schedstat_set(stats->slice_max,
6678 				max((u64)stats->slice_max,
6679 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
6680 	}
6681 
6682 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
6683 }
6684 
6685 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags);
6686 
6687 static struct sched_entity *
6688 pick_next_entity(struct rq *rq, bool protect)
6689 {
6690 	struct cfs_rq *cfs_rq = &rq->cfs;
6691 	struct sched_entity *se;
6692 
6693 	se = pick_eevdf(cfs_rq, protect);
6694 	if (se->sched_delayed) {
6695 		__dequeue_task(rq, task_of(se), DEQUEUE_SLEEP | DEQUEUE_DELAYED);
6696 		/*
6697 		 * Must not reference @se again, see __block_task().
6698 		 */
6699 		return NULL;
6700 	}
6701 	return se;
6702 }
6703 
6704 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
6705 {
6706 	/*
6707 	 * If still on the runqueue then deactivate_task()
6708 	 * was not called and update_curr() has to be done:
6709 	 */
6710 	if (prev->on_rq)
6711 		update_curr(cfs_rq);
6712 
6713 	if (prev->on_rq) {
6714 		update_stats_wait_start_fair(cfs_rq, prev);
6715 		/* in !on_rq case, update occurred at dequeue */
6716 		update_load_avg(cfs_rq, prev, 0);
6717 	}
6718 	WARN_ON_ONCE(cfs_rq->h_curr != prev);
6719 	cfs_rq->h_curr = NULL;
6720 }
6721 
6722 static void
6723 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
6724 {
6725 	/*
6726 	 * Update run-time statistics of the 'current'.
6727 	 */
6728 	update_curr(cfs_rq);
6729 
6730 	/*
6731 	 * Ensure that runnable average is periodically updated.
6732 	 */
6733 	update_load_avg(cfs_rq, curr, UPDATE_TG);
6734 	update_cfs_group(curr);
6735 
6736 #ifdef CONFIG_SCHED_HRTICK
6737 	/*
6738 	 * queued ticks are scheduled to match the slice, so don't bother
6739 	 * validating it and just reschedule.
6740 	 */
6741 	if (queued) {
6742 		resched_curr(rq_of(cfs_rq));
6743 		return;
6744 	}
6745 #endif
6746 }
6747 
6748 
6749 /**************************************************
6750  * CFS bandwidth control machinery
6751  */
6752 
6753 #ifdef CONFIG_CFS_BANDWIDTH
6754 
6755 #ifdef CONFIG_JUMP_LABEL
6756 static struct static_key __cfs_bandwidth_used;
6757 
6758 static inline bool cfs_bandwidth_used(void)
6759 {
6760 	return static_key_false(&__cfs_bandwidth_used);
6761 }
6762 
6763 void cfs_bandwidth_usage_inc(void)
6764 {
6765 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
6766 }
6767 
6768 void cfs_bandwidth_usage_dec(void)
6769 {
6770 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
6771 }
6772 #else /* !CONFIG_JUMP_LABEL: */
6773 static bool cfs_bandwidth_used(void)
6774 {
6775 	return true;
6776 }
6777 
6778 void cfs_bandwidth_usage_inc(void) {}
6779 void cfs_bandwidth_usage_dec(void) {}
6780 #endif /* !CONFIG_JUMP_LABEL */
6781 
6782 static inline u64 sched_cfs_bandwidth_slice(void)
6783 {
6784 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
6785 }
6786 
6787 /*
6788  * Replenish runtime according to assigned quota. We use sched_clock_cpu
6789  * directly instead of rq->clock to avoid adding additional synchronization
6790  * around rq->lock.
6791  *
6792  * requires cfs_b->lock
6793  */
6794 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
6795 {
6796 	s64 runtime;
6797 
6798 	if (unlikely(cfs_b->quota == RUNTIME_INF))
6799 		return;
6800 
6801 	cfs_b->runtime += cfs_b->quota;
6802 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
6803 	if (runtime > 0) {
6804 		cfs_b->burst_time += runtime;
6805 		cfs_b->nr_burst++;
6806 	}
6807 
6808 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
6809 	cfs_b->runtime_snap = cfs_b->runtime;
6810 }
6811 
6812 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6813 {
6814 	return &tg->cfs_bandwidth;
6815 }
6816 
6817 /* returns 0 on failure to allocate runtime */
6818 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
6819 				   struct cfs_rq *cfs_rq, u64 target_runtime)
6820 {
6821 	u64 min_amount, amount = 0;
6822 
6823 	lockdep_assert_held(&cfs_b->lock);
6824 
6825 	/* note: this is a positive sum as runtime_remaining <= 0 */
6826 	min_amount = target_runtime - cfs_rq->runtime_remaining;
6827 
6828 	if (cfs_b->quota == RUNTIME_INF)
6829 		amount = min_amount;
6830 	else {
6831 		start_cfs_bandwidth(cfs_b);
6832 
6833 		if (cfs_b->runtime > 0) {
6834 			amount = min(cfs_b->runtime, min_amount);
6835 			cfs_b->runtime -= amount;
6836 			cfs_b->idle = 0;
6837 		}
6838 	}
6839 
6840 	cfs_rq->runtime_remaining += amount;
6841 
6842 	return cfs_rq->runtime_remaining > 0;
6843 }
6844 
6845 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq);
6846 
6847 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6848 {
6849 	/* dock delta_exec before expiring quota (as it could span periods) */
6850 	cfs_rq->runtime_remaining -= delta_exec;
6851 
6852 	if (likely(cfs_rq->runtime_remaining > 0))
6853 		return false;
6854 
6855 	if (cfs_rq->throttled)
6856 		return true;
6857 	/*
6858 	 * throttle_cfs_rq() will try to extend the runtime first
6859 	 * before throttling the hierarchy.
6860 	 */
6861 	return throttle_cfs_rq(cfs_rq);
6862 }
6863 
6864 static __always_inline
6865 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6866 {
6867 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
6868 		return false;
6869 
6870 	return __account_cfs_rq_runtime(cfs_rq, delta_exec);
6871 }
6872 
6873 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6874 {
6875 	return cfs_bandwidth_used() && cfs_rq->throttled;
6876 }
6877 
6878 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6879 {
6880 	return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
6881 }
6882 
6883 /* check whether cfs_rq, or any parent, is throttled */
6884 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6885 {
6886 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
6887 }
6888 
6889 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6890 {
6891 	return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu));
6892 }
6893 
6894 static inline bool task_is_throttled(struct task_struct *p)
6895 {
6896 	return cfs_bandwidth_used() && p->throttled;
6897 }
6898 
6899 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
6900 static void throttle_cfs_rq_work(struct callback_head *work)
6901 {
6902 	struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
6903 	struct sched_entity *se;
6904 	struct cfs_rq *cfs_rq;
6905 	struct rq *rq;
6906 
6907 	WARN_ON_ONCE(p != current);
6908 	p->sched_throttle_work.next = &p->sched_throttle_work;
6909 
6910 	/*
6911 	 * If task is exiting, then there won't be a return to userspace, so we
6912 	 * don't have to bother with any of this.
6913 	 */
6914 	if ((p->flags & PF_EXITING))
6915 		return;
6916 
6917 	scoped_guard(task_rq_lock, p) {
6918 		se = &p->se;
6919 		cfs_rq = cfs_rq_of(se);
6920 
6921 		/* Raced, forget */
6922 		if (p->sched_class != &fair_sched_class)
6923 			return;
6924 
6925 		/*
6926 		 * If not in limbo, then either replenish has happened or this
6927 		 * task got migrated out of the throttled cfs_rq, move along.
6928 		 */
6929 		if (!cfs_rq->throttle_count)
6930 			return;
6931 		rq = scope.rq;
6932 		update_rq_clock(rq);
6933 		WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
6934 		dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
6935 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6936 		/*
6937 		 * Must not set throttled before dequeue or dequeue will
6938 		 * mistakenly regard this task as an already throttled one.
6939 		 */
6940 		p->throttled = true;
6941 		resched_curr(rq);
6942 	}
6943 }
6944 
6945 void init_cfs_throttle_work(struct task_struct *p)
6946 {
6947 	init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
6948 	/* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
6949 	p->sched_throttle_work.next = &p->sched_throttle_work;
6950 	INIT_LIST_HEAD(&p->throttle_node);
6951 }
6952 
6953 /*
6954  * Task is throttled and someone wants to dequeue it again:
6955  * it could be sched/core when core needs to do things like
6956  * task affinity change, task group change, task sched class
6957  * change etc. and in these cases, DEQUEUE_SLEEP is not set;
6958  * or the task is blocked after throttled due to freezer etc.
6959  * and in these cases, DEQUEUE_SLEEP is set.
6960  */
6961 static void detach_task_cfs_rq(struct task_struct *p);
6962 static void dequeue_throttled_task(struct task_struct *p, int flags)
6963 {
6964 	WARN_ON_ONCE(p->se.on_rq);
6965 	list_del_init(&p->throttle_node);
6966 
6967 	/* task blocked after throttled */
6968 	if (flags & DEQUEUE_SLEEP) {
6969 		p->throttled = false;
6970 		return;
6971 	}
6972 
6973 	/*
6974 	 * task is migrating off its old cfs_rq, detach
6975 	 * the task's load from its old cfs_rq.
6976 	 */
6977 	if (task_on_rq_migrating(p))
6978 		detach_task_cfs_rq(p);
6979 }
6980 
6981 static bool enqueue_throttled_task(struct task_struct *p)
6982 {
6983 	struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
6984 
6985 	/* @p should have gone through dequeue_throttled_task() first */
6986 	WARN_ON_ONCE(!list_empty(&p->throttle_node));
6987 
6988 	/*
6989 	 * If the throttled task @p is enqueued to a throttled cfs_rq,
6990 	 * take the fast path by directly putting the task on the
6991 	 * target cfs_rq's limbo list.
6992 	 *
6993 	 * Do not do that when @p is current because the following race can
6994 	 * cause @p's group_node to be incorectly re-insterted in its rq's
6995 	 * cfs_tasks list, despite being throttled:
6996 	 *
6997 	 *     cpuX                       cpuY
6998 	 *   p ret2user
6999 	 *  throttle_cfs_rq_work()  sched_move_task(p)
7000 	 *  LOCK task_rq_lock
7001 	 *  dequeue_task_fair(p)
7002 	 *  UNLOCK task_rq_lock
7003 	 *                          LOCK task_rq_lock
7004 	 *                          task_current_donor(p) == true
7005 	 *                          task_on_rq_queued(p) == true
7006 	 *                          dequeue_task(p)
7007 	 *                          put_prev_task(p)
7008 	 *                          sched_change_group()
7009 	 *                          enqueue_task(p) -> p's new cfs_rq
7010 	 *                                             is throttled, go
7011 	 *                                             fast path and skip
7012 	 *                                             actual enqueue
7013 	 *                          set_next_task(p)
7014 	 *                    list_move(&se->group_node, &rq->cfs_tasks); // bug
7015 	 *  schedule()
7016 	 *
7017 	 * In the above race case, @p current cfs_rq is in the same rq as
7018 	 * its previous cfs_rq because sched_move_task() only moves a task
7019 	 * to a different group from the same rq, so we can use its current
7020 	 * cfs_rq to derive rq and test if the task is current.
7021 	 */
7022 	if (throttled_hierarchy(cfs_rq) &&
7023 	    !task_current_donor(rq_of(cfs_rq), p)) {
7024 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
7025 		return true;
7026 	}
7027 
7028 	/* we can't take the fast path, do an actual enqueue*/
7029 	p->throttled = false;
7030 	return false;
7031 }
7032 
7033 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
7034 static int tg_unthrottle_up(struct task_group *tg, void *data)
7035 {
7036 	struct rq *rq = data;
7037 	struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7038 	struct task_struct *p, *tmp;
7039 	LIST_HEAD(throttled_tasks);
7040 
7041 	/*
7042 	 * If cfs_rq->curr is set, the cfs_rq might not have caught up
7043 	 * since the last clock update. Do it now before we begin
7044 	 * queueing task onto it to save the need for unnecessarily
7045 	 * unthrottle the hierarchy for this cfs_rq to be throttled
7046 	 * right back again.
7047 	 */
7048 	update_curr(cfs_rq);
7049 
7050 	if (--cfs_rq->throttle_count)
7051 		return 0;
7052 
7053 	if (cfs_rq->pelt_clock_throttled) {
7054 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
7055 					     cfs_rq->throttled_clock_pelt;
7056 		cfs_rq->pelt_clock_throttled = 0;
7057 	}
7058 
7059 	if (cfs_rq->throttled_clock_self) {
7060 		u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
7061 
7062 		cfs_rq->throttled_clock_self = 0;
7063 
7064 		if (WARN_ON_ONCE((s64)delta < 0))
7065 			delta = 0;
7066 
7067 		cfs_rq->throttled_clock_self_time += delta;
7068 	}
7069 
7070 	/*
7071 	 * Move the tasks to a local list since an update_curr() during
7072 	 * enqueue_task_fair() can throttle a higher cfs_rq, and it can
7073 	 * see the "throttled_limbo_list" being non-empty in
7074 	 * tg_throttle_down() if throttle_count turned 0 above.
7075 	 */
7076 	list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks);
7077 
7078 	/* Re-enqueue the tasks that have been throttled at this level. */
7079 	list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) {
7080 		/*
7081 		 * Back to being throttled! Break out and put the remaining
7082 		 * tasks back onto the limbo_list to prevent running them
7083 		 * unnecessarily.
7084 		 */
7085 		if (cfs_rq->throttle_count)
7086 			break;
7087 
7088 		list_del_init(&p->throttle_node);
7089 		p->throttled = false;
7090 		enqueue_task_fair(rq, p, ENQUEUE_WAKEUP);
7091 	}
7092 
7093 	list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list);
7094 
7095 	/* Add cfs_rq with load or one or more already running entities to the list */
7096 	if (!cfs_rq_is_decayed(cfs_rq))
7097 		list_add_leaf_cfs_rq(cfs_rq);
7098 
7099 	return 0;
7100 }
7101 
7102 static inline bool task_has_throttle_work(struct task_struct *p)
7103 {
7104 	return p->sched_throttle_work.next != &p->sched_throttle_work;
7105 }
7106 
7107 static inline void task_throttle_setup_work(struct task_struct *p)
7108 {
7109 	if (task_has_throttle_work(p))
7110 		return;
7111 
7112 	/*
7113 	 * Kthreads and exiting tasks don't return to userspace, so adding the
7114 	 * work is pointless
7115 	 */
7116 	if ((p->flags & (PF_EXITING | PF_KTHREAD)))
7117 		return;
7118 
7119 	task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
7120 }
7121 
7122 static void record_throttle_clock(struct cfs_rq *cfs_rq)
7123 {
7124 	struct rq *rq = rq_of(cfs_rq);
7125 
7126 	if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
7127 		cfs_rq->throttled_clock = rq_clock(rq);
7128 
7129 	if (!cfs_rq->throttled_clock_self)
7130 		cfs_rq->throttled_clock_self = rq_clock(rq);
7131 }
7132 
7133 static int tg_throttle_down(struct task_group *tg, void *data)
7134 {
7135 	struct rq *rq = data;
7136 	struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7137 
7138 	if (cfs_rq->throttle_count++)
7139 		return 0;
7140 
7141 	/*
7142 	 * For cfs_rqs that still have entities enqueued, PELT clock
7143 	 * stop happens at dequeue time when all entities are dequeued.
7144 	 */
7145 	if (!cfs_rq->nr_queued) {
7146 		list_del_leaf_cfs_rq(cfs_rq);
7147 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
7148 		cfs_rq->pelt_clock_throttled = 1;
7149 	}
7150 
7151 	WARN_ON_ONCE(cfs_rq->throttled_clock_self);
7152 	WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
7153 	return 0;
7154 }
7155 
7156 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
7157 {
7158 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7159 	struct sched_entity *curr = cfs_rq->h_curr;
7160 	struct rq *rq = rq_of(cfs_rq);
7161 
7162 	scoped_guard(raw_spinlock, &cfs_b->lock) {
7163 		u64 target_runtime = 1;
7164 
7165 		/*
7166 		 * If cfs_rq->h_curr is still runnable, we are here from an
7167 		 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice
7168 		 * worth of bandwidth to continue running.
7169 		 *
7170 		 * If the curr is not runnable, just request enough bandwidth
7171 		 * to be runnable next time the pick selects this cfs_rq.
7172 		 */
7173 		if (curr && curr->on_rq)
7174 			target_runtime = sched_cfs_bandwidth_slice();
7175 
7176 		/*
7177 		 * Check if We have raced with bandwidth becoming available. If
7178 		 * we actually throttled the timer might not unthrottle us for
7179 		 * an entire period. We additionally needed to make sure that
7180 		 * any subsequent check_cfs_rq_runtime calls agree not to
7181 		 * throttle us, as we may commit to do cfs put_prev+pick_next,
7182 		 * so we ask for 1ns of runtime rather than just check cfs_b.
7183 		 *
7184 		 * This will start the period timer if necessary.
7185 		 */
7186 		if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime))
7187 			return false;
7188 
7189 		/*
7190 		 * No bandwidth available; Add ourselves on the list to be
7191 		 * unthrottled later.
7192 		 */
7193 		list_add_tail_rcu(&cfs_rq->throttled_list,
7194 				  &cfs_b->throttled_cfs_rq);
7195 	}
7196 
7197 	/* freeze hierarchy runnable averages while throttled */
7198 	scoped_guard(rcu)
7199 		walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
7200 
7201 	/*
7202 	 * Note: distribution will already see us throttled via the
7203 	 * throttled-list.  rq->lock protects completion.
7204 	 */
7205 	cfs_rq->throttled = 1;
7206 	WARN_ON_ONCE(cfs_rq->throttled_clock);
7207 
7208 	/*
7209 	 * If current hierarchy was throttled, add throttle work to the
7210 	 * current donor. In case of proxy-execution, the execution
7211 	 * context cannot exit to the userspace while holding a mutex
7212 	 * and the rule of throttle deferral to only throttle the
7213 	 * throttled context at exit to userspace is still preserved.
7214 	 */
7215 	if (curr && curr->on_rq)
7216 		task_throttle_setup_work(rq->donor);
7217 
7218 	return true;
7219 }
7220 
7221 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
7222 {
7223 	struct rq *rq = rq_of(cfs_rq);
7224 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7225 	struct sched_entity *se = cfs_rq_se(cfs_rq);
7226 
7227 	/*
7228 	 * It's possible we are called with runtime_remaining < 0 due to things
7229 	 * like async unthrottled us with a positive runtime_remaining but other
7230 	 * still running entities consumed those runtime before we reached here.
7231 	 *
7232 	 * We can't unthrottle this cfs_rq without any runtime remaining because
7233 	 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
7234 	 * which is not supposed to happen on unthrottle path.
7235 	 *
7236 	 * Catch up on the remaining runtime since last clock update before
7237 	 * checking runtime remaining.
7238 	 */
7239 	update_curr(cfs_rq);
7240 	if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
7241 		return;
7242 
7243 	cfs_rq->throttled = 0;
7244 
7245 	scoped_guard(raw_spinlock, &cfs_b->lock) {
7246 		list_del_rcu(&cfs_rq->throttled_list);
7247 
7248 		if (!cfs_rq->throttled_clock)
7249 			break;
7250 
7251 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
7252 		cfs_rq->throttled_clock = 0;
7253 	}
7254 
7255 	/* update hierarchical throttle state */
7256 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
7257 
7258 	if (!cfs_rq->load.weight) {
7259 		if (!cfs_rq->on_list)
7260 			return;
7261 		/*
7262 		 * Nothing to run but something to decay (on_list)?
7263 		 * Complete the branch.
7264 		 */
7265 		for_each_sched_entity(se) {
7266 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
7267 				break;
7268 		}
7269 	}
7270 
7271 	assert_list_leaf_cfs_rq(rq);
7272 
7273 	/* Determine whether we need to wake up potentially idle CPU: */
7274 	if (rq->curr == rq->idle && rq->cfs.h_nr_queued)
7275 		resched_curr(rq);
7276 }
7277 
7278 static void __cfsb_csd_unthrottle(void *arg)
7279 {
7280 	struct cfs_rq *cursor, *tmp;
7281 	struct rq *rq = arg;
7282 
7283 	guard(rq_lock)(rq);
7284 
7285 	/*
7286 	 * Iterating over the list can trigger several call to
7287 	 * update_rq_clock() in unthrottle_cfs_rq().
7288 	 * Do it once and skip the potential next ones.
7289 	 */
7290 	update_rq_clock(rq);
7291 	rq_clock_start_loop_update(rq);
7292 
7293 	/*
7294 	 * Since we hold rq lock we're safe from concurrent manipulation of
7295 	 * the CSD list. However, this RCU critical section annotates the
7296 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
7297 	 * race with group being freed in the window between removing it
7298 	 * from the list and advancing to the next entry in the list.
7299 	 */
7300 	guard(rcu)();
7301 
7302 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
7303 				 throttled_csd_list) {
7304 		list_del_init(&cursor->throttled_csd_list);
7305 
7306 		if (cfs_rq_throttled(cursor))
7307 			unthrottle_cfs_rq(cursor);
7308 	}
7309 
7310 	rq_clock_stop_loop_update(rq);
7311 }
7312 
7313 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7314 {
7315 	struct rq *rq = rq_of(cfs_rq);
7316 	bool first;
7317 
7318 	if (rq == this_rq()) {
7319 		update_rq_clock(rq);
7320 		unthrottle_cfs_rq(cfs_rq);
7321 		return;
7322 	}
7323 
7324 	/* Already enqueued */
7325 	if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
7326 		return;
7327 
7328 	first = list_empty(&rq->cfsb_csd_list);
7329 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7330 	if (first)
7331 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
7332 }
7333 
7334 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7335 {
7336 	lockdep_assert_rq_held(rq_of(cfs_rq));
7337 
7338 	if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
7339 	    cfs_rq->runtime_remaining <= 0))
7340 		return;
7341 
7342 	__unthrottle_cfs_rq_async(cfs_rq);
7343 }
7344 
7345 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
7346 {
7347 	bool throttled = false, unthrottle_local = false;
7348 	int this_cpu = smp_processor_id();
7349 	u64 runtime, remaining = 1;
7350 	struct cfs_rq *cfs_rq;
7351 	struct rq *rq;
7352 
7353 	guard(rcu)();
7354 
7355 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
7356 				throttled_list) {
7357 		rq = rq_of(cfs_rq);
7358 
7359 		if (!remaining) {
7360 			throttled = true;
7361 			break;
7362 		}
7363 
7364 		guard(rq_lock_irqsave)(rq);
7365 
7366 		if (!cfs_rq_throttled(cfs_rq))
7367 			continue;
7368 
7369 		/* Already queued for async unthrottle */
7370 		if (!list_empty(&cfs_rq->throttled_csd_list))
7371 			continue;
7372 
7373 		if (cfs_rq->h_curr) {
7374 			update_rq_clock(rq);
7375 			update_curr(cfs_rq);
7376 		}
7377 
7378 		/* By the above checks, this should never be true */
7379 		WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
7380 
7381 		scoped_guard(raw_spinlock, &cfs_b->lock) {
7382 			runtime = -cfs_rq->runtime_remaining + 1;
7383 			if (runtime > cfs_b->runtime)
7384 				runtime = cfs_b->runtime;
7385 			cfs_b->runtime -= runtime;
7386 			remaining = cfs_b->runtime;
7387 		}
7388 
7389 		cfs_rq->runtime_remaining += runtime;
7390 
7391 		/*
7392 		 * Ran out of bandwidth during distribution!
7393 		 * Indicate throttled entities and break early.
7394 		 */
7395 		if (cfs_rq->runtime_remaining <= 0) {
7396 			throttled = true;
7397 			break;
7398 		}
7399 
7400 		/* we check whether we're throttled above */
7401 		if (cpu_of(rq) != this_cpu) {
7402 			unthrottle_cfs_rq_async(cfs_rq);
7403 			continue;
7404 		}
7405 
7406 		/*
7407 		 * Allow a parallel async unthrottle to unthrottle
7408 		 * this cfs_rq too via __cfsb_csd_unthrottle().
7409 		 * If we are first, do it ourselves at the end and
7410 		 * save on an IPI from remote CPUs.
7411 		 */
7412 		unthrottle_local = list_empty(&rq->cfsb_csd_list);
7413 		list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7414 	}
7415 
7416 	if (unthrottle_local) {
7417 		/*
7418 		 * Protect against an IPI that is also trying to flush
7419 		 * the unthrottled cfs_rq(s) from this CPU's csd_list.
7420 		 */
7421 		scoped_guard(irqsave)
7422 			__cfsb_csd_unthrottle(cpu_rq(this_cpu));
7423 	}
7424 
7425 	return throttled;
7426 }
7427 
7428 /*
7429  * Responsible for refilling a task_group's bandwidth and unthrottling its
7430  * cfs_rqs as appropriate. If there has been no activity within the last
7431  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
7432  * used to track this state.
7433  */
7434 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
7435 	__must_hold(&cfs_b->lock)
7436 {
7437 	int throttled;
7438 
7439 	/* no need to continue the timer with no bandwidth constraint */
7440 	if (cfs_b->quota == RUNTIME_INF)
7441 		goto out_deactivate;
7442 
7443 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
7444 	cfs_b->nr_periods += overrun;
7445 
7446 	/* Refill extra burst quota even if cfs_b->idle */
7447 	__refill_cfs_bandwidth_runtime(cfs_b);
7448 
7449 	/*
7450 	 * idle depends on !throttled (for the case of a large deficit), and if
7451 	 * we're going inactive then everything else can be deferred
7452 	 */
7453 	if (cfs_b->idle && !throttled)
7454 		goto out_deactivate;
7455 
7456 	if (!throttled) {
7457 		/* mark as potentially idle for the upcoming period */
7458 		cfs_b->idle = 1;
7459 		return 0;
7460 	}
7461 
7462 	/* account preceding periods in which throttling occurred */
7463 	cfs_b->nr_throttled += overrun;
7464 
7465 	/*
7466 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
7467 	 */
7468 	while (throttled && cfs_b->runtime > 0) {
7469 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
7470 		/* we can't nest cfs_b->lock while distributing bandwidth */
7471 		throttled = distribute_cfs_runtime(cfs_b);
7472 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
7473 	}
7474 
7475 	/*
7476 	 * While we are ensured activity in the period following an
7477 	 * unthrottle, this also covers the case in which the new bandwidth is
7478 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
7479 	 * timer to remain active while there are any throttled entities.)
7480 	 */
7481 	cfs_b->idle = 0;
7482 
7483 	return 0;
7484 
7485 out_deactivate:
7486 	return 1;
7487 }
7488 
7489 /* a cfs_rq won't donate quota below this amount */
7490 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
7491 /* minimum remaining period time to redistribute slack quota */
7492 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
7493 /* how long we wait to gather additional slack before distributing */
7494 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
7495 
7496 /*
7497  * Are we near the end of the current quota period?
7498  *
7499  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
7500  * hrtimer base being cleared by hrtimer_start. In the case of
7501  * migrate_hrtimers, base is never cleared, so we are fine.
7502  */
7503 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
7504 {
7505 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
7506 	s64 remaining;
7507 
7508 	/* if the call-back is running a quota refresh is already occurring */
7509 	if (hrtimer_callback_running(refresh_timer))
7510 		return 1;
7511 
7512 	/* is a quota refresh about to occur? */
7513 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
7514 	if (remaining < (s64)min_expire)
7515 		return 1;
7516 
7517 	return 0;
7518 }
7519 
7520 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
7521 {
7522 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
7523 
7524 	/* if there's a quota refresh soon don't bother with slack */
7525 	if (runtime_refresh_within(cfs_b, min_left))
7526 		return;
7527 
7528 	/* don't push forwards an existing deferred unthrottle */
7529 	if (cfs_b->slack_started)
7530 		return;
7531 	cfs_b->slack_started = true;
7532 
7533 	hrtimer_start(&cfs_b->slack_timer,
7534 			ns_to_ktime(cfs_bandwidth_slack_period),
7535 			HRTIMER_MODE_REL);
7536 }
7537 
7538 /* we know any runtime found here is valid as update_curr() precedes return */
7539 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7540 {
7541 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7542 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
7543 
7544 	if (slack_runtime <= 0)
7545 		return;
7546 
7547 	guard(raw_spinlock)(&cfs_b->lock);
7548 
7549 	if (cfs_b->quota != RUNTIME_INF) {
7550 		cfs_b->runtime += slack_runtime;
7551 
7552 		/* we are under rq->lock, defer unthrottling using a timer */
7553 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
7554 		    !list_empty(&cfs_b->throttled_cfs_rq))
7555 			start_cfs_slack_bandwidth(cfs_b);
7556 	}
7557 
7558 	/* even if it's not valid for return we don't want to try again */
7559 	cfs_rq->runtime_remaining -= slack_runtime;
7560 }
7561 
7562 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7563 {
7564 	if (!cfs_bandwidth_used())
7565 		return;
7566 
7567 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
7568 		return;
7569 
7570 	__return_cfs_rq_runtime(cfs_rq);
7571 }
7572 
7573 /*
7574  * This is done with a timer (instead of inline with bandwidth return) since
7575  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
7576  */
7577 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
7578 {
7579 	/* confirm we're still not at a refresh boundary */
7580 	scoped_guard(raw_spinlock_irqsave, &cfs_b->lock) {
7581 		u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
7582 
7583 		cfs_b->slack_started = false;
7584 
7585 		if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
7586 			return;
7587 
7588 		if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
7589 			runtime = cfs_b->runtime;
7590 
7591 		if (!runtime)
7592 			return;
7593 	}
7594 
7595 	distribute_cfs_runtime(cfs_b);
7596 }
7597 
7598 /*
7599  * When a group wakes up we want to make sure that its quota is not already
7600  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
7601  * runtime as update_curr() throttling can not trigger until it's on-rq.
7602  */
7603 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
7604 {
7605 	if (!cfs_bandwidth_used())
7606 		return;
7607 
7608 	/* an active group must be handled by the update_curr() path */
7609 	if (!cfs_rq->runtime_enabled || cfs_rq->h_curr)
7610 		return;
7611 
7612 	/* ensure the group is not already throttled */
7613 	if (cfs_rq_throttled(cfs_rq))
7614 		return;
7615 
7616 	/* update runtime allocation */
7617 	account_cfs_rq_runtime(cfs_rq, 0);
7618 }
7619 
7620 static void sync_throttle(struct task_group *tg, int cpu)
7621 {
7622 	struct cfs_rq *pcfs_rq, *cfs_rq;
7623 
7624 	if (!cfs_bandwidth_used())
7625 		return;
7626 
7627 	if (!tg->parent)
7628 		return;
7629 
7630 	cfs_rq = tg_cfs_rq(tg, cpu);
7631 	pcfs_rq = tg_cfs_rq(tg->parent, cpu);
7632 
7633 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
7634 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
7635 
7636 	/*
7637 	 * It is not enough to sync the "pelt_clock_throttled" indicator
7638 	 * with the parent cfs_rq when the hierarchy is not queued.
7639 	 * Always join a throttled hierarchy with PELT clock throttled
7640 	 * and leaf it to the first enqueue, or distribution to
7641 	 * unthrottle the PELT clock.
7642 	 */
7643 	if (cfs_rq->throttle_count)
7644 		cfs_rq->pelt_clock_throttled = 1;
7645 }
7646 
7647 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
7648 {
7649 	struct cfs_bandwidth *cfs_b =
7650 		container_of(timer, struct cfs_bandwidth, slack_timer);
7651 
7652 	do_sched_cfs_slack_timer(cfs_b);
7653 
7654 	return HRTIMER_NORESTART;
7655 }
7656 
7657 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
7658 {
7659 	struct cfs_bandwidth *cfs_b =
7660 		container_of(timer, struct cfs_bandwidth, period_timer);
7661 	int overrun;
7662 	int idle = 0;
7663 	int count = 0;
7664 
7665 	CLASS(raw_spinlock_irqsave, cfsb_guard)(&cfs_b->lock);
7666 
7667 	for (;;) {
7668 		overrun = hrtimer_forward_now(timer, cfs_b->period);
7669 		if (!overrun)
7670 			break;
7671 
7672 		idle = do_sched_cfs_period_timer(cfs_b, overrun, cfsb_guard.flags);
7673 
7674 		if (++count > 3) {
7675 			u64 new, old = ktime_to_ns(cfs_b->period);
7676 
7677 			/*
7678 			 * Grow period by a factor of 2 to avoid losing precision.
7679 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
7680 			 * to fail.
7681 			 */
7682 			new = old * 2;
7683 			if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
7684 				cfs_b->period = ns_to_ktime(new);
7685 				cfs_b->quota *= 2;
7686 				cfs_b->burst *= 2;
7687 
7688 				pr_warn_ratelimited(
7689 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7690 					smp_processor_id(),
7691 					div_u64(new, NSEC_PER_USEC),
7692 					div_u64(cfs_b->quota, NSEC_PER_USEC));
7693 			} else {
7694 				pr_warn_ratelimited(
7695 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7696 					smp_processor_id(),
7697 					div_u64(old, NSEC_PER_USEC),
7698 					div_u64(cfs_b->quota, NSEC_PER_USEC));
7699 			}
7700 
7701 			/* reset count so we don't come right back in here */
7702 			count = 0;
7703 		}
7704 	}
7705 
7706 	if (idle) {
7707 		cfs_b->period_active = 0;
7708 		return HRTIMER_NORESTART;
7709 	}
7710 
7711 	return HRTIMER_RESTART;
7712 }
7713 
7714 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
7715 {
7716 	raw_spin_lock_init(&cfs_b->lock);
7717 	cfs_b->runtime = 0;
7718 	cfs_b->quota = RUNTIME_INF;
7719 	cfs_b->period = us_to_ktime(default_bw_period_us());
7720 	cfs_b->burst = 0;
7721 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
7722 
7723 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
7724 	hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
7725 		      HRTIMER_MODE_ABS_PINNED);
7726 
7727 	/* Add a random offset so that timers interleave */
7728 	hrtimer_set_expires(&cfs_b->period_timer,
7729 			    get_random_u32_below(cfs_b->period));
7730 	hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
7731 		      HRTIMER_MODE_REL);
7732 	cfs_b->slack_started = false;
7733 }
7734 
7735 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7736 {
7737 	cfs_rq->runtime_enabled = 0;
7738 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
7739 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
7740 	INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
7741 }
7742 
7743 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7744 {
7745 	lockdep_assert_held(&cfs_b->lock);
7746 
7747 	if (cfs_b->period_active)
7748 		return;
7749 
7750 	cfs_b->period_active = 1;
7751 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
7752 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
7753 }
7754 
7755 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7756 {
7757 	int __maybe_unused i;
7758 
7759 	/* init_cfs_bandwidth() was not called */
7760 	if (!cfs_b->throttled_cfs_rq.next)
7761 		return;
7762 
7763 	hrtimer_cancel(&cfs_b->period_timer);
7764 	hrtimer_cancel(&cfs_b->slack_timer);
7765 
7766 	/*
7767 	 * It is possible that we still have some cfs_rq's pending on a CSD
7768 	 * list, though this race is very rare. In order for this to occur, we
7769 	 * must have raced with the last task leaving the group while there
7770 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
7771 	 * CSD item but the remote cpu has not yet processed it. To handle this,
7772 	 * we can simply flush all pending CSD work inline here. We're
7773 	 * guaranteed at this point that no additional cfs_rq of this group can
7774 	 * join a CSD list.
7775 	 */
7776 	for_each_possible_cpu(i) {
7777 		struct rq *rq = cpu_rq(i);
7778 
7779 		if (list_empty(&rq->cfsb_csd_list))
7780 			continue;
7781 
7782 		scoped_guard(irqsave)
7783 			__cfsb_csd_unthrottle(rq);
7784 	}
7785 }
7786 
7787 /*
7788  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
7789  *
7790  * The race is harmless, since modifying bandwidth settings of unhooked group
7791  * bits doesn't do much.
7792  */
7793 
7794 /* cpu online callback */
7795 static void __maybe_unused update_runtime_enabled(struct rq *rq)
7796 {
7797 	struct task_group *tg;
7798 
7799 	lockdep_assert_rq_held(rq);
7800 
7801 	guard(rcu)();
7802 
7803 	list_for_each_entry_rcu(tg, &task_groups, list) {
7804 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7805 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7806 
7807 		scoped_guard(raw_spinlock, &cfs_b->lock)
7808 			cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
7809 	}
7810 }
7811 
7812 /* cpu offline callback */
7813 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
7814 {
7815 	struct task_group *tg;
7816 
7817 	lockdep_assert_rq_held(rq);
7818 
7819 	// Do not unthrottle for an active CPU
7820 	if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
7821 		return;
7822 
7823 	/*
7824 	 * The rq clock has already been updated in the
7825 	 * set_rq_offline(), so we should skip updating
7826 	 * the rq clock again in unthrottle_cfs_rq().
7827 	 */
7828 	rq_clock_start_loop_update(rq);
7829 
7830 	guard(rcu)();
7831 
7832 	list_for_each_entry_rcu(tg, &task_groups, list) {
7833 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7834 
7835 		if (!cfs_rq->runtime_enabled)
7836 			continue;
7837 
7838 		/*
7839 		 * Offline rq is schedulable till CPU is completely disabled
7840 		 * in take_cpu_down(), so we prevent new cfs throttling here.
7841 		 */
7842 		cfs_rq->runtime_enabled = 0;
7843 
7844 		if (!cfs_rq_throttled(cfs_rq))
7845 			continue;
7846 
7847 		/*
7848 		 * clock_task is not advancing so we just need to make sure
7849 		 * there's some valid quota amount
7850 		 */
7851 		cfs_rq->runtime_remaining = 1;
7852 		unthrottle_cfs_rq(cfs_rq);
7853 	}
7854 
7855 	rq_clock_stop_loop_update(rq);
7856 }
7857 
7858 bool cfs_task_bw_constrained(struct task_struct *p)
7859 {
7860 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
7861 
7862 	if (!cfs_bandwidth_used())
7863 		return false;
7864 
7865 	if (cfs_rq->runtime_enabled ||
7866 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
7867 		return true;
7868 
7869 	return false;
7870 }
7871 
7872 #ifdef CONFIG_NO_HZ_FULL
7873 /* called from pick_next_task_fair() */
7874 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
7875 {
7876 	int cpu = cpu_of(rq);
7877 
7878 	if (!cfs_bandwidth_used())
7879 		return;
7880 
7881 	if (!tick_nohz_full_cpu(cpu))
7882 		return;
7883 
7884 	if (rq->nr_running != 1)
7885 		return;
7886 
7887 	/*
7888 	 *  We know there is only one task runnable and we've just picked it. The
7889 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
7890 	 *  be otherwise able to stop the tick. Just need to check if we are using
7891 	 *  bandwidth control.
7892 	 */
7893 	if (cfs_task_bw_constrained(p))
7894 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
7895 }
7896 #endif /* CONFIG_NO_HZ_FULL */
7897 
7898 #else /* !CONFIG_CFS_BANDWIDTH: */
7899 
7900 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; }
7901 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
7902 static inline void sync_throttle(struct task_group *tg, int cpu) {}
7903 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
7904 static void task_throttle_setup_work(struct task_struct *p) {}
7905 static bool task_is_throttled(struct task_struct *p) { return false; }
7906 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
7907 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
7908 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
7909 
7910 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
7911 {
7912 	return 0;
7913 }
7914 
7915 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
7916 {
7917 	return false;
7918 }
7919 
7920 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
7921 {
7922 	return 0;
7923 }
7924 
7925 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
7926 {
7927 	return 0;
7928 }
7929 
7930 #ifdef CONFIG_FAIR_GROUP_SCHED
7931 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
7932 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
7933 #endif
7934 
7935 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
7936 {
7937 	return NULL;
7938 }
7939 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
7940 static inline void update_runtime_enabled(struct rq *rq) {}
7941 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
7942 #ifdef CONFIG_CGROUP_SCHED
7943 bool cfs_task_bw_constrained(struct task_struct *p)
7944 {
7945 	return false;
7946 }
7947 #endif
7948 #endif /* !CONFIG_CFS_BANDWIDTH */
7949 
7950 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
7951 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
7952 #endif
7953 
7954 /**************************************************
7955  * CFS operations on tasks:
7956  */
7957 
7958 #ifdef CONFIG_SCHED_HRTICK
7959 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
7960 {
7961 	struct sched_entity *se = &p->se;
7962 	unsigned long scale = 1024;
7963 	unsigned long util = 0;
7964 	u64 vdelta;
7965 	u64 delta;
7966 
7967 	WARN_ON_ONCE(task_rq(p) != rq);
7968 
7969 	if (rq->cfs.h_nr_queued <= 1)
7970 		return;
7971 
7972 	/*
7973 	 * Compute time until virtual deadline
7974 	 */
7975 	vdelta = se->deadline - se->vruntime;
7976 	if ((s64)vdelta < 0) {
7977 		if (task_current_donor(rq, p))
7978 			resched_curr(rq);
7979 		return;
7980 	}
7981 	delta = (se->h_load.weight * vdelta) / NICE_0_LOAD;
7982 
7983 	/*
7984 	 * Correct for instantaneous load of other classes.
7985 	 */
7986 	util += cpu_util_irq(rq);
7987 	if (util && util < 1024) {
7988 		scale *= 1024;
7989 		scale /= (1024 - util);
7990 	}
7991 
7992 	hrtick_start(rq, (scale * delta) / 1024);
7993 }
7994 
7995 /*
7996  * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1.
7997  */
7998 static void hrtick_update(struct rq *rq)
7999 {
8000 	struct task_struct *donor = rq->donor;
8001 
8002 	if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
8003 		return;
8004 
8005 	if (hrtick_active(rq))
8006 		return;
8007 
8008 	hrtick_start_fair(rq, donor);
8009 }
8010 #else /* !CONFIG_SCHED_HRTICK: */
8011 static inline void
8012 hrtick_start_fair(struct rq *rq, struct task_struct *p)
8013 {
8014 }
8015 
8016 static inline void hrtick_update(struct rq *rq)
8017 {
8018 }
8019 #endif /* !CONFIG_SCHED_HRTICK */
8020 
8021 static inline bool cpu_overutilized(int cpu)
8022 {
8023 	unsigned long rq_util_max;
8024 
8025 	if (!sched_energy_enabled())
8026 		return false;
8027 
8028 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
8029 
8030 	/* Return true only if the utilization doesn't fit CPU's capacity */
8031 	return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu);
8032 }
8033 
8034 /*
8035  * overutilized value make sense only if EAS is enabled
8036  */
8037 static inline bool is_rd_overutilized(struct root_domain *rd)
8038 {
8039 	return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
8040 }
8041 
8042 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
8043 {
8044 	if (!sched_energy_enabled())
8045 		return;
8046 
8047 	WRITE_ONCE(rd->overutilized, flag);
8048 	trace_sched_overutilized_tp(rd, flag);
8049 }
8050 
8051 static inline void check_update_overutilized_status(struct rq *rq)
8052 {
8053 	/*
8054 	 * overutilized field is used for load balancing decisions only
8055 	 * if energy aware scheduler is being used
8056 	 */
8057 
8058 	if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
8059 		set_rd_overutilized(rq->rd, 1);
8060 }
8061 
8062 /* Runqueue only has SCHED_IDLE tasks enqueued */
8063 static int sched_idle_rq(struct rq *rq)
8064 {
8065 	return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
8066 			rq->nr_running);
8067 }
8068 
8069 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p)
8070 {
8071 	return sched_idle_rq(rq) && !task_has_idle_policy(p);
8072 }
8073 
8074 static int choose_idle_cpu(int cpu, struct task_struct *p)
8075 {
8076 	return available_idle_cpu(cpu) ||
8077 	       choose_sched_idle_rq(cpu_rq(cpu), p);
8078 }
8079 
8080 static void
8081 requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
8082 {
8083 	/*
8084 	 * se->sched_delayed should imply: se->on_rq == 1.
8085 	 * Because a delayed entity is one that is still on
8086 	 * the runqueue competing until elegibility.
8087 	 */
8088 	WARN_ON_ONCE(!se->sched_delayed);
8089 	WARN_ON_ONCE(!se->on_rq);
8090 
8091 	if (update_entity_lag(cfs_rq, se)) {
8092 		cfs_rq->h_nr_queued--;
8093 		if (se != cfs_rq->curr)
8094 			__dequeue_entity(cfs_rq, se);
8095 		place_entity(cfs_rq, se, 0);
8096 		if (se != cfs_rq->curr)
8097 			__enqueue_entity(cfs_rq, se);
8098 		cfs_rq->h_nr_queued++;
8099 	}
8100 
8101 	update_load_avg(cfs_rq, se, 0);
8102 	clear_delayed(se);
8103 }
8104 
8105 static unsigned long enqueue_hierarchy(struct task_struct *p, int flags)
8106 {
8107 	unsigned long weight = NICE_0_LOAD;
8108 	int task_new = !(flags & ENQUEUE_WAKEUP);
8109 	struct sched_entity *se = &p->se;
8110 	int h_nr_idle = task_has_idle_policy(p);
8111 	int h_nr_runnable = 1;
8112 
8113 	if (task_new && se->sched_delayed)
8114 		h_nr_runnable = 0;
8115 
8116 	for_each_sched_entity(se) {
8117 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
8118 
8119 		update_curr(cfs_rq);
8120 
8121 		if (!se->on_rq) {
8122 			enqueue_entity(cfs_rq, se, flags);
8123 		} else {
8124 			update_load_avg(cfs_rq, se, UPDATE_TG);
8125 			se_update_runnable(se);
8126 			update_cfs_group(se);
8127 		}
8128 
8129 		cfs_rq->h_nr_runnable += h_nr_runnable;
8130 		cfs_rq->h_nr_queued++;
8131 		cfs_rq->h_nr_idle += h_nr_idle;
8132 
8133 		if (cfs_rq_is_idle(cfs_rq))
8134 			h_nr_idle = 1;
8135 
8136 		weight = __calc_prop_weight(cfs_rq, se, weight);
8137 
8138 		flags = ENQUEUE_WAKEUP;
8139 	}
8140 
8141 	return weight;
8142 }
8143 
8144 /* Update curr's vruntime before placing entity or updating lag */
8145 static inline void update_curr_eevdf(struct cfs_rq *cfs_rq)
8146 {
8147 	if (!cfs_rq->curr)
8148 		return;
8149 
8150 	update_curr(cfs_rq_of(cfs_rq->curr));
8151 }
8152 
8153 /*
8154  * The enqueue_task method is called before nr_running is
8155  * increased. Here we update the fair scheduling stats and
8156  * then put the task into the rbtree:
8157  */
8158 static void
8159 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
8160 {
8161 	int rq_h_nr_queued = rq->cfs.h_nr_queued;
8162 	int task_new = !(flags & ENQUEUE_WAKEUP);
8163 	struct sched_entity *se = &p->se;
8164 	struct cfs_rq *cfs_rq = &rq->cfs;
8165 	unsigned long weight;
8166 	bool curr;
8167 
8168 	if (task_is_throttled(p) && enqueue_throttled_task(p))
8169 		return;
8170 
8171 	/*
8172 	 * The code below (indirectly) updates schedutil which looks at
8173 	 * the cfs_rq utilization to select a frequency.
8174 	 * Let's add the task's estimated utilization to the cfs_rq's
8175 	 * estimated utilization, before we update schedutil.
8176 	 */
8177 	if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
8178 		util_est_enqueue(cfs_rq, p);
8179 
8180 	update_curr_eevdf(cfs_rq);
8181 
8182 	if (flags & ENQUEUE_DELAYED) {
8183 		requeue_delayed_entity(cfs_rq, se);
8184 		return;
8185 	}
8186 
8187 	/*
8188 	 * If in_iowait is set, the code below may not trigger any cpufreq
8189 	 * utilization updates, so do it here explicitly with the IOWAIT flag
8190 	 * passed.
8191 	 */
8192 	if (p->in_iowait)
8193 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
8194 
8195 	curr = (cfs_rq->curr == se);
8196 	/*
8197 	 * This can actually happen with CFS_BANDWIDTH, a task can be throttled
8198 	 * and dequeued, unthrottled from another CPU and then enqueued again
8199 	 * before schedule().
8200 	 */
8201 	if (curr)
8202 		place_entity(cfs_rq, se, flags);
8203 
8204 	if (se->on_rq && se->sched_delayed)
8205 		requeue_delayed_entity(cfs_rq, se);
8206 
8207 	weight = enqueue_hierarchy(p, flags);
8208 
8209 	if (!curr) {
8210 		reweight_eevdf(cfs_rq, se, weight, false);
8211 		place_entity(cfs_rq, se, flags | ENQUEUE_QUEUED);
8212 		__enqueue_entity(cfs_rq, se);
8213 	}
8214 
8215 	if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
8216 		dl_server_start(&rq->fair_server);
8217 
8218 	/* At this point se is NULL and we are at root level*/
8219 	add_nr_running(rq, 1);
8220 
8221 	/*
8222 	 * Since new tasks are assigned an initial util_avg equal to
8223 	 * half of the spare capacity of their CPU, tiny tasks have the
8224 	 * ability to cross the overutilized threshold, which will
8225 	 * result in the load balancer ruining all the task placement
8226 	 * done by EAS. As a way to mitigate that effect, do not account
8227 	 * for the first enqueue operation of new tasks during the
8228 	 * overutilized flag detection.
8229 	 *
8230 	 * A better way of solving this problem would be to wait for
8231 	 * the PELT signals of tasks to converge before taking them
8232 	 * into account, but that is not straightforward to implement,
8233 	 * and the following generally works well enough in practice.
8234 	 */
8235 	if (!task_new)
8236 		check_update_overutilized_status(rq);
8237 
8238 	assert_list_leaf_cfs_rq(rq);
8239 
8240 	hrtick_update(rq);
8241 }
8242 
8243 static void dequeue_hierarchy(struct task_struct *p, int flags)
8244 {
8245 	struct sched_entity *se = &p->se;
8246 	bool task_sleep = flags & DEQUEUE_SLEEP;
8247 	bool task_delayed = flags & DEQUEUE_DELAYED;
8248 	bool task_throttled = flags & DEQUEUE_THROTTLE;
8249 	int h_nr_runnable = 0;
8250 	int h_nr_idle = task_has_idle_policy(p);
8251 	bool dequeue = true;
8252 
8253 	if (task_sleep || task_delayed || !se->sched_delayed)
8254 		h_nr_runnable = 1;
8255 
8256 	for_each_sched_entity(se) {
8257 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
8258 
8259 		update_curr(cfs_rq);
8260 
8261 		if (dequeue) {
8262 			dequeue_entity(cfs_rq, se, flags);
8263 			/* Don't dequeue parent if it has other entities besides us */
8264 			if (cfs_rq->load.weight)
8265 				dequeue = false;
8266 		} else {
8267 			update_load_avg(cfs_rq, se, UPDATE_TG);
8268 			se_update_runnable(se);
8269 			update_cfs_group(se);
8270 		}
8271 
8272 		cfs_rq->h_nr_runnable -= h_nr_runnable;
8273 		cfs_rq->h_nr_queued--;
8274 		cfs_rq->h_nr_idle -= h_nr_idle;
8275 
8276 		if (cfs_rq_is_idle(cfs_rq))
8277 			h_nr_idle = 1;
8278 
8279 		if (throttled_hierarchy(cfs_rq) && task_throttled)
8280 			record_throttle_clock(cfs_rq);
8281 
8282 		flags |= DEQUEUE_SLEEP;
8283 		flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
8284 	}
8285 }
8286 
8287 /*
8288  * The part of dequeue_task_fair() that is needed to dequeue delayed tasks.
8289  *
8290  * Returns:
8291  *   true  - dequeued
8292  *   false - delayed
8293  */
8294 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags)
8295 {
8296 	struct sched_entity *se = &p->se;
8297 	struct cfs_rq *cfs_rq = &rq->cfs;
8298 	bool was_sched_idle = sched_idle_rq(rq);
8299 	bool task_sleep = flags & DEQUEUE_SLEEP;
8300 	bool task_delayed = flags & DEQUEUE_DELAYED;
8301 
8302 	clear_buddies(cfs_rq, se);
8303 
8304 	update_curr_eevdf(cfs_rq);
8305 	update_entity_lag(cfs_rq, se);
8306 
8307 	if (flags & DEQUEUE_DELAYED) {
8308 		WARN_ON_ONCE(!se->sched_delayed);
8309 	} else {
8310 		bool delay = task_sleep;
8311 		/*
8312 		 * DELAY_DEQUEUE relies on spurious wakeups, special task
8313 		 * states must not suffer spurious wakeups, excempt them.
8314 		 */
8315 		if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
8316 			delay = false;
8317 
8318 		WARN_ON_ONCE(delay && se->sched_delayed);
8319 
8320 		if (sched_feat(DELAY_DEQUEUE) && delay &&
8321 		    !entity_eligible(cfs_rq, se)) {
8322 			update_load_avg(cfs_rq_of(se), se, UPDATE_UTIL_EST);
8323 			set_delayed(se);
8324 			return false;
8325 		}
8326 	}
8327 
8328 	dequeue_hierarchy(p, flags);
8329 
8330 	if (sched_feat(PLACE_REL_DEADLINE) && !task_sleep) {
8331 		se->deadline -= se->vruntime;
8332 		se->rel_deadline = 1;
8333 	}
8334 	if (se != cfs_rq->curr)
8335 		__dequeue_entity(cfs_rq, se);
8336 
8337 	sub_nr_running(rq, 1);
8338 
8339 	/* balance early to pull high priority tasks */
8340 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
8341 		rq->next_balance = jiffies;
8342 
8343 	if (task_delayed) {
8344 		clear_delayed(se);
8345 
8346 		WARN_ON_ONCE(!task_sleep);
8347 		WARN_ON_ONCE(p->on_rq != 1);
8348 
8349 		/*
8350 		 * Fix-up what block_task() skipped.
8351 		 *
8352 		 * Must be last, @p might not be valid after this.
8353 		 */
8354 		__block_task(rq, p);
8355 	}
8356 
8357 	return true;
8358 }
8359 
8360 /*
8361  * The dequeue_task method is called before nr_running is
8362  * decreased. We remove the task from the rbtree and
8363  * update the fair scheduling stats:
8364  */
8365 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
8366 {
8367 	if (task_is_throttled(p)) {
8368 		dequeue_throttled_task(p, flags);
8369 		return true;
8370 	}
8371 
8372 	if (!p->se.sched_delayed)
8373 		util_est_dequeue(&rq->cfs, p);
8374 
8375 	if (!__dequeue_task(rq, p, flags))
8376 		return false;
8377 
8378 	/*
8379 	 * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED).
8380 	 */
8381 	return true;
8382 }
8383 
8384 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
8385 {
8386 	return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
8387 }
8388 
8389 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
8390 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
8391 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
8392 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
8393 
8394 #ifdef CONFIG_NO_HZ_COMMON
8395 
8396 static struct {
8397 	cpumask_var_t idle_cpus_mask;
8398 	int has_blocked_load;		/* Idle CPUS has blocked load */
8399 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
8400 	unsigned long next_balance;     /* in jiffy units */
8401 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
8402 } nohz ____cacheline_aligned;
8403 
8404 #endif /* CONFIG_NO_HZ_COMMON */
8405 
8406 static unsigned long cpu_load(struct rq *rq)
8407 {
8408 	return cfs_rq_load_avg(&rq->cfs);
8409 }
8410 
8411 /*
8412  * cpu_load_without - compute CPU load without any contributions from *p
8413  * @cpu: the CPU which load is requested
8414  * @p: the task which load should be discounted
8415  *
8416  * The load of a CPU is defined by the load of tasks currently enqueued on that
8417  * CPU as well as tasks which are currently sleeping after an execution on that
8418  * CPU.
8419  *
8420  * This method returns the load of the specified CPU by discounting the load of
8421  * the specified task, whenever the task is currently contributing to the CPU
8422  * load.
8423  */
8424 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
8425 {
8426 	struct cfs_rq *cfs_rq;
8427 	unsigned int load;
8428 
8429 	/* Task has no contribution or is new */
8430 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8431 		return cpu_load(rq);
8432 
8433 	cfs_rq = &rq->cfs;
8434 	load = READ_ONCE(cfs_rq->avg.load_avg);
8435 
8436 	/* Discount task's util from CPU's util */
8437 	lsub_positive(&load, task_h_load(p));
8438 
8439 	return load;
8440 }
8441 
8442 static unsigned long cpu_runnable(struct rq *rq)
8443 {
8444 	return cfs_rq_runnable_avg(&rq->cfs);
8445 }
8446 
8447 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
8448 {
8449 	struct cfs_rq *cfs_rq;
8450 	unsigned int runnable;
8451 
8452 	/* Task has no contribution or is new */
8453 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8454 		return cpu_runnable(rq);
8455 
8456 	cfs_rq = &rq->cfs;
8457 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
8458 
8459 	/* Discount task's runnable from CPU's runnable */
8460 	lsub_positive(&runnable, p->se.avg.runnable_avg);
8461 
8462 	return runnable;
8463 }
8464 
8465 static unsigned long capacity_of(int cpu)
8466 {
8467 	return cpu_rq(cpu)->cpu_capacity;
8468 }
8469 
8470 static void record_wakee(struct task_struct *p)
8471 {
8472 	/*
8473 	 * Only decay a single time; tasks that have less then 1 wakeup per
8474 	 * jiffy will not have built up many flips.
8475 	 */
8476 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
8477 		current->wakee_flips >>= 1;
8478 		current->wakee_flip_decay_ts = jiffies;
8479 	}
8480 
8481 	if (current->last_wakee != p) {
8482 		current->last_wakee = p;
8483 		current->wakee_flips++;
8484 	}
8485 }
8486 
8487 /*
8488  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
8489  *
8490  * A waker of many should wake a different task than the one last awakened
8491  * at a frequency roughly N times higher than one of its wakees.
8492  *
8493  * In order to determine whether we should let the load spread vs consolidating
8494  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
8495  * partner, and a factor of lls_size higher frequency in the other.
8496  *
8497  * With both conditions met, we can be relatively sure that the relationship is
8498  * non-monogamous, with partner count exceeding socket size.
8499  *
8500  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
8501  * whatever is irrelevant, spread criteria is apparent partner count exceeds
8502  * socket size.
8503  */
8504 static int wake_wide(struct task_struct *p)
8505 {
8506 	unsigned int master = current->wakee_flips;
8507 	unsigned int slave = p->wakee_flips;
8508 	int factor = __this_cpu_read(sd_llc_size);
8509 
8510 	if (master < slave)
8511 		swap(master, slave);
8512 	if (slave < factor || master < slave * factor)
8513 		return 0;
8514 	return 1;
8515 }
8516 
8517 /*
8518  * The purpose of wake_affine() is to quickly determine on which CPU we can run
8519  * soonest. For the purpose of speed we only consider the waking and previous
8520  * CPU.
8521  *
8522  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
8523  *			cache-affine and is (or	will be) idle.
8524  *
8525  * wake_affine_weight() - considers the weight to reflect the average
8526  *			  scheduling latency of the CPUs. This seems to work
8527  *			  for the overloaded case.
8528  */
8529 static int
8530 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
8531 {
8532 	/*
8533 	 * If this_cpu is idle, it implies the wakeup is from interrupt
8534 	 * context. Only allow the move if cache is shared. Otherwise an
8535 	 * interrupt intensive workload could force all tasks onto one
8536 	 * node depending on the IO topology or IRQ affinity settings.
8537 	 *
8538 	 * If the prev_cpu is idle and cache affine then avoid a migration.
8539 	 * There is no guarantee that the cache hot data from an interrupt
8540 	 * is more important than cache hot data on the prev_cpu and from
8541 	 * a cpufreq perspective, it's better to have higher utilisation
8542 	 * on one CPU.
8543 	 */
8544 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
8545 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
8546 
8547 	if (sync) {
8548 		struct rq *rq = cpu_rq(this_cpu);
8549 
8550 		if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
8551 			return this_cpu;
8552 	}
8553 
8554 	if (available_idle_cpu(prev_cpu))
8555 		return prev_cpu;
8556 
8557 	return nr_cpumask_bits;
8558 }
8559 
8560 static int
8561 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
8562 		   int this_cpu, int prev_cpu, int sync)
8563 {
8564 	s64 this_eff_load, prev_eff_load;
8565 	unsigned long task_load;
8566 
8567 	this_eff_load = cpu_load(cpu_rq(this_cpu));
8568 
8569 	if (sync) {
8570 		unsigned long current_load = task_h_load(current);
8571 
8572 		if (current_load > this_eff_load)
8573 			return this_cpu;
8574 
8575 		this_eff_load -= current_load;
8576 	}
8577 
8578 	task_load = task_h_load(p);
8579 
8580 	this_eff_load += task_load;
8581 	if (sched_feat(WA_BIAS))
8582 		this_eff_load *= 100;
8583 	this_eff_load *= capacity_of(prev_cpu);
8584 
8585 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
8586 	prev_eff_load -= task_load;
8587 	if (sched_feat(WA_BIAS))
8588 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
8589 	prev_eff_load *= capacity_of(this_cpu);
8590 
8591 	/*
8592 	 * If sync, adjust the weight of prev_eff_load such that if
8593 	 * prev_eff == this_eff that select_idle_sibling() will consider
8594 	 * stacking the wakee on top of the waker if no other CPU is
8595 	 * idle.
8596 	 */
8597 	if (sync)
8598 		prev_eff_load += 1;
8599 
8600 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
8601 }
8602 
8603 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
8604 		       int this_cpu, int prev_cpu, int sync)
8605 {
8606 	int target = nr_cpumask_bits;
8607 
8608 	if (sched_feat(WA_IDLE))
8609 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
8610 
8611 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
8612 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
8613 
8614 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
8615 	if (target != this_cpu)
8616 		return prev_cpu;
8617 
8618 	schedstat_inc(sd->ttwu_move_affine);
8619 	schedstat_inc(p->stats.nr_wakeups_affine);
8620 	return target;
8621 }
8622 
8623 static struct sched_group *
8624 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
8625 
8626 /*
8627  * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
8628  */
8629 static int
8630 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
8631 {
8632 	unsigned long load, min_load = ULONG_MAX;
8633 	u64 min_exit_latency = U64_MAX;
8634 	unsigned int nr_candidates = 0;
8635 	int least_loaded_cpu = this_cpu;
8636 	int shallowest_idle_cpu = -1;
8637 	int i;
8638 
8639 	/* Check if we have any choice: */
8640 	if (group->group_weight == 1)
8641 		return cpumask_first(sched_group_span(group));
8642 
8643 	/* Traverse only the allowed CPUs */
8644 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
8645 		struct rq *rq = cpu_rq(i);
8646 
8647 		if (!sched_core_cookie_match(rq, p))
8648 			continue;
8649 
8650 		if (choose_sched_idle_rq(rq, p))
8651 			return i;
8652 
8653 		if (available_idle_cpu(i)) {
8654 			struct cpuidle_state *idle = idle_get_state(rq);
8655 			u64 exit_latency = idle ? idle->exit_latency : U64_MAX;
8656 
8657 			if (shallowest_idle_cpu == -1 || exit_latency < min_exit_latency) {
8658 				min_exit_latency = exit_latency;
8659 				shallowest_idle_cpu = i;
8660 				nr_candidates = 1;
8661 			} else if (exit_latency == min_exit_latency) {
8662 				nr_candidates++;
8663 				if (!reciprocal_scale(sched_rng(), nr_candidates))
8664 					shallowest_idle_cpu = i;
8665 			}
8666 		} else if (shallowest_idle_cpu == -1) {
8667 			load = cpu_load(cpu_rq(i));
8668 			if (load < min_load) {
8669 				min_load = load;
8670 				least_loaded_cpu = i;
8671 			}
8672 		}
8673 	}
8674 
8675 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
8676 }
8677 
8678 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
8679 				  int cpu, int prev_cpu, int sd_flag)
8680 {
8681 	int new_cpu = cpu;
8682 
8683 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
8684 		return prev_cpu;
8685 
8686 	/*
8687 	 * We need task's util for cpu_util_without, sync it up to
8688 	 * prev_cpu's last_update_time.
8689 	 */
8690 	if (!(sd_flag & SD_BALANCE_FORK))
8691 		sync_entity_load_avg(&p->se);
8692 
8693 	while (sd) {
8694 		struct sched_group *group;
8695 		struct sched_domain *tmp;
8696 		int weight;
8697 
8698 		if (!(sd->flags & sd_flag)) {
8699 			sd = sd->child;
8700 			continue;
8701 		}
8702 
8703 		group = sched_balance_find_dst_group(sd, p, cpu);
8704 		if (!group) {
8705 			sd = sd->child;
8706 			continue;
8707 		}
8708 
8709 		new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
8710 		if (new_cpu == cpu) {
8711 			/* Now try balancing at a lower domain level of 'cpu': */
8712 			sd = sd->child;
8713 			continue;
8714 		}
8715 
8716 		/* Now try balancing at a lower domain level of 'new_cpu': */
8717 		cpu = new_cpu;
8718 		weight = sd->span_weight;
8719 		sd = NULL;
8720 		for_each_domain(cpu, tmp) {
8721 			if (weight <= tmp->span_weight)
8722 				break;
8723 			if (tmp->flags & sd_flag)
8724 				sd = tmp;
8725 		}
8726 	}
8727 
8728 	return new_cpu;
8729 }
8730 
8731 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
8732 {
8733 	if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p))
8734 		return cpu;
8735 
8736 	return -1;
8737 }
8738 
8739 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
8740 EXPORT_SYMBOL_GPL(sched_smt_present);
8741 
8742 static inline void set_idle_cores(int cpu, int val)
8743 {
8744 	struct sched_domain_shared *sds;
8745 
8746 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8747 	if (sds)
8748 		WRITE_ONCE(sds->has_idle_cores, val);
8749 }
8750 
8751 static inline bool test_idle_cores(int cpu)
8752 {
8753 	struct sched_domain_shared *sds;
8754 
8755 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8756 	if (sds)
8757 		return READ_ONCE(sds->has_idle_cores);
8758 
8759 	return false;
8760 }
8761 
8762 /*
8763  * Redirect a CPU to a higher-priority available sibling in its SMT domain,
8764  * subject to task affinity.
8765  */
8766 static inline int select_idle_smt_cpu(struct task_struct *p, int cpu)
8767 {
8768 	struct sched_domain *sd;
8769 	int best = cpu;
8770 	int sibling;
8771 
8772 	if (!sched_smt_active())
8773 		return cpu;
8774 
8775 	sd = rcu_dereference_all(cpu_rq(cpu)->sd);
8776 	if (!sd || !(sd->flags & SD_SHARE_CPUCAPACITY) ||
8777 	    !(sd->flags & SD_ASYM_PACKING))
8778 		return cpu;
8779 
8780 	for_each_cpu_and(sibling, sched_domain_span(sd), p->cpus_ptr) {
8781 		if (sibling == best || !choose_idle_cpu(sibling, p))
8782 			continue;
8783 
8784 		if (sched_asym_prefer(sibling, best))
8785 			best = sibling;
8786 	}
8787 
8788 	return best;
8789 }
8790 
8791 /*
8792  * Scans the local SMT mask to see if the entire core is idle, and records this
8793  * information in sd_balance_shared->has_idle_cores.
8794  *
8795  * Since SMT siblings share all cache levels, inspecting this limited remote
8796  * state should be fairly cheap.
8797  */
8798 void __update_idle_core(struct rq *rq)
8799 {
8800 	int core = cpu_of(rq);
8801 	int cpu;
8802 
8803 	rcu_read_lock();
8804 	if (test_idle_cores(core))
8805 		goto unlock;
8806 
8807 	for_each_cpu(cpu, cpu_smt_mask(core)) {
8808 		if (cpu == core)
8809 			continue;
8810 
8811 		if (!available_idle_cpu(cpu))
8812 			goto unlock;
8813 	}
8814 
8815 	set_idle_cores(core, 1);
8816 unlock:
8817 	rcu_read_unlock();
8818 }
8819 
8820 /*
8821  * Scan the entire LLC domain for idle cores; this dynamically switches off if
8822  * there are no idle cores left in the system; tracked through
8823  * sd_balance_shared->has_idle_cores and enabled through update_idle_core()
8824  * above.
8825  */
8826 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
8827 {
8828 	bool idle = true;
8829 	int cpu;
8830 
8831 	for_each_cpu(cpu, cpu_smt_mask(core)) {
8832 		if (!available_idle_cpu(cpu)) {
8833 			idle = false;
8834 			if (*idle_cpu == -1) {
8835 				if (choose_sched_idle_rq(cpu_rq(cpu), p) &&
8836 				    cpumask_test_cpu(cpu, cpus)) {
8837 					*idle_cpu = cpu;
8838 					break;
8839 				}
8840 				continue;
8841 			}
8842 			break;
8843 		}
8844 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
8845 			*idle_cpu = cpu;
8846 	}
8847 
8848 	if (idle)
8849 		return core;
8850 
8851 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
8852 	return -1;
8853 }
8854 
8855 /*
8856  * Scan the local SMT mask for idle CPUs.
8857  */
8858 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
8859 {
8860 	int cpu;
8861 
8862 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
8863 		if (cpu == target)
8864 			continue;
8865 		/*
8866 		 * Check if the CPU is in the LLC scheduling domain of @target.
8867 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
8868 		 */
8869 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8870 			continue;
8871 		if (choose_idle_cpu(cpu, p))
8872 			return cpu;
8873 	}
8874 
8875 	return -1;
8876 }
8877 
8878 /*
8879  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
8880  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
8881  * average idle time for this rq (as found in rq->avg_idle).
8882  */
8883 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
8884 {
8885 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8886 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
8887 
8888 	if (sched_feat(SIS_UTIL) && sd->shared) {
8889 		/*
8890 		 * Increment because !--nr is the condition to stop scan.
8891 		 *
8892 		 * Since "sd" is "sd_llc" for target CPU dereferenced in the
8893 		 * caller, it is safe to directly dereference "sd->shared".
8894 		 * Topology bits always ensure it assigned for "sd_llc" abd it
8895 		 * cannot disappear as long as we have a RCU protected
8896 		 * reference to one the associated "sd" here.
8897 		 */
8898 		nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
8899 		/* overloaded LLC is unlikely to have idle cpu/core */
8900 		if (nr == 1)
8901 			return -1;
8902 	}
8903 
8904 	if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr))
8905 		return -1;
8906 
8907 	if (static_branch_unlikely(&sched_cluster_active)) {
8908 		struct sched_group *sg = sd->groups;
8909 
8910 		if (sg->flags & SD_CLUSTER) {
8911 			for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
8912 				if (!cpumask_test_cpu(cpu, cpus))
8913 					continue;
8914 
8915 				if (has_idle_core) {
8916 					i = select_idle_core(p, cpu, cpus, &idle_cpu);
8917 					if ((unsigned int)i < nr_cpumask_bits)
8918 						return i;
8919 				} else {
8920 					if (--nr <= 0)
8921 						return -1;
8922 					idle_cpu = __select_idle_cpu(cpu, p);
8923 					if ((unsigned int)idle_cpu < nr_cpumask_bits)
8924 						return idle_cpu;
8925 				}
8926 			}
8927 			cpumask_andnot(cpus, cpus, sched_group_span(sg));
8928 		}
8929 	}
8930 
8931 	for_each_cpu_wrap(cpu, cpus, target + 1) {
8932 		if (has_idle_core) {
8933 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
8934 			if ((unsigned int)i < nr_cpumask_bits)
8935 				return i;
8936 
8937 		} else {
8938 			if (--nr <= 0)
8939 				return -1;
8940 			idle_cpu = __select_idle_cpu(cpu, p);
8941 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
8942 				break;
8943 		}
8944 	}
8945 
8946 	if (has_idle_core)
8947 		set_idle_cores(target, false);
8948 
8949 	return idle_cpu;
8950 }
8951 
8952 /*
8953  * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks,
8954  * where lower values indicate a better fit - see select_idle_capacity().
8955  *
8956  * A CPU that both fits the task and sits on a fully-idle SMT core is returned
8957  * immediately and is never assigned one of these ranks. On !SMT every CPU is
8958  * its own "core", so the early return covers all fits-and-idle cases and the
8959  * core-tier ranks below become unreachable.
8960  *
8961  *   Rank                            Val  Tier    Meaning
8962  *   ------------------------------  ---  ------  ---------------------------
8963  *   ASYM_IDLE_UCLAMP_MISFIT         -4   core    Idle core; capacity fits
8964  *                                                util but uclamp_min misses.
8965  *   ASYM_IDLE_COMPLETE_MISFIT       -3   core    Idle core; capacity does
8966  *                                                not fit. Still beats every
8967  *                                                thread-tier rank: a busy
8968  *                                                sibling cuts effective
8969  *                                                capacity more than a
8970  *                                                misfit hurts a quiet core.
8971  *   ASYM_IDLE_THREAD_FITS           -2   thread  Busy SMT sibling; capacity
8972  *                                                fits util + uclamp.
8973  *   ASYM_IDLE_THREAD_UCLAMP_MISFIT  -1   thread  Busy SMT sibling; capacity
8974  *                                                fits but uclamp_min misses
8975  *                                                (native util_fits_cpu()
8976  *                                                return value).
8977  *   ASYM_IDLE_THREAD_MISFIT          0   thread  Busy SMT sibling; capacity
8978  *                                                does not fit.
8979  *
8980  * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core,
8981  * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier:
8982  *
8983  *   ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT   (-4)
8984  *   ASYM_IDLE_THREAD_MISFIT         (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3)
8985  *
8986  * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core
8987  * candidate early-returns from select_idle_capacity().
8988  */
8989 enum asym_fits_state {
8990 	ASYM_IDLE_UCLAMP_MISFIT = -4,
8991 	ASYM_IDLE_COMPLETE_MISFIT,
8992 	ASYM_IDLE_THREAD_FITS,
8993 	ASYM_IDLE_THREAD_UCLAMP_MISFIT,
8994 	ASYM_IDLE_THREAD_MISFIT,
8995 
8996 	/* util_fits_cpu() bias for idle core */
8997 	ASYM_IDLE_CORE_BIAS = -3,
8998 };
8999 
9000 /*
9001  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
9002  * the task fits. If no CPU is big enough, but there are idle ones, try to
9003  * maximize capacity.
9004  */
9005 static int
9006 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
9007 {
9008 	/*
9009 	 * On !SMT systems, has_idle_core is always false and preferred_core
9010 	 * is always true (CPU == core), so the SMT preference logic below
9011 	 * collapses to the plain capacity scan.
9012 	 */
9013 	bool has_idle_core = sched_smt_active() && test_idle_cores(target);
9014 	unsigned long task_util, util_min, util_max, best_cap = 0;
9015 	int fits, best_fits = ASYM_IDLE_THREAD_MISFIT;
9016 	int cpu, best_cpu = -1;
9017 	struct cpumask *cpus;
9018 	int nr = INT_MAX;
9019 
9020 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
9021 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
9022 
9023 	task_util = task_util_est(p);
9024 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
9025 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
9026 
9027 	if (sched_feat(SIS_UTIL) && sd->shared) {
9028 		/*
9029 		 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits
9030 		 * the scan when not preferring an idle core.
9031 		 */
9032 		nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
9033 		/* overloaded domain is unlikely to have idle cpu/core */
9034 		if (nr == 1)
9035 			return -1;
9036 	}
9037 
9038 	for_each_cpu_wrap(cpu, cpus, target) {
9039 		bool preferred_core = !has_idle_core || is_core_idle(cpu);
9040 		unsigned long cpu_cap = capacity_of(cpu);
9041 
9042 		/*
9043 		 * Stop when the nr_idle_scan is exhausted (mirrors
9044 		 * select_idle_cpu() logic).
9045 		 */
9046 		if (!has_idle_core && --nr <= 0)
9047 			return best_cpu;
9048 
9049 		if (!choose_idle_cpu(cpu, p))
9050 			continue;
9051 
9052 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
9053 
9054 		/*
9055 		 * Perfect fit: capacity satisfies util + uclamp and the CPU
9056 		 * sits on a fully-idle SMT core, this is a !SMT system, or
9057 		 * there is no idle core to find.
9058 		 * Short-circuit the rank-based selection and return
9059 		 * immediately.
9060 		 */
9061 		if (fits > 0 && preferred_core)
9062 			return cpu;
9063 		/*
9064 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
9065 		 * Look for the CPU with best capacity.
9066 		 */
9067 		else if (fits < 0)
9068 			cpu_cap = get_actual_cpu_capacity(cpu);
9069 		/*
9070 		 * fits > 0 implies we are not on a preferred core, but the util
9071 		 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS
9072 		 * so the effective range becomes
9073 		 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where:
9074 		 *    ASYM_IDLE_THREAD_MISFIT - does not fit
9075 		 *    ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN
9076 		 *    ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core
9077 		 */
9078 		else if (fits > 0)
9079 			fits = ASYM_IDLE_THREAD_FITS;
9080 
9081 		/*
9082 		 * If we are on a preferred core, translate the range of fits
9083 		 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to
9084 		 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT].
9085 		 * This ensures that an idle core is always given priority over
9086 		 * (partially) busy core.
9087 		 *
9088 		 * A fully fitting idle core would have returned early and hence
9089 		 * fits > 0 for preferred_core need not be dealt with.
9090 		 */
9091 		if (preferred_core)
9092 			fits += ASYM_IDLE_CORE_BIAS;
9093 
9094 		/*
9095 		 * First, select CPU which fits better (lower is more preferred).
9096 		 * Then, select the one with best capacity at same level.
9097 		 */
9098 		if ((fits < best_fits) ||
9099 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
9100 			best_cap = cpu_cap;
9101 			best_cpu = cpu;
9102 			best_fits = fits;
9103 		}
9104 	}
9105 
9106 	/*
9107 	 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]
9108 	 * range means the chosen CPU is in a fully idle SMT core. Values above
9109 	 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best.
9110 	 *
9111 	 * The asym-capacity wakeup path returns from select_idle_sibling()
9112 	 * after this function and never runs select_idle_cpu(), so the usual
9113 	 * select_idle_cpu() tail that clears idle cores must live here when the
9114 	 * idle-core preference did not win.
9115 	 */
9116 	if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT)
9117 		set_idle_cores(target, false);
9118 
9119 	return best_cpu;
9120 }
9121 
9122 static inline bool asym_fits_cpu(unsigned long util,
9123 				 unsigned long util_min,
9124 				 unsigned long util_max,
9125 				 int cpu)
9126 {
9127 	if (sched_asym_cpucap_active()) {
9128 		/*
9129 		 * Return true only if the cpu fully fits the task requirements
9130 		 * which include the utilization and the performance hints.
9131 		 *
9132 		 * When SMT is active, also require that the core has no busy
9133 		 * siblings.
9134 		 *
9135 		 * Note: gating on is_core_idle() also makes the early-bailout
9136 		 * candidates in select_idle_sibling() (target, prev,
9137 		 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the
9138 		 * NO_ASYM path does not do.
9139 		 */
9140 		return (!sched_smt_active() || is_core_idle(cpu)) &&
9141 		       (util_fits_cpu(util, util_min, util_max, cpu) > 0);
9142 	}
9143 
9144 	return true;
9145 }
9146 
9147 /*
9148  * Try and locate an idle core/thread in the LLC cache domain.
9149  */
9150 static int select_idle_sibling(struct task_struct *p, int prev, int target)
9151 {
9152 	bool has_idle_core = false;
9153 	struct sched_domain *sd;
9154 	unsigned long task_util, util_min, util_max;
9155 	int i, recent_used_cpu, prev_aff = -1;
9156 
9157 	/*
9158 	 * On asymmetric system, update task utilization because we will check
9159 	 * that the task fits with CPU's capacity.
9160 	 */
9161 	if (sched_asym_cpucap_active()) {
9162 		sync_entity_load_avg(&p->se);
9163 		task_util = task_util_est(p);
9164 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
9165 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
9166 	}
9167 
9168 	/*
9169 	 * per-cpu select_rq_mask usage
9170 	 */
9171 	lockdep_assert_irqs_disabled();
9172 
9173 	if (choose_idle_cpu(target, p) &&
9174 	    asym_fits_cpu(task_util, util_min, util_max, target))
9175 		goto select_smt_priority;
9176 
9177 	/*
9178 	 * If the previous CPU is cache affine and idle, don't be stupid:
9179 	 */
9180 	if (prev != target && cpus_share_cache(prev, target) &&
9181 	    choose_idle_cpu(prev, p) &&
9182 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
9183 
9184 		if (!static_branch_unlikely(&sched_cluster_active) ||
9185 		    cpus_share_resources(prev, target)) {
9186 			target = prev;
9187 			goto select_smt_priority;
9188 		}
9189 
9190 		prev_aff = prev;
9191 	}
9192 
9193 	/*
9194 	 * Allow a per-cpu kthread to stack with the wakee if the
9195 	 * kworker thread and the tasks previous CPUs are the same.
9196 	 * The assumption is that the wakee queued work for the
9197 	 * per-cpu kthread that is now complete and the wakeup is
9198 	 * essentially a sync wakeup. An obvious example of this
9199 	 * pattern is IO completions.
9200 	 */
9201 	if (is_per_cpu_kthread(current) &&
9202 	    in_task() &&
9203 	    prev == smp_processor_id() &&
9204 	    this_rq()->nr_running <= 1 &&
9205 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
9206 		target = prev;
9207 		goto select_smt_priority;
9208 	}
9209 
9210 	/* Check a recently used CPU as a potential idle candidate: */
9211 	recent_used_cpu = p->recent_used_cpu;
9212 	p->recent_used_cpu = prev;
9213 	if (recent_used_cpu != prev &&
9214 	    recent_used_cpu != target &&
9215 	    cpus_share_cache(recent_used_cpu, target) &&
9216 	    choose_idle_cpu(recent_used_cpu, p) &&
9217 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
9218 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
9219 
9220 		if (!static_branch_unlikely(&sched_cluster_active) ||
9221 		    cpus_share_resources(recent_used_cpu, target)) {
9222 			target = recent_used_cpu;
9223 			goto select_smt_priority;
9224 		}
9225 
9226 	} else {
9227 		recent_used_cpu = -1;
9228 	}
9229 
9230 	/*
9231 	 * For asymmetric CPU capacity systems, our domain of interest is
9232 	 * sd_asym_cpucapacity rather than sd_llc.
9233 	 */
9234 	if (sched_asym_cpucap_active()) {
9235 		sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target));
9236 		/*
9237 		 * On an asymmetric CPU capacity system where an exclusive
9238 		 * cpuset defines a symmetric island (i.e. one unique
9239 		 * capacity_orig value through the cpuset), the key will be set
9240 		 * but the CPUs within that cpuset will not have a domain with
9241 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
9242 		 * capacity path.
9243 		 */
9244 		if (sd) {
9245 			i = select_idle_capacity(p, sd, target);
9246 			if ((unsigned int)i < nr_cpumask_bits) {
9247 				target = i;
9248 				goto select_smt_priority;
9249 			}
9250 			return target;
9251 		}
9252 	}
9253 
9254 	sd = rcu_dereference_all(per_cpu(sd_llc, target));
9255 	if (!sd)
9256 		return target;
9257 
9258 	if (sched_smt_active()) {
9259 		has_idle_core = test_idle_cores(target);
9260 
9261 		if (!has_idle_core && cpus_share_cache(prev, target)) {
9262 			i = select_idle_smt(p, sd, prev);
9263 			if ((unsigned int)i < nr_cpumask_bits) {
9264 				target = i;
9265 				goto select_smt_priority;
9266 			}
9267 		}
9268 	}
9269 
9270 	i = select_idle_cpu(p, sd, has_idle_core, target);
9271 	if ((unsigned int)i < nr_cpumask_bits) {
9272 		target = i;
9273 		goto select_smt_priority;
9274 	}
9275 
9276 	/*
9277 	 * For cluster machines which have lower sharing cache like L2 or
9278 	 * LLC Tag, we tend to find an idle CPU in the target's cluster
9279 	 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
9280 	 * use them if possible when no idle CPU found in select_idle_cpu().
9281 	 */
9282 	if ((unsigned int)prev_aff < nr_cpumask_bits) {
9283 		target = prev_aff;
9284 		goto select_smt_priority;
9285 	}
9286 	if ((unsigned int)recent_used_cpu < nr_cpumask_bits) {
9287 		target = recent_used_cpu;
9288 		goto select_smt_priority;
9289 	}
9290 
9291 	return target;
9292 
9293 select_smt_priority:
9294 	return select_idle_smt_cpu(p, target);
9295 }
9296 
9297 /**
9298  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
9299  * @cpu: the CPU to get the utilization for
9300  * @p: task for which the CPU utilization should be predicted or NULL
9301  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
9302  * @boost: 1 to enable boosting, otherwise 0
9303  *
9304  * The unit of the return value must be the same as the one of CPU capacity
9305  * so that CPU utilization can be compared with CPU capacity.
9306  *
9307  * CPU utilization is the sum of running time of runnable tasks plus the
9308  * recent utilization of currently non-runnable tasks on that CPU.
9309  * It represents the amount of CPU capacity currently used by CFS tasks in
9310  * the range [0..max CPU capacity] with max CPU capacity being the CPU
9311  * capacity at f_max.
9312  *
9313  * The estimated CPU utilization is defined as the maximum between CPU
9314  * utilization and sum of the estimated utilization of the currently
9315  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
9316  * previously-executed tasks, which helps better deduce how busy a CPU will
9317  * be when a long-sleeping task wakes up. The contribution to CPU utilization
9318  * of such a task would be significantly decayed at this point of time.
9319  *
9320  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
9321  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
9322  * utilization. Boosting is implemented in cpu_util() so that internal
9323  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
9324  * latter via cpu_util_cfs_boost().
9325  *
9326  * CPU utilization can be higher than the current CPU capacity
9327  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
9328  * of rounding errors as well as task migrations or wakeups of new tasks.
9329  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
9330  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
9331  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
9332  * capacity. CPU utilization is allowed to overshoot current CPU capacity
9333  * though since this is useful for predicting the CPU capacity required
9334  * after task migrations (scheduler-driven DVFS).
9335  *
9336  * Return: (Boosted) (estimated) utilization for the specified CPU.
9337  */
9338 static unsigned long
9339 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
9340 {
9341 	bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu;
9342 	bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu;
9343 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
9344 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
9345 	unsigned long runnable;
9346 
9347 	/*
9348 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
9349 	 * contribution. If @p migrates from another CPU to @cpu add its
9350 	 * contribution. In all the other cases @cpu is not impacted by the
9351 	 * migration so its util_avg is already correct.
9352 	 */
9353 	if (add_task)
9354 		util += task_util(p);
9355 	else if (sub_task)
9356 		lsub_positive(&util, task_util(p));
9357 
9358 	if (boost) {
9359 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
9360 		if (add_task)
9361 			runnable += READ_ONCE(p->se.avg.runnable_avg);
9362 		else if (sub_task)
9363 			lsub_positive(&runnable,
9364 				      READ_ONCE(p->se.avg.runnable_avg));
9365 		util = max(util, runnable);
9366 	}
9367 
9368 	if (sched_feat(UTIL_EST)) {
9369 		unsigned long util_est;
9370 
9371 		util_est = READ_ONCE(cfs_rq->avg.util_est);
9372 
9373 		/*
9374 		 * During wake-up @p isn't enqueued yet and doesn't contribute
9375 		 * to any cpu_rq(cpu)->cfs.avg.util_est.
9376 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
9377 		 * has been enqueued.
9378 		 *
9379 		 * During exec (@dst_cpu = -1) @p is enqueued and does
9380 		 * contribute to cpu_rq(cpu)->cfs.util_est.
9381 		 * Remove it to "simulate" cpu_util without @p's contribution.
9382 		 *
9383 		 * Despite the task_on_rq_queued(@p) check there is still a
9384 		 * small window for a possible race when an exec
9385 		 * select_task_rq_fair() races with LB's detach_task().
9386 		 *
9387 		 *   detach_task()
9388 		 *     deactivate_task()
9389 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
9390 		 *       -------------------------------- A
9391 		 *       dequeue_task()                    \
9392 		 *         dequeue_task_fair()              + Race Time
9393 		 *           util_est_dequeue()            /
9394 		 *       -------------------------------- B
9395 		 *
9396 		 * The additional check "current == p" is required to further
9397 		 * reduce the race window.
9398 		 */
9399 		if (dst_cpu == cpu)
9400 			util_est += _task_util_est(p);
9401 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
9402 			lsub_positive(&util_est, _task_util_est(p));
9403 
9404 		util = max(util, util_est);
9405 	}
9406 
9407 	return min(util, arch_scale_cpu_capacity(cpu));
9408 }
9409 
9410 unsigned long cpu_util_cfs(int cpu)
9411 {
9412 	return cpu_util(cpu, NULL, -1, 0);
9413 }
9414 
9415 unsigned long cpu_util_cfs_boost(int cpu)
9416 {
9417 	return cpu_util(cpu, NULL, -1, 1);
9418 }
9419 
9420 /*
9421  * cpu_util_without: compute cpu utilization without any contributions from *p
9422  * @cpu: the CPU which utilization is requested
9423  * @p: the task which utilization should be discounted
9424  *
9425  * The utilization of a CPU is defined by the utilization of tasks currently
9426  * enqueued on that CPU as well as tasks which are currently sleeping after an
9427  * execution on that CPU.
9428  *
9429  * This method returns the utilization of the specified CPU by discounting the
9430  * utilization of the specified task, whenever the task is currently
9431  * contributing to the CPU utilization.
9432  */
9433 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
9434 {
9435 	/* Task has no contribution or is new */
9436 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9437 		p = NULL;
9438 
9439 	return cpu_util(cpu, p, -1, 0);
9440 }
9441 
9442 /*
9443  * This function computes an effective utilization for the given CPU, to be
9444  * used for frequency selection given the linear relation: f = u * f_max.
9445  *
9446  * The scheduler tracks the following metrics:
9447  *
9448  *   cpu_util_{cfs,rt,dl,irq}()
9449  *   cpu_bw_dl()
9450  *
9451  * Where the cfs,rt and dl util numbers are tracked with the same metric and
9452  * synchronized windows and are thus directly comparable.
9453  *
9454  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
9455  * which excludes things like IRQ and steal-time. These latter are then accrued
9456  * in the IRQ utilization.
9457  *
9458  * The DL bandwidth number OTOH is not a measured metric but a value computed
9459  * based on the task model parameters and gives the minimal utilization
9460  * required to meet deadlines.
9461  */
9462 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
9463 				 unsigned long *min,
9464 				 unsigned long *max)
9465 {
9466 	unsigned long util, irq, scale;
9467 	struct rq *rq = cpu_rq(cpu);
9468 
9469 	scale = arch_scale_cpu_capacity(cpu);
9470 
9471 	/*
9472 	 * Early check to see if IRQ/steal time saturates the CPU, can be
9473 	 * because of inaccuracies in how we track these -- see
9474 	 * update_irq_load_avg().
9475 	 */
9476 	irq = cpu_util_irq(rq);
9477 	if (unlikely(irq >= scale)) {
9478 		if (min)
9479 			*min = scale;
9480 		if (max)
9481 			*max = scale;
9482 		return scale;
9483 	}
9484 
9485 	if (min) {
9486 		/*
9487 		 * The minimum utilization returns the highest level between:
9488 		 * - the computed DL bandwidth needed with the IRQ pressure which
9489 		 *   steals time to the deadline task.
9490 		 * - The minimum performance requirement for CFS and/or RT.
9491 		 */
9492 		*min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
9493 
9494 		/*
9495 		 * When an RT task is runnable and uclamp is not used, we must
9496 		 * ensure that the task will run at maximum compute capacity.
9497 		 */
9498 		if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
9499 			*min = max(*min, scale);
9500 	}
9501 
9502 	/*
9503 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
9504 	 * CFS tasks and we use the same metric to track the effective
9505 	 * utilization (PELT windows are synchronized) we can directly add them
9506 	 * to obtain the CPU's actual utilization.
9507 	 */
9508 	util = util_cfs + cpu_util_rt(rq);
9509 	util += cpu_util_dl(rq);
9510 
9511 	/*
9512 	 * The maximum hint is a soft bandwidth requirement, which can be lower
9513 	 * than the actual utilization because of uclamp_max requirements.
9514 	 */
9515 	if (max)
9516 		*max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
9517 
9518 	if (util >= scale)
9519 		return scale;
9520 
9521 	/*
9522 	 * There is still idle time; further improve the number by using the
9523 	 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
9524 	 * need to scale the task numbers:
9525 	 *
9526 	 *              max - irq
9527 	 *   U' = irq + --------- * U
9528 	 *                 max
9529 	 */
9530 	util = scale_irq_capacity(util, irq, scale);
9531 	util += irq;
9532 
9533 	return min(scale, util);
9534 }
9535 
9536 unsigned long sched_cpu_util(int cpu)
9537 {
9538 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
9539 }
9540 
9541 /*
9542  * energy_env - Utilization landscape for energy estimation.
9543  * @task_busy_time: Utilization contribution by the task for which we test the
9544  *                  placement. Given by eenv_task_busy_time().
9545  * @pd_busy_time:   Utilization of the whole perf domain without the task
9546  *                  contribution. Given by eenv_pd_busy_time().
9547  * @cpu_cap:        Maximum CPU capacity for the perf domain.
9548  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
9549  */
9550 struct energy_env {
9551 	unsigned long task_busy_time;
9552 	unsigned long pd_busy_time;
9553 	unsigned long cpu_cap;
9554 	unsigned long pd_cap;
9555 };
9556 
9557 /*
9558  * Compute the task busy time for compute_energy(). This time cannot be
9559  * injected directly into effective_cpu_util() because of the IRQ scaling.
9560  * The latter only makes sense with the most recent CPUs where the task has
9561  * run.
9562  */
9563 static inline void eenv_task_busy_time(struct energy_env *eenv,
9564 				       struct task_struct *p, int prev_cpu)
9565 {
9566 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
9567 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
9568 
9569 	if (unlikely(irq >= max_cap))
9570 		busy_time = max_cap;
9571 	else
9572 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
9573 
9574 	eenv->task_busy_time = busy_time;
9575 }
9576 
9577 /*
9578  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
9579  * utilization for each @pd_cpus, it however doesn't take into account
9580  * clamping since the ratio (utilization / cpu_capacity) is already enough to
9581  * scale the EM reported power consumption at the (eventually clamped)
9582  * cpu_capacity.
9583  *
9584  * The contribution of the task @p for which we want to estimate the
9585  * energy cost is removed (by cpu_util()) and must be calculated
9586  * separately (see eenv_task_busy_time). This ensures:
9587  *
9588  *   - A stable PD utilization, no matter which CPU of that PD we want to place
9589  *     the task on.
9590  *
9591  *   - A fair comparison between CPUs as the task contribution (task_util())
9592  *     will always be the same no matter which CPU utilization we rely on
9593  *     (util_avg or util_est).
9594  *
9595  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
9596  * exceed @eenv->pd_cap.
9597  */
9598 static inline void eenv_pd_busy_time(struct energy_env *eenv,
9599 				     struct cpumask *pd_cpus,
9600 				     struct task_struct *p)
9601 {
9602 	unsigned long busy_time = 0;
9603 	int cpu;
9604 
9605 	for_each_cpu(cpu, pd_cpus) {
9606 		unsigned long util = cpu_util(cpu, p, -1, 0);
9607 
9608 		busy_time += effective_cpu_util(cpu, util, NULL, NULL);
9609 	}
9610 
9611 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
9612 }
9613 
9614 /*
9615  * Compute the maximum utilization for compute_energy() when the task @p
9616  * is placed on the cpu @dst_cpu.
9617  *
9618  * Returns the maximum utilization among @eenv->cpus. This utilization can't
9619  * exceed @eenv->cpu_cap.
9620  */
9621 static inline unsigned long
9622 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
9623 		 struct task_struct *p, int dst_cpu)
9624 {
9625 	unsigned long max_util = 0;
9626 	int cpu;
9627 
9628 	for_each_cpu(cpu, pd_cpus) {
9629 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
9630 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
9631 		unsigned long eff_util, min, max;
9632 
9633 		/*
9634 		 * Performance domain frequency: utilization clamping
9635 		 * must be considered since it affects the selection
9636 		 * of the performance domain frequency.
9637 		 * NOTE: in case RT tasks are running, by default the min
9638 		 * utilization can be max OPP.
9639 		 */
9640 		eff_util = effective_cpu_util(cpu, util, &min, &max);
9641 
9642 		/* Task's uclamp can modify min and max value */
9643 		if (tsk && uclamp_is_used()) {
9644 			min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
9645 
9646 			/*
9647 			 * If there is no active max uclamp constraint,
9648 			 * directly use task's one, otherwise keep max.
9649 			 */
9650 			if (uclamp_rq_is_idle(cpu_rq(cpu)))
9651 				max = uclamp_eff_value(p, UCLAMP_MAX);
9652 			else
9653 				max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
9654 		}
9655 
9656 		eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
9657 		max_util = max(max_util, eff_util);
9658 	}
9659 
9660 	return min(max_util, eenv->cpu_cap);
9661 }
9662 
9663 /*
9664  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
9665  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
9666  * contribution is ignored.
9667  */
9668 static inline unsigned long
9669 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
9670 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
9671 {
9672 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
9673 	unsigned long busy_time = eenv->pd_busy_time;
9674 	unsigned long energy;
9675 
9676 	if (dst_cpu >= 0)
9677 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
9678 
9679 	energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
9680 
9681 	trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
9682 
9683 	return energy;
9684 }
9685 
9686 /*
9687  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
9688  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
9689  * spare capacity in each performance domain and uses it as a potential
9690  * candidate to execute the task. Then, it uses the Energy Model to figure
9691  * out which of the CPU candidates is the most energy-efficient.
9692  *
9693  * The rationale for this heuristic is as follows. In a performance domain,
9694  * all the most energy efficient CPU candidates (according to the Energy
9695  * Model) are those for which we'll request a low frequency. When there are
9696  * several CPUs for which the frequency request will be the same, we don't
9697  * have enough data to break the tie between them, because the Energy Model
9698  * only includes active power costs. With this model, if we assume that
9699  * frequency requests follow utilization (e.g. using schedutil), the CPU with
9700  * the maximum spare capacity in a performance domain is guaranteed to be among
9701  * the best candidates of the performance domain.
9702  *
9703  * In practice, it could be preferable from an energy standpoint to pack
9704  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
9705  * but that could also hurt our chances to go cluster idle, and we have no
9706  * ways to tell with the current Energy Model if this is actually a good
9707  * idea or not. So, find_energy_efficient_cpu() basically favors
9708  * cluster-packing, and spreading inside a cluster. That should at least be
9709  * a good thing for latency, and this is consistent with the idea that most
9710  * of the energy savings of EAS come from the asymmetry of the system, and
9711  * not so much from breaking the tie between identical CPUs. That's also the
9712  * reason why EAS is enabled in the topology code only for systems where
9713  * SD_ASYM_CPUCAPACITY is set.
9714  *
9715  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
9716  * they don't have any useful utilization data yet and it's not possible to
9717  * forecast their impact on energy consumption. Consequently, they will be
9718  * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
9719  * to be energy-inefficient in some use-cases. The alternative would be to
9720  * bias new tasks towards specific types of CPUs first, or to try to infer
9721  * their util_avg from the parent task, but those heuristics could hurt
9722  * other use-cases too. So, until someone finds a better way to solve this,
9723  * let's keep things simple by re-using the existing slow path.
9724  */
9725 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
9726 {
9727 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
9728 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
9729 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
9730 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
9731 	struct root_domain *rd = this_rq()->rd;
9732 	int cpu, best_energy_cpu, target = -1;
9733 	int prev_fits = -1, best_fits = -1;
9734 	unsigned long best_actual_cap = 0;
9735 	unsigned long prev_actual_cap = 0;
9736 	struct sched_domain *sd;
9737 	struct perf_domain *pd;
9738 	struct energy_env eenv;
9739 
9740 	pd = rcu_dereference_all(rd->pd);
9741 	if (!pd)
9742 		return target;
9743 
9744 	/*
9745 	 * Energy-aware wake-up happens on the lowest sched_domain starting
9746 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
9747 	 */
9748 	sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity));
9749 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
9750 		sd = sd->parent;
9751 	if (!sd)
9752 		return target;
9753 
9754 	target = prev_cpu;
9755 
9756 	sync_entity_load_avg(&p->se);
9757 	if (!task_util_est(p) && p_util_min == 0)
9758 		return target;
9759 
9760 	eenv_task_busy_time(&eenv, p, prev_cpu);
9761 
9762 	for (; pd; pd = pd->next) {
9763 		unsigned long util_min = p_util_min, util_max = p_util_max;
9764 		unsigned long cpu_cap, cpu_actual_cap, util;
9765 		long prev_spare_cap = -1, max_spare_cap = -1;
9766 		unsigned long rq_util_min, rq_util_max;
9767 		unsigned long cur_delta, base_energy;
9768 		int max_spare_cap_cpu = -1;
9769 		int fits, max_fits = -1;
9770 
9771 		if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask))
9772 			continue;
9773 
9774 		/* Account external pressure for the energy estimation */
9775 		cpu = cpumask_first(cpus);
9776 		cpu_actual_cap = get_actual_cpu_capacity(cpu);
9777 
9778 		eenv.cpu_cap = cpu_actual_cap;
9779 		eenv.pd_cap = 0;
9780 
9781 		for_each_cpu(cpu, cpus) {
9782 			struct rq *rq = cpu_rq(cpu);
9783 
9784 			eenv.pd_cap += cpu_actual_cap;
9785 
9786 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
9787 				continue;
9788 
9789 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
9790 				continue;
9791 
9792 			util = cpu_util(cpu, p, cpu, 0);
9793 			cpu_cap = capacity_of(cpu);
9794 
9795 			/*
9796 			 * Skip CPUs that cannot satisfy the capacity request.
9797 			 * IOW, placing the task there would make the CPU
9798 			 * overutilized. Take uclamp into account to see how
9799 			 * much capacity we can get out of the CPU; this is
9800 			 * aligned with sched_cpu_util().
9801 			 */
9802 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
9803 				/*
9804 				 * Open code uclamp_rq_util_with() except for
9805 				 * the clamp() part. I.e.: apply max aggregation
9806 				 * only. util_fits_cpu() logic requires to
9807 				 * operate on non clamped util but must use the
9808 				 * max-aggregated uclamp_{min, max}.
9809 				 */
9810 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
9811 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
9812 
9813 				util_min = max(rq_util_min, p_util_min);
9814 				util_max = max(rq_util_max, p_util_max);
9815 			}
9816 
9817 			fits = util_fits_cpu(util, util_min, util_max, cpu);
9818 			if (!fits)
9819 				continue;
9820 
9821 			lsub_positive(&cpu_cap, util);
9822 
9823 			if (cpu == prev_cpu) {
9824 				/* Always use prev_cpu as a candidate. */
9825 				prev_spare_cap = cpu_cap;
9826 				prev_fits = fits;
9827 			} else if ((fits > max_fits) ||
9828 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
9829 				/*
9830 				 * Find the CPU with the maximum spare capacity
9831 				 * among the remaining CPUs in the performance
9832 				 * domain.
9833 				 */
9834 				max_spare_cap = cpu_cap;
9835 				max_spare_cap_cpu = cpu;
9836 				max_fits = fits;
9837 			}
9838 		}
9839 
9840 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
9841 			continue;
9842 
9843 		eenv_pd_busy_time(&eenv, cpus, p);
9844 		/* Compute the 'base' energy of the pd, without @p */
9845 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
9846 
9847 		/* Evaluate the energy impact of using prev_cpu. */
9848 		if (prev_spare_cap > -1) {
9849 			prev_delta = compute_energy(&eenv, pd, cpus, p,
9850 						    prev_cpu);
9851 			/* CPU utilization has changed */
9852 			if (prev_delta < base_energy)
9853 				return target;
9854 			prev_delta -= base_energy;
9855 			prev_actual_cap = cpu_actual_cap;
9856 			best_delta = min(best_delta, prev_delta);
9857 		}
9858 
9859 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
9860 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
9861 			/* Current best energy cpu fits better */
9862 			if (max_fits < best_fits)
9863 				continue;
9864 
9865 			/*
9866 			 * Both don't fit performance hint (i.e. uclamp_min)
9867 			 * but best energy cpu has better capacity.
9868 			 */
9869 			if ((max_fits < 0) &&
9870 			    (cpu_actual_cap <= best_actual_cap))
9871 				continue;
9872 
9873 			cur_delta = compute_energy(&eenv, pd, cpus, p,
9874 						   max_spare_cap_cpu);
9875 			/* CPU utilization has changed */
9876 			if (cur_delta < base_energy)
9877 				return target;
9878 			cur_delta -= base_energy;
9879 
9880 			/*
9881 			 * Both fit for the task but best energy cpu has lower
9882 			 * energy impact.
9883 			 */
9884 			if ((max_fits > 0) && (best_fits > 0) &&
9885 			    (cur_delta >= best_delta))
9886 				continue;
9887 
9888 			best_delta = cur_delta;
9889 			best_energy_cpu = max_spare_cap_cpu;
9890 			best_fits = max_fits;
9891 			best_actual_cap = cpu_actual_cap;
9892 		}
9893 	}
9894 
9895 	if ((best_fits > prev_fits) ||
9896 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
9897 	    ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
9898 		target = best_energy_cpu;
9899 
9900 	return target;
9901 }
9902 
9903 /*
9904  * select_task_rq_fair: Select target runqueue for the waking task in domains
9905  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
9906  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
9907  *
9908  * Balances load by selecting the idlest CPU in the idlest group, or under
9909  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
9910  *
9911  * Returns the target CPU number.
9912  */
9913 static int
9914 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
9915 {
9916 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
9917 	struct sched_domain *tmp, *sd = NULL;
9918 	int cpu = smp_processor_id();
9919 	int new_cpu = prev_cpu;
9920 	int want_affine = 0;
9921 	/* SD_flags and WF_flags share the first nibble */
9922 	int sd_flag = wake_flags & 0xF;
9923 
9924 	/*
9925 	 * required for stable ->cpus_allowed
9926 	 */
9927 	lockdep_assert_held(&p->pi_lock);
9928 	if (wake_flags & WF_TTWU) {
9929 		record_wakee(p);
9930 
9931 		if ((wake_flags & WF_CURRENT_CPU) &&
9932 		    cpumask_test_cpu(cpu, p->cpus_ptr))
9933 			return cpu;
9934 
9935 		if (!is_rd_overutilized(this_rq()->rd)) {
9936 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
9937 			if (new_cpu >= 0)
9938 				return new_cpu;
9939 			new_cpu = prev_cpu;
9940 		}
9941 
9942 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
9943 	}
9944 
9945 	for_each_domain(cpu, tmp) {
9946 		/*
9947 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
9948 		 * cpu is a valid SD_WAKE_AFFINE target.
9949 		 */
9950 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
9951 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
9952 			if (cpu != prev_cpu)
9953 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
9954 
9955 			sd = NULL; /* Prefer wake_affine over balance flags */
9956 			break;
9957 		}
9958 
9959 		/*
9960 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
9961 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
9962 		 * will usually go to the fast path.
9963 		 */
9964 		if (tmp->flags & sd_flag)
9965 			sd = tmp;
9966 		else if (!want_affine)
9967 			break;
9968 	}
9969 
9970 	/* Slow path */
9971 	if (unlikely(sd)) {
9972 		new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
9973 		return select_idle_smt_cpu(p, new_cpu);
9974 	}
9975 
9976 	/* Fast path */
9977 	if (wake_flags & WF_TTWU)
9978 		return select_idle_sibling(p, prev_cpu, new_cpu);
9979 
9980 	return new_cpu;
9981 }
9982 
9983 /*
9984  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
9985  * cfs_rq_of(p) references at time of call are still valid and identify the
9986  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
9987  */
9988 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
9989 {
9990 	struct sched_entity *se = &p->se;
9991 
9992 	if (!task_on_rq_migrating(p)) {
9993 		remove_entity_load_avg(se);
9994 
9995 		/*
9996 		 * Here, the task's PELT values have been updated according to
9997 		 * the current rq's clock. But if that clock hasn't been
9998 		 * updated in a while, a substantial idle time will be missed,
9999 		 * leading to an inflation after wake-up on the new rq.
10000 		 *
10001 		 * Estimate the missing time from the cfs_rq last_update_time
10002 		 * and update sched_avg to improve the PELT continuity after
10003 		 * migration.
10004 		 */
10005 		migrate_se_pelt_lag(se);
10006 	}
10007 
10008 	/* Tell new CPU we are migrated */
10009 	se->avg.last_update_time = 0;
10010 
10011 	update_scan_period(p, new_cpu);
10012 }
10013 
10014 static void task_dead_fair(struct task_struct *p)
10015 {
10016 	struct sched_entity *se = &p->se;
10017 	remove_entity_load_avg(se);
10018 }
10019 
10020 /*
10021  * Set the max capacity the task is allowed to run at for misfit detection.
10022  */
10023 static void set_task_max_allowed_capacity(struct task_struct *p)
10024 {
10025 	struct asym_cap_data *entry;
10026 
10027 	if (!sched_asym_cpucap_active())
10028 		return;
10029 
10030 	rcu_read_lock();
10031 	list_for_each_entry_rcu(entry, &asym_cap_list, link) {
10032 		cpumask_t *cpumask;
10033 
10034 		cpumask = cpu_capacity_span(entry);
10035 		if (!cpumask_intersects(p->cpus_ptr, cpumask))
10036 			continue;
10037 
10038 		p->max_allowed_capacity = entry->capacity;
10039 		break;
10040 	}
10041 	rcu_read_unlock();
10042 }
10043 
10044 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
10045 {
10046 	set_cpus_allowed_common(p, ctx);
10047 	set_task_max_allowed_capacity(p);
10048 }
10049 
10050 enum preempt_wakeup_action {
10051 	PREEMPT_WAKEUP_NONE,	/* No preemption. */
10052 	PREEMPT_WAKEUP_SHORT,	/* Ignore slice protection. */
10053 	PREEMPT_WAKEUP_PICK,	/* Let pick_eevdf() decide. */
10054 	PREEMPT_WAKEUP_RESCHED,	/* Force reschedule. */
10055 };
10056 
10057 static inline bool set_preempt_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
10058 {
10059 	/*
10060 	 * Keep existing buddy if the deadline is sooner than pse.
10061 	 * The older buddy may be cache cold and completely unrelated
10062 	 * to the current wakeup but that is unpredictable where as
10063 	 * obeying the deadline is more in line with EEVDF objectives.
10064 	 */
10065 	if (cfs_rq->next && entity_before(cfs_rq->next, pse))
10066 		return false;
10067 
10068 	set_next_buddy(cfs_rq, pse);
10069 	return true;
10070 }
10071 
10072 static inline bool set_short_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
10073 {
10074 	if (cfs_rq->next) {
10075 		if (cfs_rq->next->slice < pse->slice)
10076 			return false;
10077 
10078 		if (cfs_rq->next->slice == pse->slice &&
10079 		    entity_before(cfs_rq->next, pse))
10080 			return false;
10081 	}
10082 
10083 	set_next_buddy(cfs_rq, pse);
10084 	return true;
10085 }
10086 
10087 /*
10088  * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
10089  * strictly enforced because the hint is either misunderstood or
10090  * multiple tasks must be woken up.
10091  */
10092 static inline enum preempt_wakeup_action
10093 preempt_sync(struct rq *rq, int wake_flags,
10094 	     struct sched_entity *pse, struct sched_entity *se)
10095 {
10096 	u64 threshold, delta;
10097 
10098 	/*
10099 	 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
10100 	 * though it is likely harmless.
10101 	 */
10102 	WARN_ON_ONCE(!(wake_flags & WF_TTWU));
10103 
10104 	threshold = sysctl_sched_migration_cost;
10105 	delta = rq_clock_task(rq) - se->exec_start;
10106 	if ((s64)delta < 0)
10107 		delta = 0;
10108 
10109 	/*
10110 	 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
10111 	 * could run on other CPUs. Reduce the threshold before preemption is
10112 	 * allowed to an arbitrary lower value as it is more likely (but not
10113 	 * guaranteed) the waker requires the wakee to finish.
10114 	 */
10115 	if (wake_flags & WF_RQ_SELECTED)
10116 		threshold >>= 2;
10117 
10118 	/*
10119 	 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
10120 	 * wakeups to be issued.
10121 	 */
10122 	if (entity_before(pse, se) && delta >= threshold)
10123 		return PREEMPT_WAKEUP_RESCHED;
10124 
10125 	return PREEMPT_WAKEUP_NONE;
10126 }
10127 
10128 /*
10129  * Preempt the current task with a newly woken task if needed:
10130  */
10131 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags)
10132 {
10133 	enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
10134 	struct task_struct *donor = rq->donor;
10135 	struct sched_entity *nse, *se = &donor->se, *pse = &p->se;
10136 	struct cfs_rq *cfs_rq = &rq->cfs;
10137 	int cse_is_idle, pse_is_idle;
10138 
10139 	/*
10140 	 * XXX Getting preempted by higher class, try and find idle CPU?
10141 	 */
10142 	if (p->sched_class != &fair_sched_class ||
10143 	    donor->sched_class != &fair_sched_class)
10144 		return;
10145 
10146 	if (unlikely(se == pse))
10147 		return;
10148 
10149 	/*
10150 	 * This is possible from callers such as attach_tasks(), in which we
10151 	 * unconditionally wakeup_preempt() after an enqueue (which may have
10152 	 * lead to a throttle).  This both saves work and prevents false
10153 	 * next-buddy nomination below.
10154 	 */
10155 	if (task_is_throttled(p))
10156 		return;
10157 
10158 	/*
10159 	 * We can come here with TIF_NEED_RESCHED already set from new task
10160 	 * wake up path.
10161 	 *
10162 	 * Note: this also catches the edge-case of curr being in a throttled
10163 	 * group (e.g. via set_curr_task), since update_curr() (in the
10164 	 * enqueue of curr) will have resulted in resched being set.  This
10165 	 * prevents us from potentially nominating it as a false LAST_BUDDY
10166 	 * below.
10167 	 */
10168 	if (!sched_feat(PREEMPT_SHORT) && test_tsk_need_resched(rq->curr))
10169 		return;
10170 
10171 	if (!sched_feat(WAKEUP_PREEMPTION))
10172 		return;
10173 
10174 	WARN_ON_ONCE(!pse);
10175 
10176 	cse_is_idle = se_is_idle(se);
10177 	pse_is_idle = se_is_idle(pse);
10178 
10179 	nse = se;
10180 	/*
10181 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
10182 	 * in the inverse case).
10183 	 */
10184 	if (cse_is_idle && !pse_is_idle)
10185 		goto preempt;
10186 
10187 	update_curr_fair(rq);
10188 
10189 	if (cse_is_idle != pse_is_idle)
10190 		goto update;
10191 
10192 	/*
10193 	 * BATCH and IDLE tasks do not preempt others.
10194 	 */
10195 	if (unlikely(!normal_policy(p->policy)))
10196 		goto update;
10197 
10198 	/*
10199 	 * Do not preempt for tasks that are sched_delayed as it would violate
10200 	 * EEVDF to forcibly queue an ineligible task.
10201 	 */
10202 	if (pse->sched_delayed)
10203 		goto update;
10204 
10205 	/*
10206 	 * If @p has a shorter slice than current and @p is eligible, override
10207 	 * current's slice protection in order to allow preemption.
10208 	 */
10209 	if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
10210 		preempt_action = PREEMPT_WAKEUP_SHORT;
10211 		goto pick;
10212 	}
10213 
10214 	/*
10215 	 * Ignore wakee preemption on WF_FORK as it is less likely that
10216 	 * there is shared data as exec often follow fork.
10217 	 */
10218 	if (wake_flags & WF_FORK)
10219 		goto update;
10220 
10221 	/* Prefer picking wakee soon if appropriate. */
10222 	if (sched_feat(NEXT_BUDDY) && set_preempt_buddy(cfs_rq, pse)) {
10223 		/*
10224 		 * Decide whether to obey WF_SYNC hint for a new buddy. Old
10225 		 * buddies are ignored as they may not be relevant to the
10226 		 * waker and less likely to be cache hot.
10227 		 */
10228 		if (wake_flags & WF_SYNC)
10229 			preempt_action = preempt_sync(rq, wake_flags, pse, se);
10230 	}
10231 
10232 	switch (preempt_action) {
10233 	case PREEMPT_WAKEUP_NONE:
10234 		return;
10235 	case PREEMPT_WAKEUP_RESCHED:
10236 		goto preempt;
10237 	case PREEMPT_WAKEUP_SHORT:
10238 		fallthrough;
10239 	case PREEMPT_WAKEUP_PICK:
10240 		break;
10241 	}
10242 
10243 pick:
10244 	if (cfs_rq->h_nr_queued) {
10245 		nse = pick_next_entity(rq, preempt_action != PREEMPT_WAKEUP_SHORT);
10246 		if (unlikely(!nse))
10247 			goto pick;
10248 
10249 		/* If @p has become the most eligible task, force preemption */
10250 		if (nse == pse)
10251 			goto preempt;
10252 	}
10253 
10254 	/*
10255 	 * If @p is eligible but not the next task to run then cancel protection
10256 	 * to prevent large scheduling latency
10257 	 */
10258 	if (preempt_action == PREEMPT_WAKEUP_SHORT && entity_eligible(cfs_rq, pse))
10259 		goto preempt;
10260 update:
10261 	if (sched_feat(RUN_TO_PARITY))
10262 		update_protect_slice(cfs_rq, se);
10263 
10264 	return;
10265 
10266 preempt:
10267 	cancel_protect_slice(se);
10268 
10269 	if (preempt_action == PREEMPT_WAKEUP_SHORT)
10270 		set_short_buddy(cfs_rq, pse);
10271 
10272 	resched_curr_lazy(rq);
10273 }
10274 
10275 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
10276 	__must_hold(__rq_lockp(rq))
10277 {
10278 	struct cfs_rq *cfs_rq = &rq->cfs;
10279 	struct sched_entity *se;
10280 	struct task_struct *p;
10281 	int new_tasks;
10282 
10283 again:
10284 	if (!cfs_rq->h_nr_queued)
10285 		goto idle;
10286 
10287 	/* Might not have done put_prev_entity() */
10288 	if (cfs_rq->curr && cfs_rq->curr->on_rq)
10289 		update_curr_eevdf(cfs_rq);
10290 
10291 	se = pick_next_entity(rq, true);
10292 	if (!se)
10293 		goto again;
10294 
10295 	p = task_of(se);
10296 	return p;
10297 
10298 idle:
10299 	if (sched_core_enabled(rq))
10300 		return NULL;
10301 
10302 	new_tasks = sched_balance_newidle(rq, rf);
10303 	if (new_tasks < 0)
10304 		return RETRY_TASK;
10305 	if (new_tasks > 0)
10306 		goto again;
10307 	return NULL;
10308 }
10309 
10310 static struct task_struct *
10311 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
10312 	__must_hold(__rq_lockp(dl_se->rq))
10313 {
10314 	return pick_task_fair(dl_se->rq, rf);
10315 }
10316 
10317 void fair_server_init(struct rq *rq)
10318 {
10319 	struct sched_dl_entity *dl_se = &rq->fair_server;
10320 
10321 	init_dl_entity(dl_se);
10322 
10323 	dl_server_init(dl_se, rq, fair_server_pick_task);
10324 }
10325 
10326 /*
10327  * Account for a descheduled task:
10328  */
10329 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
10330 {
10331 	struct sched_entity *se = &prev->se;
10332 	struct cfs_rq *cfs_rq = &rq->cfs;
10333 	struct sched_entity *nse = NULL;
10334 
10335 #ifdef CONFIG_FAIR_GROUP_SCHED
10336 	if (next && next->sched_class == &fair_sched_class)
10337 		nse = &next->se;
10338 #endif
10339 
10340 	while (se) {
10341 		cfs_rq = cfs_rq_of(se);
10342 		if (!nse || cfs_rq->h_curr)
10343 			put_prev_entity(cfs_rq, se);
10344 #ifdef CONFIG_FAIR_GROUP_SCHED
10345 		if (nse) {
10346 			if (is_same_group(se, nse))
10347 				break;
10348 
10349 			int d = nse->depth - se->depth;
10350 			if (d >= 0) {
10351 				/* nse has equal or greater depth, ascend */
10352 				nse = parent_entity(nse);
10353 				/* if nse is the deeper, do not ascend se */
10354 				if (d > 0)
10355 					continue;
10356 			}
10357 		}
10358 #endif
10359 		se = parent_entity(se);
10360 	}
10361 
10362 	/* Put 'current' back into the tree. */
10363 	cfs_rq = &rq->cfs;
10364 	se = &prev->se;
10365 	WARN_ON_ONCE(cfs_rq->curr != se);
10366 	cfs_rq->curr = NULL;
10367 	if (se->on_rq)
10368 		__enqueue_entity(cfs_rq, se);
10369 }
10370 
10371 /*
10372  * sched_yield() is very simple
10373  */
10374 static void yield_task_fair(struct rq *rq)
10375 {
10376 	struct task_struct *curr = rq->donor;
10377 	struct sched_entity *se = &curr->se;
10378 	struct cfs_rq *cfs_rq = &rq->cfs;
10379 
10380 	/*
10381 	 * Are we the only task in the tree?
10382 	 */
10383 	if (unlikely(rq->nr_running == 1))
10384 		return;
10385 
10386 	clear_buddies(cfs_rq, se);
10387 
10388 	update_rq_clock(rq);
10389 	/*
10390 	 * Update run-time statistics of the 'current'.
10391 	 */
10392 	update_curr_eevdf(cfs_rq);
10393 	/*
10394 	 * Tell update_rq_clock() that we've just updated,
10395 	 * so we don't do microscopic update in schedule()
10396 	 * and double the fastpath cost.
10397 	 */
10398 	rq_clock_skip_update(rq);
10399 
10400 	/*
10401 	 * Forfeit the remaining vruntime, only if the entity is eligible. This
10402 	 * condition is necessary because in core scheduling we prefer to run
10403 	 * ineligible tasks rather than force idling. If this happens we may
10404 	 * end up in a loop where the core scheduler picks the yielding task,
10405 	 * which yields immediately again; without the condition the vruntime
10406 	 * ends up quickly running away.
10407 	 */
10408 	if (entity_eligible(cfs_rq, se)) {
10409 		se->vruntime = se->deadline;
10410 		update_deadline(cfs_rq, se);
10411 	}
10412 }
10413 
10414 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
10415 {
10416 	struct sched_entity *se = &p->se;
10417 
10418 	/* !se->on_rq also covers throttled task */
10419 	if (!se->on_rq || se->sched_delayed)
10420 		return false;
10421 
10422 	/* Tell the scheduler that we'd really like se to run next. */
10423 	set_next_buddy(&task_rq(p)->cfs, se);
10424 
10425 	yield_task_fair(rq);
10426 
10427 	return true;
10428 }
10429 
10430 /**************************************************
10431  * Fair scheduling class load-balancing methods.
10432  *
10433  * BASICS
10434  *
10435  * The purpose of load-balancing is to achieve the same basic fairness the
10436  * per-CPU scheduler provides, namely provide a proportional amount of compute
10437  * time to each task. This is expressed in the following equation:
10438  *
10439  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
10440  *
10441  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
10442  * W_i,0 is defined as:
10443  *
10444  *   W_i,0 = \Sum_j w_i,j                                             (2)
10445  *
10446  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
10447  * is derived from the nice value as per sched_prio_to_weight[].
10448  *
10449  * The weight average is an exponential decay average of the instantaneous
10450  * weight:
10451  *
10452  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
10453  *
10454  * C_i is the compute capacity of CPU i, typically it is the
10455  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
10456  * can also include other factors [XXX].
10457  *
10458  * To achieve this balance we define a measure of imbalance which follows
10459  * directly from (1):
10460  *
10461  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
10462  *
10463  * We them move tasks around to minimize the imbalance. In the continuous
10464  * function space it is obvious this converges, in the discrete case we get
10465  * a few fun cases generally called infeasible weight scenarios.
10466  *
10467  * [XXX expand on:
10468  *     - infeasible weights;
10469  *     - local vs global optima in the discrete case. ]
10470  *
10471  *
10472  * SCHED DOMAINS
10473  *
10474  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
10475  * for all i,j solution, we create a tree of CPUs that follows the hardware
10476  * topology where each level pairs two lower groups (or better). This results
10477  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
10478  * tree to only the first of the previous level and we decrease the frequency
10479  * of load-balance at each level inversely proportional to the number of CPUs in
10480  * the groups.
10481  *
10482  * This yields:
10483  *
10484  *     log_2 n     1     n
10485  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
10486  *     i = 0      2^i   2^i
10487  *                               `- size of each group
10488  *         |         |     `- number of CPUs doing load-balance
10489  *         |         `- freq
10490  *         `- sum over all levels
10491  *
10492  * Coupled with a limit on how many tasks we can migrate every balance pass,
10493  * this makes (5) the runtime complexity of the balancer.
10494  *
10495  * An important property here is that each CPU is still (indirectly) connected
10496  * to every other CPU in at most O(log n) steps:
10497  *
10498  * The adjacency matrix of the resulting graph is given by:
10499  *
10500  *             log_2 n
10501  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
10502  *             k = 0
10503  *
10504  * And you'll find that:
10505  *
10506  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
10507  *
10508  * Showing there's indeed a path between every CPU in at most O(log n) steps.
10509  * The task movement gives a factor of O(m), giving a convergence complexity
10510  * of:
10511  *
10512  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
10513  *
10514  *
10515  * WORK CONSERVING
10516  *
10517  * In order to avoid CPUs going idle while there's still work to do, new idle
10518  * balancing is more aggressive and has the newly idle CPU iterate up the domain
10519  * tree itself instead of relying on other CPUs to bring it work.
10520  *
10521  * This adds some complexity to both (5) and (8) but it reduces the total idle
10522  * time.
10523  *
10524  * [XXX more?]
10525  *
10526  *
10527  * CGROUPS
10528  *
10529  * Cgroups make a horror show out of (2), instead of a simple sum we get:
10530  *
10531  *                                s_k,i
10532  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
10533  *                                 S_k
10534  *
10535  * Where
10536  *
10537  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
10538  *
10539  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
10540  *
10541  * The big problem is S_k, its a global sum needed to compute a local (W_i)
10542  * property.
10543  *
10544  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
10545  *      rewrite all of this once again.]
10546  */
10547 
10548 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
10549 
10550 enum fbq_type { regular, remote, all };
10551 
10552 /*
10553  * 'group_type' describes the group of CPUs at the moment of load balancing.
10554  *
10555  * The enum is ordered by pulling priority, with the group with lowest priority
10556  * first so the group_type can simply be compared when selecting the busiest
10557  * group. See update_sd_pick_busiest().
10558  */
10559 enum group_type {
10560 	/* The group has spare capacity that can be used to run more tasks.  */
10561 	group_has_spare = 0,
10562 	/*
10563 	 * The group is fully used and the tasks don't compete for more CPU
10564 	 * cycles. Nevertheless, some tasks might wait before running.
10565 	 */
10566 	group_fully_busy,
10567 	/*
10568 	 * One task doesn't fit with CPU's capacity and must be migrated to a
10569 	 * more powerful CPU.
10570 	 */
10571 	group_misfit_task,
10572 	/*
10573 	 * Balance SMT group that's fully busy. Can benefit from migration
10574 	 * a task on SMT with busy sibling to another CPU on idle core.
10575 	 */
10576 	group_smt_balance,
10577 	/*
10578 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
10579 	 * and the task should be migrated to it instead of running on the
10580 	 * current CPU.
10581 	 */
10582 	group_asym_packing,
10583 	/*
10584 	 * The tasks' affinity constraints previously prevented the scheduler
10585 	 * from balancing the load across the system.
10586 	 */
10587 	group_imbalanced,
10588 	/*
10589 	 * There are tasks running on non-preferred LLC, possible to move
10590 	 * them to their preferred LLC without creating too much imbalance.
10591 	 * The priority of group_llc_balance is lower than that of
10592 	 * group_overloaded and higher than that of all other group types.
10593 	 * This is because group_llc_balance may exacerbate load imbalance.
10594 	 * If the LLC balancing attempt fails, the nr_balance_failed
10595 	 * mechanism will trigger other group types to rebalance the load.
10596 	 */
10597 	group_llc_balance,
10598 	/*
10599 	 * The CPU is overloaded and can't provide expected CPU cycles to all
10600 	 * tasks.
10601 	 */
10602 	group_overloaded
10603 };
10604 
10605 enum migration_type {
10606 	migrate_load = 0,
10607 	migrate_util,
10608 	migrate_task,
10609 	migrate_misfit,
10610 	migrate_llc_task
10611 };
10612 
10613 #define LBF_ALL_PINNED	0x01
10614 #define LBF_NEED_BREAK	0x02
10615 #define LBF_DST_PINNED  0x04
10616 #define LBF_SOME_PINNED	0x08
10617 #define LBF_ACTIVE_LB	0x10
10618 #define LBF_LLC_PINNED	0x20
10619 #define LBF_ACTIVE_LB_LLC	0x40
10620 
10621 struct lb_env {
10622 	struct sched_domain	*sd;
10623 
10624 	struct rq		*src_rq;
10625 	int			src_cpu;
10626 
10627 	int			dst_cpu;
10628 	struct rq		*dst_rq;
10629 	bool			dst_core_idle;
10630 
10631 	struct cpumask		*dst_grpmask;
10632 	int			new_dst_cpu;
10633 	enum cpu_idle_type	idle;
10634 	long			imbalance;
10635 	/* The set of CPUs under consideration for load-balancing */
10636 	struct cpumask		*cpus;
10637 
10638 	unsigned int		flags;
10639 
10640 	unsigned int		loop;
10641 	unsigned int		loop_break;
10642 	unsigned int		loop_max;
10643 
10644 	enum fbq_type		fbq_type;
10645 	enum migration_type	migration_type;
10646 	struct list_head	tasks;
10647 };
10648 
10649 /*
10650  * Is this task likely cache-hot:
10651  */
10652 static int task_hot(struct task_struct *p, struct lb_env *env)
10653 {
10654 	s64 delta;
10655 
10656 	lockdep_assert_rq_held(env->src_rq);
10657 
10658 	if (p->sched_class != &fair_sched_class)
10659 		return 0;
10660 
10661 	if (unlikely(task_has_idle_policy(p)))
10662 		return 0;
10663 
10664 	/* SMT siblings share cache */
10665 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
10666 		return 0;
10667 
10668 	/*
10669 	 * Buddy candidates are cache hot:
10670 	 */
10671 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
10672 	    (&p->se == cfs_rq_of(&p->se)->next))
10673 		return 1;
10674 
10675 	if (sysctl_sched_migration_cost == -1)
10676 		return 1;
10677 
10678 	/*
10679 	 * Don't migrate task if the task's cookie does not match
10680 	 * with the destination CPU's core cookie.
10681 	 */
10682 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
10683 		return 1;
10684 
10685 	if (sysctl_sched_migration_cost == 0)
10686 		return 0;
10687 
10688 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
10689 
10690 	return delta < (s64)sysctl_sched_migration_cost;
10691 }
10692 
10693 #ifdef CONFIG_NUMA_BALANCING
10694 /*
10695  * Returns a positive value, if task migration degrades locality.
10696  * Returns 0, if task migration is not affected by locality.
10697  * Returns a negative value, if task migration improves locality i.e migration preferred.
10698  */
10699 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
10700 {
10701 	struct numa_group *numa_group = rcu_dereference_all(p->numa_group);
10702 	unsigned long src_weight, dst_weight;
10703 	int src_nid, dst_nid, dist;
10704 
10705 	if (!static_branch_likely(&sched_numa_balancing))
10706 		return 0;
10707 
10708 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
10709 		return 0;
10710 
10711 	src_nid = cpu_to_node(env->src_cpu);
10712 	dst_nid = cpu_to_node(env->dst_cpu);
10713 
10714 	if (src_nid == dst_nid)
10715 		return 0;
10716 
10717 	/* Migrating away from the preferred node is always bad. */
10718 	if (src_nid == p->numa_preferred_nid) {
10719 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
10720 			return 1;
10721 		else
10722 			return 0;
10723 	}
10724 
10725 	/* Encourage migration to the preferred node. */
10726 	if (dst_nid == p->numa_preferred_nid)
10727 		return -1;
10728 
10729 	/* Leaving a core idle is often worse than degrading locality. */
10730 	if (env->idle == CPU_IDLE)
10731 		return 0;
10732 
10733 	dist = node_distance(src_nid, dst_nid);
10734 	if (numa_group) {
10735 		src_weight = group_weight(p, src_nid, dist);
10736 		dst_weight = group_weight(p, dst_nid, dist);
10737 	} else {
10738 		src_weight = task_weight(p, src_nid, dist);
10739 		dst_weight = task_weight(p, dst_nid, dist);
10740 	}
10741 
10742 	return src_weight - dst_weight;
10743 }
10744 
10745 #else /* !CONFIG_NUMA_BALANCING: */
10746 static inline long migrate_degrades_locality(struct task_struct *p,
10747 					     struct lb_env *env)
10748 {
10749 	return 0;
10750 }
10751 #endif /* !CONFIG_NUMA_BALANCING */
10752 
10753 /*
10754  * Check whether the task is ineligible on the destination cpu
10755  *
10756  * When the PLACE_LAG scheduling feature is enabled and
10757  * dst_cfs_rq->nr_queued is greater than 1, if the task
10758  * is ineligible, it will also be ineligible when
10759  * it is migrated to the destination cpu.
10760  */
10761 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
10762 {
10763 	struct cfs_rq *dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
10764 
10765 	if (sched_feat(PLACE_LAG) && dst_cfs_rq->h_nr_queued &&
10766 	    !entity_eligible(&task_rq(p)->cfs, &p->se))
10767 		return 1;
10768 
10769 	return 0;
10770 }
10771 
10772 #ifdef CONFIG_SCHED_CACHE
10773 /*
10774  * The margin used when comparing LLC utilization with CPU capacity.
10775  * It determines the LLC load level where active LLC aggregation is
10776  * done.
10777  * Derived from fits_capacity().
10778  *
10779  * (default: ~50%, tunable via debugfs)
10780  */
10781 static bool fits_llc_capacity(unsigned long util, unsigned long max)
10782 {
10783 	u32 aggr_pct = llc_overaggr_pct;
10784 
10785 	/*
10786 	 * For single core systems, raise the aggregation
10787 	 * threshold to accommodate more tasks.
10788 	 */
10789 	if (cpu_smt_num_threads == 1)
10790 		aggr_pct = (aggr_pct * 3 / 2);
10791 
10792 	return util * 100 < max * aggr_pct;
10793 }
10794 
10795 /*
10796  * The margin used when comparing utilization.
10797  * is 'util1' noticeably greater than 'util2'
10798  * Derived from capacity_greater().
10799  * Bias is in perentage.
10800  */
10801 /* Allows dst util to be bigger than src util by up to bias percent */
10802 #define util_greater(util1, util2) \
10803 	((util1) * 100 > (util2) * (100 + llc_imb_pct))
10804 
10805 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util,
10806 					 unsigned long *cap)
10807 {
10808 	struct sched_domain_shared *sd_share;
10809 
10810 	sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
10811 	if (!sd_share)
10812 		return false;
10813 
10814 	*util = READ_ONCE(sd_share->util_avg);
10815 	*cap = READ_ONCE(sd_share->capacity);
10816 
10817 	return true;
10818 }
10819 
10820 /*
10821  * Decision matrix according to the LLC utilization. To
10822  * decide whether we can do task aggregation across LLC.
10823  *
10824  * By default, 50% is the threshold for treating the LLC
10825  * as busy. The reason for choosing 50% is to avoid saturation
10826  * of SMT-2, and it is also a safe cutoff for other SMT-n
10827  * platforms. SMT-1 has higher threshold because it is
10828  * supposed to accommodate more tasks, see fits_llc_capacity().
10829  *
10830  * 20% is the utilization imbalance percentage to decide
10831  * if the preferred LLC is busier than the non-preferred LLC.
10832  * 20 is a little higher than the LLC domain's imbalance_pct
10833  * 17. The hysteresis is used to avoid task bouncing between the
10834  * preferred LLC and the non-preferred LLC, and it will
10835  * be turned into tunable debugfs.
10836  *
10837  * 1. moving towards the preferred LLC, dst is the preferred
10838  *    LLC, src is not.
10839  *
10840  * src \ dst      30%  40%  50%  60%
10841  * 30%            Y    Y    Y    N
10842  * 40%            Y    Y    Y    Y
10843  * 50%            Y    Y    G    G
10844  * 60%            Y    Y    G    G
10845  *
10846  * 2. moving out of the preferred LLC, src is the preferred
10847  *    LLC, dst is not:
10848  *
10849  * src \ dst      30%  40%  50%  60%
10850  * 30%            N    N    N    N
10851  * 40%            N    N    N    N
10852  * 50%            N    N    G    G
10853  * 60%            Y    N    G    G
10854  *
10855  * src :      src_util
10856  * dst :      dst_util
10857  * Y :        Yes, migrate
10858  * N :        No, do not migrate
10859  * G :        let the Generic load balance to even the load.
10860  *
10861  * The intention is that if both LLCs are quite busy, cache aware
10862  * load balance should not be performed, and generic load balance
10863  * should take effect. However, if one is busy and the other is not,
10864  * the preferred LLC capacity(50%) and imbalance criteria(20%) should
10865  * be considered to determine whether LLC aggregation should be
10866  * performed to bias the load towards the preferred LLC.
10867  */
10868 
10869 /* migration decision, 3 states are orthogonal. */
10870 enum llc_mig {
10871 	mig_forbid = 0,		/* N: Don't migrate task, respect LLC preference */
10872 	mig_llc,		/* Y: Do LLC preference based migration */
10873 	mig_unrestricted	/* G: Don't restrict generic load balance migration */
10874 };
10875 
10876 /*
10877  * Check if task can be moved from the source LLC to the
10878  * destination LLC without breaking cache aware preferrence.
10879  * src_cpu and dst_cpu are arbitrary CPUs within the source
10880  * and destination LLCs, respectively.
10881  */
10882 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu,
10883 				    unsigned long tsk_util,
10884 				    bool to_pref)
10885 {
10886 	unsigned long src_util, dst_util, src_cap, dst_cap;
10887 
10888 	if (!get_llc_stats(src_cpu, &src_util, &src_cap) ||
10889 	    !get_llc_stats(dst_cpu, &dst_util, &dst_cap))
10890 		return mig_unrestricted;
10891 
10892 	src_util = src_util < tsk_util ? 0 : src_util - tsk_util;
10893 	dst_util = dst_util + tsk_util;
10894 
10895 	if (!fits_llc_capacity(dst_util, dst_cap) &&
10896 	    !fits_llc_capacity(src_util, src_cap))
10897 		return mig_unrestricted;
10898 
10899 	if (to_pref) {
10900 		/*
10901 		 * Don't migrate if we will get preferred LLC too
10902 		 * heavily loaded and if the dest is much busier
10903 		 * than the src, in which case migration will
10904 		 * increase the imbalance too much.
10905 		 */
10906 		if (!fits_llc_capacity(dst_util, dst_cap) &&
10907 		    util_greater(dst_util, src_util))
10908 			return mig_forbid;
10909 	} else {
10910 		/*
10911 		 * Don't migrate if we will leave preferred LLC
10912 		 * too idle, or if this migration leads to the
10913 		 * non-preferred LLC falls within sysctl_aggr_imb percent
10914 		 * of preferred LLC, leading to migration again
10915 		 * back to preferred LLC.
10916 		 */
10917 		if (fits_llc_capacity(src_util, src_cap) ||
10918 		    !util_greater(src_util, dst_util))
10919 			return mig_forbid;
10920 	}
10921 	return mig_llc;
10922 }
10923 
10924 static inline bool task_misfits_asym_cpu(struct lb_env *env, struct task_struct *p)
10925 {
10926 	/*
10927 	 * On asymmetric CPU capacity domains, do not let cache-aware
10928 	 * balancing pull the task onto a destination CPU that cannot
10929 	 * accommodate it. Doing so would turn the task into a misfit on
10930 	 * the destination, trading a cache-locality gain for a capacity
10931 	 * loss. If the task already does not fit its source CPU, the move
10932 	 * cannot make things worse, so let the LLC preference decide.
10933 	 */
10934 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && p &&
10935 	    !task_fits_cpu(p, env->dst_cpu) &&
10936 	    task_fits_cpu(p, env->src_cpu))
10937 		return true;
10938 
10939 	return false;
10940 }
10941 
10942 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu);
10943 
10944 /*
10945  * Check if task p can migrate from source LLC to
10946  * destination LLC in terms of cache aware load balance.
10947  */
10948 static enum llc_mig can_migrate_llc_task(struct lb_env *env,
10949 					 struct task_struct *p)
10950 {
10951 	struct sched_cache_group *grp;
10952 	bool to_pref;
10953 	int cpu, src_cpu, dst_cpu;
10954 
10955 	if (task_misfits_asym_cpu(env, p))
10956 		return mig_forbid;
10957 
10958 	src_cpu = env->src_cpu;
10959 	dst_cpu = env->dst_cpu;
10960 	grp = rcu_dereference_all(p->sched_cache_grp);
10961 	if (!grp)
10962 		return mig_unrestricted;
10963 
10964 	cpu = READ_ONCE(grp->cpu);
10965 	if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu))
10966 		return mig_unrestricted;
10967 
10968 	/* Prioritize asym packing to idle core over cache awareness */
10969 	if (env->idle && sched_asym(env->sd, dst_cpu, src_cpu))
10970 		return mig_unrestricted;
10971 
10972 	/* skip cache aware load balance for too many threads */
10973 	if (invalid_llc_nr(grp, p, dst_cpu) ||
10974 	    exceed_llc_capacity(grp, dst_cpu)) {
10975 		if (READ_ONCE(grp->cpu) != -1)
10976 			WRITE_ONCE(grp->cpu, -1);
10977 		return mig_unrestricted;
10978 	}
10979 
10980 	if (cpus_share_cache(dst_cpu, cpu))
10981 		to_pref = true;
10982 	else if (cpus_share_cache(src_cpu, cpu))
10983 		to_pref = false;
10984 	else
10985 		return mig_unrestricted;
10986 
10987 	return can_migrate_llc(src_cpu, dst_cpu,
10988 			       task_util(p), to_pref);
10989 }
10990 
10991 /*
10992  * Check if active load balance breaks LLC locality in
10993  * terms of cache aware load balance. The load level and
10994  * imbalance do not warrant breaking LLC preference per
10995  * the can_migrate_llc() policy. Here, the benefit of
10996  * LLC locality outweighs the power efficiency gained from
10997  * migrating the only runnable task away.
10998  */
10999 static inline bool
11000 alb_break_llc(struct lb_env *env)
11001 {
11002 	if (!sched_cache_enabled())
11003 		return false;
11004 
11005 	if (cpus_share_cache(env->src_cpu, env->dst_cpu))
11006 		return false;
11007 	/*
11008 	 * All tasks prefer to stay on their current CPU.
11009 	 * Do not pull a task from its preferred CPU if:
11010 	 * 1. It is the only task running and does not exceed
11011 	 *    imbalance allowance; OR
11012 	 * 2. Migrating it away from its preferred LLC would violate
11013 	 *    the cache-aware scheduling policy.
11014 	 */
11015 	if (env->src_rq->nr_pref_llc_running &&
11016 	    env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) {
11017 		unsigned long util = 0;
11018 		struct task_struct *cur;
11019 
11020 		/*
11021 		 * Migrating misfit tasks from current CPU
11022 		 * to CPU with a better fit.
11023 		 * Prioritize that over LLC preference.
11024 		 */
11025 		if (env->migration_type == migrate_misfit)
11026 			return false;
11027 
11028 		if (env->src_rq->nr_running <= 1)
11029 			return true;
11030 
11031 		cur = rcu_dereference_all(env->src_rq->curr);
11032 		if (cur && cur->sched_class == &fair_sched_class)
11033 			util = task_util(cur);
11034 
11035 		if (task_misfits_asym_cpu(env, cur) ||
11036 		    can_migrate_llc(env->src_cpu, env->dst_cpu,
11037 				    util, false) == mig_forbid)
11038 			return true;
11039 	}
11040 
11041 	return false;
11042 }
11043 
11044 /*
11045  * Returns true if p's preferred LLC does not match the destination CPU
11046  * under migrate_llc_task semantics. Passive LB passes migrate_llc_task
11047  * in env->migration_type, while active LB carries LBF_ACTIVE_LB_LLC in
11048  * env->flags to avoid overwriting env->migration_type.
11049  */
11050 static inline bool
11051 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env)
11052 {
11053 	return sched_cache_enabled() &&
11054 	       (env->migration_type == migrate_llc_task ||
11055 		env->flags & LBF_ACTIVE_LB_LLC) &&
11056 	       READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu);
11057 }
11058 
11059 /*
11060  * Check if migrating task p from env->src_cpu to
11061  * env->dst_cpu breaks LLC localiy.
11062  */
11063 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
11064 {
11065 	if (!sched_cache_enabled())
11066 		return false;
11067 
11068 	if (task_has_sched_core(p))
11069 		return false;
11070 	/*
11071 	 * Skip over tasks that would degrade LLC locality;
11072 	 * only when nr_balanced_failed is sufficiently high do we
11073 	 * ignore this constraint.
11074 	 *
11075 	 * Threshold of cache_nice_tries is set to 1 higher
11076 	 * than nr_balance_failed to avoid excessive task
11077 	 * migration at the same time.
11078 	 */
11079 	if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
11080 		return false;
11081 
11082 	/*
11083 	 * We know the env->src_cpu has some tasks prefer to
11084 	 * run on env->dst_cpu, skip the tasks do not prefer
11085 	 * env->dst_cpu, and find the one that prefers.
11086 	 */
11087 	if (migrate_llc_task_wrong_dst(p, env))
11088 		return true;
11089 
11090 	if (can_migrate_llc_task(env, p) != mig_forbid)
11091 		return false;
11092 
11093 	return true;
11094 }
11095 
11096 #else
11097 static inline bool get_llc_stats(int cpu, unsigned long *util,
11098 				 unsigned long *cap)
11099 {
11100 	return false;
11101 }
11102 
11103 static inline bool
11104 alb_break_llc(struct lb_env *env)
11105 {
11106 	return false;
11107 }
11108 
11109 static inline bool
11110 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env)
11111 {
11112 	return false;
11113 }
11114 
11115 static inline bool
11116 migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
11117 {
11118 	return false;
11119 }
11120 #endif
11121 /*
11122  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
11123  */
11124 static
11125 int can_migrate_task(struct task_struct *p, struct lb_env *env)
11126 {
11127 	long degrades, hot;
11128 
11129 	lockdep_assert_rq_held(env->src_rq);
11130 	if (p->sched_task_hot)
11131 		p->sched_task_hot = 0;
11132 
11133 	/*
11134 	 * We do not migrate tasks that are:
11135 	 * 1) delayed dequeued unless we migrate load, or
11136 	 * 2) target cfs_rq is in throttled hierarchy, or
11137 	 * 3) cannot be migrated to this CPU due to cpus_ptr, or
11138 	 * 4) running (obviously), or
11139 	 * 5) are cache-hot on their current CPU, or
11140 	 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
11141 	 */
11142 	if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
11143 		return 0;
11144 
11145 	if (lb_throttled_hierarchy(p, env->dst_cpu))
11146 		return 0;
11147 
11148 	/*
11149 	 * We want to prioritize the migration of eligible tasks.
11150 	 * For ineligible tasks we soft-limit them and only allow
11151 	 * them to migrate when nr_balance_failed is non-zero to
11152 	 * avoid load-balancing trying very hard to balance the load.
11153 	 */
11154 	if (!env->sd->nr_balance_failed &&
11155 	    task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
11156 		return 0;
11157 
11158 	/* Disregard percpu kthreads; they are where they need to be. */
11159 	if (kthread_is_per_cpu(p))
11160 		return 0;
11161 
11162 	if (task_is_blocked(p))
11163 		return 0;
11164 
11165 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
11166 		int cpu;
11167 
11168 		schedstat_inc(p->stats.nr_failed_migrations_affine);
11169 
11170 		env->flags |= LBF_SOME_PINNED;
11171 
11172 		/*
11173 		 * Remember if this task can be migrated to any other CPU in
11174 		 * our sched_group. We may want to revisit it if we couldn't
11175 		 * meet load balance goals by pulling other tasks on src_cpu.
11176 		 *
11177 		 * Avoid computing new_dst_cpu
11178 		 * - for NEWLY_IDLE
11179 		 * - if we have already computed one in current iteration
11180 		 * - if it's an active balance
11181 		 */
11182 		if (env->idle == CPU_NEWLY_IDLE ||
11183 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
11184 			return 0;
11185 
11186 		/* Prevent to re-select dst_cpu via env's CPUs: */
11187 		cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
11188 
11189 		if (cpu < nr_cpu_ids) {
11190 			env->flags |= LBF_DST_PINNED;
11191 			env->new_dst_cpu = cpu;
11192 		}
11193 
11194 		return 0;
11195 	}
11196 
11197 	/* Record that we found at least one task that could run on dst_cpu */
11198 	env->flags &= ~LBF_ALL_PINNED;
11199 
11200 	if (task_on_cpu(env->src_rq, p) ||
11201 	    task_current_donor(env->src_rq, p)) {
11202 		schedstat_inc(p->stats.nr_failed_migrations_running);
11203 		return 0;
11204 	}
11205 
11206 	/*
11207 	 * Aggressive migration if:
11208 	 * 1) active balance
11209 	 * 2) destination numa is preferred
11210 	 * 3) task is cache cold, or
11211 	 * 4) too many balance attempts have failed.
11212 	 */
11213 	if (env->flags & LBF_ACTIVE_LB)
11214 		return !migrate_llc_task_wrong_dst(p, env);
11215 
11216 	degrades = migrate_degrades_locality(p, env);
11217 	if (!degrades) {
11218 		/*
11219 		 * If the NUMA locality is not broken,
11220 		 * further check if migration would hurt
11221 		 * LLC locality.
11222 		 */
11223 		if (migrate_degrades_llc(p, env)) {
11224 			/*
11225 			 * If regular load balancing fails to pull a task
11226 			 * due to LLC locality, this is expected behavior
11227 			 * and we set LBF_LLC_PINNED so we don't increase
11228 			 * nr_balance_failed unecessarily.
11229 			 */
11230 			if (env->migration_type != migrate_llc_task)
11231 				env->flags |= LBF_LLC_PINNED;
11232 
11233 			return 0;
11234 		}
11235 
11236 		hot = task_hot(p, env);
11237 	} else {
11238 		hot = degrades > 0;
11239 	}
11240 
11241 	if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
11242 		if (hot)
11243 			p->sched_task_hot = 1;
11244 		return 1;
11245 	}
11246 
11247 	schedstat_inc(p->stats.nr_failed_migrations_hot);
11248 	return 0;
11249 }
11250 
11251 /*
11252  * detach_task() -- detach the task for the migration specified in env
11253  */
11254 static void detach_task(struct task_struct *p, struct lb_env *env)
11255 {
11256 	lockdep_assert_rq_held(env->src_rq);
11257 
11258 	if (p->sched_task_hot) {
11259 		p->sched_task_hot = 0;
11260 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
11261 		schedstat_inc(p->stats.nr_forced_migrations);
11262 	}
11263 
11264 	WARN_ON(task_current(env->src_rq, p));
11265 	WARN_ON(task_current_donor(env->src_rq, p));
11266 
11267 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
11268 	set_task_cpu(p, env->dst_cpu);
11269 }
11270 
11271 /*
11272  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
11273  * part of active balancing operations within "domain".
11274  *
11275  * Returns a task if successful and NULL otherwise.
11276  */
11277 static struct task_struct *detach_one_task(struct lb_env *env)
11278 {
11279 	struct task_struct *p;
11280 
11281 	lockdep_assert_rq_held(env->src_rq);
11282 
11283 	list_for_each_entry_reverse(p,
11284 			&env->src_rq->cfs_tasks, se.group_node) {
11285 		if (!can_migrate_task(p, env))
11286 			continue;
11287 
11288 		detach_task(p, env);
11289 
11290 		/*
11291 		 * Right now, this is only the second place where
11292 		 * lb_gained[env->idle] is updated (other is detach_tasks)
11293 		 * so we can safely collect stats here rather than
11294 		 * inside detach_tasks().
11295 		 */
11296 		schedstat_inc(env->sd->lb_gained[env->idle]);
11297 		return p;
11298 	}
11299 	return NULL;
11300 }
11301 
11302 /*
11303  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
11304  * busiest_rq, as part of a balancing operation within domain "sd".
11305  *
11306  * Returns number of detached tasks if successful and 0 otherwise.
11307  */
11308 static int detach_tasks(struct lb_env *env)
11309 {
11310 	struct list_head *tasks = &env->src_rq->cfs_tasks;
11311 	unsigned long util, load;
11312 	struct task_struct *p;
11313 	int detached = 0;
11314 
11315 	lockdep_assert_rq_held(env->src_rq);
11316 
11317 	/*
11318 	 * Source run queue has been emptied by another CPU, clear
11319 	 * LBF_ALL_PINNED flag as we will not test any task.
11320 	 */
11321 	if (env->src_rq->nr_running <= 1) {
11322 		env->flags &= ~LBF_ALL_PINNED;
11323 		return 0;
11324 	}
11325 
11326 	if (env->imbalance <= 0)
11327 		return 0;
11328 
11329 	while (!list_empty(tasks)) {
11330 		/*
11331 		 * We don't want to steal all, otherwise we may be treated likewise,
11332 		 * which could at worst lead to a livelock crash.
11333 		 */
11334 		if (env->idle && env->src_rq->nr_running <= 1)
11335 			break;
11336 
11337 		env->loop++;
11338 		/* We've more or less seen every task there is, call it quits */
11339 		if (env->loop > env->loop_max)
11340 			break;
11341 
11342 		/* take a breather every nr_migrate tasks */
11343 		if (env->loop > env->loop_break) {
11344 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
11345 			env->flags |= LBF_NEED_BREAK;
11346 			break;
11347 		}
11348 
11349 		p = list_last_entry(tasks, struct task_struct, se.group_node);
11350 
11351 		if (!can_migrate_task(p, env))
11352 			goto next;
11353 
11354 		switch (env->migration_type) {
11355 		case migrate_load:
11356 			/*
11357 			 * Depending of the number of CPUs and tasks and the
11358 			 * cgroup hierarchy, task_h_load() can return a null
11359 			 * value. Make sure that env->imbalance decreases
11360 			 * otherwise detach_tasks() will stop only after
11361 			 * detaching up to loop_max tasks.
11362 			 */
11363 			load = max_t(unsigned long, task_h_load(p), 1);
11364 
11365 			if (sched_feat(LB_MIN) &&
11366 			    load < 16 && !env->sd->nr_balance_failed)
11367 				goto next;
11368 
11369 			/*
11370 			 * Make sure that we don't migrate too much load.
11371 			 * Nevertheless, let relax the constraint if
11372 			 * scheduler fails to find a good waiting task to
11373 			 * migrate.
11374 			 */
11375 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
11376 				goto next;
11377 
11378 			env->imbalance -= load;
11379 			break;
11380 
11381 		case migrate_util:
11382 			util = task_util_est(p);
11383 
11384 			if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
11385 				goto next;
11386 
11387 			env->imbalance -= util;
11388 			break;
11389 
11390 		case migrate_task:
11391 			env->imbalance--;
11392 			break;
11393 
11394 		case migrate_misfit:
11395 			/* This is not a misfit task */
11396 			if (task_fits_cpu(p, env->src_cpu))
11397 				goto next;
11398 
11399 			env->imbalance = 0;
11400 			break;
11401 
11402 		case migrate_llc_task:
11403 			env->imbalance--;
11404 			break;
11405 		}
11406 
11407 		detach_task(p, env);
11408 		list_add(&p->se.group_node, &env->tasks);
11409 
11410 		detached++;
11411 
11412 #ifdef CONFIG_PREEMPTION
11413 		/*
11414 		 * NEWIDLE balancing is a source of latency, so preemptible
11415 		 * kernels will stop after the first task is detached to minimize
11416 		 * the critical section.
11417 		 */
11418 		if (env->idle == CPU_NEWLY_IDLE)
11419 			break;
11420 #endif
11421 
11422 		/*
11423 		 * We only want to steal up to the prescribed amount of
11424 		 * load/util/tasks.
11425 		 */
11426 		if (env->imbalance <= 0)
11427 			break;
11428 
11429 		continue;
11430 next:
11431 		if (p->sched_task_hot)
11432 			schedstat_inc(p->stats.nr_failed_migrations_hot);
11433 
11434 		list_move(&p->se.group_node, tasks);
11435 	}
11436 
11437 	/*
11438 	 * Right now, this is one of only two places we collect this stat
11439 	 * so we can safely collect detach_one_task() stats here rather
11440 	 * than inside detach_one_task().
11441 	 */
11442 	schedstat_add(env->sd->lb_gained[env->idle], detached);
11443 
11444 	return detached;
11445 }
11446 
11447 /*
11448  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
11449  * new rq.
11450  */
11451 static void attach_tasks(struct lb_env *env)
11452 {
11453 	__attach_tasks(env->dst_rq, &env->tasks);
11454 }
11455 
11456 #ifdef CONFIG_NO_HZ_COMMON
11457 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq)
11458 {
11459 	if (cfs_rq->avg.load_avg)
11460 		return true;
11461 
11462 	if (cfs_rq->avg.util_avg)
11463 		return true;
11464 
11465 	return false;
11466 }
11467 
11468 static inline bool others_have_blocked(struct rq *rq)
11469 {
11470 	if (cpu_util_rt(rq))
11471 		return true;
11472 
11473 	if (cpu_util_dl(rq))
11474 		return true;
11475 
11476 	if (hw_load_avg(rq))
11477 		return true;
11478 
11479 	if (cpu_util_irq(rq))
11480 		return true;
11481 
11482 	return false;
11483 }
11484 
11485 static inline void update_blocked_load_tick(struct rq *rq)
11486 {
11487 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
11488 }
11489 
11490 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load)
11491 {
11492 	if (!has_blocked_load)
11493 		rq->has_blocked_load = 0;
11494 }
11495 #else /* !CONFIG_NO_HZ_COMMON: */
11496 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; }
11497 static inline bool others_have_blocked(struct rq *rq) { return false; }
11498 static inline void update_blocked_load_tick(struct rq *rq) {}
11499 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {}
11500 #endif /* !CONFIG_NO_HZ_COMMON */
11501 
11502 static bool __update_blocked_others(struct rq *rq, bool *done)
11503 {
11504 	bool updated;
11505 
11506 	/*
11507 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
11508 	 * DL and IRQ signals have been updated before updating CFS.
11509 	 */
11510 	updated = update_other_load_avgs(rq);
11511 
11512 	if (others_have_blocked(rq))
11513 		*done = false;
11514 
11515 	return updated;
11516 }
11517 
11518 #ifdef CONFIG_FAIR_GROUP_SCHED
11519 
11520 static bool __update_blocked_fair(struct rq *rq, bool *done)
11521 {
11522 	struct cfs_rq *cfs_rq, *pos;
11523 	bool decayed = false;
11524 
11525 	/*
11526 	 * Iterates the task_group tree in a bottom up fashion, see
11527 	 * list_add_leaf_cfs_rq() for details.
11528 	 */
11529 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
11530 		struct sched_entity *se;
11531 
11532 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
11533 			update_tg_load_avg(cfs_rq);
11534 
11535 			if (cfs_rq->nr_queued == 0)
11536 				update_idle_cfs_rq_clock_pelt(cfs_rq);
11537 
11538 			if (cfs_rq == &rq->cfs)
11539 				decayed = true;
11540 		}
11541 
11542 		/* Propagate pending load changes to the parent, if any: */
11543 		se = cfs_rq_se(cfs_rq);
11544 		if (se && !skip_blocked_update(se))
11545 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11546 
11547 		/*
11548 		 * There can be a lot of idle CPU cgroups.  Don't let fully
11549 		 * decayed cfs_rqs linger on the list.
11550 		 */
11551 		if (cfs_rq_is_decayed(cfs_rq))
11552 			list_del_leaf_cfs_rq(cfs_rq);
11553 
11554 		/* Don't need periodic decay once load/util_avg are null */
11555 		if (cfs_rq_has_blocked_load(cfs_rq))
11556 			*done = false;
11557 	}
11558 
11559 	return decayed;
11560 }
11561 
11562 /*
11563  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
11564  * This needs to be done in a top-down fashion because the load of a child
11565  * group is a fraction of its parents load.
11566  */
11567 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
11568 {
11569 	struct sched_entity *se = cfs_rq_se(cfs_rq);
11570 	unsigned long now = jiffies;
11571 	unsigned long load;
11572 
11573 	if (cfs_rq->last_h_load_update == now)
11574 		return;
11575 
11576 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
11577 	for_each_sched_entity(se) {
11578 		cfs_rq = cfs_rq_of(se);
11579 		WRITE_ONCE(cfs_rq->h_load_next, se);
11580 		if (cfs_rq->last_h_load_update == now)
11581 			break;
11582 	}
11583 
11584 	if (!se) {
11585 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
11586 		cfs_rq->last_h_load_update = now;
11587 	}
11588 
11589 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
11590 		load = cfs_rq->h_load;
11591 		load = div64_ul(load * se->avg.load_avg,
11592 				cfs_rq_load_avg(cfs_rq) + 1);
11593 		cfs_rq = group_cfs_rq(se);
11594 		cfs_rq->h_load = load;
11595 		cfs_rq->last_h_load_update = now;
11596 	}
11597 }
11598 
11599 static unsigned long task_h_load(struct task_struct *p)
11600 {
11601 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
11602 
11603 	update_cfs_rq_h_load(cfs_rq);
11604 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
11605 			cfs_rq_load_avg(cfs_rq) + 1);
11606 }
11607 #else /* !CONFIG_FAIR_GROUP_SCHED: */
11608 static bool __update_blocked_fair(struct rq *rq, bool *done)
11609 {
11610 	struct cfs_rq *cfs_rq = &rq->cfs;
11611 	bool decayed;
11612 
11613 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
11614 	if (cfs_rq_has_blocked_load(cfs_rq))
11615 		*done = false;
11616 
11617 	return decayed;
11618 }
11619 
11620 static unsigned long task_h_load(struct task_struct *p)
11621 {
11622 	return p->se.avg.load_avg;
11623 }
11624 #endif /* !CONFIG_FAIR_GROUP_SCHED */
11625 
11626 static void __sched_balance_update_blocked_averages(struct rq *rq)
11627 {
11628 	bool decayed = false, done = true;
11629 
11630 	update_blocked_load_tick(rq);
11631 
11632 	decayed |= __update_blocked_others(rq, &done);
11633 	decayed |= __update_blocked_fair(rq, &done);
11634 
11635 	update_has_blocked_load_status(rq, !done);
11636 	if (decayed)
11637 		cpufreq_update_util(rq, 0);
11638 }
11639 
11640 static void sched_balance_update_blocked_averages(int cpu)
11641 {
11642 	struct rq *rq = cpu_rq(cpu);
11643 
11644 	guard(rq_lock_irqsave)(rq);
11645 	update_rq_clock(rq);
11646 	__sched_balance_update_blocked_averages(rq);
11647 }
11648 
11649 /********** Helpers for sched_balance_find_src_group ************************/
11650 
11651 /*
11652  * sg_lb_stats - stats of a sched_group required for load-balancing:
11653  */
11654 struct sg_lb_stats {
11655 	unsigned long avg_load;			/* Avg load            over the CPUs of the group */
11656 	unsigned long group_load;		/* Total load          over the CPUs of the group */
11657 	unsigned long group_capacity;		/* Capacity            over the CPUs of the group */
11658 	unsigned long group_util;		/* Total utilization   over the CPUs of the group */
11659 	unsigned long group_runnable;		/* Total runnable time over the CPUs of the group */
11660 	unsigned int sum_nr_running;		/* Nr of all tasks running in the group */
11661 	unsigned int sum_h_nr_running;		/* Nr of CFS tasks running in the group */
11662 	unsigned int idle_cpus;                 /* Nr of idle CPUs         in the group */
11663 	unsigned int group_weight;
11664 	enum group_type group_type;
11665 	unsigned int group_asym_packing;	/* Tasks should be moved to preferred CPU */
11666 	unsigned int group_smt_balance;		/* Task on busy SMT be moved */
11667 	unsigned int group_llc_balance;		/* Tasks should be moved to preferred LLC */
11668 	unsigned long group_misfit_task_load;	/* A CPU has a task too big for its capacity */
11669 	unsigned int group_overutilized;	/* At least one CPU is overutilized in the group */
11670 #ifdef CONFIG_NUMA_BALANCING
11671 	unsigned int nr_numa_running;
11672 	unsigned int nr_preferred_running;
11673 #endif
11674 #ifdef CONFIG_SCHED_CACHE
11675 	unsigned int nr_pref_dst_llc;
11676 #endif
11677 };
11678 
11679 /*
11680  * sd_lb_stats - stats of a sched_domain required for load-balancing:
11681  */
11682 struct sd_lb_stats {
11683 	struct sched_group *busiest;		/* Busiest group in this sd */
11684 	struct sched_group *local;		/* Local group in this sd */
11685 	unsigned long total_load;		/* Total load of all groups in sd */
11686 	unsigned long total_capacity;		/* Total capacity of all groups in sd */
11687 	unsigned long avg_load;			/* Average load across all groups in sd */
11688 	unsigned int prefer_sibling;		/* Tasks should go to sibling first */
11689 
11690 	struct sg_lb_stats busiest_stat;	/* Statistics of the busiest group */
11691 	struct sg_lb_stats local_stat;		/* Statistics of the local group */
11692 };
11693 
11694 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
11695 {
11696 	/*
11697 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
11698 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
11699 	 * We must however set busiest_stat::group_type and
11700 	 * busiest_stat::idle_cpus to the worst busiest group because
11701 	 * update_sd_pick_busiest() reads these before assignment.
11702 	 */
11703 	*sds = (struct sd_lb_stats){
11704 		.busiest = NULL,
11705 		.local = NULL,
11706 		.total_load = 0UL,
11707 		.total_capacity = 0UL,
11708 		.busiest_stat = {
11709 			.idle_cpus = UINT_MAX,
11710 			.group_type = group_has_spare,
11711 		},
11712 	};
11713 }
11714 
11715 static unsigned long scale_rt_capacity(int cpu)
11716 {
11717 	unsigned long max = get_actual_cpu_capacity(cpu);
11718 	struct rq *rq = cpu_rq(cpu);
11719 	unsigned long used, free;
11720 	unsigned long irq;
11721 
11722 	irq = cpu_util_irq(rq);
11723 
11724 	if (unlikely(irq >= max))
11725 		return 1;
11726 
11727 	/*
11728 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
11729 	 * (running and not running) with weights 0 and 1024 respectively.
11730 	 */
11731 	used = cpu_util_rt(rq);
11732 	used += cpu_util_dl(rq);
11733 
11734 	if (unlikely(used >= max))
11735 		return 1;
11736 
11737 	free = max - used;
11738 
11739 	return scale_irq_capacity(free, irq, max);
11740 }
11741 
11742 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
11743 {
11744 	unsigned long capacity = scale_rt_capacity(cpu);
11745 	struct sched_group *sdg = sd->groups;
11746 
11747 	if (!capacity)
11748 		capacity = 1;
11749 
11750 	cpu_rq(cpu)->cpu_capacity = capacity;
11751 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
11752 
11753 	sdg->sgc->capacity = capacity;
11754 	sdg->sgc->min_capacity = capacity;
11755 	sdg->sgc->max_capacity = capacity;
11756 }
11757 
11758 void update_group_capacity(struct sched_domain *sd, int cpu)
11759 {
11760 	struct sched_domain *child = sd->child;
11761 	struct sched_group *group, *sdg = sd->groups;
11762 	unsigned long capacity, min_capacity, max_capacity;
11763 	unsigned long interval;
11764 
11765 	interval = msecs_to_jiffies(sd->balance_interval);
11766 	interval = clamp(interval, 1UL, max_load_balance_interval);
11767 	sdg->sgc->next_update = jiffies + interval;
11768 
11769 	if (!child) {
11770 		update_cpu_capacity(sd, cpu);
11771 		return;
11772 	}
11773 
11774 	capacity = 0;
11775 	min_capacity = ULONG_MAX;
11776 	max_capacity = 0;
11777 
11778 	if (child->flags & SD_NUMA) {
11779 		/*
11780 		 * SD_NUMA domains cannot assume that child groups
11781 		 * span the current group.
11782 		 */
11783 
11784 		for_each_cpu(cpu, sched_group_span(sdg)) {
11785 			unsigned long cpu_cap = capacity_of(cpu);
11786 
11787 			capacity += cpu_cap;
11788 			min_capacity = min(cpu_cap, min_capacity);
11789 			max_capacity = max(cpu_cap, max_capacity);
11790 		}
11791 	} else  {
11792 		/*
11793 		 * !SD_NUMA domains can assume that child groups
11794 		 * span the current group.
11795 		 */
11796 
11797 		group = child->groups;
11798 		do {
11799 			struct sched_group_capacity *sgc = group->sgc;
11800 
11801 			capacity += sgc->capacity;
11802 			min_capacity = min(sgc->min_capacity, min_capacity);
11803 			max_capacity = max(sgc->max_capacity, max_capacity);
11804 			group = group->next;
11805 		} while (group != child->groups);
11806 	}
11807 
11808 	sdg->sgc->capacity = capacity;
11809 	sdg->sgc->min_capacity = min_capacity;
11810 	sdg->sgc->max_capacity = max_capacity;
11811 }
11812 
11813 /*
11814  * Check whether the capacity of the rq has been noticeably reduced by side
11815  * activity. The imbalance_pct is used for the threshold.
11816  * Return true is the capacity is reduced
11817  */
11818 static inline int
11819 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
11820 {
11821 	return ((rq->cpu_capacity * sd->imbalance_pct) <
11822 				(arch_scale_cpu_capacity(cpu_of(rq)) * 100));
11823 }
11824 
11825 /* Check if the rq has a misfit task */
11826 static inline bool check_misfit_status(struct rq *rq)
11827 {
11828 	return rq->misfit_task_load;
11829 }
11830 
11831 /*
11832  * Group imbalance indicates (and tries to solve) the problem where balancing
11833  * groups is inadequate due to ->cpus_ptr constraints.
11834  *
11835  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
11836  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
11837  * Something like:
11838  *
11839  *	{ 0 1 2 3 } { 4 5 6 7 }
11840  *	        *     * * *
11841  *
11842  * If we were to balance group-wise we'd place two tasks in the first group and
11843  * two tasks in the second group. Clearly this is undesired as it will overload
11844  * cpu 3 and leave one of the CPUs in the second group unused.
11845  *
11846  * The current solution to this issue is detecting the skew in the first group
11847  * by noticing the lower domain failed to reach balance and had difficulty
11848  * moving tasks due to affinity constraints.
11849  *
11850  * When this is so detected; this group becomes a candidate for busiest; see
11851  * update_sd_pick_busiest(). And calculate_imbalance() and
11852  * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
11853  * to create an effective group imbalance.
11854  *
11855  * This is a somewhat tricky proposition since the next run might not find the
11856  * group imbalance and decide the groups need to be balanced again. A most
11857  * subtle and fragile situation.
11858  */
11859 
11860 static inline int sg_imbalanced(struct sched_group *group)
11861 {
11862 	return group->sgc->imbalance;
11863 }
11864 
11865 /*
11866  * group_has_capacity returns true if the group has spare capacity that could
11867  * be used by some tasks.
11868  * We consider that a group has spare capacity if the number of task is
11869  * smaller than the number of CPUs or if the utilization is lower than the
11870  * available capacity for CFS tasks.
11871  * For the latter, we use a threshold to stabilize the state, to take into
11872  * account the variance of the tasks' load and to return true if the available
11873  * capacity in meaningful for the load balancer.
11874  * As an example, an available capacity of 1% can appear but it doesn't make
11875  * any benefit for the load balance.
11876  */
11877 static inline bool
11878 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11879 {
11880 	if (sgs->sum_nr_running < sgs->group_weight)
11881 		return true;
11882 
11883 	if ((sgs->group_capacity * imbalance_pct) <
11884 			(sgs->group_runnable * 100))
11885 		return false;
11886 
11887 	if ((sgs->group_capacity * 100) >
11888 			(sgs->group_util * imbalance_pct))
11889 		return true;
11890 
11891 	return false;
11892 }
11893 
11894 /*
11895  *  group_is_overloaded returns true if the group has more tasks than it can
11896  *  handle.
11897  *  group_is_overloaded is not equals to !group_has_capacity because a group
11898  *  with the exact right number of tasks, has no more spare capacity but is not
11899  *  overloaded so both group_has_capacity and group_is_overloaded return
11900  *  false.
11901  */
11902 static inline bool
11903 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11904 {
11905 	/*
11906 	 * With EAS and uclamp, 1 CPU in the group must be overutilized to
11907 	 * consider the group overloaded.
11908 	 */
11909 	if (sched_energy_enabled() && !sgs->group_overutilized)
11910 		return false;
11911 
11912 	if (sgs->sum_nr_running <= sgs->group_weight)
11913 		return false;
11914 
11915 	if ((sgs->group_capacity * 100) <
11916 			(sgs->group_util * imbalance_pct))
11917 		return true;
11918 
11919 	if ((sgs->group_capacity * imbalance_pct) <
11920 			(sgs->group_runnable * 100))
11921 		return true;
11922 
11923 	return false;
11924 }
11925 
11926 static inline enum
11927 group_type group_classify(unsigned int imbalance_pct,
11928 			  struct sched_group *group,
11929 			  struct sg_lb_stats *sgs)
11930 {
11931 	if (group_is_overloaded(imbalance_pct, sgs))
11932 		return group_overloaded;
11933 
11934 	if (sgs->group_llc_balance)
11935 		return group_llc_balance;
11936 
11937 	if (sg_imbalanced(group))
11938 		return group_imbalanced;
11939 
11940 	if (sgs->group_asym_packing)
11941 		return group_asym_packing;
11942 
11943 	if (sgs->group_smt_balance)
11944 		return group_smt_balance;
11945 
11946 	if (sgs->group_misfit_task_load)
11947 		return group_misfit_task;
11948 
11949 	if (!group_has_capacity(imbalance_pct, sgs))
11950 		return group_fully_busy;
11951 
11952 	return group_has_spare;
11953 }
11954 
11955 /**
11956  * sched_use_asym_prio - Check whether asym_packing priority must be used
11957  * @sd:		The scheduling domain of the load balancing
11958  * @cpu:	A CPU
11959  *
11960  * Always use CPU priority when balancing load between SMT siblings. When
11961  * balancing load between cores, it is not sufficient that @cpu is idle. Only
11962  * use CPU priority if the whole core is idle.
11963  *
11964  * Returns: True if the priority of @cpu must be followed. False otherwise.
11965  */
11966 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
11967 {
11968 	if (!(sd->flags & SD_ASYM_PACKING))
11969 		return false;
11970 
11971 	if (!sched_smt_active())
11972 		return true;
11973 
11974 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
11975 }
11976 
11977 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
11978 {
11979 	/*
11980 	 * First check if @dst_cpu can do asym_packing load balance. Only do it
11981 	 * if it has higher priority than @src_cpu.
11982 	 */
11983 	return sched_use_asym_prio(sd, dst_cpu) &&
11984 		sched_asym_prefer(dst_cpu, src_cpu);
11985 }
11986 
11987 /**
11988  * sched_group_asym - Check if the destination CPU can do asym_packing balance
11989  * @env:	The load balancing environment
11990  * @sgs:	Load-balancing statistics of the candidate busiest group
11991  * @group:	The candidate busiest group
11992  *
11993  * @env::dst_cpu can do asym_packing if it has higher priority than the
11994  * preferred CPU of @group.
11995  *
11996  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
11997  * otherwise.
11998  */
11999 static inline bool
12000 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
12001 {
12002 	/*
12003 	 * CPU priorities do not make sense for SMT cores with more than one
12004 	 * busy sibling.
12005 	 */
12006 	if ((group->flags & SD_SHARE_CPUCAPACITY) &&
12007 	    (sgs->group_weight - sgs->idle_cpus != 1))
12008 		return false;
12009 
12010 	return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
12011 }
12012 
12013 /* One group has more than one SMT CPU while the other group does not */
12014 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
12015 				    struct sched_group *sg2)
12016 {
12017 	if (!sg1 || !sg2)
12018 		return false;
12019 
12020 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
12021 		(sg2->flags & SD_SHARE_CPUCAPACITY);
12022 }
12023 
12024 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12025 			       struct sched_group *group)
12026 {
12027 	if (!env->idle)
12028 		return false;
12029 
12030 	/*
12031 	 * For SMT source group, it is better to move a task
12032 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
12033 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
12034 	 * will not be on.
12035 	 */
12036 	if (group->flags & SD_SHARE_CPUCAPACITY &&
12037 	    sgs->sum_h_nr_running > 1)
12038 		return true;
12039 
12040 	return false;
12041 }
12042 
12043 static inline long sibling_imbalance(struct lb_env *env,
12044 				    struct sd_lb_stats *sds,
12045 				    struct sg_lb_stats *busiest,
12046 				    struct sg_lb_stats *local)
12047 {
12048 	int ncores_busiest, ncores_local;
12049 	long imbalance;
12050 
12051 	if (!env->idle || !busiest->sum_nr_running)
12052 		return 0;
12053 
12054 	ncores_busiest = sds->busiest->cores;
12055 	ncores_local = sds->local->cores;
12056 
12057 	if (ncores_busiest == ncores_local) {
12058 		imbalance = busiest->sum_nr_running;
12059 		lsub_positive(&imbalance, local->sum_nr_running);
12060 		return imbalance;
12061 	}
12062 
12063 	/* Balance such that nr_running/ncores ratio are same on both groups */
12064 	imbalance = ncores_local * busiest->sum_nr_running;
12065 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
12066 	/* Normalize imbalance and do rounding on normalization */
12067 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
12068 	imbalance /= ncores_local + ncores_busiest;
12069 
12070 	/* Take advantage of resource in an empty sched group */
12071 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
12072 	    busiest->sum_nr_running > 1)
12073 		imbalance = 2;
12074 
12075 	return imbalance;
12076 }
12077 
12078 static inline bool
12079 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
12080 {
12081 	/*
12082 	 * When there is more than 1 task, the group_overloaded case already
12083 	 * takes care of cpu with reduced capacity
12084 	 */
12085 	if (rq->cfs.h_nr_runnable != 1)
12086 		return false;
12087 
12088 	return check_cpu_capacity(rq, sd);
12089 }
12090 
12091 #ifdef CONFIG_SCHED_CACHE
12092 /*
12093  * Record the statistics for this scheduler group for later
12094  * use. These values guide load balancing on aggregating tasks
12095  * to a LLC.
12096  */
12097 static void record_sg_llc_stats(struct lb_env *env,
12098 				struct sg_lb_stats *sgs,
12099 				struct sched_group *group)
12100 {
12101 	struct sched_domain_shared *sd_share;
12102 	int cpu;
12103 
12104 	if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE)
12105 		return;
12106 
12107 	/* Only care about sched domain spanning multiple LLCs */
12108 	if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu)))
12109 		return;
12110 
12111 	/*
12112 	 * A redo repeats stats published on the first pass. Hotplug can
12113 	 * still leave env->cpus partial, so util would not match capacity.
12114 	 */
12115 	if ((env->flags & LBF_ALL_PINNED) ||
12116 	    !cpumask_subset(sched_group_span(group), env->cpus))
12117 		return;
12118 
12119 	/*
12120 	 * At this point we know this group spans a LLC domain.
12121 	 * Record the statistic of this group in its corresponding
12122 	 * shared LLC domain.
12123 	 * Note: sd_share cannot be obtained via sd->child->shared,
12124 	 * because the latter refers to the domain that covers the
12125 	 * local group. Instead, sd_share should be located using
12126 	 * the first CPU of the LLC group.
12127 	 */
12128 	cpu = cpumask_first(sched_group_span(group));
12129 	sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
12130 	if (!sd_share)
12131 		return;
12132 
12133 	if (READ_ONCE(sd_share->util_avg) != sgs->group_util)
12134 		WRITE_ONCE(sd_share->util_avg, sgs->group_util);
12135 
12136 	if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity))
12137 		WRITE_ONCE(sd_share->capacity, sgs->group_capacity);
12138 }
12139 
12140 /*
12141  * Do LLC balance on sched group that contains LLC, and have tasks preferring
12142  * to run on LLC in idle dst_cpu.
12143  */
12144 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12145 			       struct sched_group *group)
12146 {
12147 	if (!sched_cache_enabled())
12148 		return false;
12149 
12150 	if (env->sd->flags & SD_SHARE_LLC)
12151 		return false;
12152 
12153 	/*
12154 	 * On asymmetric domains, group_misfit_task_load
12155 	 * should be prioritized to move tasks to CPU that fit them
12156 	 * over aggregating tasks to their preferred LLC.
12157 	 */
12158 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12159 	    sgs->group_misfit_task_load)
12160 		return false;
12161 
12162 	/*
12163 	 * On asym packing domains, if the destination CPU
12164 	 * has higher priority than all CPUs in the source group,
12165 	 * prioritize asym packing.
12166 	 */
12167 	if (sgs->group_asym_packing)
12168 		return false;
12169 
12170 	/*
12171 	 * Skip cache aware tagging if nr_balanced_failed is sufficiently high.
12172 	 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed
12173 	 * to avoid excessive task migration at the same time.
12174 	 */
12175 	if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
12176 		return false;
12177 
12178 	if (sgs->nr_pref_dst_llc &&
12179 	    can_migrate_llc(cpumask_first(sched_group_span(group)),
12180 			    env->dst_cpu, 0, true) == mig_llc)
12181 		return true;
12182 
12183 	return false;
12184 }
12185 
12186 static bool update_llc_busiest(struct lb_env *env,
12187 			       struct sg_lb_stats *busiest,
12188 			       struct sg_lb_stats *sgs)
12189 {
12190 	/*
12191 	 * There are more tasks that want to run on dst_cpu's LLC.
12192 	 */
12193 	return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc;
12194 }
12195 #else
12196 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs,
12197 				       struct sched_group *group)
12198 {
12199 }
12200 
12201 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
12202 			       struct sched_group *group)
12203 {
12204 	return false;
12205 }
12206 
12207 static bool update_llc_busiest(struct lb_env *env,
12208 			       struct sg_lb_stats *busiest,
12209 			       struct sg_lb_stats *sgs)
12210 {
12211 	return false;
12212 }
12213 #endif
12214 
12215 /**
12216  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
12217  * @env: The load balancing environment.
12218  * @sds: Load-balancing data with statistics of the local group.
12219  * @group: sched_group whose statistics are to be updated.
12220  * @sgs: variable to hold the statistics for this group.
12221  * @sg_overloaded: sched_group is overloaded
12222  */
12223 static inline void update_sg_lb_stats(struct lb_env *env,
12224 				      struct sd_lb_stats *sds,
12225 				      struct sched_group *group,
12226 				      struct sg_lb_stats *sgs,
12227 				      bool *sg_overloaded)
12228 {
12229 	int i, nr_running, local_group, sd_flags = env->sd->flags;
12230 	bool balancing_at_rd = !env->sd->parent;
12231 
12232 	memset(sgs, 0, sizeof(*sgs));
12233 
12234 	local_group = group == sds->local;
12235 
12236 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
12237 		struct rq *rq = cpu_rq(i);
12238 		unsigned long load = cpu_load(rq);
12239 
12240 		sgs->group_load += load;
12241 		sgs->group_util += cpu_util_cfs(i);
12242 		sgs->group_runnable += cpu_runnable(rq);
12243 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
12244 
12245 		nr_running = rq->nr_running;
12246 		sgs->sum_nr_running += nr_running;
12247 
12248 		if (cpu_overutilized(i))
12249 			sgs->group_overutilized = 1;
12250 
12251 #ifdef CONFIG_SCHED_CACHE
12252 		if (sched_cache_enabled()) {
12253 			struct sched_domain *sd_tmp;
12254 			int dst_llc;
12255 
12256 			dst_llc = llc_id(env->dst_cpu);
12257 			if (llc_id(i) != dst_llc) {
12258 				sd_tmp = rcu_dereference_all(rq->sd);
12259 				if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max)
12260 					sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc];
12261 			}
12262 		}
12263 #endif
12264 
12265 		/*
12266 		 * No need to call idle_cpu() if nr_running is not 0
12267 		 */
12268 		if (!nr_running && idle_cpu(i)) {
12269 			sgs->idle_cpus++;
12270 			/* Idle cpu can't have misfit task */
12271 			continue;
12272 		}
12273 
12274 		/* Overload indicator is only updated at root domain */
12275 		if (balancing_at_rd && nr_running > 1)
12276 			*sg_overloaded = 1;
12277 
12278 #ifdef CONFIG_NUMA_BALANCING
12279 		/* Only fbq_classify_group() uses this to classify NUMA groups */
12280 		if (sd_flags & SD_NUMA) {
12281 			sgs->nr_numa_running += rq->nr_numa_running;
12282 			sgs->nr_preferred_running += rq->nr_preferred_running;
12283 		}
12284 #endif
12285 		if (local_group)
12286 			continue;
12287 
12288 		if (sd_flags & SD_ASYM_CPUCAPACITY) {
12289 			if (rq->misfit_task_load) {
12290 				/*
12291 				 * Always mark the root domain overloaded so big
12292 				 * CPUs can pick up misfit tasks via newly idle
12293 				 * balance.
12294 				 */
12295 				if (balancing_at_rd)
12296 					*sg_overloaded = 1;
12297 
12298 				/*
12299 				 * Only account misfit load if @dst_cpu can
12300 				 * help; otherwise, the group may be classified
12301 				 * as misfit_task and update_sd_pick_busiest()
12302 				 * will skip it.
12303 				 */
12304 				if (capacity_greater(capacity_of(env->dst_cpu),
12305 						     group->sgc->max_capacity) &&
12306 				    (sgs->group_misfit_task_load < rq->misfit_task_load))
12307 					sgs->group_misfit_task_load = rq->misfit_task_load;
12308 			}
12309 		} else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
12310 			/* Check for a task running on a CPU with reduced capacity */
12311 			if (sgs->group_misfit_task_load < load)
12312 				sgs->group_misfit_task_load = load;
12313 		}
12314 	}
12315 
12316 	sgs->group_capacity = group->sgc->capacity;
12317 
12318 	sgs->group_weight = group->group_weight;
12319 
12320 	if (!local_group) {
12321 		/* Check if dst CPU is idle and preferred to this group */
12322 		if (env->idle && sgs->sum_h_nr_running &&
12323 		    sched_group_asym(env, sgs, group))
12324 			sgs->group_asym_packing = 1;
12325 
12326 		/* Check for loaded SMT group to be balanced to dst CPU */
12327 		if (smt_balance(env, sgs, group))
12328 			sgs->group_smt_balance = 1;
12329 
12330 		/* Check for tasks in this group can be moved to their preferred LLC */
12331 		if (llc_balance(env, sgs, group))
12332 			sgs->group_llc_balance = 1;
12333 	}
12334 
12335 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
12336 
12337 	record_sg_llc_stats(env, sgs, group);
12338 	/* Computing avg_load makes sense only when group is overloaded */
12339 	if (sgs->group_type == group_overloaded)
12340 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12341 				sgs->group_capacity;
12342 }
12343 
12344 /**
12345  * update_sd_pick_busiest - return 1 on busiest group
12346  * @env: The load balancing environment.
12347  * @sds: sched_domain statistics
12348  * @sg: sched_group candidate to be checked for being the busiest
12349  * @sgs: sched_group statistics
12350  *
12351  * Determine if @sg is a busier group than the previously selected
12352  * busiest group.
12353  *
12354  * Return: %true if @sg is a busier group than the previously selected
12355  * busiest group. %false otherwise.
12356  */
12357 static bool update_sd_pick_busiest(struct lb_env *env,
12358 				   struct sd_lb_stats *sds,
12359 				   struct sched_group *sg,
12360 				   struct sg_lb_stats *sgs)
12361 {
12362 	struct sg_lb_stats *busiest = &sds->busiest_stat;
12363 
12364 	/* Make sure that there is at least one task to pull */
12365 	if (!sgs->sum_h_nr_running)
12366 		return false;
12367 
12368 	/*
12369 	 * Don't try to pull misfit tasks we can't help.
12370 	 * We can use max_capacity here as reduction in capacity on some
12371 	 * CPUs in the group should either be possible to resolve
12372 	 * internally or be covered by avg_load imbalance (eventually).
12373 	 *
12374 	 * When SMT is active, only pull a misfit to dst_cpu if it is on a
12375 	 * fully idle core; otherwise the effective capacity of the core is
12376 	 * reduced and we may not actually provide more capacity than the
12377 	 * source.
12378 	 */
12379 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12380 	    (sgs->group_type == group_misfit_task) &&
12381 	    (!env->dst_core_idle ||
12382 	     !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
12383 	     sds->local_stat.group_type != group_has_spare))
12384 		return false;
12385 
12386 	/*
12387 	 * Candidate sg has no more than one task per CPU and has higher
12388 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
12389 	 * throughput. Maximize throughput, power/energy consequences are not
12390 	 * considered.
12391 	 */
12392 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12393 	    (sgs->group_type <= group_fully_busy) &&
12394 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
12395 		return false;
12396 
12397 	if (sgs->group_type > busiest->group_type)
12398 		return true;
12399 
12400 	if (sgs->group_type < busiest->group_type)
12401 		return false;
12402 
12403 	/*
12404 	 * The candidate and the current busiest group are the same type of
12405 	 * group. Let check which one is the busiest according to the type.
12406 	 */
12407 
12408 	switch (sgs->group_type) {
12409 	case group_overloaded:
12410 		/* Select the overloaded group with highest avg_load. */
12411 		return sgs->avg_load > busiest->avg_load;
12412 
12413 	case group_llc_balance:
12414 		/* Select the group with most tasks preferring dst LLC */
12415 		return update_llc_busiest(env, busiest, sgs);
12416 
12417 	case group_imbalanced:
12418 		/*
12419 		 * Select the 1st imbalanced group as we don't have any way to
12420 		 * choose one more than another.
12421 		 */
12422 		return false;
12423 
12424 	case group_asym_packing:
12425 		/* Prefer to move from lowest priority CPU's work */
12426 		return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
12427 					 READ_ONCE(sg->asym_prefer_cpu));
12428 
12429 	case group_misfit_task:
12430 		/*
12431 		 * If we have more than one misfit sg go with the biggest
12432 		 * misfit.
12433 		 */
12434 		return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
12435 
12436 	case group_smt_balance:
12437 		/*
12438 		 * Check if we have spare CPUs on either SMT group to
12439 		 * choose has spare or fully busy handling.
12440 		 */
12441 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
12442 			goto has_spare;
12443 
12444 		fallthrough;
12445 
12446 	case group_fully_busy:
12447 		/*
12448 		 * Select the fully busy group with highest avg_load. In
12449 		 * theory, there is no need to pull task from such kind of
12450 		 * group because tasks have all compute capacity that they need
12451 		 * but we can still improve the overall throughput by reducing
12452 		 * contention when accessing shared HW resources.
12453 		 *
12454 		 * XXX for now avg_load is not computed and always 0 so we
12455 		 * select the 1st one, except if @sg is composed of SMT
12456 		 * siblings.
12457 		 */
12458 
12459 		if (sgs->avg_load < busiest->avg_load)
12460 			return false;
12461 
12462 		if (sgs->avg_load == busiest->avg_load) {
12463 			/*
12464 			 * SMT sched groups need more help than non-SMT groups.
12465 			 * If @sg happens to also be SMT, either choice is good.
12466 			 */
12467 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
12468 				return false;
12469 		}
12470 
12471 		break;
12472 
12473 	case group_has_spare:
12474 		/*
12475 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
12476 		 * as we do not want to pull task off SMT core with one task
12477 		 * and make the core idle.
12478 		 */
12479 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
12480 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
12481 				return false;
12482 			else
12483 				return true;
12484 		}
12485 has_spare:
12486 
12487 		/*
12488 		 * Select not overloaded group with lowest number of idle CPUs
12489 		 * and highest number of running tasks. We could also compare
12490 		 * the spare capacity which is more stable but it can end up
12491 		 * that the group has less spare capacity but finally more idle
12492 		 * CPUs which means less opportunity to pull tasks.
12493 		 */
12494 		if (sgs->idle_cpus > busiest->idle_cpus)
12495 			return false;
12496 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
12497 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
12498 			return false;
12499 
12500 		break;
12501 	}
12502 
12503 	return true;
12504 }
12505 
12506 #ifdef CONFIG_NUMA_BALANCING
12507 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12508 {
12509 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
12510 		return regular;
12511 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
12512 		return remote;
12513 	return all;
12514 }
12515 
12516 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12517 {
12518 	if (rq->nr_running > rq->nr_numa_running)
12519 		return regular;
12520 	if (rq->nr_running > rq->nr_preferred_running)
12521 		return remote;
12522 	return all;
12523 }
12524 #else /* !CONFIG_NUMA_BALANCING: */
12525 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12526 {
12527 	return all;
12528 }
12529 
12530 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12531 {
12532 	return regular;
12533 }
12534 #endif /* !CONFIG_NUMA_BALANCING */
12535 
12536 
12537 struct sg_lb_stats;
12538 
12539 /*
12540  * task_running_on_cpu - return 1 if @p is running on @cpu.
12541  */
12542 
12543 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
12544 {
12545 	/* Task has no contribution or is new */
12546 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
12547 		return 0;
12548 
12549 	if (task_on_rq_queued(p))
12550 		return 1;
12551 
12552 	return 0;
12553 }
12554 
12555 /**
12556  * idle_cpu_without - would a given CPU be idle without p ?
12557  * @cpu: the processor on which idleness is tested.
12558  * @p: task which should be ignored.
12559  *
12560  * Return: 1 if the CPU would be idle. 0 otherwise.
12561  */
12562 static int idle_cpu_without(int cpu, struct task_struct *p)
12563 {
12564 	struct rq *rq = cpu_rq(cpu);
12565 
12566 	if (rq->curr != rq->idle && rq->curr != p)
12567 		return 0;
12568 
12569 	/*
12570 	 * rq->nr_running can't be used but an updated version without the
12571 	 * impact of p on cpu must be used instead. The updated nr_running
12572 	 * be computed and tested before calling idle_cpu_without().
12573 	 */
12574 
12575 	if (rq->ttwu_pending)
12576 		return 0;
12577 
12578 	return 1;
12579 }
12580 
12581 /*
12582  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
12583  * @sd: The sched_domain level to look for idlest group.
12584  * @group: sched_group whose statistics are to be updated.
12585  * @sgs: variable to hold the statistics for this group.
12586  * @p: The task for which we look for the idlest group/CPU.
12587  */
12588 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
12589 					  struct sched_group *group,
12590 					  struct sg_lb_stats *sgs,
12591 					  struct task_struct *p)
12592 {
12593 	int i, nr_running;
12594 
12595 	memset(sgs, 0, sizeof(*sgs));
12596 
12597 	/* Assume that task can't fit any CPU of the group */
12598 	if (sd->flags & SD_ASYM_CPUCAPACITY)
12599 		sgs->group_misfit_task_load = 1;
12600 
12601 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
12602 		struct rq *rq = cpu_rq(i);
12603 		unsigned int local;
12604 
12605 		sgs->group_load += cpu_load_without(rq, p);
12606 		sgs->group_util += cpu_util_without(i, p);
12607 		sgs->group_runnable += cpu_runnable_without(rq, p);
12608 		local = task_running_on_cpu(i, p);
12609 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
12610 
12611 		nr_running = rq->nr_running - local;
12612 		sgs->sum_nr_running += nr_running;
12613 
12614 		/*
12615 		 * No need to call idle_cpu_without() if nr_running is not 0
12616 		 */
12617 		if (!nr_running && idle_cpu_without(i, p))
12618 			sgs->idle_cpus++;
12619 
12620 		/* Check if task fits in the CPU */
12621 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
12622 		    sgs->group_misfit_task_load &&
12623 		    task_fits_cpu(p, i))
12624 			sgs->group_misfit_task_load = 0;
12625 
12626 	}
12627 
12628 	sgs->group_capacity = group->sgc->capacity;
12629 
12630 	sgs->group_weight = group->group_weight;
12631 
12632 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
12633 
12634 	/*
12635 	 * Computing avg_load makes sense only when group is fully busy or
12636 	 * overloaded
12637 	 */
12638 	if (sgs->group_type == group_fully_busy ||
12639 		sgs->group_type == group_overloaded)
12640 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12641 				sgs->group_capacity;
12642 }
12643 
12644 static bool update_pick_idlest(struct sched_group *idlest,
12645 			       struct sg_lb_stats *idlest_sgs,
12646 			       struct sched_group *group,
12647 			       struct sg_lb_stats *sgs)
12648 {
12649 	if (sgs->group_type < idlest_sgs->group_type)
12650 		return true;
12651 
12652 	if (sgs->group_type > idlest_sgs->group_type)
12653 		return false;
12654 
12655 	/*
12656 	 * The candidate and the current idlest group are the same type of
12657 	 * group. Let check which one is the idlest according to the type.
12658 	 */
12659 
12660 	switch (sgs->group_type) {
12661 	case group_overloaded:
12662 	case group_fully_busy:
12663 		/* Select the group with lowest avg_load. */
12664 		if (idlest_sgs->avg_load <= sgs->avg_load)
12665 			return false;
12666 		break;
12667 
12668 	case group_llc_balance:
12669 	case group_imbalanced:
12670 	case group_asym_packing:
12671 	case group_smt_balance:
12672 		/* Those types are not used in the slow wakeup path */
12673 		return false;
12674 
12675 	case group_misfit_task:
12676 		/* Select group with the highest max capacity */
12677 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
12678 			return false;
12679 		break;
12680 
12681 	case group_has_spare:
12682 		/* Select group with most idle CPUs */
12683 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
12684 			return false;
12685 
12686 		/* Select group with lowest group_util */
12687 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
12688 			idlest_sgs->group_util <= sgs->group_util)
12689 			return false;
12690 
12691 		break;
12692 	}
12693 
12694 	return true;
12695 }
12696 
12697 /*
12698  * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
12699  * domain.
12700  *
12701  * Assumes p is allowed on at least one CPU in sd.
12702  */
12703 static struct sched_group *
12704 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
12705 {
12706 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
12707 	struct sg_lb_stats local_sgs, tmp_sgs;
12708 	struct sg_lb_stats *sgs;
12709 	unsigned long imbalance;
12710 	struct sg_lb_stats idlest_sgs = {
12711 			.avg_load = UINT_MAX,
12712 			.group_type = group_overloaded,
12713 	};
12714 
12715 	do {
12716 		int local_group;
12717 
12718 		/* Skip over this group if it has no CPUs allowed */
12719 		if (!cpumask_intersects(sched_group_span(group),
12720 					p->cpus_ptr))
12721 			continue;
12722 
12723 		/* Skip over this group if no cookie matched */
12724 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
12725 			continue;
12726 
12727 		local_group = cpumask_test_cpu(this_cpu,
12728 					       sched_group_span(group));
12729 
12730 		if (local_group) {
12731 			sgs = &local_sgs;
12732 			local = group;
12733 		} else {
12734 			sgs = &tmp_sgs;
12735 		}
12736 
12737 		update_sg_wakeup_stats(sd, group, sgs, p);
12738 
12739 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
12740 			idlest = group;
12741 			idlest_sgs = *sgs;
12742 		}
12743 
12744 	} while (group = group->next, group != sd->groups);
12745 
12746 
12747 	/* There is no idlest group to push tasks to */
12748 	if (!idlest)
12749 		return NULL;
12750 
12751 	/* The local group has been skipped because of CPU affinity */
12752 	if (!local)
12753 		return idlest;
12754 
12755 	/*
12756 	 * If the local group is idler than the selected idlest group
12757 	 * don't try and push the task.
12758 	 */
12759 	if (local_sgs.group_type < idlest_sgs.group_type)
12760 		return NULL;
12761 
12762 	/*
12763 	 * If the local group is busier than the selected idlest group
12764 	 * try and push the task.
12765 	 */
12766 	if (local_sgs.group_type > idlest_sgs.group_type)
12767 		return idlest;
12768 
12769 	switch (local_sgs.group_type) {
12770 	case group_overloaded:
12771 	case group_fully_busy:
12772 
12773 		/* Calculate allowed imbalance based on load */
12774 		imbalance = scale_load_down(NICE_0_LOAD) *
12775 				(sd->imbalance_pct-100) / 100;
12776 
12777 		/*
12778 		 * When comparing groups across NUMA domains, it's possible for
12779 		 * the local domain to be very lightly loaded relative to the
12780 		 * remote domains but "imbalance" skews the comparison making
12781 		 * remote CPUs look much more favourable. When considering
12782 		 * cross-domain, add imbalance to the load on the remote node
12783 		 * and consider staying local.
12784 		 */
12785 
12786 		if ((sd->flags & SD_NUMA) &&
12787 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
12788 			return NULL;
12789 
12790 		/*
12791 		 * If the local group is less loaded than the selected
12792 		 * idlest group don't try and push any tasks.
12793 		 */
12794 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
12795 			return NULL;
12796 
12797 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
12798 			return NULL;
12799 		break;
12800 
12801 	case group_llc_balance:
12802 	case group_imbalanced:
12803 	case group_asym_packing:
12804 	case group_smt_balance:
12805 		/* Those type are not used in the slow wakeup path */
12806 		return NULL;
12807 
12808 	case group_misfit_task:
12809 		/* Select group with the highest max capacity */
12810 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
12811 			return NULL;
12812 		break;
12813 
12814 	case group_has_spare:
12815 #ifdef CONFIG_NUMA
12816 		if (sd->flags & SD_NUMA) {
12817 			int imb_numa_nr = sd->imb_numa_nr;
12818 #ifdef CONFIG_NUMA_BALANCING
12819 			int idlest_cpu;
12820 			/*
12821 			 * If there is spare capacity at NUMA, try to select
12822 			 * the preferred node
12823 			 */
12824 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
12825 				return NULL;
12826 
12827 			idlest_cpu = cpumask_first(sched_group_span(idlest));
12828 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
12829 				return idlest;
12830 #endif /* CONFIG_NUMA_BALANCING */
12831 			/*
12832 			 * Otherwise, keep the task close to the wakeup source
12833 			 * and improve locality if the number of running tasks
12834 			 * would remain below threshold where an imbalance is
12835 			 * allowed while accounting for the possibility the
12836 			 * task is pinned to a subset of CPUs. If there is a
12837 			 * real need of migration, periodic load balance will
12838 			 * take care of it.
12839 			 */
12840 			if (p->nr_cpus_allowed != NR_CPUS) {
12841 				unsigned int w = cpumask_weight_and(p->cpus_ptr,
12842 								sched_group_span(local));
12843 				imb_numa_nr = min(w, sd->imb_numa_nr);
12844 			}
12845 
12846 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
12847 			if (!adjust_numa_imbalance(imbalance,
12848 						   local_sgs.sum_nr_running + 1,
12849 						   imb_numa_nr)) {
12850 				return NULL;
12851 			}
12852 		}
12853 #endif /* CONFIG_NUMA */
12854 
12855 		/*
12856 		 * Select group with highest number of idle CPUs. We could also
12857 		 * compare the utilization which is more stable but it can end
12858 		 * up that the group has less spare capacity but finally more
12859 		 * idle CPUs which means more opportunity to run task.
12860 		 */
12861 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
12862 			return NULL;
12863 		break;
12864 	}
12865 
12866 	return idlest;
12867 }
12868 
12869 static void update_idle_cpu_scan(struct lb_env *env,
12870 				 unsigned long sum_util)
12871 {
12872 	struct sched_domain_shared *sd_share;
12873 	struct sched_domain *sd = env->sd;
12874 	int llc_weight, pct;
12875 	u64 x, y, tmp;
12876 	/*
12877 	 * Update the number of CPUs to scan in LLC domain, which could
12878 	 * be used as a hint in select_idle_cpu(). The update of sd_share
12879 	 * could be expensive because it is within a shared cache line.
12880 	 * So the write of this hint only occurs during periodic load
12881 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
12882 	 * can fire way more frequently than the former.
12883 	 */
12884 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
12885 		return;
12886 
12887 	sd_share = sd->shared;
12888 	if (!sd_share)
12889 		return;
12890 
12891 	/*
12892 	 * The number of CPUs to search drops as sum_util increases, when
12893 	 * sum_util hits 85% or above, the scan stops.
12894 	 * The reason to choose 85% as the threshold is because this is the
12895 	 * imbalance_pct(117) when a LLC sched group is overloaded.
12896 	 *
12897 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
12898 	 * and y'= y / SCHED_CAPACITY_SCALE
12899 	 *
12900 	 * x is the ratio of sum_util compared to the CPU capacity:
12901 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
12902 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
12903 	 * and the number of CPUs to scan is calculated by:
12904 	 *
12905 	 * nr_scan = llc_weight * y'                                    [2]
12906 	 *
12907 	 * When x hits the threshold of overloaded, AKA, when
12908 	 * x = 100 / pct, y drops to 0. According to [1],
12909 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
12910 	 *
12911 	 * Scale x by SCHED_CAPACITY_SCALE:
12912 	 * x' = sum_util / llc_weight;                                  [3]
12913 	 *
12914 	 * and finally [1] becomes:
12915 	 * y = SCHED_CAPACITY_SCALE -
12916 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
12917 	 *
12918 	 */
12919 	/* equation [3] */
12920 	x = sum_util;
12921 	llc_weight = sd->span_weight;
12922 	do_div(x, llc_weight);
12923 
12924 	/* equation [4] */
12925 	pct = sd->imbalance_pct;
12926 	tmp = x * x * pct * pct;
12927 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
12928 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
12929 	y = SCHED_CAPACITY_SCALE - tmp;
12930 
12931 	/* equation [2] */
12932 	y *= llc_weight;
12933 	do_div(y, SCHED_CAPACITY_SCALE);
12934 	if ((int)y != sd_share->nr_idle_scan)
12935 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
12936 }
12937 
12938 /**
12939  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
12940  * @env: The load balancing environment.
12941  * @sds: variable to hold the statistics for this sched_domain.
12942  */
12943 
12944 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
12945 {
12946 	struct sched_group *sg = env->sd->groups;
12947 	struct sg_lb_stats *local = &sds->local_stat;
12948 	struct sg_lb_stats tmp_sgs;
12949 	unsigned long sum_util = 0;
12950 	bool sg_overloaded = 0, sg_overutilized = 0;
12951 
12952 	env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu);
12953 
12954 	do {
12955 		struct sg_lb_stats *sgs = &tmp_sgs;
12956 		int local_group;
12957 
12958 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
12959 		if (local_group) {
12960 			sds->local = sg;
12961 			sgs = local;
12962 
12963 			if (env->idle != CPU_NEWLY_IDLE ||
12964 			    time_after_eq(jiffies, sg->sgc->next_update))
12965 				update_group_capacity(env->sd, env->dst_cpu);
12966 		}
12967 
12968 		update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded);
12969 
12970 		if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
12971 			sds->busiest = sg;
12972 			sds->busiest_stat = *sgs;
12973 		}
12974 
12975 		sg_overutilized |= sgs->group_overutilized;
12976 
12977 		/* Now, start updating sd_lb_stats */
12978 		sds->total_load += sgs->group_load;
12979 		sds->total_capacity += sgs->group_capacity;
12980 
12981 		sum_util += sgs->group_util;
12982 		sg = sg->next;
12983 	} while (sg != env->sd->groups);
12984 
12985 	/*
12986 	 * Indicate that the child domain of the busiest group prefers tasks
12987 	 * go to a child's sibling domains first. NB the flags of a sched group
12988 	 * are those of the child domain.
12989 	 */
12990 	if (sds->busiest)
12991 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
12992 
12993 
12994 	if (env->sd->flags & SD_NUMA)
12995 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
12996 
12997 	if (!env->sd->parent) {
12998 		/* update overload indicator if we are at root domain */
12999 		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
13000 
13001 		/* Update over-utilization (tipping point, U >= 0) indicator */
13002 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
13003 	} else if (sg_overutilized) {
13004 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
13005 	}
13006 
13007 	update_idle_cpu_scan(env, sum_util);
13008 }
13009 
13010 /**
13011  * calculate_imbalance - Calculate the amount of imbalance present within the
13012  *			 groups of a given sched_domain during load balance.
13013  * @env: load balance environment
13014  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
13015  */
13016 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
13017 {
13018 	struct sg_lb_stats *local, *busiest;
13019 
13020 	local = &sds->local_stat;
13021 	busiest = &sds->busiest_stat;
13022 
13023 	if (busiest->group_type == group_misfit_task) {
13024 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
13025 			/* Set imbalance to allow misfit tasks to be balanced. */
13026 			env->migration_type = migrate_misfit;
13027 			env->imbalance = 1;
13028 		} else {
13029 			/*
13030 			 * Set load imbalance to allow moving task from cpu
13031 			 * with reduced capacity.
13032 			 */
13033 			env->migration_type = migrate_load;
13034 			env->imbalance = busiest->group_misfit_task_load;
13035 		}
13036 		return;
13037 	}
13038 
13039 	if (busiest->group_type == group_asym_packing) {
13040 		/*
13041 		 * In case of asym capacity, we will try to migrate all load to
13042 		 * the preferred CPU.
13043 		 */
13044 		env->migration_type = migrate_task;
13045 		env->imbalance = busiest->sum_h_nr_running;
13046 		return;
13047 	}
13048 
13049 	if (busiest->group_type == group_smt_balance) {
13050 		/* Reduce number of tasks sharing CPU capacity */
13051 		env->migration_type = migrate_task;
13052 		env->imbalance = 1;
13053 		return;
13054 	}
13055 
13056 #ifdef CONFIG_SCHED_CACHE
13057 	if (busiest->group_type == group_llc_balance) {
13058 		/* Move a task that prefer local LLC */
13059 		env->migration_type = migrate_llc_task;
13060 		env->imbalance = 1;
13061 		return;
13062 	}
13063 #endif
13064 
13065 	if (busiest->group_type == group_imbalanced) {
13066 		/*
13067 		 * In the group_imb case we cannot rely on group-wide averages
13068 		 * to ensure CPU-load equilibrium, try to move any task to fix
13069 		 * the imbalance. The next load balance will take care of
13070 		 * balancing back the system.
13071 		 */
13072 		env->migration_type = migrate_task;
13073 		env->imbalance = 1;
13074 		return;
13075 	}
13076 
13077 	/*
13078 	 * Try to use spare capacity of local group without overloading it or
13079 	 * emptying busiest.
13080 	 */
13081 	if (local->group_type == group_has_spare) {
13082 		if ((busiest->group_type > group_fully_busy) &&
13083 		    !(env->sd->flags & SD_SHARE_LLC)) {
13084 			/*
13085 			 * If busiest is overloaded, try to fill spare
13086 			 * capacity. This might end up creating spare capacity
13087 			 * in busiest or busiest still being overloaded but
13088 			 * there is no simple way to directly compute the
13089 			 * amount of load to migrate in order to balance the
13090 			 * system.
13091 			 */
13092 			env->migration_type = migrate_util;
13093 			env->imbalance = max(local->group_capacity, local->group_util) -
13094 					 local->group_util;
13095 
13096 			/*
13097 			 * In some cases, the group's utilization is max or even
13098 			 * higher than capacity because of migrations but the
13099 			 * local CPU is (newly) idle. There is at least one
13100 			 * waiting task in this overloaded busiest group. Let's
13101 			 * try to pull it.
13102 			 */
13103 			if (env->idle && env->imbalance == 0) {
13104 				env->migration_type = migrate_task;
13105 				env->imbalance = 1;
13106 			}
13107 
13108 			return;
13109 		}
13110 
13111 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
13112 			/*
13113 			 * When prefer sibling, evenly spread running tasks on
13114 			 * groups.
13115 			 */
13116 			env->migration_type = migrate_task;
13117 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
13118 		} else {
13119 
13120 			/*
13121 			 * If there is no overload, we just want to even the number of
13122 			 * idle CPUs.
13123 			 */
13124 			env->migration_type = migrate_task;
13125 			env->imbalance = max_t(long, 0,
13126 					       (local->idle_cpus - busiest->idle_cpus));
13127 		}
13128 
13129 #ifdef CONFIG_NUMA
13130 		/* Consider allowing a small imbalance between NUMA groups */
13131 		if (env->sd->flags & SD_NUMA) {
13132 			env->imbalance = adjust_numa_imbalance(env->imbalance,
13133 							       local->sum_nr_running + 1,
13134 							       env->sd->imb_numa_nr);
13135 		}
13136 #endif
13137 
13138 		/* Number of tasks to move to restore balance */
13139 		env->imbalance >>= 1;
13140 
13141 		return;
13142 	}
13143 
13144 	/*
13145 	 * Local is fully busy but has to take more load to relieve the
13146 	 * busiest group
13147 	 */
13148 	if (local->group_type < group_overloaded) {
13149 		/*
13150 		 * Local will become overloaded so the avg_load metrics are
13151 		 * finally needed.
13152 		 */
13153 
13154 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
13155 				  local->group_capacity;
13156 
13157 		/*
13158 		 * If the local group is more loaded than the selected
13159 		 * busiest group don't try to pull any tasks.
13160 		 */
13161 		if (local->avg_load >= busiest->avg_load) {
13162 			env->imbalance = 0;
13163 			return;
13164 		}
13165 
13166 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
13167 				sds->total_capacity;
13168 
13169 		/*
13170 		 * If the local group is more loaded than the average system
13171 		 * load, don't try to pull any tasks.
13172 		 */
13173 		if (local->avg_load >= sds->avg_load) {
13174 			env->imbalance = 0;
13175 			return;
13176 		}
13177 
13178 	}
13179 
13180 	/*
13181 	 * Both group are or will become overloaded and we're trying to get all
13182 	 * the CPUs to the average_load, so we don't want to push ourselves
13183 	 * above the average load, nor do we wish to reduce the max loaded CPU
13184 	 * below the average load. At the same time, we also don't want to
13185 	 * reduce the group load below the group capacity. Thus we look for
13186 	 * the minimum possible imbalance.
13187 	 */
13188 	env->migration_type = migrate_load;
13189 	env->imbalance = min(
13190 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
13191 		(sds->avg_load - local->avg_load) * local->group_capacity
13192 	) / SCHED_CAPACITY_SCALE;
13193 }
13194 
13195 /******* sched_balance_find_src_group() helpers end here *********************/
13196 
13197 /*
13198  * Decision matrix according to the local and busiest group type:
13199  *
13200  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
13201  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
13202  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
13203  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
13204  * asym_packing     force     force      N/A    N/A  force      force
13205  * imbalanced       force     force      N/A    N/A  force      force
13206  * overloaded       force     force      N/A    N/A  force      avg_load
13207  *
13208  * N/A :      Not Applicable because already filtered while updating
13209  *            statistics.
13210  * balanced : The system is balanced for these 2 groups.
13211  * force :    Calculate the imbalance as load migration is probably needed.
13212  * avg_load : Only if imbalance is significant enough.
13213  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
13214  *            different in groups.
13215  */
13216 
13217 /**
13218  * sched_balance_find_src_group - Returns the busiest group within the sched_domain
13219  * if there is an imbalance.
13220  * @env: The load balancing environment.
13221  *
13222  * Also calculates the amount of runnable load which should be moved
13223  * to restore balance.
13224  *
13225  * Return:	- The busiest group if imbalance exists.
13226  */
13227 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
13228 {
13229 	struct sg_lb_stats *local, *busiest;
13230 	struct sd_lb_stats sds;
13231 
13232 	init_sd_lb_stats(&sds);
13233 
13234 	/*
13235 	 * Compute the various statistics relevant for load balancing at
13236 	 * this level.
13237 	 */
13238 	update_sd_lb_stats(env, &sds);
13239 
13240 	/* There is no busy sibling group to pull tasks from */
13241 	if (!sds.busiest)
13242 		goto out_balanced;
13243 
13244 	busiest = &sds.busiest_stat;
13245 
13246 	/* Misfit tasks should be dealt with regardless of the avg load */
13247 	if (busiest->group_type == group_misfit_task)
13248 		goto force_balance;
13249 
13250 	if (!is_rd_overutilized(env->dst_rq->rd) &&
13251 	    rcu_dereference_all(env->dst_rq->rd->pd))
13252 		goto out_balanced;
13253 
13254 	/* ASYM feature bypasses nice load balance check */
13255 	if (busiest->group_type == group_asym_packing)
13256 		goto force_balance;
13257 
13258 	/*
13259 	 * If the busiest group is imbalanced the below checks don't
13260 	 * work because they assume all things are equal, which typically
13261 	 * isn't true due to cpus_ptr constraints and the like.
13262 	 */
13263 	if (busiest->group_type == group_imbalanced)
13264 		goto force_balance;
13265 
13266 	local = &sds.local_stat;
13267 	/*
13268 	 * If the local group is busier than the selected busiest group
13269 	 * don't try and pull any tasks.
13270 	 */
13271 	if (local->group_type > busiest->group_type)
13272 		goto out_balanced;
13273 
13274 	/*
13275 	 * When groups are overloaded, use the avg_load to ensure fairness
13276 	 * between tasks.
13277 	 */
13278 	if (local->group_type == group_overloaded) {
13279 		/*
13280 		 * If the local group is more loaded than the selected
13281 		 * busiest group don't try to pull any tasks.
13282 		 */
13283 		if (local->avg_load >= busiest->avg_load)
13284 			goto out_balanced;
13285 
13286 		/* XXX broken for overlapping NUMA groups */
13287 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
13288 				sds.total_capacity;
13289 
13290 		/*
13291 		 * Don't pull any tasks if this group is already above the
13292 		 * domain average load.
13293 		 */
13294 		if (local->avg_load >= sds.avg_load)
13295 			goto out_balanced;
13296 
13297 		/*
13298 		 * If the busiest group is more loaded, use imbalance_pct to be
13299 		 * conservative.
13300 		 */
13301 		if (100 * busiest->avg_load <=
13302 				env->sd->imbalance_pct * local->avg_load)
13303 			goto out_balanced;
13304 	}
13305 
13306 	/*
13307 	 * Try to move all excess tasks to a sibling domain of the busiest
13308 	 * group's child domain.
13309 	 */
13310 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
13311 	    (busiest->group_type == group_llc_balance ||
13312 	    sibling_imbalance(env, &sds, busiest, local) > 1))
13313 		goto force_balance;
13314 
13315 	if (busiest->group_type != group_overloaded) {
13316 		if (!env->idle) {
13317 			/*
13318 			 * If the busiest group is not overloaded (and as a
13319 			 * result the local one too) but this CPU is already
13320 			 * busy, let another idle CPU try to pull task.
13321 			 */
13322 			goto out_balanced;
13323 		}
13324 
13325 		if (busiest->group_type == group_smt_balance &&
13326 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
13327 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
13328 			goto force_balance;
13329 		}
13330 
13331 		if (busiest->group_weight > 1 &&
13332 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
13333 			/*
13334 			 * If the busiest group is not overloaded
13335 			 * and there is no imbalance between this and busiest
13336 			 * group wrt idle CPUs, it is balanced. The imbalance
13337 			 * becomes significant if the diff is greater than 1
13338 			 * otherwise we might end up to just move the imbalance
13339 			 * on another group. Of course this applies only if
13340 			 * there is more than 1 CPU per group.
13341 			 */
13342 			goto out_balanced;
13343 		}
13344 
13345 		if (busiest->sum_h_nr_running == 1) {
13346 			/*
13347 			 * busiest doesn't have any tasks waiting to run
13348 			 */
13349 			goto out_balanced;
13350 		}
13351 	}
13352 
13353 force_balance:
13354 	/* Looks like there is an imbalance. Compute it */
13355 	calculate_imbalance(env, &sds);
13356 	return env->imbalance ? sds.busiest : NULL;
13357 
13358 out_balanced:
13359 	env->imbalance = 0;
13360 	return NULL;
13361 }
13362 
13363 /*
13364  * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
13365  */
13366 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
13367 				     struct sched_group *group)
13368 {
13369 	struct rq *busiest = NULL, *rq;
13370 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
13371 	unsigned int __maybe_unused busiest_pref_llc = 0;
13372 	struct sched_domain __maybe_unused *sd_tmp;
13373 	unsigned int busiest_nr = 0;
13374 	int __maybe_unused dst_llc;
13375 	int i;
13376 
13377 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
13378 		unsigned long capacity, load, util;
13379 		unsigned int nr_running;
13380 		enum fbq_type rt;
13381 
13382 		rq = cpu_rq(i);
13383 		rt = fbq_classify_rq(rq);
13384 
13385 		/*
13386 		 * We classify groups/runqueues into three groups:
13387 		 *  - regular: there are !numa tasks
13388 		 *  - remote:  there are numa tasks that run on the 'wrong' node
13389 		 *  - all:     there is no distinction
13390 		 *
13391 		 * In order to avoid migrating ideally placed numa tasks,
13392 		 * ignore those when there's better options.
13393 		 *
13394 		 * If we ignore the actual busiest queue to migrate another
13395 		 * task, the next balance pass can still reduce the busiest
13396 		 * queue by moving tasks around inside the node.
13397 		 *
13398 		 * If we cannot move enough load due to this classification
13399 		 * the next pass will adjust the group classification and
13400 		 * allow migration of more tasks.
13401 		 *
13402 		 * Both cases only affect the total convergence complexity.
13403 		 */
13404 		if (rt > env->fbq_type)
13405 			continue;
13406 
13407 		nr_running = rq->cfs.h_nr_runnable;
13408 		if (!nr_running)
13409 			continue;
13410 
13411 		capacity = capacity_of(i);
13412 
13413 		/*
13414 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
13415 		 * eventually lead to active_balancing high->low capacity.
13416 		 * Higher per-CPU capacity is considered better than balancing
13417 		 * average load.
13418 		 */
13419 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
13420 		    nr_running == 1) {
13421 			bool cluster_equal_cap = static_branch_unlikely(&sched_cluster_active) &&
13422 						 (get_actual_cpu_capacity(env->dst_cpu) ==
13423 						  get_actual_cpu_capacity(i));
13424 			bool smt_degraded_cap = sched_smt_active() && !is_core_idle(i);
13425 
13426 			/*
13427 			 * Busy SMT siblings reduce the capacity of CPU @i. Do
13428 			 * not skip it in this case.
13429 			 *
13430 			 * CONFIG_SCHED_CLUSTER requires balancing load across
13431 			 * clusters of identical capacity, accounting for
13432 			 * hardware and cpufreq pressure.
13433 			 */
13434 			if (!smt_degraded_cap && !cluster_equal_cap &&
13435 			    !capacity_greater(capacity_of(env->dst_cpu), capacity))
13436 				continue;
13437 		}
13438 
13439 		/*
13440 		 * Make sure we only pull tasks from a CPU of lower priority
13441 		 * when balancing between SMT siblings.
13442 		 *
13443 		 * If balancing between cores, let lower priority CPUs help
13444 		 * SMT cores with more than one busy sibling.
13445 		 */
13446 		if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
13447 			continue;
13448 
13449 		switch (env->migration_type) {
13450 		case migrate_load:
13451 			/*
13452 			 * When comparing with load imbalance, use cpu_load()
13453 			 * which is not scaled with the CPU capacity.
13454 			 */
13455 			load = cpu_load(rq);
13456 
13457 			if (nr_running == 1 && load > env->imbalance &&
13458 			    !check_cpu_capacity(rq, env->sd))
13459 				break;
13460 
13461 			/*
13462 			 * For the load comparisons with the other CPUs,
13463 			 * consider the cpu_load() scaled with the CPU
13464 			 * capacity, so that the load can be moved away
13465 			 * from the CPU that is potentially running at a
13466 			 * lower capacity.
13467 			 *
13468 			 * Thus we're looking for max(load_i / capacity_i),
13469 			 * crosswise multiplication to rid ourselves of the
13470 			 * division works out to:
13471 			 * load_i * capacity_j > load_j * capacity_i;
13472 			 * where j is our previous maximum.
13473 			 */
13474 			if (load * busiest_capacity > busiest_load * capacity) {
13475 				busiest_load = load;
13476 				busiest_capacity = capacity;
13477 				busiest = rq;
13478 			}
13479 			break;
13480 
13481 		case migrate_util:
13482 			util = cpu_util_cfs_boost(i);
13483 
13484 			/*
13485 			 * Don't try to pull utilization from a CPU with one
13486 			 * running task. Whatever its utilization, we will fail
13487 			 * detach the task.
13488 			 */
13489 			if (nr_running <= 1)
13490 				continue;
13491 
13492 			if (busiest_util < util) {
13493 				busiest_util = util;
13494 				busiest = rq;
13495 			}
13496 			break;
13497 
13498 		case migrate_task:
13499 			if (busiest_nr < nr_running) {
13500 				busiest_nr = nr_running;
13501 				busiest = rq;
13502 			}
13503 			break;
13504 
13505 		case migrate_misfit:
13506 			/*
13507 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
13508 			 * simply seek the "biggest" misfit task.
13509 			 */
13510 			if (rq->misfit_task_load > busiest_load) {
13511 				busiest_load = rq->misfit_task_load;
13512 				busiest = rq;
13513 			}
13514 
13515 			break;
13516 
13517 		case migrate_llc_task:
13518 #ifdef CONFIG_SCHED_CACHE
13519 			sd_tmp = rcu_dereference_all(rq->sd);
13520 			dst_llc = llc_id(env->dst_cpu);
13521 
13522 			if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) {
13523 				unsigned int this_pref_llc =
13524 					sd_tmp->llc_counts[dst_llc];
13525 
13526 				if (busiest_pref_llc < this_pref_llc) {
13527 					busiest_pref_llc = this_pref_llc;
13528 					busiest = rq;
13529 				}
13530 			}
13531 #endif
13532 			break;
13533 
13534 		}
13535 	}
13536 
13537 	return busiest;
13538 }
13539 
13540 /*
13541  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
13542  * so long as it is large enough.
13543  */
13544 #define MAX_PINNED_INTERVAL	512
13545 
13546 static inline bool
13547 asym_active_balance(struct lb_env *env)
13548 {
13549 	/*
13550 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
13551 	 * priority CPUs in order to pack all tasks in the highest priority
13552 	 * CPUs. When done between cores, do it only if the whole core if the
13553 	 * whole core is idle.
13554 	 *
13555 	 * If @env::src_cpu is an SMT core with busy siblings, let
13556 	 * the lower priority @env::dst_cpu help it. Do not follow
13557 	 * CPU priority.
13558 	 */
13559 	return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
13560 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
13561 		!sched_use_asym_prio(env->sd, env->src_cpu));
13562 }
13563 
13564 static inline bool
13565 imbalanced_active_balance(struct lb_env *env)
13566 {
13567 	struct sched_domain *sd = env->sd;
13568 
13569 	/*
13570 	 * The imbalanced case includes the case of pinned tasks preventing a fair
13571 	 * distribution of the load on the system but also the even distribution of the
13572 	 * threads on a system with spare capacity
13573 	 */
13574 	if ((env->migration_type == migrate_task) &&
13575 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
13576 		return 1;
13577 
13578 	return 0;
13579 }
13580 
13581 static int need_active_balance(struct lb_env *env)
13582 {
13583 	struct sched_domain *sd = env->sd;
13584 
13585 	if (asym_active_balance(env))
13586 		return 1;
13587 
13588 	if (alb_break_llc(env))
13589 		return 0;
13590 
13591 	if (imbalanced_active_balance(env))
13592 		return 1;
13593 
13594 	/*
13595 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
13596 	 * It's worth migrating the task if the src_cpu's capacity is reduced
13597 	 * because of other sched_class or IRQs if more capacity stays
13598 	 * available on dst_cpu.
13599 	 */
13600 	if (env->idle &&
13601 	    (env->src_rq->cfs.h_nr_runnable == 1)) {
13602 		if ((check_cpu_capacity(env->src_rq, sd)) &&
13603 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
13604 			return 1;
13605 	}
13606 
13607 	if (env->migration_type == migrate_misfit ||
13608 	    env->migration_type == migrate_llc_task)
13609 		return 1;
13610 
13611 	return 0;
13612 }
13613 
13614 static int active_load_balance_cpu_stop(void *data);
13615 static int active_load_balance_llc_cpu_stop(void *data);
13616 
13617 /*
13618  * migration_type is checked elsewhere to decide migration policy, so
13619  * it shouldn't be repurposed just to flag an LLC-directed active
13620  * balance across the stopper. Pick the callback here instead.
13621  */
13622 static inline cpu_stop_fn_t alb_stop_fn(struct lb_env *env)
13623 {
13624 	if (env->migration_type == migrate_llc_task)
13625 		return active_load_balance_llc_cpu_stop;
13626 
13627 	return active_load_balance_cpu_stop;
13628 }
13629 
13630 static int should_we_balance(struct lb_env *env)
13631 {
13632 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
13633 	struct sched_group *sg = env->sd->groups;
13634 	int cpu, idle_smt = -1;
13635 
13636 	/*
13637 	 * Ensure the balancing environment is consistent; can happen
13638 	 * when the softirq triggers 'during' hotplug.
13639 	 */
13640 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
13641 		return 0;
13642 
13643 	/*
13644 	 * In the newly idle case, we will allow all the CPUs
13645 	 * to do the newly idle load balance.
13646 	 *
13647 	 * However, we bail out if we already have tasks or a wakeup pending,
13648 	 * to optimize wakeup latency.
13649 	 */
13650 	if (env->idle == CPU_NEWLY_IDLE) {
13651 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
13652 			return 0;
13653 		return 1;
13654 	}
13655 
13656 	cpumask_copy(swb_cpus, group_balance_mask(sg));
13657 	/* Try to find first idle CPU */
13658 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
13659 		if (!idle_cpu(cpu))
13660 			continue;
13661 
13662 		/*
13663 		 * Don't balance to idle SMT in busy core right away when
13664 		 * balancing cores, but remember the first idle SMT CPU for
13665 		 * later consideration.  Find CPU on an idle core first.
13666 		 */
13667 		if (sched_smt_active() &&
13668 		    !(env->sd->flags & SD_SHARE_CPUCAPACITY) &&
13669 		    !is_core_idle(cpu)) {
13670 			if (idle_smt == -1)
13671 				idle_smt = cpu;
13672 			/*
13673 			 * If the core is not idle, and first SMT sibling which is
13674 			 * idle has been found, then its not needed to check other
13675 			 * SMT siblings for idleness:
13676 			 */
13677 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
13678 			continue;
13679 		}
13680 
13681 		/*
13682 		 * Are we the first idle core in a non-SMT domain or higher,
13683 		 * or the first idle CPU in a SMT domain?
13684 		 */
13685 		return cpu == env->dst_cpu;
13686 	}
13687 
13688 	/* Are we the first idle CPU with busy siblings? */
13689 	if (idle_smt != -1)
13690 		return idle_smt == env->dst_cpu;
13691 
13692 	/* Are we the first CPU of this group ? */
13693 	return group_balance_cpu(sg) == env->dst_cpu;
13694 }
13695 
13696 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
13697 				     enum cpu_idle_type idle)
13698 {
13699 	if (!schedstat_enabled())
13700 		return;
13701 
13702 	switch (env->migration_type) {
13703 	case migrate_load:
13704 		__schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
13705 		break;
13706 	case migrate_util:
13707 		__schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
13708 		break;
13709 	case migrate_task:
13710 		__schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
13711 		break;
13712 	case migrate_misfit:
13713 		__schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
13714 		break;
13715 	case migrate_llc_task:
13716 		break;
13717 	}
13718 }
13719 
13720 /*
13721  * This flag serializes load-balancing passes over large domains
13722  * (above the NODE topology level) - only one load-balancing instance
13723  * may run at a time, to reduce overhead on very large systems with
13724  * lots of CPUs and large NUMA distances.
13725  *
13726  * - Note that load-balancing passes triggered while another one
13727  *   is executing are skipped and not re-tried.
13728  *
13729  * - Also note that this does not serialize rebalance_domains()
13730  *   execution, as non-SD_SERIALIZE domains will still be
13731  *   load-balanced in parallel.
13732  */
13733 static atomic_t sched_balance_running = ATOMIC_INIT(0);
13734 
13735 /*
13736  * Check this_cpu to ensure it is balanced within domain. Attempt to move
13737  * tasks if there is an imbalance.
13738  */
13739 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
13740 			struct sched_domain *sd, enum cpu_idle_type idle,
13741 			int *continue_balancing)
13742 {
13743 	int ld_moved, cur_ld_moved, active_balance = 0;
13744 	struct sched_domain *sd_parent = sd->parent;
13745 	struct sched_group *group;
13746 	struct rq *busiest;
13747 	struct rq_flags rf;
13748 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
13749 	struct lb_env env = {
13750 		.sd		= sd,
13751 		.dst_cpu	= this_cpu,
13752 		.dst_rq		= this_rq,
13753 		.dst_grpmask    = group_balance_mask(sd->groups),
13754 		.idle		= idle,
13755 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
13756 		.cpus		= cpus,
13757 		.fbq_type	= all,
13758 		.tasks		= LIST_HEAD_INIT(env.tasks),
13759 	};
13760 	bool need_unlock = false;
13761 
13762 	cpumask_and(cpus, sched_domain_span(sd), cpu_preferred_mask);
13763 
13764 	schedstat_inc(sd->lb_count[idle]);
13765 
13766 redo:
13767 	if (!should_we_balance(&env)) {
13768 		*continue_balancing = 0;
13769 		goto out_balanced;
13770 	}
13771 
13772 	if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
13773 		int zero = 0;
13774 		if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
13775 			goto out_balanced;
13776 
13777 		need_unlock = true;
13778 	}
13779 
13780 	group = sched_balance_find_src_group(&env);
13781 	if (!group) {
13782 		schedstat_inc(sd->lb_nobusyg[idle]);
13783 		goto out_balanced;
13784 	}
13785 
13786 	busiest = sched_balance_find_src_rq(&env, group);
13787 	if (!busiest) {
13788 		schedstat_inc(sd->lb_nobusyq[idle]);
13789 		goto out_balanced;
13790 	}
13791 
13792 	WARN_ON_ONCE(busiest == env.dst_rq);
13793 
13794 	update_lb_imbalance_stat(&env, sd, idle);
13795 
13796 	env.src_cpu = busiest->cpu;
13797 	env.src_rq = busiest;
13798 
13799 	ld_moved = 0;
13800 	/* Clear this flag as soon as we find a pullable task */
13801 	env.flags |= LBF_ALL_PINNED;
13802 	if (busiest->nr_running > 1) {
13803 		/*
13804 		 * Attempt to move tasks. If sched_balance_find_src_group has found
13805 		 * an imbalance but busiest->nr_running <= 1, the group is
13806 		 * still unbalanced. ld_moved simply stays zero, so it is
13807 		 * correctly treated as an imbalance.
13808 		 */
13809 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
13810 
13811 more_balance:
13812 		rq_lock_irqsave(busiest, &rf);
13813 		update_rq_clock(busiest);
13814 
13815 		/*
13816 		 * cur_ld_moved - load moved in current iteration
13817 		 * ld_moved     - cumulative load moved across iterations
13818 		 */
13819 		cur_ld_moved = detach_tasks(&env);
13820 
13821 		/*
13822 		 * We've detached some tasks from busiest_rq. Every
13823 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
13824 		 * unlock busiest->lock, and we are able to be sure
13825 		 * that nobody can manipulate the tasks in parallel.
13826 		 * See task_rq_lock() family for the details.
13827 		 */
13828 
13829 		rq_unlock(busiest, &rf);
13830 
13831 		if (cur_ld_moved) {
13832 			attach_tasks(&env);
13833 			ld_moved += cur_ld_moved;
13834 		}
13835 
13836 		local_irq_restore(rf.flags);
13837 
13838 		if (env.flags & LBF_NEED_BREAK) {
13839 			env.flags &= ~LBF_NEED_BREAK;
13840 			goto more_balance;
13841 		}
13842 
13843 		/*
13844 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
13845 		 * us and move them to an alternate dst_cpu in our sched_group
13846 		 * where they can run. The upper limit on how many times we
13847 		 * iterate on same src_cpu is dependent on number of CPUs in our
13848 		 * sched_group.
13849 		 *
13850 		 * This changes load balance semantics a bit on who can move
13851 		 * load to a given_cpu. In addition to the given_cpu itself
13852 		 * (or a ilb_cpu acting on its behalf where given_cpu is
13853 		 * nohz-idle), we now have balance_cpu in a position to move
13854 		 * load to given_cpu. In rare situations, this may cause
13855 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
13856 		 * _independently_ and at _same_ time to move some load to
13857 		 * given_cpu) causing excess load to be moved to given_cpu.
13858 		 * This however should not happen so much in practice and
13859 		 * moreover subsequent load balance cycles should correct the
13860 		 * excess load moved.
13861 		 */
13862 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
13863 
13864 			/* Prevent to re-select dst_cpu via env's CPUs */
13865 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
13866 
13867 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
13868 			env.dst_cpu	 = env.new_dst_cpu;
13869 			env.flags	&= ~LBF_DST_PINNED;
13870 			env.loop	 = 0;
13871 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
13872 
13873 			/*
13874 			 * Go back to "more_balance" rather than "redo" since we
13875 			 * need to continue with same src_cpu.
13876 			 */
13877 			goto more_balance;
13878 		}
13879 
13880 		/*
13881 		 * We failed to reach balance because of affinity.
13882 		 */
13883 		if (sd_parent) {
13884 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
13885 
13886 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
13887 				*group_imbalance = 1;
13888 		}
13889 
13890 		/* All tasks on this runqueue were pinned by CPU affinity */
13891 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
13892 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
13893 			/*
13894 			 * Attempting to continue load balancing at the current
13895 			 * sched_domain level only makes sense if there are
13896 			 * active CPUs remaining as possible busiest CPUs to
13897 			 * pull load from which are not contained within the
13898 			 * destination group that is receiving any migrated
13899 			 * load.
13900 			 */
13901 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
13902 				env.loop = 0;
13903 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
13904 				goto redo;
13905 			}
13906 			goto out_all_pinned;
13907 		}
13908 	}
13909 
13910 	if (ld_moved) {
13911 		sd->nr_balance_failed = 0;
13912 		goto out_unbalanced;
13913 	}
13914 
13915 	schedstat_inc(sd->lb_failed[idle]);
13916 	/*
13917 	 * Increment the failure counter only on periodic balance.
13918 	 * We do not want newidle balance, which can be very
13919 	 * frequent, pollute the failure counter causing
13920 	 * excessive cache_hot migrations and active balances.
13921 	 *
13922 	 * Similarly for migration_misfit which is not related to
13923 	 * load/util migration, don't pollute nr_balance_failed.
13924 	 *
13925 	 * The same for cache aware scheduling's allowance for
13926 	 * load imbalance. If regular load balance does not
13927 	 * migrate task due to LLC locality, it is a expected
13928 	 * behavior and don't pollute nr_balance_failed.
13929 	 * See can_migrate_task().
13930 	 */
13931 	if (idle != CPU_NEWLY_IDLE &&
13932 	    env.migration_type != migrate_misfit &&
13933 	    !(env.flags & LBF_LLC_PINNED))
13934 		sd->nr_balance_failed++;
13935 
13936 	if (!need_active_balance(&env))
13937 		goto out_unbalanced;
13938 
13939 	scoped_guard (raw_spin_rq_lock_irqsave, busiest) {
13940 		/*
13941 		 * Don't kick the active_load_balance_cpu_stop,
13942 		 * if the curr task on busiest CPU can't be
13943 		 * moved to this_cpu:
13944 		 */
13945 		if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr))
13946 			goto out_one_pinned;
13947 
13948 		/* Record that we found at least one task that could run on this_cpu */
13949 		env.flags &= ~LBF_ALL_PINNED;
13950 
13951 		/*
13952 		 * ->active_balance synchronizes accesses to
13953 		 * ->active_balance_work.  Once set, it's cleared
13954 		 * only after active load balance is finished.
13955 		 */
13956 		if (busiest->active_balance)
13957 			goto out_unbalanced;
13958 
13959 		/*
13960 		 * @busiest dropped its rq_lock in the middle of
13961 		 * scheduling out its ->curr task (->on_rq := 0), no
13962 		 * need to forcefully punt it away with active balance.
13963 		 */
13964 		if (!busiest->curr->on_rq)
13965 			goto out_unbalanced;
13966 
13967 		busiest->active_balance = 1;
13968 		busiest->push_cpu = this_cpu;
13969 		active_balance = 1;
13970 		preempt_disable();
13971 	}
13972 	if (active_balance) {
13973 		stop_one_cpu_nowait(cpu_of(busiest),
13974 				    alb_stop_fn(&env), busiest,
13975 				    &busiest->active_balance_work);
13976 	}
13977 	preempt_enable();
13978 
13979 out_unbalanced:
13980 	/* We were unbalanced, so reset the balancing interval */
13981 	sd->balance_interval = sd->min_interval;
13982 	goto out;
13983 
13984 out_balanced:
13985 	/*
13986 	 * We reach balance although we may have faced some affinity
13987 	 * constraints. Clear the imbalance flag only if other tasks got
13988 	 * a chance to move and fix the imbalance.
13989 	 */
13990 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
13991 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
13992 
13993 		if (*group_imbalance)
13994 			*group_imbalance = 0;
13995 	}
13996 
13997 out_all_pinned:
13998 	/*
13999 	 * We reach balance because all tasks are pinned at this level so
14000 	 * we can't migrate them. Let the imbalance flag set so parent level
14001 	 * can try to migrate them.
14002 	 */
14003 	schedstat_inc(sd->lb_balanced[idle]);
14004 
14005 	sd->nr_balance_failed = 0;
14006 
14007 out_one_pinned:
14008 	ld_moved = 0;
14009 
14010 	/*
14011 	 * sched_balance_newidle() disregards balance intervals, so we could
14012 	 * repeatedly reach this code, which would lead to balance_interval
14013 	 * skyrocketing in a short amount of time. Skip the balance_interval
14014 	 * increase logic to avoid that.
14015 	 *
14016 	 * Similarly misfit migration which is not necessarily an indication of
14017 	 * the system being busy and requires lb to backoff to let it settle
14018 	 * down.
14019 	 */
14020 	if (env.idle == CPU_NEWLY_IDLE ||
14021 	    env.migration_type == migrate_misfit)
14022 		goto out;
14023 
14024 	/* tune up the balancing interval */
14025 	if ((env.flags & LBF_ALL_PINNED &&
14026 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
14027 	    sd->balance_interval < sd->max_interval)
14028 		sd->balance_interval *= 2;
14029 out:
14030 	if (need_unlock)
14031 		atomic_set_release(&sched_balance_running, 0);
14032 
14033 	return ld_moved;
14034 }
14035 
14036 static inline unsigned long
14037 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
14038 {
14039 	unsigned long interval = sd->balance_interval;
14040 
14041 	if (cpu_busy)
14042 		interval *= sd->busy_factor;
14043 
14044 	/* scale ms to jiffies */
14045 	interval = msecs_to_jiffies(interval);
14046 
14047 	/*
14048 	 * Reduce likelihood of busy balancing at higher domains racing with
14049 	 * balancing at lower domains by preventing their balancing periods
14050 	 * from being multiples of each other.
14051 	 */
14052 	if (cpu_busy)
14053 		interval -= 1;
14054 
14055 	interval = clamp(interval, 1UL, max_load_balance_interval);
14056 
14057 	return interval;
14058 }
14059 
14060 static inline void
14061 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
14062 {
14063 	unsigned long interval, next;
14064 
14065 	/* used by idle balance, so cpu_busy = 0 */
14066 	interval = get_sd_balance_interval(sd, 0);
14067 	next = sd->last_balance + interval;
14068 
14069 	if (time_after(*next_balance, next))
14070 		*next_balance = next;
14071 }
14072 
14073 /*
14074  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
14075  * running tasks off the busiest CPU onto idle CPUs. It requires at
14076  * least 1 task to be running on each physical CPU where possible, and
14077  * avoids physical / logical imbalances.
14078  */
14079 static int __active_load_balance_cpu_stop(void *data, unsigned int lb_flags)
14080 {
14081 	struct rq *busiest_rq = data;
14082 	int busiest_cpu = cpu_of(busiest_rq);
14083 	int target_cpu = busiest_rq->push_cpu;
14084 	struct rq *target_rq = cpu_rq(target_cpu);
14085 	struct sched_domain *sd;
14086 	struct task_struct *p = NULL;
14087 	struct rq_flags rf;
14088 
14089 	rq_lock_irq(busiest_rq, &rf);
14090 	/*
14091 	 * Between queueing the stop-work and running it is a hole in which
14092 	 * CPUs can become inactive. We should not move tasks from or to
14093 	 * inactive CPUs.
14094 	 */
14095 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
14096 		goto out_unlock;
14097 
14098 	/* Make sure the requested CPU hasn't gone down in the meantime: */
14099 	if (unlikely(busiest_cpu != smp_processor_id() ||
14100 		     !busiest_rq->active_balance))
14101 		goto out_unlock;
14102 
14103 	/* Is there any task to move? */
14104 	if (busiest_rq->nr_running <= 1)
14105 		goto out_unlock;
14106 
14107 	/*
14108 	 * This condition is "impossible", if it occurs
14109 	 * we need to fix it. Originally reported by
14110 	 * Bjorn Helgaas on a 128-CPU setup.
14111 	 */
14112 	WARN_ON_ONCE(busiest_rq == target_rq);
14113 
14114 	/* Search for an sd spanning us and the target CPU. */
14115 	rcu_read_lock();
14116 	for_each_domain(target_cpu, sd) {
14117 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
14118 			break;
14119 	}
14120 
14121 	if (likely(sd)) {
14122 		struct lb_env env = {
14123 			.sd		= sd,
14124 			.dst_cpu	= target_cpu,
14125 			.dst_rq		= target_rq,
14126 			.src_cpu	= busiest_rq->cpu,
14127 			.src_rq		= busiest_rq,
14128 			.idle		= CPU_IDLE,
14129 			.flags		= LBF_ACTIVE_LB | lb_flags,
14130 		};
14131 
14132 		schedstat_inc(sd->alb_count);
14133 		update_rq_clock(busiest_rq);
14134 
14135 		p = detach_one_task(&env);
14136 		if (p) {
14137 			schedstat_inc(sd->alb_pushed);
14138 			/* Active balancing done, reset the failure counter. */
14139 			sd->nr_balance_failed = 0;
14140 		} else {
14141 			schedstat_inc(sd->alb_failed);
14142 		}
14143 	}
14144 	rcu_read_unlock();
14145 out_unlock:
14146 	busiest_rq->active_balance = 0;
14147 	rq_unlock(busiest_rq, &rf);
14148 
14149 	if (p)
14150 		attach_one_task(target_rq, p);
14151 
14152 	local_irq_enable();
14153 
14154 	return 0;
14155 }
14156 
14157 static int active_load_balance_cpu_stop(void *data)
14158 {
14159 	return __active_load_balance_cpu_stop(data, 0);
14160 }
14161 
14162 static int active_load_balance_llc_cpu_stop(void *data)
14163 {
14164 	return __active_load_balance_cpu_stop(data, LBF_ACTIVE_LB_LLC);
14165 }
14166 
14167 /*
14168  * Scale the max sched_balance_rq interval with the number of CPUs in the system.
14169  * This trades load-balance latency on larger machines for less cross talk.
14170  */
14171 void update_max_interval(void)
14172 {
14173 	max_load_balance_interval = HZ*num_online_cpus()/10;
14174 }
14175 
14176 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
14177 {
14178 	sd->newidle_call++;
14179 	sd->newidle_success += success;
14180 
14181 	if (sd->newidle_call >= 1024) {
14182 		u64 now = sched_clock();
14183 		s64 delta = now - sd->newidle_stamp;
14184 		sd->newidle_stamp = now;
14185 		int ratio = 0;
14186 
14187 		if (delta < 0)
14188 			delta = 0;
14189 
14190 		if (sched_feat(NI_RATE)) {
14191 			/*
14192 			 * ratio  delta   freq
14193 			 *
14194 			 * 1024 -  4  s -  128 Hz
14195 			 *  512 -  2  s -  256 Hz
14196 			 *  256 -  1  s -  512 Hz
14197 			 *  128 - .5  s - 1024 Hz
14198 			 *   64 - .25 s - 2048 Hz
14199 			 */
14200 			ratio = delta >> 22;
14201 		}
14202 
14203 		ratio += sd->newidle_success;
14204 
14205 		sd->newidle_ratio = min(1024, ratio);
14206 		sd->newidle_call /= 2;
14207 		sd->newidle_success /= 2;
14208 	}
14209 }
14210 
14211 static inline bool
14212 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
14213 {
14214 	unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
14215 	unsigned long now = jiffies;
14216 
14217 	if (cost)
14218 		update_newidle_stats(sd, success);
14219 
14220 	if (cost > sd->max_newidle_lb_cost) {
14221 		/*
14222 		 * Track max cost of a domain to make sure to not delay the
14223 		 * next wakeup on the CPU.
14224 		 */
14225 		sd->max_newidle_lb_cost = cost;
14226 		sd->last_decay_max_lb_cost = now;
14227 
14228 	} else if (time_after(now, next_decay)) {
14229 		/*
14230 		 * Decay the newidle max times by ~1% per second to ensure that
14231 		 * it is not outdated and the current max cost is actually
14232 		 * shorter.
14233 		 */
14234 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
14235 		sd->last_decay_max_lb_cost = now;
14236 		return true;
14237 	}
14238 
14239 	return false;
14240 }
14241 
14242 /*
14243  * It checks each scheduling domain to see if it is due to be balanced,
14244  * and initiates a balancing operation if so.
14245  *
14246  * Balancing parameters are set up in init_sched_domains.
14247  */
14248 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
14249 {
14250 	int continue_balancing = 1;
14251 	int cpu = rq->cpu;
14252 	int busy = idle != CPU_IDLE && !sched_idle_rq(rq);
14253 	unsigned long interval;
14254 	struct sched_domain *sd;
14255 	/* Earliest time when we have to do rebalance again */
14256 	unsigned long next_balance = jiffies + 60*HZ;
14257 	int update_next_balance = 0;
14258 	int need_decay = 0;
14259 	u64 max_cost = 0;
14260 
14261 	rcu_read_lock();
14262 	for_each_domain(cpu, sd) {
14263 		/*
14264 		 * Decay the newidle max times here because this is a regular
14265 		 * visit to all the domains.
14266 		 */
14267 		need_decay = update_newidle_cost(sd, 0, 0);
14268 		max_cost += sd->max_newidle_lb_cost;
14269 
14270 		/*
14271 		 * Stop the load balance at this level. There is another
14272 		 * CPU in our sched group which is doing load balancing more
14273 		 * actively.
14274 		 */
14275 		if (!continue_balancing) {
14276 			if (need_decay)
14277 				continue;
14278 			break;
14279 		}
14280 
14281 		interval = get_sd_balance_interval(sd, busy);
14282 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
14283 			if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
14284 				/*
14285 				 * The LBF_DST_PINNED logic could have changed
14286 				 * env->dst_cpu, so we can't know our idle
14287 				 * state even if we migrated tasks. Update it.
14288 				 */
14289 				idle = idle_cpu(cpu);
14290 				busy = !idle && !sched_idle_rq(rq);
14291 			}
14292 			sd->last_balance = jiffies;
14293 			interval = get_sd_balance_interval(sd, busy);
14294 		}
14295 		if (time_after(next_balance, sd->last_balance + interval)) {
14296 			next_balance = sd->last_balance + interval;
14297 			update_next_balance = 1;
14298 		}
14299 	}
14300 	if (need_decay) {
14301 		/*
14302 		 * Ensure the rq-wide value also decays but keep it at a
14303 		 * reasonable floor to avoid funnies with rq->avg_idle.
14304 		 */
14305 		rq->max_idle_balance_cost =
14306 			max((u64)sysctl_sched_migration_cost, max_cost);
14307 	}
14308 	rcu_read_unlock();
14309 
14310 	/*
14311 	 * next_balance will be updated only when there is a need.
14312 	 * When the cpu is attached to null domain for ex, it will not be
14313 	 * updated.
14314 	 */
14315 	if (likely(update_next_balance))
14316 		rq->next_balance = next_balance;
14317 
14318 }
14319 
14320 static inline int on_null_domain(struct rq *rq)
14321 {
14322 	return unlikely(!rcu_dereference_sched(rq->sd));
14323 }
14324 
14325 #ifdef CONFIG_NO_HZ_COMMON
14326 /*
14327  * NOHZ idle load balancing (ILB) details:
14328  *
14329  * - When one of the busy CPUs notices that there may be an idle rebalancing
14330  *   needed, they will kick the idle load balancer, which then does idle
14331  *   load balancing for all the idle CPUs.
14332  */
14333 static inline int find_new_ilb(void)
14334 {
14335 	struct cpumask *ilb_cpus;
14336 	int ilb_cpu, fallback = -1;
14337 
14338 	lockdep_assert_irqs_disabled();
14339 
14340 	/*
14341 	 * Reuse the per-CPU select_rq_mask, which is protected from concurrent
14342 	 * use on this CPU by having interrupts disabled.
14343 	 */
14344 	ilb_cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
14345 	cpumask_and(ilb_cpus, nohz.idle_cpus_mask,
14346 		    housekeeping_cpumask(HK_TYPE_KERNEL_NOISE));
14347 
14348 	for_each_cpu(ilb_cpu, ilb_cpus) {
14349 		if (!idle_cpu(ilb_cpu)) {
14350 			/*
14351 			 * Once an idle fallback exists, a busy CPU proves that
14352 			 * this core cannot be fully idle. Skip its siblings.
14353 			 */
14354 			if (sched_smt_active() && fallback >= 0)
14355 				cpumask_andnot(ilb_cpus, ilb_cpus, cpu_smt_mask(ilb_cpu));
14356 			continue;
14357 		}
14358 
14359 		/*
14360 		 * Running the idle load balancer on an idle sibling of a busy
14361 		 * SMT core can reduce the capacity available to its sibling. Prefer
14362 		 * a CPU whose entire core is idle, but retain the first idle CPU as
14363 		 * a fallback so idle balancing can still make progress when no fully
14364 		 * idle core exists.
14365 		 */
14366 		if (sched_smt_active() && !is_core_idle(ilb_cpu)) {
14367 			if (fallback < 0)
14368 				fallback = ilb_cpu;
14369 
14370 			/*
14371 			 * The core is not idle, so there is no need to check
14372 			 * any of its other SMT siblings.
14373 			 */
14374 			cpumask_andnot(ilb_cpus, ilb_cpus,
14375 				       cpu_smt_mask(ilb_cpu));
14376 			continue;
14377 		}
14378 
14379 		return ilb_cpu;
14380 	}
14381 
14382 	return fallback;
14383 }
14384 
14385 /*
14386  * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
14387  * SMP function call (IPI).
14388  *
14389  * Prefer a CPU on a fully idle core in the HK_TYPE_KERNEL_NOISE housekeeping
14390  * set. Fall back to the first idle CPU when no fully idle core exists.
14391  */
14392 static void kick_ilb(unsigned int flags)
14393 {
14394 	int ilb_cpu;
14395 
14396 	/*
14397 	 * Increase nohz.next_balance only when if full ilb is triggered but
14398 	 * not if we only update stats.
14399 	 */
14400 	if (flags & NOHZ_BALANCE_KICK)
14401 		nohz.next_balance = jiffies+1;
14402 
14403 	ilb_cpu = find_new_ilb();
14404 	if (ilb_cpu < 0)
14405 		return;
14406 
14407 	/*
14408 	 * Don't bother if no new NOHZ balance work items for ilb_cpu,
14409 	 * i.e. all bits in flags are already set in ilb_cpu.
14410 	 */
14411 	if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
14412 		return;
14413 
14414 	/*
14415 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
14416 	 * the first flag owns it; cleared by nohz_csd_func().
14417 	 */
14418 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
14419 	if (flags & NOHZ_KICK_MASK)
14420 		return;
14421 
14422 	/*
14423 	 * This way we generate an IPI on the target CPU which
14424 	 * is idle, and the softirq performing NOHZ idle load balancing
14425 	 * will be run before returning from the IPI.
14426 	 */
14427 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
14428 }
14429 
14430 /*
14431  * Current decision point for kicking the idle load balancer in the presence
14432  * of idle CPUs in the system.
14433  */
14434 static void nohz_balancer_kick(struct rq *rq)
14435 {
14436 	unsigned long now = jiffies;
14437 	struct sched_domain_shared *sds;
14438 	struct sched_domain *sd;
14439 	int nr_busy, i, cpu = rq->cpu;
14440 	unsigned int flags = 0;
14441 
14442 	if (unlikely(rq->idle_balance))
14443 		return;
14444 
14445 	/*
14446 	 * We may be recently in ticked or tickless idle mode. At the first
14447 	 * busy tick after returning from idle, we will update the busy stats.
14448 	 */
14449 	nohz_balance_exit_idle(rq);
14450 
14451 	if (READ_ONCE(nohz.has_blocked_load) &&
14452 	    time_after(now, READ_ONCE(nohz.next_blocked)))
14453 		flags = NOHZ_STATS_KICK;
14454 
14455 	/*
14456 	 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0
14457 	 * Skip the read if time is not due.
14458 	 *
14459 	 * If none are in tickless mode, there maybe a narrow window
14460 	 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called.
14461 	 * But idle load balancing is not done as find_new_ilb fails.
14462 	 * That's very rare. So read nohz.nr_cpus only if time is due.
14463 	 */
14464 	if (time_before(now, nohz.next_balance))
14465 		goto out;
14466 
14467 	/*
14468 	 * None are in tickless mode and hence no need for NOHZ idle load
14469 	 * balancing
14470 	 */
14471 	if (unlikely(cpumask_empty(nohz.idle_cpus_mask)))
14472 		return;
14473 
14474 	if (rq->nr_running >= 2) {
14475 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14476 		goto out;
14477 	}
14478 
14479 	sd = rcu_dereference_all(rq->sd);
14480 	if (sd) {
14481 		/*
14482 		 * If there's a runnable CFS task and the current CPU has reduced
14483 		 * capacity, kick the ILB to see if there's a better CPU to run on:
14484 		 */
14485 		if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
14486 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14487 			goto out;
14488 		}
14489 	}
14490 
14491 	sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu));
14492 	if (sd) {
14493 		/*
14494 		 * When ASYM_PACKING; see if there's a more preferred CPU
14495 		 * currently idle; in which case, kick the ILB to move tasks
14496 		 * around.
14497 		 *
14498 		 * When balancing between cores, all the SMT siblings of the
14499 		 * preferred CPU must be idle.
14500 		 */
14501 		for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
14502 			if (sched_asym(sd, i, cpu)) {
14503 				flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14504 				goto out;
14505 			}
14506 		}
14507 	}
14508 
14509 	sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu));
14510 	if (sd) {
14511 		/*
14512 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
14513 		 * to run the misfit task on.
14514 		 */
14515 		if (check_misfit_status(rq))
14516 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14517 
14518 		/*
14519 		 * For asymmetric systems, we do not want to nicely balance
14520 		 * cache use, instead we want to embrace asymmetry and only
14521 		 * ensure tasks have enough CPU capacity.
14522 		 *
14523 		 * Skip the LLC logic because it's not relevant in that case.
14524 		 */
14525 		goto out;
14526 	}
14527 
14528 	sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
14529 	if (sds) {
14530 		/*
14531 		 * If there is an imbalance between LLC domains (IOW we could
14532 		 * increase the overall cache utilization), we need a less-loaded LLC
14533 		 * domain to pull some load from. Likewise, we may need to spread
14534 		 * load within the current LLC domain (e.g. packed SMT cores but
14535 		 * other CPUs are idle). We can't really know from here how busy
14536 		 * the others are - so just get a NOHZ balance going if it looks
14537 		 * like this LLC domain has tasks we could move.
14538 		 */
14539 		nr_busy = atomic_read(&sds->nr_busy_cpus);
14540 		if (nr_busy > 1)
14541 			flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14542 	}
14543 out:
14544 	if (READ_ONCE(nohz.needs_update))
14545 		flags |= NOHZ_NEXT_KICK;
14546 
14547 	if (flags)
14548 		kick_ilb(flags);
14549 }
14550 
14551 static void set_cpu_sd_state_busy(int cpu)
14552 {
14553 	struct sched_domain *sd;
14554 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14555 
14556 	/*
14557 	 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this
14558 	 * domain has no shared object there is nothing to clear or account.
14559 	 */
14560 	if (!sd || !sd->shared || !sd->nohz_idle)
14561 		return;
14562 	sd->nohz_idle = 0;
14563 
14564 	atomic_inc(&sd->shared->nr_busy_cpus);
14565 }
14566 
14567 void nohz_balance_exit_idle(struct rq *rq)
14568 {
14569 	WARN_ON_ONCE(rq != this_rq());
14570 
14571 	if (likely(!rq->nohz_tick_stopped))
14572 		return;
14573 
14574 	rq->nohz_tick_stopped = 0;
14575 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
14576 
14577 	set_cpu_sd_state_busy(rq->cpu);
14578 }
14579 
14580 static void set_cpu_sd_state_idle(int cpu)
14581 {
14582 	struct sched_domain *sd;
14583 	sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14584 
14585 	/* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */
14586 	if (!sd || !sd->shared || sd->nohz_idle)
14587 		return;
14588 	sd->nohz_idle = 1;
14589 
14590 	atomic_dec(&sd->shared->nr_busy_cpus);
14591 }
14592 
14593 /*
14594  * This routine will record that the CPU is going idle with tick stopped.
14595  * This info will be used in performing idle load balancing in the future.
14596  */
14597 void nohz_balance_enter_idle(int cpu)
14598 {
14599 	struct rq *rq = cpu_rq(cpu);
14600 
14601 	WARN_ON_ONCE(cpu != smp_processor_id());
14602 
14603 	/* If this CPU is going down, then nothing needs to be done: */
14604 	if (!cpu_active(cpu))
14605 		return;
14606 
14607 	/*
14608 	 * Can be set safely without rq->lock held
14609 	 * If a clear happens, it will have evaluated last additions because
14610 	 * rq->lock is held during the check and the clear
14611 	 */
14612 	rq->has_blocked_load = 1;
14613 
14614 	/*
14615 	 * The tick is still stopped but load could have been added in the
14616 	 * meantime. We set the nohz.has_blocked_load flag to trig a check of the
14617 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
14618 	 * of nohz.has_blocked_load can only happen after checking the new load
14619 	 */
14620 	if (rq->nohz_tick_stopped)
14621 		goto out;
14622 
14623 	/* If we're a completely isolated CPU, we don't play: */
14624 	if (on_null_domain(rq))
14625 		return;
14626 
14627 	rq->nohz_tick_stopped = 1;
14628 
14629 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
14630 
14631 	/*
14632 	 * Ensures that if nohz_idle_balance() fails to observe our
14633 	 * @idle_cpus_mask store, it must observe the @has_blocked_load
14634 	 * and @needs_update stores.
14635 	 */
14636 	smp_mb__after_atomic();
14637 
14638 	set_cpu_sd_state_idle(cpu);
14639 
14640 	WRITE_ONCE(nohz.needs_update, 1);
14641 out:
14642 	/*
14643 	 * Each time a cpu enter idle, we assume that it has blocked load and
14644 	 * enable the periodic update of the load of idle CPUs
14645 	 */
14646 	WRITE_ONCE(nohz.has_blocked_load, 1);
14647 }
14648 
14649 static bool update_nohz_stats(struct rq *rq)
14650 {
14651 	unsigned int cpu = rq->cpu;
14652 
14653 	if (!rq->has_blocked_load)
14654 		return false;
14655 
14656 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
14657 		return false;
14658 
14659 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
14660 		return true;
14661 
14662 	sched_balance_update_blocked_averages(cpu);
14663 
14664 	return rq->has_blocked_load;
14665 }
14666 
14667 /*
14668  * Internal function that runs load balance for all idle CPUs. The load balance
14669  * can be a simple update of blocked load or a complete load balance with
14670  * tasks movement depending of flags.
14671  */
14672 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
14673 {
14674 	/* Earliest time when we have to do rebalance again */
14675 	unsigned long now = jiffies;
14676 	unsigned long next_balance = now + 60*HZ;
14677 	bool has_blocked_load = false;
14678 	int update_next_balance = 0;
14679 	int this_cpu = this_rq->cpu;
14680 	int balance_cpu;
14681 	struct rq *rq;
14682 
14683 	WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
14684 
14685 	/*
14686 	 * We assume there will be no idle load after this update and clear
14687 	 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will
14688 	 * set the has_blocked_load flag and trigger another update of idle load.
14689 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
14690 	 * setting the flag, we are sure to not clear the state and not
14691 	 * check the load of an idle cpu.
14692 	 *
14693 	 * Same applies to idle_cpus_mask vs needs_update.
14694 	 */
14695 	if (flags & NOHZ_STATS_KICK)
14696 		WRITE_ONCE(nohz.has_blocked_load, 0);
14697 	if (flags & NOHZ_NEXT_KICK)
14698 		WRITE_ONCE(nohz.needs_update, 0);
14699 
14700 	/*
14701 	 * Ensures that if we miss the CPU, we must see the has_blocked_load
14702 	 * store from nohz_balance_enter_idle().
14703 	 */
14704 	smp_mb();
14705 
14706 	/*
14707 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
14708 	 * chance for other idle cpu to pull load.
14709 	 */
14710 	for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
14711 		if (!idle_cpu(balance_cpu))
14712 			continue;
14713 
14714 		/*
14715 		 * If this CPU gets work to do, stop the load balancing
14716 		 * work being done for other CPUs. Next load
14717 		 * balancing owner will pick it up.
14718 		 */
14719 		if (!idle_cpu(this_cpu) && need_resched()) {
14720 			if (flags & NOHZ_STATS_KICK)
14721 				has_blocked_load = true;
14722 			if (flags & NOHZ_NEXT_KICK)
14723 				WRITE_ONCE(nohz.needs_update, 1);
14724 			goto abort;
14725 		}
14726 
14727 		rq = cpu_rq(balance_cpu);
14728 
14729 		if (flags & NOHZ_STATS_KICK)
14730 			has_blocked_load |= update_nohz_stats(rq);
14731 
14732 		/*
14733 		 * If time for next balance is due,
14734 		 * do the balance.
14735 		 */
14736 		if (time_after_eq(jiffies, rq->next_balance)) {
14737 			struct rq_flags rf;
14738 
14739 			rq_lock_irqsave(rq, &rf);
14740 			update_rq_clock(rq);
14741 			rq_unlock_irqrestore(rq, &rf);
14742 
14743 			if (flags & NOHZ_BALANCE_KICK)
14744 				sched_balance_domains(rq, CPU_IDLE);
14745 		}
14746 
14747 		if (time_after(next_balance, rq->next_balance)) {
14748 			next_balance = rq->next_balance;
14749 			update_next_balance = 1;
14750 		}
14751 	}
14752 
14753 	/*
14754 	 * next_balance will be updated only when there is a need.
14755 	 * When the CPU is attached to null domain for ex, it will not be
14756 	 * updated.
14757 	 */
14758 	if (likely(update_next_balance))
14759 		nohz.next_balance = next_balance;
14760 
14761 	if (flags & NOHZ_STATS_KICK)
14762 		WRITE_ONCE(nohz.next_blocked,
14763 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
14764 
14765 abort:
14766 	/* There is still blocked load, enable periodic update */
14767 	if (has_blocked_load)
14768 		WRITE_ONCE(nohz.has_blocked_load, 1);
14769 }
14770 
14771 /*
14772  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
14773  * rebalancing for all the CPUs for whom scheduler ticks are stopped.
14774  */
14775 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14776 {
14777 	unsigned int flags = this_rq->nohz_idle_balance;
14778 
14779 	if (!flags)
14780 		return false;
14781 
14782 	this_rq->nohz_idle_balance = 0;
14783 
14784 	if (idle != CPU_IDLE)
14785 		return false;
14786 
14787 	_nohz_idle_balance(this_rq, flags);
14788 
14789 	return true;
14790 }
14791 
14792 /*
14793  * Check if we need to directly run the ILB for updating blocked load before
14794  * entering idle state. Here we run ILB directly without issuing IPIs.
14795  *
14796  * Note that when this function is called, the tick may not yet be stopped on
14797  * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
14798  * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
14799  * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
14800  * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
14801  * called from this function on (this) CPU that's not yet in the mask. That's
14802  * OK because the goal of nohz_run_idle_balance() is to run ILB only for
14803  * updating the blocked load of already idle CPUs without waking up one of
14804  * those idle CPUs and outside the preempt disable / IRQ off phase of the local
14805  * cpu about to enter idle, because it can take a long time.
14806  */
14807 void nohz_run_idle_balance(int cpu)
14808 {
14809 	unsigned int flags;
14810 
14811 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
14812 
14813 	/*
14814 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
14815 	 * (i.e. NOHZ_STATS_KICK set) and will do the same.
14816 	 */
14817 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
14818 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
14819 }
14820 
14821 static void nohz_newidle_balance(struct rq *this_rq)
14822 {
14823 	int this_cpu = this_rq->cpu;
14824 
14825 	/* Will wake up very soon. No time for doing anything else*/
14826 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
14827 		return;
14828 
14829 	/* Don't need to update blocked load of idle CPUs*/
14830 	if (!READ_ONCE(nohz.has_blocked_load) ||
14831 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
14832 		return;
14833 
14834 	/*
14835 	 * Set the need to trigger ILB in order to update blocked load
14836 	 * before entering idle state.
14837 	 */
14838 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
14839 }
14840 
14841 #else /* !CONFIG_NO_HZ_COMMON: */
14842 static inline void nohz_balancer_kick(struct rq *rq) { }
14843 
14844 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14845 {
14846 	return false;
14847 }
14848 
14849 static inline void nohz_newidle_balance(struct rq *this_rq) { }
14850 #endif /* !CONFIG_NO_HZ_COMMON */
14851 
14852 /*
14853  * sched_balance_newidle is called by schedule() if this_cpu is about to become
14854  * idle. Attempts to pull tasks from other CPUs.
14855  *
14856  * Returns:
14857  *   < 0 - we released the lock and there are !fair tasks present
14858  *     0 - failed, no new tasks
14859  *   > 0 - success, new (fair) tasks present
14860  */
14861 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
14862 	__must_hold(__rq_lockp(this_rq))
14863 {
14864 	unsigned long next_balance = jiffies + HZ;
14865 	int this_cpu = this_rq->cpu;
14866 	int continue_balancing = 1;
14867 	u64 t0, t1, curr_cost = 0;
14868 	struct sched_domain *sd;
14869 	int pulled_task = 0;
14870 
14871 	update_misfit_status(NULL, this_rq);
14872 
14873 	/*
14874 	 * There is a task waiting to run. No need to search for one.
14875 	 * Return 0; the task will be enqueued when switching to idle.
14876 	 */
14877 	if (this_rq->ttwu_pending)
14878 		return 0;
14879 
14880 	/*
14881 	 * We must set idle_stamp _before_ calling sched_balance_rq()
14882 	 * for CPU_NEWLY_IDLE, such that we measure the this duration
14883 	 * as idle time.
14884 	 */
14885 	this_rq->idle_stamp = rq_clock(this_rq);
14886 
14887 	/* Do not pull tasks towards !preferred CPUs */
14888 	if (!cpu_preferred(this_cpu))
14889 		return 0;
14890 
14891 	/*
14892 	 * This is OK, because current is on_cpu, which avoids it being picked
14893 	 * for load-balance and preemption/IRQs are still disabled avoiding
14894 	 * further scheduler activity on it and we're being very careful to
14895 	 * re-start the picking loop.
14896 	 */
14897 	rq_unpin_lock(this_rq, rf);
14898 
14899 	sd = rcu_dereference_sched_domain(this_rq->sd);
14900 	if (!sd)
14901 		goto out;
14902 
14903 	if (!get_rd_overloaded(this_rq->rd) ||
14904 	    this_rq->avg_idle < sd->max_newidle_lb_cost) {
14905 
14906 		update_next_balance(sd, &next_balance);
14907 		goto out;
14908 	}
14909 
14910 	/*
14911 	 * Include sched_balance_update_blocked_averages() in the cost
14912 	 * calculation because it can be quite costly -- this ensures we skip
14913 	 * it when avg_idle gets to be very low.
14914 	 */
14915 	t0 = sched_clock_cpu(this_cpu);
14916 	__sched_balance_update_blocked_averages(this_rq);
14917 
14918 	rq_modified_begin(this_rq, &fair_sched_class);
14919 	raw_spin_rq_unlock(this_rq);
14920 
14921 	for_each_domain(this_cpu, sd) {
14922 		u64 domain_cost;
14923 
14924 		update_next_balance(sd, &next_balance);
14925 
14926 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
14927 			break;
14928 
14929 		if (sd->flags & SD_BALANCE_NEWIDLE) {
14930 			unsigned int weight = 1;
14931 
14932 			if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) {
14933 				/*
14934 				 * Throw a 1k sided dice; and only run
14935 				 * newidle_balance according to the success
14936 				 * rate.
14937 				 */
14938 				u32 d1k = sched_rng() % 1024;
14939 				weight = 1 + sd->newidle_ratio;
14940 				if (d1k > weight) {
14941 					update_newidle_stats(sd, 0);
14942 					continue;
14943 				}
14944 				weight = (1024 + weight/2) / weight;
14945 			}
14946 
14947 			pulled_task = sched_balance_rq(this_cpu, this_rq,
14948 						   sd, CPU_NEWLY_IDLE,
14949 						   &continue_balancing);
14950 
14951 			t1 = sched_clock_cpu(this_cpu);
14952 			domain_cost = t1 - t0;
14953 			curr_cost += domain_cost;
14954 			t0 = t1;
14955 
14956 			/*
14957 			 * Track max cost of a domain to make sure to not delay the
14958 			 * next wakeup on the CPU.
14959 			 */
14960 			update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
14961 		}
14962 
14963 		/*
14964 		 * Stop searching for tasks to pull if there are
14965 		 * now runnable tasks on this rq.
14966 		 */
14967 		if (pulled_task || !continue_balancing)
14968 			break;
14969 	}
14970 
14971 	raw_spin_rq_lock(this_rq);
14972 
14973 	if (curr_cost > this_rq->max_idle_balance_cost)
14974 		this_rq->max_idle_balance_cost = curr_cost;
14975 
14976 	/*
14977 	 * While browsing the domains, we released the rq lock, a task could
14978 	 * have been enqueued in the meantime. Since we're not going idle,
14979 	 * pretend we pulled a task.
14980 	 */
14981 	if (this_rq->cfs.h_nr_queued && !pulled_task)
14982 		pulled_task = 1;
14983 
14984 	/* If a higher prio class was modified, restart the pick */
14985 	if (rq_modified_above(this_rq, &fair_sched_class))
14986 		pulled_task = -1;
14987 
14988 out:
14989 	/* Move the next balance forward */
14990 	if (time_after(this_rq->next_balance, next_balance))
14991 		this_rq->next_balance = next_balance;
14992 
14993 	if (pulled_task)
14994 		this_rq->idle_stamp = 0;
14995 	else
14996 		nohz_newidle_balance(this_rq);
14997 
14998 	rq_repin_lock(this_rq, rf);
14999 
15000 	return pulled_task;
15001 }
15002 
15003 /*
15004  * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
15005  *
15006  * - directly from the local sched_tick() for periodic load balancing
15007  *
15008  * - indirectly from a remote sched_tick() for NOHZ idle balancing
15009  *   through the SMP cross-call nohz_csd_func()
15010  */
15011 static __latent_entropy void sched_balance_softirq(void)
15012 {
15013 	struct rq *this_rq = this_rq();
15014 	enum cpu_idle_type idle = this_rq->idle_balance;
15015 	/*
15016 	 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
15017 	 * balancing on behalf of the other idle CPUs whose ticks are
15018 	 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
15019 	 * give the idle CPUs a chance to load balance. Else we may
15020 	 * load balance only within the local sched_domain hierarchy
15021 	 * and abort nohz_idle_balance altogether if we pull some load.
15022 	 */
15023 	if (nohz_idle_balance(this_rq, idle))
15024 		return;
15025 
15026 	/* normal load balance */
15027 	sched_balance_update_blocked_averages(this_rq->cpu);
15028 	sched_balance_domains(this_rq, idle);
15029 }
15030 
15031 /*
15032  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
15033  */
15034 void sched_balance_trigger(struct rq *rq)
15035 {
15036 	/*
15037 	 * Don't need to rebalance while attached to NULL domain or
15038 	 * runqueue CPU is not active
15039 	 */
15040 	if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
15041 		return;
15042 
15043 	if (time_after_eq(jiffies, rq->next_balance))
15044 		raise_softirq(SCHED_SOFTIRQ);
15045 
15046 	nohz_balancer_kick(rq);
15047 }
15048 
15049 static void rq_online_fair(struct rq *rq)
15050 {
15051 	update_sysctl();
15052 
15053 	update_runtime_enabled(rq);
15054 }
15055 
15056 static void rq_offline_fair(struct rq *rq)
15057 {
15058 	update_sysctl();
15059 
15060 	/* Ensure any throttled groups are reachable by pick_next_task */
15061 	unthrottle_offline_cfs_rqs(rq);
15062 
15063 	/* Ensure that we remove rq contribution to group share: */
15064 	clear_tg_offline_cfs_rqs(rq);
15065 }
15066 
15067 #ifdef CONFIG_SCHED_CORE
15068 static inline bool
15069 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
15070 {
15071 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
15072 	u64 slice = se->slice;
15073 
15074 	return (rtime * min_nr_tasks > slice);
15075 }
15076 
15077 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
15078 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
15079 {
15080 	if (!sched_core_enabled(rq))
15081 		return;
15082 
15083 	/*
15084 	 * If runqueue has only one task which used up its slice and
15085 	 * if the sibling is forced idle, then trigger schedule to
15086 	 * give forced idle task a chance.
15087 	 *
15088 	 * __entity_slice_used() considers only this active rq and it gets the
15089 	 * whole slice. But during force idle, we have siblings acting
15090 	 * like a single runqueue and hence we need to consider runnable
15091 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
15092 	 * go through the forced idle rq, but that would be a perf hit.
15093 	 * We can assume that the forced idle CPU has at least
15094 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
15095 	 * if we need to give up the CPU.
15096 	 */
15097 	if (rq->core->core_forceidle_count && rq->cfs.h_nr_queued == 1 &&
15098 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
15099 		resched_curr(rq);
15100 }
15101 
15102 /*
15103  * Consider any infeasible weight scenario. Take for instance two tasks,
15104  * each bound to their respective sibling, one with weight 1 and one with
15105  * weight 2. Then the lower weight task will run ahead of the higher weight
15106  * task without bound.
15107  *
15108  * This utterly destroys the concept of a shared time base.
15109  *
15110  * Remember; all this is about a proportionally fair scheduling, where each
15111  * tasks receives:
15112  *
15113  *              w_i
15114  *   dt_i = ---------- dt                                     (1)
15115  *          \Sum_j w_j
15116  *
15117  * which we do by tracking a virtual time, s_i:
15118  *
15119  *          1
15120  *   s_i = --- d[t]_i                                         (2)
15121  *         w_i
15122  *
15123  * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
15124  * The immediate corollary is that the ideal schedule S, where (2) to use
15125  * an infinitesimal delta, is:
15126  *
15127  *           1
15128  *   S = ---------- dt                                        (3)
15129  *       \Sum_i w_i
15130  *
15131  * From which we can define the lag, or deviation from the ideal, as:
15132  *
15133  *   lag(i) = S - s_i                                         (4)
15134  *
15135  * And since the one and only purpose is to approximate S, we get that:
15136  *
15137  *   \Sum_i w_i lag(i) := 0                                   (5)
15138  *
15139  * If this were not so, we no longer converge to S, and we can no longer
15140  * claim our scheduler has any of the properties we derive from S. This is
15141  * exactly what you did above, you broke it!
15142  *
15143  *
15144  * Let's continue for a while though; to see if there is anything useful to
15145  * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
15146  *
15147  *       \Sum_i w_i s_i
15148  *   S = --------------                                       (6)
15149  *         \Sum_i w_i
15150  *
15151  * Which gives us a way to compute S, given our s_i. Now, if you've read
15152  * our code, you know that we do not in fact do this, the reason for this
15153  * is two-fold. Firstly, computing S in that way requires a 64bit division
15154  * for every time we'd use it (see 12), and secondly, this only describes
15155  * the steady-state, it doesn't handle dynamics.
15156  *
15157  * Anyway, in (6):  s_i -> x + (s_i - x), to get:
15158  *
15159  *           \Sum_i w_i (s_i - x)
15160  *   S - x = --------------------                             (7)
15161  *              \Sum_i w_i
15162  *
15163  * Which shows that S and s_i transform alike (which makes perfect sense
15164  * given that S is basically the (weighted) average of s_i).
15165  *
15166  * So the thing to remember is that the above is strictly UP. It is
15167  * possible to generalize to multiple runqueues -- however it gets really
15168  * yuck when you have to add affinity support, as illustrated by our very
15169  * first counter-example.
15170  *
15171  * Luckily I think we can avoid needing a full multi-queue variant for
15172  * core-scheduling (or load-balancing). The crucial observation is that we
15173  * only actually need this comparison in the presence of forced-idle; only
15174  * then do we need to tell if the stalled rq has higher priority over the
15175  * other.
15176  *
15177  * [XXX assumes SMT2; better consider the more general case, I suspect
15178  * it'll work out because our comparison is always between 2 rqs and the
15179  * answer is only interesting if one of them is forced-idle]
15180  *
15181  * And (under assumption of SMT2) when there is forced-idle, there is only
15182  * a single queue, so everything works like normal.
15183  *
15184  * Let, for our runqueue 'k':
15185  *
15186  *   T_k = \Sum_i w_i s_i
15187  *   W_k = \Sum_i w_i      ; for all i of k                  (8)
15188  *
15189  * Then we can write (6) like:
15190  *
15191  *         T_k
15192  *   S_k = ---                                               (9)
15193  *         W_k
15194  *
15195  * From which immediately follows that:
15196  *
15197  *           T_k + T_l
15198  *   S_k+l = ---------                                       (10)
15199  *           W_k + W_l
15200  *
15201  * On which we can define a combined lag:
15202  *
15203  *   lag_k+l(i) := S_k+l - s_i                               (11)
15204  *
15205  * And that gives us the tools to compare tasks across a combined runqueue.
15206  *
15207  *
15208  * Combined this gives the following:
15209  *
15210  *  a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
15211  *     using (7); this only requires storing single 'time'-stamps.
15212  *
15213  *  b) when comparing tasks between 2 runqueues of which one is forced-idle,
15214  *     compare the combined lag, per (11).
15215  *
15216  * Now, of course cgroups (I so hate them) make this more interesting in
15217  * that a) seems to suggest we need to iterate all cgroup on a CPU at such
15218  * boundaries, but I think we can avoid that. The force-idle is for the
15219  * whole CPU, all it's rqs. So we can mark it in the root and lazily
15220  * propagate downward on demand.
15221  */
15222 
15223 /*
15224  * So this sync is basically a relative reset of S to 0.
15225  *
15226  * So with 2 queues, when one goes idle, we drop them both to 0 and one
15227  * then increases due to not being idle, and the idle one builds up lag to
15228  * get re-elected. So far so simple, right?
15229  *
15230  * When there's 3, we can have the situation where 2 run and one is idle,
15231  * we sync to 0 and let the idle one build up lag to get re-election. Now
15232  * suppose another one also drops idle. At this point dropping all to 0
15233  * again would destroy the built-up lag from the queue that was already
15234  * idle, not good.
15235  *
15236  * So instead of syncing everything, we can:
15237  *
15238  *   less := !((s64)(s_a - s_b) <= 0)
15239  *
15240  *   (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
15241  *                             == v_a - (v_b - S_a + S_b)
15242  *
15243  * IOW, we can recast the (lag) comparison to a one-sided difference.
15244  * So if then, instead of syncing the whole queue, sync the idle queue
15245  * against the active queue with S_a + S_b at the point where we sync.
15246  *
15247  * (XXX consider the implication of living in a cyclic group: N / 2^n N)
15248  *
15249  * This gives us means of syncing single queues against the active queue,
15250  * and for already idle queues to preserve their build-up lag.
15251  *
15252  * Of course, then we get the situation where there's 2 active and one
15253  * going idle, who do we pick to sync against? Theory would have us sync
15254  * against the combined S, but as we've already demonstrated, there is no
15255  * such thing in infeasible weight scenarios.
15256  *
15257  * One thing I've considered; and this is where that core_active rudiment
15258  * came from, is having active queues sync up between themselves after
15259  * every tick. This limits the observed divergence due to the work
15260  * conservancy.
15261  *
15262  * On top of that, we can improve upon things by employing (10) here.
15263  */
15264 
15265 /*
15266  * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
15267  */
15268 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
15269 			 bool forceidle)
15270 {
15271 	for_each_sched_entity(se) {
15272 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
15273 
15274 		if (forceidle) {
15275 			if (cfs_rq->forceidle_seq == fi_seq)
15276 				break;
15277 			cfs_rq->forceidle_seq = fi_seq;
15278 		}
15279 
15280 		cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
15281 	}
15282 }
15283 
15284 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
15285 {
15286 	struct sched_entity *se = &p->se;
15287 
15288 	if (p->sched_class != &fair_sched_class)
15289 		return;
15290 
15291 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
15292 }
15293 
15294 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
15295 			bool in_fi)
15296 {
15297 	struct rq *rq = task_rq(a);
15298 	const struct sched_entity *sea = &a->se;
15299 	const struct sched_entity *seb = &b->se;
15300 	struct cfs_rq *cfs_rqa;
15301 	struct cfs_rq *cfs_rqb;
15302 	s64 delta;
15303 
15304 	WARN_ON_ONCE(task_rq(b)->core != rq->core);
15305 
15306 	cfs_rqa = &task_rq(a)->cfs;
15307 	cfs_rqb = &task_rq(b)->cfs;
15308 
15309 	/*
15310 	 * Find delta after normalizing se's vruntime with its cfs_rq's
15311 	 * zero_vruntime_fi, which would have been updated in prior calls
15312 	 * to se_fi_update().
15313 	 */
15314 	delta = vruntime_op(sea->vruntime, "-", seb->vruntime) +
15315 		vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi);
15316 
15317 	return delta > 0;
15318 }
15319 
15320 static int task_is_throttled_fair(struct task_struct *p, int cpu)
15321 {
15322 	struct cfs_rq *cfs_rq;
15323 
15324 #ifdef CONFIG_FAIR_GROUP_SCHED
15325 	cfs_rq = tg_cfs_rq(task_group(p), cpu);
15326 #else
15327 	cfs_rq = &cpu_rq(cpu)->cfs;
15328 #endif
15329 	return throttled_hierarchy(cfs_rq);
15330 }
15331 #else /* !CONFIG_SCHED_CORE: */
15332 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
15333 #endif /* !CONFIG_SCHED_CORE */
15334 
15335 /*
15336  * scheduler tick hitting a task of our scheduling class.
15337  *
15338  * NOTE: This function can be called remotely by the tick offload that
15339  * goes along full dynticks. Therefore no local assumption can be made
15340  * and everything must be accessed through the @rq and @curr passed in
15341  * parameters.
15342  */
15343 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
15344 {
15345 	struct sched_entity *se = &curr->se;
15346 
15347 	if (se->on_rq) {
15348 		unsigned long weight = NICE_0_LOAD;
15349 		struct cfs_rq *cfs_rq;
15350 
15351 		for_each_sched_entity(se) {
15352 			cfs_rq = cfs_rq_of(se);
15353 			entity_tick(cfs_rq, se, queued);
15354 
15355 			weight = __calc_prop_weight(cfs_rq, se, weight);
15356 		}
15357 
15358 		se = &curr->se;
15359 		reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15360 	}
15361 
15362 	if (queued)
15363 		return;
15364 
15365 	if (static_branch_unlikely(&sched_numa_balancing))
15366 		task_tick_numa(rq, curr);
15367 
15368 	task_tick_cache(rq, curr);
15369 
15370 	update_misfit_status(curr, rq);
15371 	check_update_overutilized_status(task_rq(curr));
15372 
15373 	task_tick_core(rq, curr);
15374 }
15375 
15376 /*
15377  * called on fork with the child task as argument from the parent's context
15378  *  - child not yet on the tasklist
15379  *  - preemption disabled
15380  */
15381 static void task_fork_fair(struct task_struct *p)
15382 {
15383 	set_task_max_allowed_capacity(p);
15384 }
15385 
15386 /*
15387  * Priority of the task has changed. Check to see if we preempt
15388  * the current task.
15389  */
15390 static void
15391 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
15392 {
15393 	if (!task_on_rq_queued(p))
15394 		return;
15395 
15396 	if (p->prio == oldprio)
15397 		return;
15398 
15399 	if (rq->cfs.h_nr_queued == 1)
15400 		return;
15401 
15402 	/*
15403 	 * Reschedule if we are currently running on this runqueue and
15404 	 * our priority decreased, or if we are not currently running on
15405 	 * this runqueue and our priority is higher than the current's
15406 	 */
15407 	if (task_current_donor(rq, p)) {
15408 		if (p->prio > oldprio)
15409 			resched_curr(rq);
15410 	} else {
15411 		wakeup_preempt(rq, p, 0);
15412 	}
15413 }
15414 
15415 #ifdef CONFIG_FAIR_GROUP_SCHED
15416 /*
15417  * Propagate the changes of the sched_entity across the tg tree to make it
15418  * visible to the root
15419  */
15420 static void propagate_entity_cfs_rq(struct sched_entity *se)
15421 {
15422 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15423 
15424 	/*
15425 	 * If a task gets attached to this cfs_rq and before being queued,
15426 	 * it gets migrated to another CPU due to reasons like affinity
15427 	 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
15428 	 * that removed load decayed or it can cause faireness problem.
15429 	 */
15430 	if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15431 		list_add_leaf_cfs_rq(cfs_rq);
15432 
15433 	/* Start to propagate at parent */
15434 	se = se->parent;
15435 
15436 	for_each_sched_entity(se) {
15437 		cfs_rq = cfs_rq_of(se);
15438 
15439 		update_load_avg(cfs_rq, se, UPDATE_TG);
15440 
15441 		if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15442 			list_add_leaf_cfs_rq(cfs_rq);
15443 	}
15444 
15445 	assert_list_leaf_cfs_rq(rq_of(cfs_rq));
15446 }
15447 #else /* !CONFIG_FAIR_GROUP_SCHED: */
15448 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
15449 #endif /* !CONFIG_FAIR_GROUP_SCHED */
15450 
15451 static void detach_entity_cfs_rq(struct sched_entity *se)
15452 {
15453 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15454 
15455 	/*
15456 	 * In case the task sched_avg hasn't been attached:
15457 	 * - A forked task which hasn't been woken up by wake_up_new_task().
15458 	 * - A task which has been woken up by try_to_wake_up() but is
15459 	 *   waiting for actually being woken up by sched_ttwu_pending().
15460 	 */
15461 	if (!se->avg.last_update_time)
15462 		return;
15463 
15464 	/* Catch up with the cfs_rq and remove our load when we leave */
15465 	update_load_avg(cfs_rq, se, 0);
15466 	detach_entity_load_avg(cfs_rq, se);
15467 	update_tg_load_avg(cfs_rq);
15468 	propagate_entity_cfs_rq(se);
15469 }
15470 
15471 static void attach_entity_cfs_rq(struct sched_entity *se)
15472 {
15473 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
15474 
15475 	/* Synchronize entity with its cfs_rq */
15476 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
15477 	attach_entity_load_avg(cfs_rq, se);
15478 	update_tg_load_avg(cfs_rq);
15479 	propagate_entity_cfs_rq(se);
15480 }
15481 
15482 static void detach_task_cfs_rq(struct task_struct *p)
15483 {
15484 	struct sched_entity *se = &p->se;
15485 
15486 	detach_entity_cfs_rq(se);
15487 }
15488 
15489 static void attach_task_cfs_rq(struct task_struct *p)
15490 {
15491 	struct sched_entity *se = &p->se;
15492 
15493 	attach_entity_cfs_rq(se);
15494 }
15495 
15496 static void switching_from_fair(struct rq *rq, struct task_struct *p)
15497 {
15498 	if (p->se.sched_delayed)
15499 		dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
15500 }
15501 
15502 static void switched_from_fair(struct rq *rq, struct task_struct *p)
15503 {
15504 	detach_task_cfs_rq(p);
15505 }
15506 
15507 static void switched_to_fair(struct rq *rq, struct task_struct *p)
15508 {
15509 	WARN_ON_ONCE(p->se.sched_delayed);
15510 
15511 	attach_task_cfs_rq(p);
15512 
15513 	set_task_max_allowed_capacity(p);
15514 
15515 	if (task_on_rq_queued(p)) {
15516 		/*
15517 		 * We were most likely switched from sched_rt, so
15518 		 * kick off the schedule if running, otherwise just see
15519 		 * if we can still preempt the current task.
15520 		 */
15521 		if (task_current_donor(rq, p))
15522 			resched_curr(rq);
15523 		else
15524 			wakeup_preempt(rq, p, 0);
15525 	}
15526 }
15527 
15528 static void set_next_task_fair(struct rq *rq, struct task_struct *p, enum snt_e type)
15529 {
15530 	struct sched_entity *se = &p->se;
15531 	struct cfs_rq *cfs_rq = &rq->cfs;
15532 	unsigned long weight = NICE_0_LOAD;
15533 	bool first = type == SNT_PICK;
15534 	bool throttled = false;
15535 	bool on_rq = se->on_rq;
15536 
15537 	if (type == SNT_REPICK)
15538 		goto repick;
15539 
15540 	clear_buddies(cfs_rq, se);
15541 
15542 	if (on_rq)
15543 		__dequeue_entity(cfs_rq, se);
15544 
15545 	for_each_sched_entity(se) {
15546 		cfs_rq = cfs_rq_of(se);
15547 
15548 		if (!IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) ||
15549 		    !first || !cfs_rq->h_curr)
15550 			set_next_entity(cfs_rq, se);
15551 
15552 		/* ensure bandwidth has been allocated on our new cfs_rq */
15553 		throttled |= account_cfs_rq_runtime(cfs_rq, 0);
15554 
15555 		if (on_rq)
15556 			weight = __calc_prop_weight(cfs_rq, se, weight);
15557 	}
15558 
15559 	if (throttled)
15560 		task_throttle_setup_work(p);
15561 
15562 	se = &p->se;
15563 	cfs_rq->curr = se;
15564 
15565 	if (on_rq) {
15566 		reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15567 		if (first)
15568 			set_protect_slice(cfs_rq, se);
15569 	}
15570 
15571 	if (task_on_rq_queued(p)) {
15572 		/*
15573 		 * Move the next running task to the front of the list, so our
15574 		 * cfs_tasks list becomes MRU one.
15575 		 */
15576 		list_move(&se->group_node, &rq->cfs_tasks);
15577 	}
15578 	if (!first)
15579 		return;
15580 
15581 	WARN_ON_ONCE(se->sched_delayed);
15582 
15583 	update_misfit_status(p, rq);
15584 	sched_fair_update_stop_tick(rq, p);
15585 
15586 repick:
15587 	/*
15588 	 * A same-task repick skips put_prev_task_fair(), but
15589 	 * pick_task_fair() refreshed the entity hrtick_start_fair() reads
15590 	 * before selecting it again. rq->cfs.curr identifies that entity,
15591 	 * including with group scheduling.
15592 	 */
15593 	if (hrtick_enabled_fair(rq))
15594 		hrtick_start_fair(rq, p);
15595 }
15596 
15597 void init_cfs_rq(struct cfs_rq *cfs_rq)
15598 {
15599 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
15600 	cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
15601 	raw_spin_lock_init(&cfs_rq->removed.lock);
15602 }
15603 
15604 #ifdef CONFIG_FAIR_GROUP_SCHED
15605 static void task_change_group_fair(struct task_struct *p)
15606 {
15607 	/*
15608 	 * We couldn't detach or attach a forked task which
15609 	 * hasn't been woken up by wake_up_new_task().
15610 	 */
15611 	if (READ_ONCE(p->__state) == TASK_NEW)
15612 		return;
15613 
15614 	detach_task_cfs_rq(p);
15615 
15616 	/* Tell se's cfs_rq has been changed -- migrated */
15617 	p->se.avg.last_update_time = 0;
15618 	set_task_rq(p, task_cpu(p));
15619 	attach_task_cfs_rq(p);
15620 }
15621 
15622 void free_fair_sched_group(struct task_group *tg)
15623 {
15624 	free_percpu(tg->cfs_rq);
15625 }
15626 
15627 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
15628 {
15629 	struct cfs_tg_state __percpu *state;
15630 	struct sched_entity *se;
15631 	struct cfs_rq *cfs_rq;
15632 	int i;
15633 
15634 	state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL);
15635 	if (!state)
15636 		goto err;
15637 
15638 	tg->cfs_rq = &state->cfs_rq;
15639 	tg->shares = NICE_0_LOAD;
15640 
15641 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
15642 
15643 	for_each_possible_cpu(i) {
15644 		cfs_rq = tg_cfs_rq(tg, i);
15645 		if (!cfs_rq)
15646 			goto err;
15647 
15648 		se = tg_se(tg, i);
15649 		init_cfs_rq(cfs_rq);
15650 		init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i));
15651 		init_entity_runnable_average(se);
15652 	}
15653 
15654 	return 1;
15655 
15656 err:
15657 	return 0;
15658 }
15659 
15660 void online_fair_sched_group(struct task_group *tg)
15661 {
15662 	struct sched_entity *se;
15663 	struct rq_flags rf;
15664 	struct rq *rq;
15665 	int i;
15666 
15667 	for_each_possible_cpu(i) {
15668 		rq = cpu_rq(i);
15669 		se = tg_se(tg, i);
15670 		rq_lock_irq(rq, &rf);
15671 		update_rq_clock(rq);
15672 		attach_entity_cfs_rq(se);
15673 		sync_throttle(tg, i);
15674 		rq_unlock_irq(rq, &rf);
15675 	}
15676 }
15677 
15678 void unregister_fair_sched_group(struct task_group *tg)
15679 {
15680 	int cpu;
15681 
15682 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
15683 
15684 	for_each_possible_cpu(cpu) {
15685 		struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);
15686 		struct sched_entity *se = tg_se(tg, cpu);
15687 		struct rq *rq = cpu_rq(cpu);
15688 
15689 		if (se)
15690 			remove_entity_load_avg(se);
15691 
15692 		/*
15693 		 * Only empty task groups can be destroyed; so we can speculatively
15694 		 * check on_list without danger of it being re-added.
15695 		 */
15696 		if (cfs_rq->on_list) {
15697 			guard(rq_lock_irqsave)(rq);
15698 			list_del_leaf_cfs_rq(cfs_rq);
15699 		}
15700 	}
15701 }
15702 
15703 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
15704 			struct sched_entity *se, int cpu,
15705 			struct sched_entity *parent)
15706 {
15707 	struct rq *rq = cpu_rq(cpu);
15708 
15709 	cfs_rq->tg = tg;
15710 	cfs_rq->rq = rq;
15711 	init_cfs_rq_runtime(cfs_rq);
15712 
15713 	/* se could be NULL for root_task_group */
15714 	if (!se)
15715 		return;
15716 
15717 	if (!parent) {
15718 		se->cfs_rq = &rq->cfs;
15719 		se->depth = 0;
15720 	} else {
15721 		se->cfs_rq = parent->my_q;
15722 		se->depth = parent->depth + 1;
15723 	}
15724 
15725 	se->my_q = cfs_rq;
15726 	/* guarantee group entities always have weight */
15727 	update_load_set(&se->load, NICE_0_LOAD);
15728 	se->parent = parent;
15729 }
15730 
15731 static DEFINE_MUTEX(shares_mutex);
15732 
15733 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
15734 {
15735 	int i;
15736 
15737 	lockdep_assert_held(&shares_mutex);
15738 
15739 	/*
15740 	 * We can't change the weight of the root cgroup.
15741 	 */
15742 	if (is_root_task_group(tg))
15743 		return -EINVAL;
15744 
15745 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
15746 
15747 	if (tg->shares == shares)
15748 		return 0;
15749 
15750 	tg->shares = shares;
15751 	for_each_possible_cpu(i) {
15752 		struct rq *rq = cpu_rq(i);
15753 		struct sched_entity *se = tg_se(tg, i);
15754 		struct rq_flags rf;
15755 
15756 		/* Propagate contribution to hierarchy */
15757 		rq_lock_irqsave(rq, &rf);
15758 		update_rq_clock(rq);
15759 		for_each_sched_entity(se) {
15760 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
15761 			update_cfs_group(se);
15762 		}
15763 		rq_unlock_irqrestore(rq, &rf);
15764 	}
15765 
15766 	return 0;
15767 }
15768 
15769 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
15770 {
15771 	int ret;
15772 
15773 	mutex_lock(&shares_mutex);
15774 	if (tg_is_idle(tg))
15775 		ret = -EINVAL;
15776 	else
15777 		ret = __sched_group_set_shares(tg, shares);
15778 	mutex_unlock(&shares_mutex);
15779 
15780 	return ret;
15781 }
15782 
15783 int sched_group_set_idle(struct task_group *tg, long idle)
15784 {
15785 	int i;
15786 
15787 	if (tg == &root_task_group)
15788 		return -EINVAL;
15789 
15790 	if (idle < 0 || idle > 1)
15791 		return -EINVAL;
15792 
15793 	mutex_lock(&shares_mutex);
15794 
15795 	if (tg->idle == idle) {
15796 		mutex_unlock(&shares_mutex);
15797 		return 0;
15798 	}
15799 
15800 	tg->idle = idle;
15801 
15802 	for_each_possible_cpu(i) {
15803 		struct rq *rq = cpu_rq(i);
15804 		struct sched_entity *se = tg_se(tg, i);
15805 		struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i);
15806 		bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
15807 		long idle_task_delta;
15808 		struct rq_flags rf;
15809 
15810 		rq_lock_irqsave(rq, &rf);
15811 
15812 		grp_cfs_rq->idle = idle;
15813 		if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
15814 			goto next_cpu;
15815 
15816 		idle_task_delta = grp_cfs_rq->h_nr_queued -
15817 				  grp_cfs_rq->h_nr_idle;
15818 		if (!cfs_rq_is_idle(grp_cfs_rq))
15819 			idle_task_delta *= -1;
15820 
15821 		for_each_sched_entity(se) {
15822 			struct cfs_rq *cfs_rq = cfs_rq_of(se);
15823 
15824 			if (!se->on_rq)
15825 				break;
15826 
15827 			cfs_rq->h_nr_idle += idle_task_delta;
15828 
15829 			/* Already accounted at parent level and above. */
15830 			if (cfs_rq_is_idle(cfs_rq))
15831 				break;
15832 		}
15833 
15834 next_cpu:
15835 		rq_unlock_irqrestore(rq, &rf);
15836 	}
15837 
15838 	/* Idle groups have minimum weight. */
15839 	if (tg_is_idle(tg))
15840 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
15841 	else
15842 		__sched_group_set_shares(tg, NICE_0_LOAD);
15843 
15844 	mutex_unlock(&shares_mutex);
15845 	return 0;
15846 }
15847 
15848 #endif /* CONFIG_FAIR_GROUP_SCHED */
15849 
15850 
15851 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
15852 {
15853 	struct sched_entity *se = &task->se;
15854 	unsigned int rr_interval = 0;
15855 
15856 	/*
15857 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
15858 	 * idle runqueue:
15859 	 */
15860 	if (rq->cfs.load.weight)
15861 		rr_interval = NS_TO_JIFFIES(se->slice);
15862 
15863 	return rr_interval;
15864 }
15865 
15866 /*
15867  * All the scheduling class methods:
15868  */
15869 DEFINE_SCHED_CLASS(fair) = {
15870 	.enqueue_task		= enqueue_task_fair,
15871 	.dequeue_task		= dequeue_task_fair,
15872 	.yield_task		= yield_task_fair,
15873 	.yield_to_task		= yield_to_task_fair,
15874 
15875 	.wakeup_preempt		= wakeup_preempt_fair,
15876 
15877 	.pick_task		= pick_task_fair,
15878 	.put_prev_task		= put_prev_task_fair,
15879 	.set_next_task          = set_next_task_fair,
15880 
15881 	.select_task_rq		= select_task_rq_fair,
15882 	.migrate_task_rq	= migrate_task_rq_fair,
15883 
15884 	.rq_online		= rq_online_fair,
15885 	.rq_offline		= rq_offline_fair,
15886 
15887 	.task_dead		= task_dead_fair,
15888 	.set_cpus_allowed	= set_cpus_allowed_fair,
15889 
15890 	.task_tick		= task_tick_fair,
15891 	.task_fork		= task_fork_fair,
15892 
15893 	.reweight_task		= reweight_task_fair,
15894 	.prio_changed		= prio_changed_fair,
15895 	.switching_from		= switching_from_fair,
15896 	.switched_from		= switched_from_fair,
15897 	.switched_to		= switched_to_fair,
15898 
15899 	.get_rr_interval	= get_rr_interval_fair,
15900 
15901 	.update_curr		= update_curr_fair,
15902 
15903 #ifdef CONFIG_FAIR_GROUP_SCHED
15904 	.task_change_group	= task_change_group_fair,
15905 #endif
15906 
15907 #ifdef CONFIG_SCHED_CORE
15908 	.task_is_throttled	= task_is_throttled_fair,
15909 #endif
15910 
15911 #ifdef CONFIG_UCLAMP_TASK
15912 	.uclamp_enabled		= 1,
15913 #endif
15914 };
15915 
15916 void print_cfs_stats(struct seq_file *m, int cpu)
15917 {
15918 	struct cfs_rq *cfs_rq, *pos;
15919 
15920 	rcu_read_lock();
15921 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
15922 		print_cfs_rq(m, cpu, cfs_rq);
15923 	rcu_read_unlock();
15924 }
15925 
15926 #ifdef CONFIG_NUMA_BALANCING
15927 void show_numa_stats(struct task_struct *p, struct seq_file *m)
15928 {
15929 	int node;
15930 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
15931 	struct numa_group *ng;
15932 
15933 	rcu_read_lock();
15934 	ng = rcu_dereference_all(p->numa_group);
15935 	for_each_online_node(node) {
15936 		if (p->numa_faults) {
15937 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
15938 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
15939 		}
15940 		if (ng) {
15941 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
15942 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
15943 		}
15944 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
15945 	}
15946 	rcu_read_unlock();
15947 }
15948 #endif /* CONFIG_NUMA_BALANCING */
15949 
15950 __init void init_sched_fair_class(void)
15951 {
15952 	int i;
15953 
15954 	for_each_possible_cpu(i) {
15955 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
15956 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
15957 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
15958 					GFP_KERNEL, cpu_to_node(i));
15959 
15960 #ifdef CONFIG_CFS_BANDWIDTH
15961 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
15962 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
15963 #endif
15964 	}
15965 
15966 	open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
15967 
15968 #ifdef CONFIG_NO_HZ_COMMON
15969 	nohz.next_balance = jiffies;
15970 	nohz.next_blocked = jiffies;
15971 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
15972 #endif
15973 }
15974