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