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