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