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