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