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