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