• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4  *
5  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6  *
7  *  Interactivity improvements by Mike Galbraith
8  *  (C) 2007 Mike Galbraith <efault@gmx.de>
9  *
10  *  Various enhancements by Dmitry Adamushko.
11  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12  *
13  *  Group scheduling enhancements by Srivatsa Vaddagiri
14  *  Copyright IBM Corporation, 2007
15  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16  *
17  *  Scaled math optimizations by Thomas Gleixner
18  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19  *
20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22  */
23 #include <linux/energy_model.h>
24 #include <linux/mmap_lock.h>
25 #include <linux/hugetlb_inline.h>
26 #include <linux/jiffies.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/spinlock_api.h>
30 #include <linux/cpumask_api.h>
31 #include <linux/lockdep_api.h>
32 #include <linux/softirq.h>
33 #include <linux/refcount_api.h>
34 #include <linux/topology.h>
35 #include <linux/sched/clock.h>
36 #include <linux/sched/cond_resched.h>
37 #include <linux/sched/cputime.h>
38 #include <linux/sched/isolation.h>
39 #include <linux/sched/nohz.h>
40 
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
51 
52 #include <asm/switch_to.h>
53 
54 #include "sched.h"
55 #include "stats.h"
56 #include "autogroup.h"
57 
58 #include <trace/hooks/sched.h>
59 
60 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_stat_runtime);
61 
62 /*
63  * Targeted preemption latency for CPU-bound tasks:
64  *
65  * NOTE: this latency value is not the same as the concept of
66  * 'timeslice length' - timeslices in CFS are of variable length
67  * and have no persistent notion like in traditional, time-slice
68  * based scheduling concepts.
69  *
70  * (to see the precise effective timeslice length of your workload,
71  *  run vmstat and monitor the context-switches (cs) field)
72  *
73  * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
74  */
75 unsigned int sysctl_sched_latency			= 6000000ULL;
76 EXPORT_SYMBOL_GPL(sysctl_sched_latency);
77 
78 /*
79  * The initial- and re-scaling of tunables is configurable
80  *
81  * Options are:
82  *
83  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
84  *   SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
85  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
86  *
87  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
88  */
89 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
90 
91 /*
92  * Minimal preemption granularity for CPU-bound tasks:
93  *
94  * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
95  */
96 unsigned int sysctl_sched_base_slice			= 700000ULL;
97 EXPORT_SYMBOL_GPL(sysctl_sched_base_slice);
98 static unsigned int normalized_sysctl_sched_base_slice	= 700000ULL;
99 
100 /*
101  * After fork, child runs first. If set to 0 (default) then
102  * parent will (try to) run first.
103  */
104 unsigned int sysctl_sched_child_runs_first __read_mostly;
105 
106 const_debug unsigned int sysctl_sched_migration_cost	= 500000UL;
107 
setup_sched_thermal_decay_shift(char * str)108 static int __init setup_sched_thermal_decay_shift(char *str)
109 {
110 	pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
111 	return 1;
112 }
113 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
114 
115 #ifdef CONFIG_SMP
116 /*
117  * For asym packing, by default the lower numbered CPU has higher priority.
118  */
arch_asym_cpu_priority(int cpu)119 int __weak arch_asym_cpu_priority(int cpu)
120 {
121 	return -cpu;
122 }
123 
124 /*
125  * The margin used when comparing utilization with CPU capacity.
126  *
127  * (default: ~20%)
128  */
129 #define fits_capacity(cap, max)	((cap) * 1280 < (max) * 1024)
130 
131 /*
132  * The margin used when comparing CPU capacities.
133  * is 'cap1' noticeably greater than 'cap2'
134  *
135  * (default: ~5%)
136  */
137 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
138 #endif
139 
140 #ifdef CONFIG_CFS_BANDWIDTH
141 /*
142  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
143  * each time a cfs_rq requests quota.
144  *
145  * Note: in the case that the slice exceeds the runtime remaining (either due
146  * to consumption or the quota being specified to be smaller than the slice)
147  * we will always only issue the remaining available time.
148  *
149  * (default: 5 msec, units: microseconds)
150  */
151 static unsigned int sysctl_sched_cfs_bandwidth_slice		= 5000UL;
152 #endif
153 
154 #ifdef CONFIG_NUMA_BALANCING
155 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
156 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
157 #endif
158 
159 #ifdef CONFIG_SYSCTL
160 static struct ctl_table sched_fair_sysctls[] = {
161 	{
162 		.procname       = "sched_child_runs_first",
163 		.data           = &sysctl_sched_child_runs_first,
164 		.maxlen         = sizeof(unsigned int),
165 		.mode           = 0644,
166 		.proc_handler   = proc_dointvec,
167 	},
168 #ifdef CONFIG_CFS_BANDWIDTH
169 	{
170 		.procname       = "sched_cfs_bandwidth_slice_us",
171 		.data           = &sysctl_sched_cfs_bandwidth_slice,
172 		.maxlen         = sizeof(unsigned int),
173 		.mode           = 0644,
174 		.proc_handler   = proc_dointvec_minmax,
175 		.extra1         = SYSCTL_ONE,
176 	},
177 #endif
178 #ifdef CONFIG_NUMA_BALANCING
179 	{
180 		.procname	= "numa_balancing_promote_rate_limit_MBps",
181 		.data		= &sysctl_numa_balancing_promote_rate_limit,
182 		.maxlen		= sizeof(unsigned int),
183 		.mode		= 0644,
184 		.proc_handler	= proc_dointvec_minmax,
185 		.extra1		= SYSCTL_ZERO,
186 	},
187 #endif /* CONFIG_NUMA_BALANCING */
188 };
189 
sched_fair_sysctl_init(void)190 static int __init sched_fair_sysctl_init(void)
191 {
192 	register_sysctl_init("kernel", sched_fair_sysctls);
193 	return 0;
194 }
195 late_initcall(sched_fair_sysctl_init);
196 #endif
197 
update_load_add(struct load_weight * lw,unsigned long inc)198 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
199 {
200 	lw->weight += inc;
201 	lw->inv_weight = 0;
202 }
203 
update_load_sub(struct load_weight * lw,unsigned long dec)204 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
205 {
206 	lw->weight -= dec;
207 	lw->inv_weight = 0;
208 }
209 
update_load_set(struct load_weight * lw,unsigned long w)210 static inline void update_load_set(struct load_weight *lw, unsigned long w)
211 {
212 	lw->weight = w;
213 	lw->inv_weight = 0;
214 }
215 
216 /*
217  * Increase the granularity value when there are more CPUs,
218  * because with more CPUs the 'effective latency' as visible
219  * to users decreases. But the relationship is not linear,
220  * so pick a second-best guess by going with the log2 of the
221  * number of CPUs.
222  *
223  * This idea comes from the SD scheduler of Con Kolivas:
224  */
get_update_sysctl_factor(void)225 static unsigned int get_update_sysctl_factor(void)
226 {
227 	unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
228 	unsigned int factor;
229 
230 	switch (sysctl_sched_tunable_scaling) {
231 	case SCHED_TUNABLESCALING_NONE:
232 		factor = 1;
233 		break;
234 	case SCHED_TUNABLESCALING_LINEAR:
235 		factor = cpus;
236 		break;
237 	case SCHED_TUNABLESCALING_LOG:
238 	default:
239 		factor = 1 + ilog2(cpus);
240 		break;
241 	}
242 
243 	return factor;
244 }
245 
update_sysctl(void)246 static void update_sysctl(void)
247 {
248 	unsigned int factor = get_update_sysctl_factor();
249 
250 #define SET_SYSCTL(name) \
251 	(sysctl_##name = (factor) * normalized_sysctl_##name)
252 	SET_SYSCTL(sched_base_slice);
253 #undef SET_SYSCTL
254 }
255 
sched_init_granularity(void)256 void __init sched_init_granularity(void)
257 {
258 	update_sysctl();
259 }
260 
261 #define WMULT_CONST	(~0U)
262 #define WMULT_SHIFT	32
263 
__update_inv_weight(struct load_weight * lw)264 static void __update_inv_weight(struct load_weight *lw)
265 {
266 	unsigned long w;
267 
268 	if (likely(lw->inv_weight))
269 		return;
270 
271 	w = scale_load_down(lw->weight);
272 
273 	if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
274 		lw->inv_weight = 1;
275 	else if (unlikely(!w))
276 		lw->inv_weight = WMULT_CONST;
277 	else
278 		lw->inv_weight = WMULT_CONST / w;
279 }
280 
281 /*
282  * delta_exec * weight / lw.weight
283  *   OR
284  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
285  *
286  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
287  * we're guaranteed shift stays positive because inv_weight is guaranteed to
288  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
289  *
290  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
291  * weight/lw.weight <= 1, and therefore our shift will also be positive.
292  */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)293 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
294 {
295 	u64 fact = scale_load_down(weight);
296 	u32 fact_hi = (u32)(fact >> 32);
297 	int shift = WMULT_SHIFT;
298 	int fs;
299 
300 	__update_inv_weight(lw);
301 
302 	if (unlikely(fact_hi)) {
303 		fs = fls(fact_hi);
304 		shift -= fs;
305 		fact >>= fs;
306 	}
307 
308 	fact = mul_u32_u32(fact, lw->inv_weight);
309 
310 	fact_hi = (u32)(fact >> 32);
311 	if (fact_hi) {
312 		fs = fls(fact_hi);
313 		shift -= fs;
314 		fact >>= fs;
315 	}
316 
317 	return mul_u64_u32_shr(delta_exec, fact, shift);
318 }
319 
320 /*
321  * delta /= w
322  */
calc_delta_fair(u64 delta,struct sched_entity * se)323 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
324 {
325 	if (unlikely(se->load.weight != NICE_0_LOAD))
326 		delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
327 
328 	return delta;
329 }
330 
331 const struct sched_class fair_sched_class;
332 
333 /**************************************************************
334  * CFS operations on generic schedulable entities:
335  */
336 
337 #ifdef CONFIG_FAIR_GROUP_SCHED
338 
339 /* Walk up scheduling entities hierarchy */
340 #define for_each_sched_entity(se) \
341 		for (; se; se = se->parent)
342 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)343 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
344 {
345 	struct rq *rq = rq_of(cfs_rq);
346 	int cpu = cpu_of(rq);
347 
348 	if (cfs_rq->on_list)
349 		return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
350 
351 	cfs_rq->on_list = 1;
352 
353 	/*
354 	 * Ensure we either appear before our parent (if already
355 	 * enqueued) or force our parent to appear after us when it is
356 	 * enqueued. The fact that we always enqueue bottom-up
357 	 * reduces this to two cases and a special case for the root
358 	 * cfs_rq. Furthermore, it also means that we will always reset
359 	 * tmp_alone_branch either when the branch is connected
360 	 * to a tree or when we reach the top of the tree
361 	 */
362 	if (cfs_rq->tg->parent &&
363 	    cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
364 		/*
365 		 * If parent is already on the list, we add the child
366 		 * just before. Thanks to circular linked property of
367 		 * the list, this means to put the child at the tail
368 		 * of the list that starts by parent.
369 		 */
370 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
371 			&(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
372 		/*
373 		 * The branch is now connected to its tree so we can
374 		 * reset tmp_alone_branch to the beginning of the
375 		 * list.
376 		 */
377 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
378 		return true;
379 	}
380 
381 	if (!cfs_rq->tg->parent) {
382 		/*
383 		 * cfs rq without parent should be put
384 		 * at the tail of the list.
385 		 */
386 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
387 			&rq->leaf_cfs_rq_list);
388 		/*
389 		 * We have reach the top of a tree so we can reset
390 		 * tmp_alone_branch to the beginning of the list.
391 		 */
392 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
393 		return true;
394 	}
395 
396 	/*
397 	 * The parent has not already been added so we want to
398 	 * make sure that it will be put after us.
399 	 * tmp_alone_branch points to the begin of the branch
400 	 * where we will add parent.
401 	 */
402 	list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
403 	/*
404 	 * update tmp_alone_branch to points to the new begin
405 	 * of the branch
406 	 */
407 	rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
408 	return false;
409 }
410 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)411 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
412 {
413 	if (cfs_rq->on_list) {
414 		struct rq *rq = rq_of(cfs_rq);
415 
416 		/*
417 		 * With cfs_rq being unthrottled/throttled during an enqueue,
418 		 * it can happen the tmp_alone_branch points to the leaf that
419 		 * we finally want to delete. In this case, tmp_alone_branch moves
420 		 * to the prev element but it will point to rq->leaf_cfs_rq_list
421 		 * at the end of the enqueue.
422 		 */
423 		if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
424 			rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
425 
426 		list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
427 		cfs_rq->on_list = 0;
428 	}
429 }
430 
assert_list_leaf_cfs_rq(struct rq * rq)431 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
432 {
433 	SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
434 }
435 
436 /* Iterate through all leaf cfs_rq's on a runqueue */
437 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)			\
438 	list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,	\
439 				 leaf_cfs_rq_list)
440 
441 /* Do the two (enqueued) entities belong to the same group ? */
442 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)443 is_same_group(struct sched_entity *se, struct sched_entity *pse)
444 {
445 	if (se->cfs_rq == pse->cfs_rq)
446 		return se->cfs_rq;
447 
448 	return NULL;
449 }
450 
parent_entity(const struct sched_entity * se)451 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
452 {
453 	return se->parent;
454 }
455 
456 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)457 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
458 {
459 	int se_depth, pse_depth;
460 
461 	/*
462 	 * preemption test can be made between sibling entities who are in the
463 	 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
464 	 * both tasks until we find their ancestors who are siblings of common
465 	 * parent.
466 	 */
467 
468 	/* First walk up until both entities are at same depth */
469 	se_depth = (*se)->depth;
470 	pse_depth = (*pse)->depth;
471 
472 	while (se_depth > pse_depth) {
473 		se_depth--;
474 		*se = parent_entity(*se);
475 	}
476 
477 	while (pse_depth > se_depth) {
478 		pse_depth--;
479 		*pse = parent_entity(*pse);
480 	}
481 
482 	while (!is_same_group(*se, *pse)) {
483 		*se = parent_entity(*se);
484 		*pse = parent_entity(*pse);
485 	}
486 }
487 
tg_is_idle(struct task_group * tg)488 static int tg_is_idle(struct task_group *tg)
489 {
490 	return tg->idle > 0;
491 }
492 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)493 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
494 {
495 	return cfs_rq->idle > 0;
496 }
497 
se_is_idle(struct sched_entity * se)498 static int se_is_idle(struct sched_entity *se)
499 {
500 	if (entity_is_task(se))
501 		return task_has_idle_policy(task_of(se));
502 	return cfs_rq_is_idle(group_cfs_rq(se));
503 }
504 
505 #else	/* !CONFIG_FAIR_GROUP_SCHED */
506 
507 #define for_each_sched_entity(se) \
508 		for (; se; se = NULL)
509 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)510 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
511 {
512 	return true;
513 }
514 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)515 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
516 {
517 }
518 
assert_list_leaf_cfs_rq(struct rq * rq)519 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
520 {
521 }
522 
523 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
524 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
525 
parent_entity(struct sched_entity * se)526 static inline struct sched_entity *parent_entity(struct sched_entity *se)
527 {
528 	return NULL;
529 }
530 
531 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)532 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
533 {
534 }
535 
tg_is_idle(struct task_group * tg)536 static inline int tg_is_idle(struct task_group *tg)
537 {
538 	return 0;
539 }
540 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)541 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
542 {
543 	return 0;
544 }
545 
se_is_idle(struct sched_entity * se)546 static int se_is_idle(struct sched_entity *se)
547 {
548 	return task_has_idle_policy(task_of(se));
549 }
550 
551 #endif	/* CONFIG_FAIR_GROUP_SCHED */
552 
553 static __always_inline
554 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
555 
556 /**************************************************************
557  * Scheduling class tree data structure manipulation methods:
558  */
559 
max_vruntime(u64 max_vruntime,u64 vruntime)560 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
561 {
562 	s64 delta = (s64)(vruntime - max_vruntime);
563 	if (delta > 0)
564 		max_vruntime = vruntime;
565 
566 	return max_vruntime;
567 }
568 
min_vruntime(u64 min_vruntime,u64 vruntime)569 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
570 {
571 	s64 delta = (s64)(vruntime - min_vruntime);
572 	if (delta < 0)
573 		min_vruntime = vruntime;
574 
575 	return min_vruntime;
576 }
577 
entity_before(const struct sched_entity * a,const struct sched_entity * b)578 static inline bool entity_before(const struct sched_entity *a,
579 				 const struct sched_entity *b)
580 {
581 	/*
582 	 * Tiebreak on vruntime seems unnecessary since it can
583 	 * hardly happen.
584 	 */
585 	return (s64)(a->deadline - b->deadline) < 0;
586 }
587 
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)588 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
589 {
590 	return (s64)(se->vruntime - cfs_rq->min_vruntime);
591 }
592 
593 #define __node_2_se(node) \
594 	rb_entry((node), struct sched_entity, run_node)
595 
596 /*
597  * Compute virtual time from the per-task service numbers:
598  *
599  * Fair schedulers conserve lag:
600  *
601  *   \Sum lag_i = 0
602  *
603  * Where lag_i is given by:
604  *
605  *   lag_i = S - s_i = w_i * (V - v_i)
606  *
607  * Where S is the ideal service time and V is it's virtual time counterpart.
608  * Therefore:
609  *
610  *   \Sum lag_i = 0
611  *   \Sum w_i * (V - v_i) = 0
612  *   \Sum w_i * V - w_i * v_i = 0
613  *
614  * From which we can solve an expression for V in v_i (which we have in
615  * se->vruntime):
616  *
617  *       \Sum v_i * w_i   \Sum v_i * w_i
618  *   V = -------------- = --------------
619  *          \Sum w_i            W
620  *
621  * Specifically, this is the weighted average of all entity virtual runtimes.
622  *
623  * [[ NOTE: this is only equal to the ideal scheduler under the condition
624  *          that join/leave operations happen at lag_i = 0, otherwise the
625  *          virtual time has non-contiguous motion equivalent to:
626  *
627  *	      V +-= lag_i / W
628  *
629  *	    Also see the comment in place_entity() that deals with this. ]]
630  *
631  * However, since v_i is u64, and the multiplication could easily overflow
632  * transform it into a relative form that uses smaller quantities:
633  *
634  * Substitute: v_i == (v_i - v0) + v0
635  *
636  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
637  * V = ---------------------------- = --------------------- + v0
638  *                  W                            W
639  *
640  * Which we track using:
641  *
642  *                    v0 := cfs_rq->min_vruntime
643  * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
644  *              \Sum w_i := cfs_rq->avg_load
645  *
646  * Since min_vruntime is a monotonic increasing variable that closely tracks
647  * the per-task service, these deltas: (v_i - v), will be in the order of the
648  * maximal (virtual) lag induced in the system due to quantisation.
649  *
650  * Also, we use scale_load_down() to reduce the size.
651  *
652  * As measured, the max (key * weight) value was ~44 bits for a kernel build.
653  */
654 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)655 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
656 {
657 	unsigned long weight = scale_load_down(se->load.weight);
658 	s64 key = entity_key(cfs_rq, se);
659 
660 	cfs_rq->avg_vruntime += key * weight;
661 	cfs_rq->avg_load += weight;
662 }
663 
664 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)665 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
666 {
667 	unsigned long weight = scale_load_down(se->load.weight);
668 	s64 key = entity_key(cfs_rq, se);
669 
670 	cfs_rq->avg_vruntime -= key * weight;
671 	cfs_rq->avg_load -= weight;
672 }
673 
674 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)675 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
676 {
677 	/*
678 	 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
679 	 */
680 	cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
681 }
682 
683 /*
684  * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
685  * For this to be so, the result of this function must have a left bias.
686  */
avg_vruntime(struct cfs_rq * cfs_rq)687 u64 avg_vruntime(struct cfs_rq *cfs_rq)
688 {
689 	struct sched_entity *curr = cfs_rq->curr;
690 	s64 avg = cfs_rq->avg_vruntime;
691 	long load = cfs_rq->avg_load;
692 
693 	if (curr && curr->on_rq) {
694 		unsigned long weight = scale_load_down(curr->load.weight);
695 
696 		avg += entity_key(cfs_rq, curr) * weight;
697 		load += weight;
698 	}
699 
700 	if (load) {
701 		/* sign flips effective floor / ceiling */
702 		if (avg < 0)
703 			avg -= (load - 1);
704 		avg = div_s64(avg, load);
705 	}
706 
707 	return cfs_rq->min_vruntime + avg;
708 }
709 
710 /*
711  * lag_i = S - s_i = w_i * (V - v_i)
712  *
713  * However, since V is approximated by the weighted average of all entities it
714  * is possible -- by addition/removal/reweight to the tree -- to move V around
715  * and end up with a larger lag than we started with.
716  *
717  * Limit this to either double the slice length with a minimum of TICK_NSEC
718  * since that is the timing granularity.
719  *
720  * EEVDF gives the following limit for a steady state system:
721  *
722  *   -r_max < lag < max(r_max, q)
723  *
724  * XXX could add max_slice to the augmented data to track this.
725  */
entity_lag(u64 avruntime,struct sched_entity * se)726 static s64 entity_lag(u64 avruntime, struct sched_entity *se)
727 {
728 	s64 vlag, limit;
729 
730 	vlag = avruntime - se->vruntime;
731 	limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
732 
733 	return clamp(vlag, -limit, limit);
734 }
735 
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)736 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
737 {
738 	SCHED_WARN_ON(!se->on_rq);
739 
740 	se->vlag = entity_lag(avg_vruntime(cfs_rq), se);
741 }
742 
743 /*
744  * Entity is eligible once it received less service than it ought to have,
745  * eg. lag >= 0.
746  *
747  * lag_i = S - s_i = w_i*(V - v_i)
748  *
749  * lag_i >= 0 -> V >= v_i
750  *
751  *     \Sum (v_i - v)*w_i
752  * V = ------------------ + v
753  *          \Sum w_i
754  *
755  * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
756  *
757  * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
758  *       to the loss in precision caused by the division.
759  */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)760 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
761 {
762 	struct sched_entity *curr = cfs_rq->curr;
763 	s64 avg = cfs_rq->avg_vruntime;
764 	long load = cfs_rq->avg_load;
765 
766 	if (curr && curr->on_rq) {
767 		unsigned long weight = scale_load_down(curr->load.weight);
768 
769 		avg += entity_key(cfs_rq, curr) * weight;
770 		load += weight;
771 	}
772 
773 	return avg >= (s64)(vruntime - cfs_rq->min_vruntime) * load;
774 }
775 
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)776 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
777 {
778 	return vruntime_eligible(cfs_rq, se->vruntime);
779 }
780 
__update_min_vruntime(struct cfs_rq * cfs_rq,u64 vruntime)781 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
782 {
783 	u64 min_vruntime = cfs_rq->min_vruntime;
784 	/*
785 	 * open coded max_vruntime() to allow updating avg_vruntime
786 	 */
787 	s64 delta = (s64)(vruntime - min_vruntime);
788 	if (delta > 0) {
789 		avg_vruntime_update(cfs_rq, delta);
790 		min_vruntime = vruntime;
791 	}
792 	return min_vruntime;
793 }
794 
update_min_vruntime(struct cfs_rq * cfs_rq)795 static void update_min_vruntime(struct cfs_rq *cfs_rq)
796 {
797 	struct sched_entity *se = __pick_root_entity(cfs_rq);
798 	struct sched_entity *curr = cfs_rq->curr;
799 	u64 vruntime = cfs_rq->min_vruntime;
800 
801 	if (curr) {
802 		if (curr->on_rq)
803 			vruntime = curr->vruntime;
804 		else
805 			curr = NULL;
806 	}
807 
808 	if (se) {
809 		if (!curr)
810 			vruntime = se->min_vruntime;
811 		else
812 			vruntime = min_vruntime(vruntime, se->min_vruntime);
813 	}
814 
815 	/* ensure we never gain time by being placed backwards. */
816 	cfs_rq->min_vruntime = __update_min_vruntime(cfs_rq, vruntime);
817 }
818 
cfs_rq_min_slice(struct cfs_rq * cfs_rq)819 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
820 {
821 	struct sched_entity *root = __pick_root_entity(cfs_rq);
822 	struct sched_entity *curr = cfs_rq->curr;
823 	u64 min_slice = ~0ULL;
824 
825 	if (curr && curr->on_rq)
826 		min_slice = curr->slice;
827 
828 	if (root)
829 		min_slice = min(min_slice, root->min_slice);
830 
831 	return min_slice;
832 }
833 
__entity_less(struct rb_node * a,const struct rb_node * b)834 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
835 {
836 	return entity_before(__node_2_se(a), __node_2_se(b));
837 }
838 
839 #define vruntime_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
840 
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)841 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
842 {
843 	if (node) {
844 		struct sched_entity *rse = __node_2_se(node);
845 		if (vruntime_gt(min_vruntime, se, rse))
846 			se->min_vruntime = rse->min_vruntime;
847 	}
848 }
849 
__min_slice_update(struct sched_entity * se,struct rb_node * node)850 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
851 {
852 	if (node) {
853 		struct sched_entity *rse = __node_2_se(node);
854 		if (rse->min_slice < se->min_slice)
855 			se->min_slice = rse->min_slice;
856 	}
857 }
858 
859 /*
860  * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
861  */
min_vruntime_update(struct sched_entity * se,bool exit)862 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
863 {
864 	u64 old_min_vruntime = se->min_vruntime;
865 	u64 old_min_slice = se->min_slice;
866 	struct rb_node *node = &se->run_node;
867 
868 	se->min_vruntime = se->vruntime;
869 	__min_vruntime_update(se, node->rb_right);
870 	__min_vruntime_update(se, node->rb_left);
871 
872 	se->min_slice = se->slice;
873 	__min_slice_update(se, node->rb_right);
874 	__min_slice_update(se, node->rb_left);
875 
876 	return se->min_vruntime == old_min_vruntime &&
877 	       se->min_slice == old_min_slice;
878 }
879 
880 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
881 		     run_node, min_vruntime, min_vruntime_update);
882 
883 /*
884  * Enqueue an entity into the rb-tree:
885  */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)886 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
887 {
888 	trace_android_rvh_enqueue_entity(cfs_rq, se);
889 	avg_vruntime_add(cfs_rq, se);
890 	se->min_vruntime = se->vruntime;
891 	se->min_slice = se->slice;
892 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
893 				__entity_less, &min_vruntime_cb);
894 }
895 
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)896 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
897 {
898 	trace_android_rvh_dequeue_entity(cfs_rq, se);
899 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
900 				  &min_vruntime_cb);
901 	avg_vruntime_sub(cfs_rq, se);
902 }
903 
__pick_root_entity(struct cfs_rq * cfs_rq)904 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
905 {
906 	struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
907 
908 	if (!root)
909 		return NULL;
910 
911 	return __node_2_se(root);
912 }
913 
__pick_first_entity(struct cfs_rq * cfs_rq)914 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
915 {
916 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
917 
918 	if (!left)
919 		return NULL;
920 
921 	return __node_2_se(left);
922 }
923 
924 /*
925  * HACK, stash a copy of deadline at the point of pick in vlag,
926  * which isn't used until dequeue.
927  */
set_protect_slice(struct sched_entity * se)928 static inline void set_protect_slice(struct sched_entity *se)
929 {
930 	se->vlag = se->deadline;
931 }
932 
protect_slice(struct sched_entity * se)933 static inline bool protect_slice(struct sched_entity *se)
934 {
935 	return se->vlag == se->deadline;
936 }
937 
cancel_protect_slice(struct sched_entity * se)938 static inline void cancel_protect_slice(struct sched_entity *se)
939 {
940 	if (protect_slice(se))
941 		se->vlag = se->deadline + 1;
942 }
943 
944 /*
945  * Earliest Eligible Virtual Deadline First
946  *
947  * In order to provide latency guarantees for different request sizes
948  * EEVDF selects the best runnable task from two criteria:
949  *
950  *  1) the task must be eligible (must be owed service)
951  *
952  *  2) from those tasks that meet 1), we select the one
953  *     with the earliest virtual deadline.
954  *
955  * We can do this in O(log n) time due to an augmented RB-tree. The
956  * tree keeps the entries sorted on deadline, but also functions as a
957  * heap based on the vruntime by keeping:
958  *
959  *  se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
960  *
961  * Which allows tree pruning through eligibility.
962  */
pick_eevdf(struct cfs_rq * cfs_rq)963 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
964 {
965 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
966 	struct sched_entity *se = __pick_first_entity(cfs_rq);
967 	struct sched_entity *curr = cfs_rq->curr;
968 	struct sched_entity *best = NULL;
969 
970 	/*
971 	 * We can safely skip eligibility check if there is only one entity
972 	 * in this cfs_rq, saving some cycles.
973 	 */
974 	if (cfs_rq->nr_running == 1)
975 		return curr && curr->on_rq ? curr : se;
976 
977 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
978 		curr = NULL;
979 
980 	if (sched_feat(RUN_TO_PARITY) && curr && protect_slice(curr))
981 		return curr;
982 
983 	/* Pick the leftmost entity if it's eligible */
984 	if (se && entity_eligible(cfs_rq, se)) {
985 		best = se;
986 		goto found;
987 	}
988 
989 	/* Heap search for the EEVD entity */
990 	while (node) {
991 		struct rb_node *left = node->rb_left;
992 
993 		/*
994 		 * Eligible entities in left subtree are always better
995 		 * choices, since they have earlier deadlines.
996 		 */
997 		if (left && vruntime_eligible(cfs_rq,
998 					__node_2_se(left)->min_vruntime)) {
999 			node = left;
1000 			continue;
1001 		}
1002 
1003 		se = __node_2_se(node);
1004 
1005 		/*
1006 		 * The left subtree either is empty or has no eligible
1007 		 * entity, so check the current node since it is the one
1008 		 * with earliest deadline that might be eligible.
1009 		 */
1010 		if (entity_eligible(cfs_rq, se)) {
1011 			best = se;
1012 			break;
1013 		}
1014 
1015 		node = node->rb_right;
1016 	}
1017 found:
1018 	if (!best || (curr && entity_before(curr, best)))
1019 		best = curr;
1020 
1021 	return best;
1022 }
1023 
1024 #ifdef CONFIG_SCHED_DEBUG
__pick_last_entity(struct cfs_rq * cfs_rq)1025 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1026 {
1027 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1028 
1029 	if (!last)
1030 		return NULL;
1031 
1032 	return __node_2_se(last);
1033 }
1034 
1035 /**************************************************************
1036  * Scheduling class statistics methods:
1037  */
1038 #ifdef CONFIG_SMP
sched_update_scaling(void)1039 int sched_update_scaling(void)
1040 {
1041 	unsigned int factor = get_update_sysctl_factor();
1042 
1043 #define WRT_SYSCTL(name) \
1044 	(normalized_sysctl_##name = sysctl_##name / (factor))
1045 	WRT_SYSCTL(sched_base_slice);
1046 #undef WRT_SYSCTL
1047 
1048 	return 0;
1049 }
1050 #endif
1051 #endif
1052 
1053 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1054 
1055 /*
1056  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1057  * this is probably good enough.
1058  */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1059 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1060 {
1061 	bool skip_preempt = false;
1062 
1063 	trace_android_rvh_update_deadline(cfs_rq, se, &skip_preempt);
1064 	if (skip_preempt)
1065 		return false;
1066 
1067 	if ((s64)(se->vruntime - se->deadline) < 0)
1068 		return false;
1069 
1070 	/*
1071 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1072 	 * nice) while the request time r_i is determined by
1073 	 * sysctl_sched_base_slice.
1074 	 */
1075 	if (!se->custom_slice)
1076 		se->slice = sysctl_sched_base_slice;
1077 
1078 	/*
1079 	 * EEVDF: vd_i = ve_i + r_i / w_i
1080 	 */
1081 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1082 
1083 	/*
1084 	 * The task has consumed its request, reschedule.
1085 	 */
1086 	return true;
1087 }
1088 
1089 #include "pelt.h"
1090 #ifdef CONFIG_SMP
1091 
1092 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1093 static unsigned long task_h_load(struct task_struct *p);
1094 static unsigned long capacity_of(int cpu);
1095 
1096 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1097 void init_entity_runnable_average(struct sched_entity *se)
1098 {
1099 	struct sched_avg *sa = &se->avg;
1100 
1101 	memset(sa, 0, sizeof(*sa));
1102 
1103 	/*
1104 	 * Tasks are initialized with full load to be seen as heavy tasks until
1105 	 * they get a chance to stabilize to their real load level.
1106 	 * Group entities are initialized with zero load to reflect the fact that
1107 	 * nothing has been attached to the task group yet.
1108 	 */
1109 	if (entity_is_task(se))
1110 		sa->load_avg = scale_load_down(se->load.weight);
1111 
1112 	/* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1113 }
1114 
1115 /*
1116  * With new tasks being created, their initial util_avgs are extrapolated
1117  * based on the cfs_rq's current util_avg:
1118  *
1119  *   util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1120  *		* se_weight(se)
1121  *
1122  * However, in many cases, the above util_avg does not give a desired
1123  * value. Moreover, the sum of the util_avgs may be divergent, such
1124  * as when the series is a harmonic series.
1125  *
1126  * To solve this problem, we also cap the util_avg of successive tasks to
1127  * only 1/2 of the left utilization budget:
1128  *
1129  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1130  *
1131  * where n denotes the nth task and cpu_scale the CPU capacity.
1132  *
1133  * For example, for a CPU with 1024 of capacity, a simplest series from
1134  * the beginning would be like:
1135  *
1136  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1137  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1138  *
1139  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1140  * if util_avg > util_avg_cap.
1141  */
post_init_entity_util_avg(struct task_struct * p)1142 void post_init_entity_util_avg(struct task_struct *p)
1143 {
1144 	struct sched_entity *se = &p->se;
1145 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1146 	struct sched_avg *sa = &se->avg;
1147 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1148 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1149 
1150 	if (p->sched_class != &fair_sched_class) {
1151 		/*
1152 		 * For !fair tasks do:
1153 		 *
1154 		update_cfs_rq_load_avg(now, cfs_rq);
1155 		attach_entity_load_avg(cfs_rq, se);
1156 		switched_from_fair(rq, p);
1157 		 *
1158 		 * such that the next switched_to_fair() has the
1159 		 * expected state.
1160 		 */
1161 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1162 		return;
1163 	}
1164 
1165 	if (cap > 0) {
1166 		if (cfs_rq->avg.util_avg != 0) {
1167 			sa->util_avg  = cfs_rq->avg.util_avg * se_weight(se);
1168 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1169 
1170 			if (sa->util_avg > cap)
1171 				sa->util_avg = cap;
1172 		} else {
1173 			sa->util_avg = cap;
1174 		}
1175 	}
1176 
1177 	sa->runnable_avg = sa->util_avg;
1178 
1179 	/* Hook before this se's util is attached to cfs_rq's util */
1180 	trace_android_rvh_post_init_entity_util_avg(se);
1181 }
1182 
1183 #else /* !CONFIG_SMP */
init_entity_runnable_average(struct sched_entity * se)1184 void init_entity_runnable_average(struct sched_entity *se)
1185 {
1186 }
post_init_entity_util_avg(struct task_struct * p)1187 void post_init_entity_util_avg(struct task_struct *p)
1188 {
1189 }
update_tg_load_avg(struct cfs_rq * cfs_rq)1190 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1191 {
1192 }
1193 #endif /* CONFIG_SMP */
1194 
update_se(struct rq * rq,struct sched_entity * se)1195 static s64 update_se(struct rq *rq, struct sched_entity *se)
1196 {
1197 	u64 now = rq_clock_task(rq);
1198 	s64 delta_exec;
1199 
1200 	delta_exec = now - se->exec_start;
1201 	if (unlikely(delta_exec <= 0))
1202 		return delta_exec;
1203 
1204 	se->exec_start = now;
1205 	if (entity_is_task(se)) {
1206 		struct task_struct *donor = task_of(se);
1207 		struct task_struct *running = rq->curr;
1208 		/*
1209 		 * If se is a task, we account the time against the running
1210 		 * task, as w/ proxy-exec they may not be the same.
1211 		 */
1212 		running->se.exec_start = now;
1213 		running->se.sum_exec_runtime += delta_exec;
1214 
1215 		trace_sched_stat_runtime(running, delta_exec);
1216 		account_group_exec_runtime(running, delta_exec);
1217 
1218 		/* cgroup time is always accounted against the donor */
1219 		cgroup_account_cputime(donor, delta_exec);
1220 	} else {
1221 		/* If not task, account the time against donor se  */
1222 		se->sum_exec_runtime += delta_exec;
1223 	}
1224 
1225 	if (schedstat_enabled()) {
1226 		struct sched_statistics *stats;
1227 
1228 		stats = __schedstats_from_se(se);
1229 		__schedstat_set(stats->exec_max,
1230 				max(delta_exec, stats->exec_max));
1231 	}
1232 
1233 	return delta_exec;
1234 }
1235 
did_preempt_short(struct cfs_rq * cfs_rq,struct sched_entity * curr)1236 static inline bool did_preempt_short(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1237 {
1238 	if (!sched_feat(PREEMPT_SHORT))
1239 		return false;
1240 
1241 	if (curr->vlag == curr->deadline)
1242 		return false;
1243 
1244 	return !entity_eligible(cfs_rq, curr);
1245 }
1246 
do_preempt_short(struct cfs_rq * cfs_rq,struct sched_entity * pse,struct sched_entity * se)1247 static inline bool do_preempt_short(struct cfs_rq *cfs_rq,
1248 				    struct sched_entity *pse, struct sched_entity *se)
1249 {
1250 	if (!sched_feat(PREEMPT_SHORT))
1251 		return false;
1252 
1253 	if (pse->slice >= se->slice)
1254 		return false;
1255 
1256 	if (!entity_eligible(cfs_rq, pse))
1257 		return false;
1258 
1259 	if (entity_before(pse, se))
1260 		return true;
1261 
1262 	if (!entity_eligible(cfs_rq, se))
1263 		return true;
1264 
1265 	return false;
1266 }
1267 
1268 /*
1269  * Used by other classes to account runtime.
1270  */
update_curr_common(struct rq * rq)1271 s64 update_curr_common(struct rq *rq)
1272 {
1273 	return update_se(rq, &rq->donor->se);
1274 }
1275 
1276 /*
1277  * Update the current task's runtime statistics.
1278  */
update_curr(struct cfs_rq * cfs_rq)1279 static void update_curr(struct cfs_rq *cfs_rq)
1280 {
1281 	/*
1282 	 * Note: cfs_rq->curr corresponds to the task picked to
1283 	 * run (ie: rq->donor.se) which due to proxy-exec may
1284 	 * not necessarily be the actual task running
1285 	 * (rq->curr.se). This is easy to confuse!
1286 	 */
1287 	struct sched_entity *curr = cfs_rq->curr;
1288 	struct rq *rq = rq_of(cfs_rq);
1289 	s64 delta_exec;
1290 	bool resched;
1291 
1292 	if (unlikely(!curr))
1293 		return;
1294 
1295 	delta_exec = update_se(rq, curr);
1296 	if (unlikely(delta_exec <= 0))
1297 		return;
1298 
1299 	curr->vruntime += calc_delta_fair(delta_exec, curr);
1300 	resched = update_deadline(cfs_rq, curr);
1301 	update_min_vruntime(cfs_rq);
1302 
1303 	if (entity_is_task(curr)) {
1304 		/*
1305 		 * If the fair_server is active, we need to account for the
1306 		 * fair_server time whether or not the task is running on
1307 		 * behalf of fair_server or not:
1308 		 *  - If the task is running on behalf of fair_server, we need
1309 		 *    to limit its time based on the assigned runtime.
1310 		 *  - Fair task that runs outside of fair_server should account
1311 		 *    against fair_server such that it can account for this time
1312 		 *    and possibly avoid running this period.
1313 		 */
1314 		if (dl_server_active(&rq->fair_server))
1315 			dl_server_update(&rq->fair_server, delta_exec);
1316 	}
1317 
1318 	account_cfs_rq_runtime(cfs_rq, delta_exec);
1319 
1320 	if (cfs_rq->nr_running == 1)
1321 		return;
1322 
1323 	if (resched || did_preempt_short(cfs_rq, curr)) {
1324 		resched_curr(rq);
1325 		clear_buddies(cfs_rq, curr);
1326 	}
1327 }
1328 
update_curr_fair(struct rq * rq)1329 static void update_curr_fair(struct rq *rq)
1330 {
1331 	update_curr(cfs_rq_of(&rq->donor->se));
1332 }
1333 
1334 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1335 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1336 {
1337 	struct sched_statistics *stats;
1338 	struct task_struct *p = NULL;
1339 
1340 	if (!schedstat_enabled())
1341 		return;
1342 
1343 	stats = __schedstats_from_se(se);
1344 
1345 	if (entity_is_task(se))
1346 		p = task_of(se);
1347 
1348 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
1349 }
1350 
1351 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1352 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1353 {
1354 	struct sched_statistics *stats;
1355 	struct task_struct *p = NULL;
1356 
1357 	if (!schedstat_enabled())
1358 		return;
1359 
1360 	stats = __schedstats_from_se(se);
1361 
1362 	/*
1363 	 * When the sched_schedstat changes from 0 to 1, some sched se
1364 	 * maybe already in the runqueue, the se->statistics.wait_start
1365 	 * will be 0.So it will let the delta wrong. We need to avoid this
1366 	 * scenario.
1367 	 */
1368 	if (unlikely(!schedstat_val(stats->wait_start)))
1369 		return;
1370 
1371 	if (entity_is_task(se))
1372 		p = task_of(se);
1373 
1374 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
1375 }
1376 
1377 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1378 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1379 {
1380 	struct sched_statistics *stats;
1381 	struct task_struct *tsk = NULL;
1382 
1383 	if (!schedstat_enabled())
1384 		return;
1385 
1386 	stats = __schedstats_from_se(se);
1387 
1388 	if (entity_is_task(se))
1389 		tsk = task_of(se);
1390 
1391 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1392 }
1393 
1394 /*
1395  * Task is being enqueued - update stats:
1396  */
1397 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1398 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1399 {
1400 	if (!schedstat_enabled())
1401 		return;
1402 
1403 	/*
1404 	 * Are we enqueueing a waiting task? (for current tasks
1405 	 * a dequeue/enqueue event is a NOP)
1406 	 */
1407 	if (se != cfs_rq->curr)
1408 		update_stats_wait_start_fair(cfs_rq, se);
1409 
1410 	if (flags & ENQUEUE_WAKEUP)
1411 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
1412 }
1413 
1414 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1415 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1416 {
1417 
1418 	if (!schedstat_enabled())
1419 		return;
1420 
1421 	/*
1422 	 * Mark the end of the wait period if dequeueing a
1423 	 * waiting task:
1424 	 */
1425 	if (se != cfs_rq->curr)
1426 		update_stats_wait_end_fair(cfs_rq, se);
1427 
1428 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1429 		struct task_struct *tsk = task_of(se);
1430 		unsigned int state;
1431 
1432 		/* XXX racy against TTWU */
1433 		state = READ_ONCE(tsk->__state);
1434 		if (state & TASK_INTERRUPTIBLE)
1435 			__schedstat_set(tsk->stats.sleep_start,
1436 				      rq_clock(rq_of(cfs_rq)));
1437 		if (state & TASK_UNINTERRUPTIBLE)
1438 			__schedstat_set(tsk->stats.block_start,
1439 				      rq_clock(rq_of(cfs_rq)));
1440 	}
1441 }
1442 
1443 /*
1444  * We are picking a new current task - update its stats:
1445  */
1446 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1447 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1448 {
1449 	/*
1450 	 * We are starting a new run period:
1451 	 */
1452 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
1453 }
1454 
1455 /**************************************************
1456  * Scheduling class queueing methods:
1457  */
1458 
is_core_idle(int cpu)1459 static inline bool is_core_idle(int cpu)
1460 {
1461 #ifdef CONFIG_SCHED_SMT
1462 	int sibling;
1463 
1464 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1465 		if (cpu == sibling)
1466 			continue;
1467 
1468 		if (!idle_cpu(sibling))
1469 			return false;
1470 	}
1471 #endif
1472 
1473 	return true;
1474 }
1475 
1476 #ifdef CONFIG_NUMA
1477 #define NUMA_IMBALANCE_MIN 2
1478 
1479 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1480 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1481 {
1482 	/*
1483 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1484 	 * threshold. Above this threshold, individual tasks may be contending
1485 	 * for both memory bandwidth and any shared HT resources.  This is an
1486 	 * approximation as the number of running tasks may not be related to
1487 	 * the number of busy CPUs due to sched_setaffinity.
1488 	 */
1489 	if (dst_running > imb_numa_nr)
1490 		return imbalance;
1491 
1492 	/*
1493 	 * Allow a small imbalance based on a simple pair of communicating
1494 	 * tasks that remain local when the destination is lightly loaded.
1495 	 */
1496 	if (imbalance <= NUMA_IMBALANCE_MIN)
1497 		return 0;
1498 
1499 	return imbalance;
1500 }
1501 #endif /* CONFIG_NUMA */
1502 
1503 #ifdef CONFIG_NUMA_BALANCING
1504 /*
1505  * Approximate time to scan a full NUMA task in ms. The task scan period is
1506  * calculated based on the tasks virtual memory size and
1507  * numa_balancing_scan_size.
1508  */
1509 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1510 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1511 
1512 /* Portion of address space to scan in MB */
1513 unsigned int sysctl_numa_balancing_scan_size = 256;
1514 
1515 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1516 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1517 
1518 /* The page with hint page fault latency < threshold in ms is considered hot */
1519 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1520 
1521 struct numa_group {
1522 	refcount_t refcount;
1523 
1524 	spinlock_t lock; /* nr_tasks, tasks */
1525 	int nr_tasks;
1526 	pid_t gid;
1527 	int active_nodes;
1528 
1529 	struct rcu_head rcu;
1530 	unsigned long total_faults;
1531 	unsigned long max_faults_cpu;
1532 	/*
1533 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
1534 	 *
1535 	 * Faults_cpu is used to decide whether memory should move
1536 	 * towards the CPU. As a consequence, these stats are weighted
1537 	 * more by CPU use than by memory faults.
1538 	 */
1539 	unsigned long faults[];
1540 };
1541 
1542 /*
1543  * For functions that can be called in multiple contexts that permit reading
1544  * ->numa_group (see struct task_struct for locking rules).
1545  */
deref_task_numa_group(struct task_struct * p)1546 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1547 {
1548 	return rcu_dereference_check(p->numa_group, p == current ||
1549 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1550 }
1551 
deref_curr_numa_group(struct task_struct * p)1552 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1553 {
1554 	return rcu_dereference_protected(p->numa_group, p == current);
1555 }
1556 
1557 static inline unsigned long group_faults_priv(struct numa_group *ng);
1558 static inline unsigned long group_faults_shared(struct numa_group *ng);
1559 
task_nr_scan_windows(struct task_struct * p)1560 static unsigned int task_nr_scan_windows(struct task_struct *p)
1561 {
1562 	unsigned long rss = 0;
1563 	unsigned long nr_scan_pages;
1564 
1565 	/*
1566 	 * Calculations based on RSS as non-present and empty pages are skipped
1567 	 * by the PTE scanner and NUMA hinting faults should be trapped based
1568 	 * on resident pages
1569 	 */
1570 	nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1571 	rss = get_mm_rss(p->mm);
1572 	if (!rss)
1573 		rss = nr_scan_pages;
1574 
1575 	rss = round_up(rss, nr_scan_pages);
1576 	return rss / nr_scan_pages;
1577 }
1578 
1579 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1580 #define MAX_SCAN_WINDOW 2560
1581 
task_scan_min(struct task_struct * p)1582 static unsigned int task_scan_min(struct task_struct *p)
1583 {
1584 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1585 	unsigned int scan, floor;
1586 	unsigned int windows = 1;
1587 
1588 	if (scan_size < MAX_SCAN_WINDOW)
1589 		windows = MAX_SCAN_WINDOW / scan_size;
1590 	floor = 1000 / windows;
1591 
1592 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1593 	return max_t(unsigned int, floor, scan);
1594 }
1595 
task_scan_start(struct task_struct * p)1596 static unsigned int task_scan_start(struct task_struct *p)
1597 {
1598 	unsigned long smin = task_scan_min(p);
1599 	unsigned long period = smin;
1600 	struct numa_group *ng;
1601 
1602 	/* Scale the maximum scan period with the amount of shared memory. */
1603 	rcu_read_lock();
1604 	ng = rcu_dereference(p->numa_group);
1605 	if (ng) {
1606 		unsigned long shared = group_faults_shared(ng);
1607 		unsigned long private = group_faults_priv(ng);
1608 
1609 		period *= refcount_read(&ng->refcount);
1610 		period *= shared + 1;
1611 		period /= private + shared + 1;
1612 	}
1613 	rcu_read_unlock();
1614 
1615 	return max(smin, period);
1616 }
1617 
task_scan_max(struct task_struct * p)1618 static unsigned int task_scan_max(struct task_struct *p)
1619 {
1620 	unsigned long smin = task_scan_min(p);
1621 	unsigned long smax;
1622 	struct numa_group *ng;
1623 
1624 	/* Watch for min being lower than max due to floor calculations */
1625 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1626 
1627 	/* Scale the maximum scan period with the amount of shared memory. */
1628 	ng = deref_curr_numa_group(p);
1629 	if (ng) {
1630 		unsigned long shared = group_faults_shared(ng);
1631 		unsigned long private = group_faults_priv(ng);
1632 		unsigned long period = smax;
1633 
1634 		period *= refcount_read(&ng->refcount);
1635 		period *= shared + 1;
1636 		period /= private + shared + 1;
1637 
1638 		smax = max(smax, period);
1639 	}
1640 
1641 	return max(smin, smax);
1642 }
1643 
account_numa_enqueue(struct rq * rq,struct task_struct * p)1644 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1645 {
1646 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1647 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1648 }
1649 
account_numa_dequeue(struct rq * rq,struct task_struct * p)1650 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1651 {
1652 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1653 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1654 }
1655 
1656 /* Shared or private faults. */
1657 #define NR_NUMA_HINT_FAULT_TYPES 2
1658 
1659 /* Memory and CPU locality */
1660 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1661 
1662 /* Averaged statistics, and temporary buffers. */
1663 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1664 
task_numa_group_id(struct task_struct * p)1665 pid_t task_numa_group_id(struct task_struct *p)
1666 {
1667 	struct numa_group *ng;
1668 	pid_t gid = 0;
1669 
1670 	rcu_read_lock();
1671 	ng = rcu_dereference(p->numa_group);
1672 	if (ng)
1673 		gid = ng->gid;
1674 	rcu_read_unlock();
1675 
1676 	return gid;
1677 }
1678 
1679 /*
1680  * The averaged statistics, shared & private, memory & CPU,
1681  * occupy the first half of the array. The second half of the
1682  * array is for current counters, which are averaged into the
1683  * first set by task_numa_placement.
1684  */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1685 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1686 {
1687 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1688 }
1689 
task_faults(struct task_struct * p,int nid)1690 static inline unsigned long task_faults(struct task_struct *p, int nid)
1691 {
1692 	if (!p->numa_faults)
1693 		return 0;
1694 
1695 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1696 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1697 }
1698 
group_faults(struct task_struct * p,int nid)1699 static inline unsigned long group_faults(struct task_struct *p, int nid)
1700 {
1701 	struct numa_group *ng = deref_task_numa_group(p);
1702 
1703 	if (!ng)
1704 		return 0;
1705 
1706 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1707 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1708 }
1709 
group_faults_cpu(struct numa_group * group,int nid)1710 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1711 {
1712 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1713 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1714 }
1715 
group_faults_priv(struct numa_group * ng)1716 static inline unsigned long group_faults_priv(struct numa_group *ng)
1717 {
1718 	unsigned long faults = 0;
1719 	int node;
1720 
1721 	for_each_online_node(node) {
1722 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1723 	}
1724 
1725 	return faults;
1726 }
1727 
group_faults_shared(struct numa_group * ng)1728 static inline unsigned long group_faults_shared(struct numa_group *ng)
1729 {
1730 	unsigned long faults = 0;
1731 	int node;
1732 
1733 	for_each_online_node(node) {
1734 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1735 	}
1736 
1737 	return faults;
1738 }
1739 
1740 /*
1741  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1742  * considered part of a numa group's pseudo-interleaving set. Migrations
1743  * between these nodes are slowed down, to allow things to settle down.
1744  */
1745 #define ACTIVE_NODE_FRACTION 3
1746 
numa_is_active_node(int nid,struct numa_group * ng)1747 static bool numa_is_active_node(int nid, struct numa_group *ng)
1748 {
1749 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1750 }
1751 
1752 /* 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)1753 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1754 					int lim_dist, bool task)
1755 {
1756 	unsigned long score = 0;
1757 	int node, max_dist;
1758 
1759 	/*
1760 	 * All nodes are directly connected, and the same distance
1761 	 * from each other. No need for fancy placement algorithms.
1762 	 */
1763 	if (sched_numa_topology_type == NUMA_DIRECT)
1764 		return 0;
1765 
1766 	/* sched_max_numa_distance may be changed in parallel. */
1767 	max_dist = READ_ONCE(sched_max_numa_distance);
1768 	/*
1769 	 * This code is called for each node, introducing N^2 complexity,
1770 	 * which should be OK given the number of nodes rarely exceeds 8.
1771 	 */
1772 	for_each_online_node(node) {
1773 		unsigned long faults;
1774 		int dist = node_distance(nid, node);
1775 
1776 		/*
1777 		 * The furthest away nodes in the system are not interesting
1778 		 * for placement; nid was already counted.
1779 		 */
1780 		if (dist >= max_dist || node == nid)
1781 			continue;
1782 
1783 		/*
1784 		 * On systems with a backplane NUMA topology, compare groups
1785 		 * of nodes, and move tasks towards the group with the most
1786 		 * memory accesses. When comparing two nodes at distance
1787 		 * "hoplimit", only nodes closer by than "hoplimit" are part
1788 		 * of each group. Skip other nodes.
1789 		 */
1790 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1791 			continue;
1792 
1793 		/* Add up the faults from nearby nodes. */
1794 		if (task)
1795 			faults = task_faults(p, node);
1796 		else
1797 			faults = group_faults(p, node);
1798 
1799 		/*
1800 		 * On systems with a glueless mesh NUMA topology, there are
1801 		 * no fixed "groups of nodes". Instead, nodes that are not
1802 		 * directly connected bounce traffic through intermediate
1803 		 * nodes; a numa_group can occupy any set of nodes.
1804 		 * The further away a node is, the less the faults count.
1805 		 * This seems to result in good task placement.
1806 		 */
1807 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1808 			faults *= (max_dist - dist);
1809 			faults /= (max_dist - LOCAL_DISTANCE);
1810 		}
1811 
1812 		score += faults;
1813 	}
1814 
1815 	return score;
1816 }
1817 
1818 /*
1819  * These return the fraction of accesses done by a particular task, or
1820  * task group, on a particular numa node.  The group weight is given a
1821  * larger multiplier, in order to group tasks together that are almost
1822  * evenly spread out between numa nodes.
1823  */
task_weight(struct task_struct * p,int nid,int dist)1824 static inline unsigned long task_weight(struct task_struct *p, int nid,
1825 					int dist)
1826 {
1827 	unsigned long faults, total_faults;
1828 
1829 	if (!p->numa_faults)
1830 		return 0;
1831 
1832 	total_faults = p->total_numa_faults;
1833 
1834 	if (!total_faults)
1835 		return 0;
1836 
1837 	faults = task_faults(p, nid);
1838 	faults += score_nearby_nodes(p, nid, dist, true);
1839 
1840 	return 1000 * faults / total_faults;
1841 }
1842 
group_weight(struct task_struct * p,int nid,int dist)1843 static inline unsigned long group_weight(struct task_struct *p, int nid,
1844 					 int dist)
1845 {
1846 	struct numa_group *ng = deref_task_numa_group(p);
1847 	unsigned long faults, total_faults;
1848 
1849 	if (!ng)
1850 		return 0;
1851 
1852 	total_faults = ng->total_faults;
1853 
1854 	if (!total_faults)
1855 		return 0;
1856 
1857 	faults = group_faults(p, nid);
1858 	faults += score_nearby_nodes(p, nid, dist, false);
1859 
1860 	return 1000 * faults / total_faults;
1861 }
1862 
1863 /*
1864  * If memory tiering mode is enabled, cpupid of slow memory page is
1865  * used to record scan time instead of CPU and PID.  When tiering mode
1866  * is disabled at run time, the scan time (in cpupid) will be
1867  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
1868  * access out of array bound.
1869  */
cpupid_valid(int cpupid)1870 static inline bool cpupid_valid(int cpupid)
1871 {
1872 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1873 }
1874 
1875 /*
1876  * For memory tiering mode, if there are enough free pages (more than
1877  * enough watermark defined here) in fast memory node, to take full
1878  * advantage of fast memory capacity, all recently accessed slow
1879  * memory pages will be migrated to fast memory node without
1880  * considering hot threshold.
1881  */
pgdat_free_space_enough(struct pglist_data * pgdat)1882 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1883 {
1884 	int z;
1885 	unsigned long enough_wmark;
1886 
1887 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1888 			   pgdat->node_present_pages >> 4);
1889 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1890 		struct zone *zone = pgdat->node_zones + z;
1891 
1892 		if (!populated_zone(zone))
1893 			continue;
1894 
1895 		if (zone_watermark_ok(zone, 0,
1896 				      promo_wmark_pages(zone) + enough_wmark,
1897 				      ZONE_MOVABLE, 0))
1898 			return true;
1899 	}
1900 	return false;
1901 }
1902 
1903 /*
1904  * For memory tiering mode, when page tables are scanned, the scan
1905  * time will be recorded in struct page in addition to make page
1906  * PROT_NONE for slow memory page.  So when the page is accessed, in
1907  * hint page fault handler, the hint page fault latency is calculated
1908  * via,
1909  *
1910  *	hint page fault latency = hint page fault time - scan time
1911  *
1912  * The smaller the hint page fault latency, the higher the possibility
1913  * for the page to be hot.
1914  */
numa_hint_fault_latency(struct folio * folio)1915 static int numa_hint_fault_latency(struct folio *folio)
1916 {
1917 	int last_time, time;
1918 
1919 	time = jiffies_to_msecs(jiffies);
1920 	last_time = folio_xchg_access_time(folio, time);
1921 
1922 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1923 }
1924 
1925 /*
1926  * For memory tiering mode, too high promotion/demotion throughput may
1927  * hurt application latency.  So we provide a mechanism to rate limit
1928  * the number of pages that are tried to be promoted.
1929  */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1930 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1931 				      unsigned long rate_limit, int nr)
1932 {
1933 	unsigned long nr_cand;
1934 	unsigned int now, start;
1935 
1936 	now = jiffies_to_msecs(jiffies);
1937 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1938 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1939 	start = pgdat->nbp_rl_start;
1940 	if (now - start > MSEC_PER_SEC &&
1941 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1942 		pgdat->nbp_rl_nr_cand = nr_cand;
1943 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1944 		return true;
1945 	return false;
1946 }
1947 
1948 #define NUMA_MIGRATION_ADJUST_STEPS	16
1949 
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1950 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1951 					    unsigned long rate_limit,
1952 					    unsigned int ref_th)
1953 {
1954 	unsigned int now, start, th_period, unit_th, th;
1955 	unsigned long nr_cand, ref_cand, diff_cand;
1956 
1957 	now = jiffies_to_msecs(jiffies);
1958 	th_period = sysctl_numa_balancing_scan_period_max;
1959 	start = pgdat->nbp_th_start;
1960 	if (now - start > th_period &&
1961 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1962 		ref_cand = rate_limit *
1963 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1964 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1965 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1966 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1967 		th = pgdat->nbp_threshold ? : ref_th;
1968 		if (diff_cand > ref_cand * 11 / 10)
1969 			th = max(th - unit_th, unit_th);
1970 		else if (diff_cand < ref_cand * 9 / 10)
1971 			th = min(th + unit_th, ref_th * 2);
1972 		pgdat->nbp_th_nr_cand = nr_cand;
1973 		pgdat->nbp_threshold = th;
1974 	}
1975 }
1976 
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)1977 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1978 				int src_nid, int dst_cpu)
1979 {
1980 	struct numa_group *ng = deref_curr_numa_group(p);
1981 	int dst_nid = cpu_to_node(dst_cpu);
1982 	int last_cpupid, this_cpupid;
1983 
1984 	/*
1985 	 * Cannot migrate to memoryless nodes.
1986 	 */
1987 	if (!node_state(dst_nid, N_MEMORY))
1988 		return false;
1989 
1990 	/*
1991 	 * The pages in slow memory node should be migrated according
1992 	 * to hot/cold instead of private/shared.
1993 	 */
1994 	if (folio_use_access_time(folio)) {
1995 		struct pglist_data *pgdat;
1996 		unsigned long rate_limit;
1997 		unsigned int latency, th, def_th;
1998 
1999 		pgdat = NODE_DATA(dst_nid);
2000 		if (pgdat_free_space_enough(pgdat)) {
2001 			/* workload changed, reset hot threshold */
2002 			pgdat->nbp_threshold = 0;
2003 			return true;
2004 		}
2005 
2006 		def_th = sysctl_numa_balancing_hot_threshold;
2007 		rate_limit = sysctl_numa_balancing_promote_rate_limit << \
2008 			(20 - PAGE_SHIFT);
2009 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
2010 
2011 		th = pgdat->nbp_threshold ? : def_th;
2012 		latency = numa_hint_fault_latency(folio);
2013 		if (latency >= th)
2014 			return false;
2015 
2016 		return !numa_promotion_rate_limit(pgdat, rate_limit,
2017 						  folio_nr_pages(folio));
2018 	}
2019 
2020 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
2021 	last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
2022 
2023 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
2024 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
2025 		return false;
2026 
2027 	/*
2028 	 * Allow first faults or private faults to migrate immediately early in
2029 	 * the lifetime of a task. The magic number 4 is based on waiting for
2030 	 * two full passes of the "multi-stage node selection" test that is
2031 	 * executed below.
2032 	 */
2033 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
2034 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
2035 		return true;
2036 
2037 	/*
2038 	 * Multi-stage node selection is used in conjunction with a periodic
2039 	 * migration fault to build a temporal task<->page relation. By using
2040 	 * a two-stage filter we remove short/unlikely relations.
2041 	 *
2042 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2043 	 * a task's usage of a particular page (n_p) per total usage of this
2044 	 * page (n_t) (in a given time-span) to a probability.
2045 	 *
2046 	 * Our periodic faults will sample this probability and getting the
2047 	 * same result twice in a row, given these samples are fully
2048 	 * independent, is then given by P(n)^2, provided our sample period
2049 	 * is sufficiently short compared to the usage pattern.
2050 	 *
2051 	 * This quadric squishes small probabilities, making it less likely we
2052 	 * act on an unlikely task<->page relation.
2053 	 */
2054 	if (!cpupid_pid_unset(last_cpupid) &&
2055 				cpupid_to_nid(last_cpupid) != dst_nid)
2056 		return false;
2057 
2058 	/* Always allow migrate on private faults */
2059 	if (cpupid_match_pid(p, last_cpupid))
2060 		return true;
2061 
2062 	/* A shared fault, but p->numa_group has not been set up yet. */
2063 	if (!ng)
2064 		return true;
2065 
2066 	/*
2067 	 * Destination node is much more heavily used than the source
2068 	 * node? Allow migration.
2069 	 */
2070 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2071 					ACTIVE_NODE_FRACTION)
2072 		return true;
2073 
2074 	/*
2075 	 * Distribute memory according to CPU & memory use on each node,
2076 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2077 	 *
2078 	 * faults_cpu(dst)   3   faults_cpu(src)
2079 	 * --------------- * - > ---------------
2080 	 * faults_mem(dst)   4   faults_mem(src)
2081 	 */
2082 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2083 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2084 }
2085 
2086 /*
2087  * 'numa_type' describes the node at the moment of load balancing.
2088  */
2089 enum numa_type {
2090 	/* The node has spare capacity that can be used to run more tasks.  */
2091 	node_has_spare = 0,
2092 	/*
2093 	 * The node is fully used and the tasks don't compete for more CPU
2094 	 * cycles. Nevertheless, some tasks might wait before running.
2095 	 */
2096 	node_fully_busy,
2097 	/*
2098 	 * The node is overloaded and can't provide expected CPU cycles to all
2099 	 * tasks.
2100 	 */
2101 	node_overloaded
2102 };
2103 
2104 /* Cached statistics for all CPUs within a node */
2105 struct numa_stats {
2106 	unsigned long load;
2107 	unsigned long runnable;
2108 	unsigned long util;
2109 	/* Total compute capacity of CPUs on a node */
2110 	unsigned long compute_capacity;
2111 	unsigned int nr_running;
2112 	unsigned int weight;
2113 	enum numa_type node_type;
2114 	int idle_cpu;
2115 };
2116 
2117 struct task_numa_env {
2118 	struct task_struct *p;
2119 
2120 	int src_cpu, src_nid;
2121 	int dst_cpu, dst_nid;
2122 	int imb_numa_nr;
2123 
2124 	struct numa_stats src_stats, dst_stats;
2125 
2126 	int imbalance_pct;
2127 	int dist;
2128 
2129 	struct task_struct *best_task;
2130 	long best_imp;
2131 	int best_cpu;
2132 };
2133 
2134 static unsigned long cpu_load(struct rq *rq);
2135 static unsigned long cpu_runnable(struct rq *rq);
2136 
2137 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2138 numa_type numa_classify(unsigned int imbalance_pct,
2139 			 struct numa_stats *ns)
2140 {
2141 	if ((ns->nr_running > ns->weight) &&
2142 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2143 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2144 		return node_overloaded;
2145 
2146 	if ((ns->nr_running < ns->weight) ||
2147 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2148 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2149 		return node_has_spare;
2150 
2151 	return node_fully_busy;
2152 }
2153 
2154 #ifdef CONFIG_SCHED_SMT
2155 /* Forward declarations of select_idle_sibling helpers */
2156 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2157 static inline int numa_idle_core(int idle_core, int cpu)
2158 {
2159 	if (!static_branch_likely(&sched_smt_present) ||
2160 	    idle_core >= 0 || !test_idle_cores(cpu))
2161 		return idle_core;
2162 
2163 	/*
2164 	 * Prefer cores instead of packing HT siblings
2165 	 * and triggering future load balancing.
2166 	 */
2167 	if (is_core_idle(cpu))
2168 		idle_core = cpu;
2169 
2170 	return idle_core;
2171 }
2172 #else
numa_idle_core(int idle_core,int cpu)2173 static inline int numa_idle_core(int idle_core, int cpu)
2174 {
2175 	return idle_core;
2176 }
2177 #endif
2178 
2179 /*
2180  * Gather all necessary information to make NUMA balancing placement
2181  * decisions that are compatible with standard load balancer. This
2182  * borrows code and logic from update_sg_lb_stats but sharing a
2183  * common implementation is impractical.
2184  */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2185 static void update_numa_stats(struct task_numa_env *env,
2186 			      struct numa_stats *ns, int nid,
2187 			      bool find_idle)
2188 {
2189 	int cpu, idle_core = -1;
2190 
2191 	memset(ns, 0, sizeof(*ns));
2192 	ns->idle_cpu = -1;
2193 
2194 	rcu_read_lock();
2195 	for_each_cpu(cpu, cpumask_of_node(nid)) {
2196 		struct rq *rq = cpu_rq(cpu);
2197 
2198 		ns->load += cpu_load(rq);
2199 		ns->runnable += cpu_runnable(rq);
2200 		ns->util += cpu_util_cfs(cpu);
2201 		ns->nr_running += rq->cfs.h_nr_running;
2202 		ns->compute_capacity += capacity_of(cpu);
2203 
2204 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2205 			if (READ_ONCE(rq->numa_migrate_on) ||
2206 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2207 				continue;
2208 
2209 			if (ns->idle_cpu == -1)
2210 				ns->idle_cpu = cpu;
2211 
2212 			idle_core = numa_idle_core(idle_core, cpu);
2213 		}
2214 	}
2215 	rcu_read_unlock();
2216 
2217 	ns->weight = cpumask_weight(cpumask_of_node(nid));
2218 
2219 	ns->node_type = numa_classify(env->imbalance_pct, ns);
2220 
2221 	if (idle_core >= 0)
2222 		ns->idle_cpu = idle_core;
2223 }
2224 
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2225 static void task_numa_assign(struct task_numa_env *env,
2226 			     struct task_struct *p, long imp)
2227 {
2228 	struct rq *rq = cpu_rq(env->dst_cpu);
2229 
2230 	/* Check if run-queue part of active NUMA balance. */
2231 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2232 		int cpu;
2233 		int start = env->dst_cpu;
2234 
2235 		/* Find alternative idle CPU. */
2236 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2237 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2238 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2239 				continue;
2240 			}
2241 
2242 			env->dst_cpu = cpu;
2243 			rq = cpu_rq(env->dst_cpu);
2244 			if (!xchg(&rq->numa_migrate_on, 1))
2245 				goto assign;
2246 		}
2247 
2248 		/* Failed to find an alternative idle CPU */
2249 		return;
2250 	}
2251 
2252 assign:
2253 	/*
2254 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
2255 	 * found a better CPU to move/swap.
2256 	 */
2257 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2258 		rq = cpu_rq(env->best_cpu);
2259 		WRITE_ONCE(rq->numa_migrate_on, 0);
2260 	}
2261 
2262 	if (env->best_task)
2263 		put_task_struct(env->best_task);
2264 	if (p)
2265 		get_task_struct(p);
2266 
2267 	env->best_task = p;
2268 	env->best_imp = imp;
2269 	env->best_cpu = env->dst_cpu;
2270 }
2271 
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2272 static bool load_too_imbalanced(long src_load, long dst_load,
2273 				struct task_numa_env *env)
2274 {
2275 	long imb, old_imb;
2276 	long orig_src_load, orig_dst_load;
2277 	long src_capacity, dst_capacity;
2278 
2279 	/*
2280 	 * The load is corrected for the CPU capacity available on each node.
2281 	 *
2282 	 * src_load        dst_load
2283 	 * ------------ vs ---------
2284 	 * src_capacity    dst_capacity
2285 	 */
2286 	src_capacity = env->src_stats.compute_capacity;
2287 	dst_capacity = env->dst_stats.compute_capacity;
2288 
2289 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2290 
2291 	orig_src_load = env->src_stats.load;
2292 	orig_dst_load = env->dst_stats.load;
2293 
2294 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2295 
2296 	/* Would this change make things worse? */
2297 	return (imb > old_imb);
2298 }
2299 
2300 /*
2301  * Maximum NUMA importance can be 1998 (2*999);
2302  * SMALLIMP @ 30 would be close to 1998/64.
2303  * Used to deter task migration.
2304  */
2305 #define SMALLIMP	30
2306 
2307 /*
2308  * This checks if the overall compute and NUMA accesses of the system would
2309  * be improved if the source tasks was migrated to the target dst_cpu taking
2310  * into account that it might be best if task running on the dst_cpu should
2311  * be exchanged with the source task
2312  */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2313 static bool task_numa_compare(struct task_numa_env *env,
2314 			      long taskimp, long groupimp, bool maymove)
2315 {
2316 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2317 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
2318 	long imp = p_ng ? groupimp : taskimp;
2319 	struct task_struct *cur;
2320 	long src_load, dst_load;
2321 	int dist = env->dist;
2322 	long moveimp = imp;
2323 	long load;
2324 	bool stopsearch = false;
2325 
2326 	if (READ_ONCE(dst_rq->numa_migrate_on))
2327 		return false;
2328 
2329 	rcu_read_lock();
2330 	cur = rcu_dereference(dst_rq->curr);
2331 	if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2332 		cur = NULL;
2333 
2334 	/*
2335 	 * Because we have preemption enabled we can get migrated around and
2336 	 * end try selecting ourselves (current == env->p) as a swap candidate.
2337 	 */
2338 	if (cur == env->p) {
2339 		stopsearch = true;
2340 		goto unlock;
2341 	}
2342 
2343 	if (!cur) {
2344 		if (maymove && moveimp >= env->best_imp)
2345 			goto assign;
2346 		else
2347 			goto unlock;
2348 	}
2349 
2350 	/* Skip this swap candidate if cannot move to the source cpu. */
2351 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2352 		goto unlock;
2353 
2354 	/*
2355 	 * Skip this swap candidate if it is not moving to its preferred
2356 	 * node and the best task is.
2357 	 */
2358 	if (env->best_task &&
2359 	    env->best_task->numa_preferred_nid == env->src_nid &&
2360 	    cur->numa_preferred_nid != env->src_nid) {
2361 		goto unlock;
2362 	}
2363 
2364 	/*
2365 	 * "imp" is the fault differential for the source task between the
2366 	 * source and destination node. Calculate the total differential for
2367 	 * the source task and potential destination task. The more negative
2368 	 * the value is, the more remote accesses that would be expected to
2369 	 * be incurred if the tasks were swapped.
2370 	 *
2371 	 * If dst and source tasks are in the same NUMA group, or not
2372 	 * in any group then look only at task weights.
2373 	 */
2374 	cur_ng = rcu_dereference(cur->numa_group);
2375 	if (cur_ng == p_ng) {
2376 		/*
2377 		 * Do not swap within a group or between tasks that have
2378 		 * no group if there is spare capacity. Swapping does
2379 		 * not address the load imbalance and helps one task at
2380 		 * the cost of punishing another.
2381 		 */
2382 		if (env->dst_stats.node_type == node_has_spare)
2383 			goto unlock;
2384 
2385 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
2386 		      task_weight(cur, env->dst_nid, dist);
2387 		/*
2388 		 * Add some hysteresis to prevent swapping the
2389 		 * tasks within a group over tiny differences.
2390 		 */
2391 		if (cur_ng)
2392 			imp -= imp / 16;
2393 	} else {
2394 		/*
2395 		 * Compare the group weights. If a task is all by itself
2396 		 * (not part of a group), use the task weight instead.
2397 		 */
2398 		if (cur_ng && p_ng)
2399 			imp += group_weight(cur, env->src_nid, dist) -
2400 			       group_weight(cur, env->dst_nid, dist);
2401 		else
2402 			imp += task_weight(cur, env->src_nid, dist) -
2403 			       task_weight(cur, env->dst_nid, dist);
2404 	}
2405 
2406 	/* Discourage picking a task already on its preferred node */
2407 	if (cur->numa_preferred_nid == env->dst_nid)
2408 		imp -= imp / 16;
2409 
2410 	/*
2411 	 * Encourage picking a task that moves to its preferred node.
2412 	 * This potentially makes imp larger than it's maximum of
2413 	 * 1998 (see SMALLIMP and task_weight for why) but in this
2414 	 * case, it does not matter.
2415 	 */
2416 	if (cur->numa_preferred_nid == env->src_nid)
2417 		imp += imp / 8;
2418 
2419 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
2420 		imp = moveimp;
2421 		cur = NULL;
2422 		goto assign;
2423 	}
2424 
2425 	/*
2426 	 * Prefer swapping with a task moving to its preferred node over a
2427 	 * task that is not.
2428 	 */
2429 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2430 	    env->best_task->numa_preferred_nid != env->src_nid) {
2431 		goto assign;
2432 	}
2433 
2434 	/*
2435 	 * If the NUMA importance is less than SMALLIMP,
2436 	 * task migration might only result in ping pong
2437 	 * of tasks and also hurt performance due to cache
2438 	 * misses.
2439 	 */
2440 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2441 		goto unlock;
2442 
2443 	/*
2444 	 * In the overloaded case, try and keep the load balanced.
2445 	 */
2446 	load = task_h_load(env->p) - task_h_load(cur);
2447 	if (!load)
2448 		goto assign;
2449 
2450 	dst_load = env->dst_stats.load + load;
2451 	src_load = env->src_stats.load - load;
2452 
2453 	if (load_too_imbalanced(src_load, dst_load, env))
2454 		goto unlock;
2455 
2456 assign:
2457 	/* Evaluate an idle CPU for a task numa move. */
2458 	if (!cur) {
2459 		int cpu = env->dst_stats.idle_cpu;
2460 
2461 		/* Nothing cached so current CPU went idle since the search. */
2462 		if (cpu < 0)
2463 			cpu = env->dst_cpu;
2464 
2465 		/*
2466 		 * If the CPU is no longer truly idle and the previous best CPU
2467 		 * is, keep using it.
2468 		 */
2469 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2470 		    idle_cpu(env->best_cpu)) {
2471 			cpu = env->best_cpu;
2472 		}
2473 
2474 		env->dst_cpu = cpu;
2475 	}
2476 
2477 	task_numa_assign(env, cur, imp);
2478 
2479 	/*
2480 	 * If a move to idle is allowed because there is capacity or load
2481 	 * balance improves then stop the search. While a better swap
2482 	 * candidate may exist, a search is not free.
2483 	 */
2484 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2485 		stopsearch = true;
2486 
2487 	/*
2488 	 * If a swap candidate must be identified and the current best task
2489 	 * moves its preferred node then stop the search.
2490 	 */
2491 	if (!maymove && env->best_task &&
2492 	    env->best_task->numa_preferred_nid == env->src_nid) {
2493 		stopsearch = true;
2494 	}
2495 unlock:
2496 	rcu_read_unlock();
2497 
2498 	return stopsearch;
2499 }
2500 
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2501 static void task_numa_find_cpu(struct task_numa_env *env,
2502 				long taskimp, long groupimp)
2503 {
2504 	bool maymove = false;
2505 	int cpu;
2506 
2507 	/*
2508 	 * If dst node has spare capacity, then check if there is an
2509 	 * imbalance that would be overruled by the load balancer.
2510 	 */
2511 	if (env->dst_stats.node_type == node_has_spare) {
2512 		unsigned int imbalance;
2513 		int src_running, dst_running;
2514 
2515 		/*
2516 		 * Would movement cause an imbalance? Note that if src has
2517 		 * more running tasks that the imbalance is ignored as the
2518 		 * move improves the imbalance from the perspective of the
2519 		 * CPU load balancer.
2520 		 * */
2521 		src_running = env->src_stats.nr_running - 1;
2522 		dst_running = env->dst_stats.nr_running + 1;
2523 		imbalance = max(0, dst_running - src_running);
2524 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
2525 						  env->imb_numa_nr);
2526 
2527 		/* Use idle CPU if there is no imbalance */
2528 		if (!imbalance) {
2529 			maymove = true;
2530 			if (env->dst_stats.idle_cpu >= 0) {
2531 				env->dst_cpu = env->dst_stats.idle_cpu;
2532 				task_numa_assign(env, NULL, 0);
2533 				return;
2534 			}
2535 		}
2536 	} else {
2537 		long src_load, dst_load, load;
2538 		/*
2539 		 * If the improvement from just moving env->p direction is better
2540 		 * than swapping tasks around, check if a move is possible.
2541 		 */
2542 		load = task_h_load(env->p);
2543 		dst_load = env->dst_stats.load + load;
2544 		src_load = env->src_stats.load - load;
2545 		maymove = !load_too_imbalanced(src_load, dst_load, env);
2546 	}
2547 
2548 	for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2549 		/* Skip this CPU if the source task cannot migrate */
2550 		if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2551 			continue;
2552 
2553 		env->dst_cpu = cpu;
2554 		if (task_numa_compare(env, taskimp, groupimp, maymove))
2555 			break;
2556 	}
2557 }
2558 
task_numa_migrate(struct task_struct * p)2559 static int task_numa_migrate(struct task_struct *p)
2560 {
2561 	struct task_numa_env env = {
2562 		.p = p,
2563 
2564 		.src_cpu = task_cpu(p),
2565 		.src_nid = task_node(p),
2566 
2567 		.imbalance_pct = 112,
2568 
2569 		.best_task = NULL,
2570 		.best_imp = 0,
2571 		.best_cpu = -1,
2572 	};
2573 	unsigned long taskweight, groupweight;
2574 	struct sched_domain *sd;
2575 	long taskimp, groupimp;
2576 	struct numa_group *ng;
2577 	struct rq *best_rq;
2578 	int nid, ret, dist;
2579 
2580 	/*
2581 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
2582 	 * imbalance and would be the first to start moving tasks about.
2583 	 *
2584 	 * And we want to avoid any moving of tasks about, as that would create
2585 	 * random movement of tasks -- counter the numa conditions we're trying
2586 	 * to satisfy here.
2587 	 */
2588 	rcu_read_lock();
2589 	sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2590 	if (sd) {
2591 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2592 		env.imb_numa_nr = sd->imb_numa_nr;
2593 	}
2594 	rcu_read_unlock();
2595 
2596 	/*
2597 	 * Cpusets can break the scheduler domain tree into smaller
2598 	 * balance domains, some of which do not cross NUMA boundaries.
2599 	 * Tasks that are "trapped" in such domains cannot be migrated
2600 	 * elsewhere, so there is no point in (re)trying.
2601 	 */
2602 	if (unlikely(!sd)) {
2603 		sched_setnuma(p, task_node(p));
2604 		return -EINVAL;
2605 	}
2606 
2607 	env.dst_nid = p->numa_preferred_nid;
2608 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2609 	taskweight = task_weight(p, env.src_nid, dist);
2610 	groupweight = group_weight(p, env.src_nid, dist);
2611 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2612 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2613 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2614 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2615 
2616 	/* Try to find a spot on the preferred nid. */
2617 	task_numa_find_cpu(&env, taskimp, groupimp);
2618 
2619 	/*
2620 	 * Look at other nodes in these cases:
2621 	 * - there is no space available on the preferred_nid
2622 	 * - the task is part of a numa_group that is interleaved across
2623 	 *   multiple NUMA nodes; in order to better consolidate the group,
2624 	 *   we need to check other locations.
2625 	 */
2626 	ng = deref_curr_numa_group(p);
2627 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2628 		for_each_node_state(nid, N_CPU) {
2629 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
2630 				continue;
2631 
2632 			dist = node_distance(env.src_nid, env.dst_nid);
2633 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
2634 						dist != env.dist) {
2635 				taskweight = task_weight(p, env.src_nid, dist);
2636 				groupweight = group_weight(p, env.src_nid, dist);
2637 			}
2638 
2639 			/* Only consider nodes where both task and groups benefit */
2640 			taskimp = task_weight(p, nid, dist) - taskweight;
2641 			groupimp = group_weight(p, nid, dist) - groupweight;
2642 			if (taskimp < 0 && groupimp < 0)
2643 				continue;
2644 
2645 			env.dist = dist;
2646 			env.dst_nid = nid;
2647 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2648 			task_numa_find_cpu(&env, taskimp, groupimp);
2649 		}
2650 	}
2651 
2652 	/*
2653 	 * If the task is part of a workload that spans multiple NUMA nodes,
2654 	 * and is migrating into one of the workload's active nodes, remember
2655 	 * this node as the task's preferred numa node, so the workload can
2656 	 * settle down.
2657 	 * A task that migrated to a second choice node will be better off
2658 	 * trying for a better one later. Do not set the preferred node here.
2659 	 */
2660 	if (ng) {
2661 		if (env.best_cpu == -1)
2662 			nid = env.src_nid;
2663 		else
2664 			nid = cpu_to_node(env.best_cpu);
2665 
2666 		if (nid != p->numa_preferred_nid)
2667 			sched_setnuma(p, nid);
2668 	}
2669 
2670 	/* No better CPU than the current one was found. */
2671 	if (env.best_cpu == -1) {
2672 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2673 		return -EAGAIN;
2674 	}
2675 
2676 	best_rq = cpu_rq(env.best_cpu);
2677 	if (env.best_task == NULL) {
2678 		ret = migrate_task_to(p, env.best_cpu);
2679 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
2680 		if (ret != 0)
2681 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2682 		return ret;
2683 	}
2684 
2685 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2686 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
2687 
2688 	if (ret != 0)
2689 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2690 	put_task_struct(env.best_task);
2691 	return ret;
2692 }
2693 
2694 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2695 static void numa_migrate_preferred(struct task_struct *p)
2696 {
2697 	unsigned long interval = HZ;
2698 
2699 	/* This task has no NUMA fault statistics yet */
2700 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2701 		return;
2702 
2703 	/* Periodically retry migrating the task to the preferred node */
2704 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2705 	p->numa_migrate_retry = jiffies + interval;
2706 
2707 	/* Success if task is already running on preferred CPU */
2708 	if (task_node(p) == p->numa_preferred_nid)
2709 		return;
2710 
2711 	/* Otherwise, try migrate to a CPU on the preferred node */
2712 	task_numa_migrate(p);
2713 }
2714 
2715 /*
2716  * Find out how many nodes the workload is actively running on. Do this by
2717  * tracking the nodes from which NUMA hinting faults are triggered. This can
2718  * be different from the set of nodes where the workload's memory is currently
2719  * located.
2720  */
numa_group_count_active_nodes(struct numa_group * numa_group)2721 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2722 {
2723 	unsigned long faults, max_faults = 0;
2724 	int nid, active_nodes = 0;
2725 
2726 	for_each_node_state(nid, N_CPU) {
2727 		faults = group_faults_cpu(numa_group, nid);
2728 		if (faults > max_faults)
2729 			max_faults = faults;
2730 	}
2731 
2732 	for_each_node_state(nid, N_CPU) {
2733 		faults = group_faults_cpu(numa_group, nid);
2734 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
2735 			active_nodes++;
2736 	}
2737 
2738 	numa_group->max_faults_cpu = max_faults;
2739 	numa_group->active_nodes = active_nodes;
2740 }
2741 
2742 /*
2743  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2744  * increments. The more local the fault statistics are, the higher the scan
2745  * period will be for the next scan window. If local/(local+remote) ratio is
2746  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2747  * the scan period will decrease. Aim for 70% local accesses.
2748  */
2749 #define NUMA_PERIOD_SLOTS 10
2750 #define NUMA_PERIOD_THRESHOLD 7
2751 
2752 /*
2753  * Increase the scan period (slow down scanning) if the majority of
2754  * our memory is already on our local node, or if the majority of
2755  * the page accesses are shared with other processes.
2756  * Otherwise, decrease the scan period.
2757  */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2758 static void update_task_scan_period(struct task_struct *p,
2759 			unsigned long shared, unsigned long private)
2760 {
2761 	unsigned int period_slot;
2762 	int lr_ratio, ps_ratio;
2763 	int diff;
2764 
2765 	unsigned long remote = p->numa_faults_locality[0];
2766 	unsigned long local = p->numa_faults_locality[1];
2767 
2768 	/*
2769 	 * If there were no record hinting faults then either the task is
2770 	 * completely idle or all activity is in areas that are not of interest
2771 	 * to automatic numa balancing. Related to that, if there were failed
2772 	 * migration then it implies we are migrating too quickly or the local
2773 	 * node is overloaded. In either case, scan slower
2774 	 */
2775 	if (local + shared == 0 || p->numa_faults_locality[2]) {
2776 		p->numa_scan_period = min(p->numa_scan_period_max,
2777 			p->numa_scan_period << 1);
2778 
2779 		p->mm->numa_next_scan = jiffies +
2780 			msecs_to_jiffies(p->numa_scan_period);
2781 
2782 		return;
2783 	}
2784 
2785 	/*
2786 	 * Prepare to scale scan period relative to the current period.
2787 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
2788 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2789 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2790 	 */
2791 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2792 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2793 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2794 
2795 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2796 		/*
2797 		 * Most memory accesses are local. There is no need to
2798 		 * do fast NUMA scanning, since memory is already local.
2799 		 */
2800 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2801 		if (!slot)
2802 			slot = 1;
2803 		diff = slot * period_slot;
2804 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2805 		/*
2806 		 * Most memory accesses are shared with other tasks.
2807 		 * There is no point in continuing fast NUMA scanning,
2808 		 * since other tasks may just move the memory elsewhere.
2809 		 */
2810 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2811 		if (!slot)
2812 			slot = 1;
2813 		diff = slot * period_slot;
2814 	} else {
2815 		/*
2816 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2817 		 * yet they are not on the local NUMA node. Speed up
2818 		 * NUMA scanning to get the memory moved over.
2819 		 */
2820 		int ratio = max(lr_ratio, ps_ratio);
2821 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2822 	}
2823 
2824 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
2825 			task_scan_min(p), task_scan_max(p));
2826 	memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2827 }
2828 
2829 /*
2830  * Get the fraction of time the task has been running since the last
2831  * NUMA placement cycle. The scheduler keeps similar statistics, but
2832  * decays those on a 32ms period, which is orders of magnitude off
2833  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2834  * stats only if the task is so new there are no NUMA statistics yet.
2835  */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2836 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2837 {
2838 	u64 runtime, delta, now;
2839 	/* Use the start of this time slice to avoid calculations. */
2840 	now = p->se.exec_start;
2841 	runtime = p->se.sum_exec_runtime;
2842 
2843 	if (p->last_task_numa_placement) {
2844 		delta = runtime - p->last_sum_exec_runtime;
2845 		*period = now - p->last_task_numa_placement;
2846 
2847 		/* Avoid time going backwards, prevent potential divide error: */
2848 		if (unlikely((s64)*period < 0))
2849 			*period = 0;
2850 	} else {
2851 		delta = p->se.avg.load_sum;
2852 		*period = LOAD_AVG_MAX;
2853 	}
2854 
2855 	p->last_sum_exec_runtime = runtime;
2856 	p->last_task_numa_placement = now;
2857 
2858 	return delta;
2859 }
2860 
2861 /*
2862  * Determine the preferred nid for a task in a numa_group. This needs to
2863  * be done in a way that produces consistent results with group_weight,
2864  * otherwise workloads might not converge.
2865  */
preferred_group_nid(struct task_struct * p,int nid)2866 static int preferred_group_nid(struct task_struct *p, int nid)
2867 {
2868 	nodemask_t nodes;
2869 	int dist;
2870 
2871 	/* Direct connections between all NUMA nodes. */
2872 	if (sched_numa_topology_type == NUMA_DIRECT)
2873 		return nid;
2874 
2875 	/*
2876 	 * On a system with glueless mesh NUMA topology, group_weight
2877 	 * scores nodes according to the number of NUMA hinting faults on
2878 	 * both the node itself, and on nearby nodes.
2879 	 */
2880 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2881 		unsigned long score, max_score = 0;
2882 		int node, max_node = nid;
2883 
2884 		dist = sched_max_numa_distance;
2885 
2886 		for_each_node_state(node, N_CPU) {
2887 			score = group_weight(p, node, dist);
2888 			if (score > max_score) {
2889 				max_score = score;
2890 				max_node = node;
2891 			}
2892 		}
2893 		return max_node;
2894 	}
2895 
2896 	/*
2897 	 * Finding the preferred nid in a system with NUMA backplane
2898 	 * interconnect topology is more involved. The goal is to locate
2899 	 * tasks from numa_groups near each other in the system, and
2900 	 * untangle workloads from different sides of the system. This requires
2901 	 * searching down the hierarchy of node groups, recursively searching
2902 	 * inside the highest scoring group of nodes. The nodemask tricks
2903 	 * keep the complexity of the search down.
2904 	 */
2905 	nodes = node_states[N_CPU];
2906 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2907 		unsigned long max_faults = 0;
2908 		nodemask_t max_group = NODE_MASK_NONE;
2909 		int a, b;
2910 
2911 		/* Are there nodes at this distance from each other? */
2912 		if (!find_numa_distance(dist))
2913 			continue;
2914 
2915 		for_each_node_mask(a, nodes) {
2916 			unsigned long faults = 0;
2917 			nodemask_t this_group;
2918 			nodes_clear(this_group);
2919 
2920 			/* Sum group's NUMA faults; includes a==b case. */
2921 			for_each_node_mask(b, nodes) {
2922 				if (node_distance(a, b) < dist) {
2923 					faults += group_faults(p, b);
2924 					node_set(b, this_group);
2925 					node_clear(b, nodes);
2926 				}
2927 			}
2928 
2929 			/* Remember the top group. */
2930 			if (faults > max_faults) {
2931 				max_faults = faults;
2932 				max_group = this_group;
2933 				/*
2934 				 * subtle: at the smallest distance there is
2935 				 * just one node left in each "group", the
2936 				 * winner is the preferred nid.
2937 				 */
2938 				nid = a;
2939 			}
2940 		}
2941 		/* Next round, evaluate the nodes within max_group. */
2942 		if (!max_faults)
2943 			break;
2944 		nodes = max_group;
2945 	}
2946 	return nid;
2947 }
2948 
task_numa_placement(struct task_struct * p)2949 static void task_numa_placement(struct task_struct *p)
2950 {
2951 	int seq, nid, max_nid = NUMA_NO_NODE;
2952 	unsigned long max_faults = 0;
2953 	unsigned long fault_types[2] = { 0, 0 };
2954 	unsigned long total_faults;
2955 	u64 runtime, period;
2956 	spinlock_t *group_lock = NULL;
2957 	struct numa_group *ng;
2958 
2959 	/*
2960 	 * The p->mm->numa_scan_seq field gets updated without
2961 	 * exclusive access. Use READ_ONCE() here to ensure
2962 	 * that the field is read in a single access:
2963 	 */
2964 	seq = READ_ONCE(p->mm->numa_scan_seq);
2965 	if (p->numa_scan_seq == seq)
2966 		return;
2967 	p->numa_scan_seq = seq;
2968 	p->numa_scan_period_max = task_scan_max(p);
2969 
2970 	total_faults = p->numa_faults_locality[0] +
2971 		       p->numa_faults_locality[1];
2972 	runtime = numa_get_avg_runtime(p, &period);
2973 
2974 	/* If the task is part of a group prevent parallel updates to group stats */
2975 	ng = deref_curr_numa_group(p);
2976 	if (ng) {
2977 		group_lock = &ng->lock;
2978 		spin_lock_irq(group_lock);
2979 	}
2980 
2981 	/* Find the node with the highest number of faults */
2982 	for_each_online_node(nid) {
2983 		/* Keep track of the offsets in numa_faults array */
2984 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2985 		unsigned long faults = 0, group_faults = 0;
2986 		int priv;
2987 
2988 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2989 			long diff, f_diff, f_weight;
2990 
2991 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2992 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2993 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2994 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2995 
2996 			/* Decay existing window, copy faults since last scan */
2997 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2998 			fault_types[priv] += p->numa_faults[membuf_idx];
2999 			p->numa_faults[membuf_idx] = 0;
3000 
3001 			/*
3002 			 * Normalize the faults_from, so all tasks in a group
3003 			 * count according to CPU use, instead of by the raw
3004 			 * number of faults. Tasks with little runtime have
3005 			 * little over-all impact on throughput, and thus their
3006 			 * faults are less important.
3007 			 */
3008 			f_weight = div64_u64(runtime << 16, period + 1);
3009 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
3010 				   (total_faults + 1);
3011 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
3012 			p->numa_faults[cpubuf_idx] = 0;
3013 
3014 			p->numa_faults[mem_idx] += diff;
3015 			p->numa_faults[cpu_idx] += f_diff;
3016 			faults += p->numa_faults[mem_idx];
3017 			p->total_numa_faults += diff;
3018 			if (ng) {
3019 				/*
3020 				 * safe because we can only change our own group
3021 				 *
3022 				 * mem_idx represents the offset for a given
3023 				 * nid and priv in a specific region because it
3024 				 * is at the beginning of the numa_faults array.
3025 				 */
3026 				ng->faults[mem_idx] += diff;
3027 				ng->faults[cpu_idx] += f_diff;
3028 				ng->total_faults += diff;
3029 				group_faults += ng->faults[mem_idx];
3030 			}
3031 		}
3032 
3033 		if (!ng) {
3034 			if (faults > max_faults) {
3035 				max_faults = faults;
3036 				max_nid = nid;
3037 			}
3038 		} else if (group_faults > max_faults) {
3039 			max_faults = group_faults;
3040 			max_nid = nid;
3041 		}
3042 	}
3043 
3044 	/* Cannot migrate task to CPU-less node */
3045 	max_nid = numa_nearest_node(max_nid, N_CPU);
3046 
3047 	if (ng) {
3048 		numa_group_count_active_nodes(ng);
3049 		spin_unlock_irq(group_lock);
3050 		max_nid = preferred_group_nid(p, max_nid);
3051 	}
3052 
3053 	if (max_faults) {
3054 		/* Set the new preferred node */
3055 		if (max_nid != p->numa_preferred_nid)
3056 			sched_setnuma(p, max_nid);
3057 	}
3058 
3059 	update_task_scan_period(p, fault_types[0], fault_types[1]);
3060 }
3061 
get_numa_group(struct numa_group * grp)3062 static inline int get_numa_group(struct numa_group *grp)
3063 {
3064 	return refcount_inc_not_zero(&grp->refcount);
3065 }
3066 
put_numa_group(struct numa_group * grp)3067 static inline void put_numa_group(struct numa_group *grp)
3068 {
3069 	if (refcount_dec_and_test(&grp->refcount))
3070 		kfree_rcu(grp, rcu);
3071 }
3072 
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)3073 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3074 			int *priv)
3075 {
3076 	struct numa_group *grp, *my_grp;
3077 	struct task_struct *tsk;
3078 	bool join = false;
3079 	int cpu = cpupid_to_cpu(cpupid);
3080 	int i;
3081 
3082 	if (unlikely(!deref_curr_numa_group(p))) {
3083 		unsigned int size = sizeof(struct numa_group) +
3084 				    NR_NUMA_HINT_FAULT_STATS *
3085 				    nr_node_ids * sizeof(unsigned long);
3086 
3087 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3088 		if (!grp)
3089 			return;
3090 
3091 		refcount_set(&grp->refcount, 1);
3092 		grp->active_nodes = 1;
3093 		grp->max_faults_cpu = 0;
3094 		spin_lock_init(&grp->lock);
3095 		grp->gid = p->pid;
3096 
3097 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3098 			grp->faults[i] = p->numa_faults[i];
3099 
3100 		grp->total_faults = p->total_numa_faults;
3101 
3102 		grp->nr_tasks++;
3103 		rcu_assign_pointer(p->numa_group, grp);
3104 	}
3105 
3106 	rcu_read_lock();
3107 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
3108 
3109 	if (!cpupid_match_pid(tsk, cpupid))
3110 		goto no_join;
3111 
3112 	grp = rcu_dereference(tsk->numa_group);
3113 	if (!grp)
3114 		goto no_join;
3115 
3116 	my_grp = deref_curr_numa_group(p);
3117 	if (grp == my_grp)
3118 		goto no_join;
3119 
3120 	/*
3121 	 * Only join the other group if its bigger; if we're the bigger group,
3122 	 * the other task will join us.
3123 	 */
3124 	if (my_grp->nr_tasks > grp->nr_tasks)
3125 		goto no_join;
3126 
3127 	/*
3128 	 * Tie-break on the grp address.
3129 	 */
3130 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3131 		goto no_join;
3132 
3133 	/* Always join threads in the same process. */
3134 	if (tsk->mm == current->mm)
3135 		join = true;
3136 
3137 	/* Simple filter to avoid false positives due to PID collisions */
3138 	if (flags & TNF_SHARED)
3139 		join = true;
3140 
3141 	/* Update priv based on whether false sharing was detected */
3142 	*priv = !join;
3143 
3144 	if (join && !get_numa_group(grp))
3145 		goto no_join;
3146 
3147 	rcu_read_unlock();
3148 
3149 	if (!join)
3150 		return;
3151 
3152 	WARN_ON_ONCE(irqs_disabled());
3153 	double_lock_irq(&my_grp->lock, &grp->lock);
3154 
3155 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3156 		my_grp->faults[i] -= p->numa_faults[i];
3157 		grp->faults[i] += p->numa_faults[i];
3158 	}
3159 	my_grp->total_faults -= p->total_numa_faults;
3160 	grp->total_faults += p->total_numa_faults;
3161 
3162 	my_grp->nr_tasks--;
3163 	grp->nr_tasks++;
3164 
3165 	spin_unlock(&my_grp->lock);
3166 	spin_unlock_irq(&grp->lock);
3167 
3168 	rcu_assign_pointer(p->numa_group, grp);
3169 
3170 	put_numa_group(my_grp);
3171 	return;
3172 
3173 no_join:
3174 	rcu_read_unlock();
3175 	return;
3176 }
3177 
3178 /*
3179  * Get rid of NUMA statistics associated with a task (either current or dead).
3180  * If @final is set, the task is dead and has reached refcount zero, so we can
3181  * safely free all relevant data structures. Otherwise, there might be
3182  * concurrent reads from places like load balancing and procfs, and we should
3183  * reset the data back to default state without freeing ->numa_faults.
3184  */
task_numa_free(struct task_struct * p,bool final)3185 void task_numa_free(struct task_struct *p, bool final)
3186 {
3187 	/* safe: p either is current or is being freed by current */
3188 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3189 	unsigned long *numa_faults = p->numa_faults;
3190 	unsigned long flags;
3191 	int i;
3192 
3193 	if (!numa_faults)
3194 		return;
3195 
3196 	if (grp) {
3197 		spin_lock_irqsave(&grp->lock, flags);
3198 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3199 			grp->faults[i] -= p->numa_faults[i];
3200 		grp->total_faults -= p->total_numa_faults;
3201 
3202 		grp->nr_tasks--;
3203 		spin_unlock_irqrestore(&grp->lock, flags);
3204 		RCU_INIT_POINTER(p->numa_group, NULL);
3205 		put_numa_group(grp);
3206 	}
3207 
3208 	if (final) {
3209 		p->numa_faults = NULL;
3210 		kfree(numa_faults);
3211 	} else {
3212 		p->total_numa_faults = 0;
3213 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3214 			numa_faults[i] = 0;
3215 	}
3216 }
3217 
3218 /*
3219  * Got a PROT_NONE fault for a page on @node.
3220  */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3221 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3222 {
3223 	struct task_struct *p = current;
3224 	bool migrated = flags & TNF_MIGRATED;
3225 	int cpu_node = task_node(current);
3226 	int local = !!(flags & TNF_FAULT_LOCAL);
3227 	struct numa_group *ng;
3228 	int priv;
3229 
3230 	if (!static_branch_likely(&sched_numa_balancing))
3231 		return;
3232 
3233 	/* for example, ksmd faulting in a user's mm */
3234 	if (!p->mm)
3235 		return;
3236 
3237 	/*
3238 	 * NUMA faults statistics are unnecessary for the slow memory
3239 	 * node for memory tiering mode.
3240 	 */
3241 	if (!node_is_toptier(mem_node) &&
3242 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3243 	     !cpupid_valid(last_cpupid)))
3244 		return;
3245 
3246 	/* Allocate buffer to track faults on a per-node basis */
3247 	if (unlikely(!p->numa_faults)) {
3248 		int size = sizeof(*p->numa_faults) *
3249 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3250 
3251 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3252 		if (!p->numa_faults)
3253 			return;
3254 
3255 		p->total_numa_faults = 0;
3256 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3257 	}
3258 
3259 	/*
3260 	 * First accesses are treated as private, otherwise consider accesses
3261 	 * to be private if the accessing pid has not changed
3262 	 */
3263 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3264 		priv = 1;
3265 	} else {
3266 		priv = cpupid_match_pid(p, last_cpupid);
3267 		if (!priv && !(flags & TNF_NO_GROUP))
3268 			task_numa_group(p, last_cpupid, flags, &priv);
3269 	}
3270 
3271 	/*
3272 	 * If a workload spans multiple NUMA nodes, a shared fault that
3273 	 * occurs wholly within the set of nodes that the workload is
3274 	 * actively using should be counted as local. This allows the
3275 	 * scan rate to slow down when a workload has settled down.
3276 	 */
3277 	ng = deref_curr_numa_group(p);
3278 	if (!priv && !local && ng && ng->active_nodes > 1 &&
3279 				numa_is_active_node(cpu_node, ng) &&
3280 				numa_is_active_node(mem_node, ng))
3281 		local = 1;
3282 
3283 	/*
3284 	 * Retry to migrate task to preferred node periodically, in case it
3285 	 * previously failed, or the scheduler moved us.
3286 	 */
3287 	if (time_after(jiffies, p->numa_migrate_retry)) {
3288 		task_numa_placement(p);
3289 		numa_migrate_preferred(p);
3290 	}
3291 
3292 	if (migrated)
3293 		p->numa_pages_migrated += pages;
3294 	if (flags & TNF_MIGRATE_FAIL)
3295 		p->numa_faults_locality[2] += pages;
3296 
3297 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3298 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3299 	p->numa_faults_locality[local] += pages;
3300 }
3301 
reset_ptenuma_scan(struct task_struct * p)3302 static void reset_ptenuma_scan(struct task_struct *p)
3303 {
3304 	/*
3305 	 * We only did a read acquisition of the mmap sem, so
3306 	 * p->mm->numa_scan_seq is written to without exclusive access
3307 	 * and the update is not guaranteed to be atomic. That's not
3308 	 * much of an issue though, since this is just used for
3309 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3310 	 * expensive, to avoid any form of compiler optimizations:
3311 	 */
3312 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3313 	p->mm->numa_scan_offset = 0;
3314 }
3315 
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3316 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3317 {
3318 	unsigned long pids;
3319 	/*
3320 	 * Allow unconditional access first two times, so that all the (pages)
3321 	 * of VMAs get prot_none fault introduced irrespective of accesses.
3322 	 * This is also done to avoid any side effect of task scanning
3323 	 * amplifying the unfairness of disjoint set of VMAs' access.
3324 	 */
3325 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3326 		return true;
3327 
3328 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3329 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3330 		return true;
3331 
3332 	/*
3333 	 * Complete a scan that has already started regardless of PID access, or
3334 	 * some VMAs may never be scanned in multi-threaded applications:
3335 	 */
3336 	if (mm->numa_scan_offset > vma->vm_start) {
3337 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3338 		return true;
3339 	}
3340 
3341 	/*
3342 	 * This vma has not been accessed for a while, and if the number
3343 	 * the threads in the same process is low, which means no other
3344 	 * threads can help scan this vma, force a vma scan.
3345 	 */
3346 	if (READ_ONCE(mm->numa_scan_seq) >
3347 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3348 		return true;
3349 
3350 	return false;
3351 }
3352 
3353 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3354 
3355 /*
3356  * The expensive part of numa migration is done from task_work context.
3357  * Triggered from task_tick_numa().
3358  */
task_numa_work(struct callback_head * work)3359 static void task_numa_work(struct callback_head *work)
3360 {
3361 	unsigned long migrate, next_scan, now = jiffies;
3362 	struct task_struct *p = current;
3363 	struct mm_struct *mm = p->mm;
3364 	u64 runtime = p->se.sum_exec_runtime;
3365 	struct vm_area_struct *vma;
3366 	unsigned long start, end;
3367 	unsigned long nr_pte_updates = 0;
3368 	long pages, virtpages;
3369 	struct vma_iterator vmi;
3370 	bool vma_pids_skipped;
3371 	bool vma_pids_forced = false;
3372 
3373 	SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3374 
3375 	work->next = work;
3376 	/*
3377 	 * Who cares about NUMA placement when they're dying.
3378 	 *
3379 	 * NOTE: make sure not to dereference p->mm before this check,
3380 	 * exit_task_work() happens _after_ exit_mm() so we could be called
3381 	 * without p->mm even though we still had it when we enqueued this
3382 	 * work.
3383 	 */
3384 	if (p->flags & PF_EXITING)
3385 		return;
3386 
3387 	if (!mm->numa_next_scan) {
3388 		mm->numa_next_scan = now +
3389 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3390 	}
3391 
3392 	/*
3393 	 * Enforce maximal scan/migration frequency..
3394 	 */
3395 	migrate = mm->numa_next_scan;
3396 	if (time_before(now, migrate))
3397 		return;
3398 
3399 	if (p->numa_scan_period == 0) {
3400 		p->numa_scan_period_max = task_scan_max(p);
3401 		p->numa_scan_period = task_scan_start(p);
3402 	}
3403 
3404 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3405 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3406 		return;
3407 
3408 	/*
3409 	 * Delay this task enough that another task of this mm will likely win
3410 	 * the next time around.
3411 	 */
3412 	p->node_stamp += 2 * TICK_NSEC;
3413 
3414 	pages = sysctl_numa_balancing_scan_size;
3415 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3416 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
3417 	if (!pages)
3418 		return;
3419 
3420 
3421 	if (!mmap_read_trylock(mm))
3422 		return;
3423 
3424 	/*
3425 	 * VMAs are skipped if the current PID has not trapped a fault within
3426 	 * the VMA recently. Allow scanning to be forced if there is no
3427 	 * suitable VMA remaining.
3428 	 */
3429 	vma_pids_skipped = false;
3430 
3431 retry_pids:
3432 	start = mm->numa_scan_offset;
3433 	vma_iter_init(&vmi, mm, start);
3434 	vma = vma_next(&vmi);
3435 	if (!vma) {
3436 		reset_ptenuma_scan(p);
3437 		start = 0;
3438 		vma_iter_set(&vmi, start);
3439 		vma = vma_next(&vmi);
3440 	}
3441 
3442 	for (; vma; vma = vma_next(&vmi)) {
3443 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3444 			is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3445 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3446 			continue;
3447 		}
3448 
3449 		/*
3450 		 * Shared library pages mapped by multiple processes are not
3451 		 * migrated as it is expected they are cache replicated. Avoid
3452 		 * hinting faults in read-only file-backed mappings or the vDSO
3453 		 * as migrating the pages will be of marginal benefit.
3454 		 */
3455 		if (!vma->vm_mm ||
3456 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3457 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3458 			continue;
3459 		}
3460 
3461 		/*
3462 		 * Skip inaccessible VMAs to avoid any confusion between
3463 		 * PROT_NONE and NUMA hinting PTEs
3464 		 */
3465 		if (!vma_is_accessible(vma)) {
3466 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3467 			continue;
3468 		}
3469 
3470 		/* Initialise new per-VMA NUMAB state. */
3471 		if (!vma->numab_state) {
3472 			struct vma_numab_state *ptr;
3473 
3474 			ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3475 			if (!ptr)
3476 				continue;
3477 
3478 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3479 				kfree(ptr);
3480 				continue;
3481 			}
3482 
3483 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3484 
3485 			vma->numab_state->next_scan = now +
3486 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3487 
3488 			/* Reset happens after 4 times scan delay of scan start */
3489 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
3490 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3491 
3492 			/*
3493 			 * Ensure prev_scan_seq does not match numa_scan_seq,
3494 			 * to prevent VMAs being skipped prematurely on the
3495 			 * first scan:
3496 			 */
3497 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3498 		}
3499 
3500 		/*
3501 		 * Scanning the VMAs of short lived tasks add more overhead. So
3502 		 * delay the scan for new VMAs.
3503 		 */
3504 		if (mm->numa_scan_seq && time_before(jiffies,
3505 						vma->numab_state->next_scan)) {
3506 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3507 			continue;
3508 		}
3509 
3510 		/* RESET access PIDs regularly for old VMAs. */
3511 		if (mm->numa_scan_seq &&
3512 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
3513 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3514 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3515 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3516 			vma->numab_state->pids_active[1] = 0;
3517 		}
3518 
3519 		/* Do not rescan VMAs twice within the same sequence. */
3520 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3521 			mm->numa_scan_offset = vma->vm_end;
3522 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3523 			continue;
3524 		}
3525 
3526 		/*
3527 		 * Do not scan the VMA if task has not accessed it, unless no other
3528 		 * VMA candidate exists.
3529 		 */
3530 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3531 			vma_pids_skipped = true;
3532 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3533 			continue;
3534 		}
3535 
3536 		do {
3537 			start = max(start, vma->vm_start);
3538 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3539 			end = min(end, vma->vm_end);
3540 			nr_pte_updates = change_prot_numa(vma, start, end);
3541 
3542 			/*
3543 			 * Try to scan sysctl_numa_balancing_size worth of
3544 			 * hpages that have at least one present PTE that
3545 			 * is not already PTE-numa. If the VMA contains
3546 			 * areas that are unused or already full of prot_numa
3547 			 * PTEs, scan up to virtpages, to skip through those
3548 			 * areas faster.
3549 			 */
3550 			if (nr_pte_updates)
3551 				pages -= (end - start) >> PAGE_SHIFT;
3552 			virtpages -= (end - start) >> PAGE_SHIFT;
3553 
3554 			start = end;
3555 			if (pages <= 0 || virtpages <= 0)
3556 				goto out;
3557 
3558 			cond_resched();
3559 		} while (end != vma->vm_end);
3560 
3561 		/* VMA scan is complete, do not scan until next sequence. */
3562 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3563 
3564 		/*
3565 		 * Only force scan within one VMA at a time, to limit the
3566 		 * cost of scanning a potentially uninteresting VMA.
3567 		 */
3568 		if (vma_pids_forced)
3569 			break;
3570 	}
3571 
3572 	/*
3573 	 * If no VMAs are remaining and VMAs were skipped due to the PID
3574 	 * not accessing the VMA previously, then force a scan to ensure
3575 	 * forward progress:
3576 	 */
3577 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
3578 		vma_pids_forced = true;
3579 		goto retry_pids;
3580 	}
3581 
3582 out:
3583 	/*
3584 	 * It is possible to reach the end of the VMA list but the last few
3585 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3586 	 * would find the !migratable VMA on the next scan but not reset the
3587 	 * scanner to the start so check it now.
3588 	 */
3589 	if (vma)
3590 		mm->numa_scan_offset = start;
3591 	else
3592 		reset_ptenuma_scan(p);
3593 	mmap_read_unlock(mm);
3594 
3595 	/*
3596 	 * Make sure tasks use at least 32x as much time to run other code
3597 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3598 	 * Usually update_task_scan_period slows down scanning enough; on an
3599 	 * overloaded system we need to limit overhead on a per task basis.
3600 	 */
3601 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
3602 		u64 diff = p->se.sum_exec_runtime - runtime;
3603 		p->node_stamp += 32 * diff;
3604 	}
3605 }
3606 
init_numa_balancing(unsigned long clone_flags,struct task_struct * p)3607 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3608 {
3609 	int mm_users = 0;
3610 	struct mm_struct *mm = p->mm;
3611 
3612 	if (mm) {
3613 		mm_users = atomic_read(&mm->mm_users);
3614 		if (mm_users == 1) {
3615 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3616 			mm->numa_scan_seq = 0;
3617 		}
3618 	}
3619 	p->node_stamp			= 0;
3620 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
3621 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
3622 	p->numa_migrate_retry		= 0;
3623 	/* Protect against double add, see task_tick_numa and task_numa_work */
3624 	p->numa_work.next		= &p->numa_work;
3625 	p->numa_faults			= NULL;
3626 	p->numa_pages_migrated		= 0;
3627 	p->total_numa_faults		= 0;
3628 	RCU_INIT_POINTER(p->numa_group, NULL);
3629 	p->last_task_numa_placement	= 0;
3630 	p->last_sum_exec_runtime	= 0;
3631 
3632 	init_task_work(&p->numa_work, task_numa_work);
3633 
3634 	/* New address space, reset the preferred nid */
3635 	if (!(clone_flags & CLONE_VM)) {
3636 		p->numa_preferred_nid = NUMA_NO_NODE;
3637 		return;
3638 	}
3639 
3640 	/*
3641 	 * New thread, keep existing numa_preferred_nid which should be copied
3642 	 * already by arch_dup_task_struct but stagger when scans start.
3643 	 */
3644 	if (mm) {
3645 		unsigned int delay;
3646 
3647 		delay = min_t(unsigned int, task_scan_max(current),
3648 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3649 		delay += 2 * TICK_NSEC;
3650 		p->node_stamp = delay;
3651 	}
3652 }
3653 
3654 /*
3655  * Drive the periodic memory faults..
3656  */
task_tick_numa(struct rq * rq,struct task_struct * curr)3657 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3658 {
3659 	struct callback_head *work = &curr->numa_work;
3660 	u64 period, now;
3661 
3662 	/*
3663 	 * We don't care about NUMA placement if we don't have memory.
3664 	 */
3665 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3666 		return;
3667 
3668 	/*
3669 	 * Using runtime rather than walltime has the dual advantage that
3670 	 * we (mostly) drive the selection from busy threads and that the
3671 	 * task needs to have done some actual work before we bother with
3672 	 * NUMA placement.
3673 	 */
3674 	now = curr->se.sum_exec_runtime;
3675 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3676 
3677 	if (now > curr->node_stamp + period) {
3678 		if (!curr->node_stamp)
3679 			curr->numa_scan_period = task_scan_start(curr);
3680 		curr->node_stamp += period;
3681 
3682 		if (!time_before(jiffies, curr->mm->numa_next_scan))
3683 			task_work_add(curr, work, TWA_RESUME);
3684 	}
3685 }
3686 
update_scan_period(struct task_struct * p,int new_cpu)3687 static void update_scan_period(struct task_struct *p, int new_cpu)
3688 {
3689 	int src_nid = cpu_to_node(task_cpu(p));
3690 	int dst_nid = cpu_to_node(new_cpu);
3691 
3692 	if (!static_branch_likely(&sched_numa_balancing))
3693 		return;
3694 
3695 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3696 		return;
3697 
3698 	if (src_nid == dst_nid)
3699 		return;
3700 
3701 	/*
3702 	 * Allow resets if faults have been trapped before one scan
3703 	 * has completed. This is most likely due to a new task that
3704 	 * is pulled cross-node due to wakeups or load balancing.
3705 	 */
3706 	if (p->numa_scan_seq) {
3707 		/*
3708 		 * Avoid scan adjustments if moving to the preferred
3709 		 * node or if the task was not previously running on
3710 		 * the preferred node.
3711 		 */
3712 		if (dst_nid == p->numa_preferred_nid ||
3713 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
3714 			src_nid != p->numa_preferred_nid))
3715 			return;
3716 	}
3717 
3718 	p->numa_scan_period = task_scan_start(p);
3719 }
3720 
3721 #else
task_tick_numa(struct rq * rq,struct task_struct * curr)3722 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3723 {
3724 }
3725 
account_numa_enqueue(struct rq * rq,struct task_struct * p)3726 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3727 {
3728 }
3729 
account_numa_dequeue(struct rq * rq,struct task_struct * p)3730 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3731 {
3732 }
3733 
update_scan_period(struct task_struct * p,int new_cpu)3734 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3735 {
3736 }
3737 
3738 #endif /* CONFIG_NUMA_BALANCING */
3739 
3740 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3741 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3742 {
3743 	update_load_add(&cfs_rq->load, se->load.weight);
3744 #ifdef CONFIG_SMP
3745 	if (entity_is_task(se)) {
3746 		struct rq *rq = rq_of(cfs_rq);
3747 
3748 		account_numa_enqueue(rq, task_of(se));
3749 		list_add(&se->group_node, &rq->cfs_tasks);
3750 	}
3751 #endif
3752 	cfs_rq->nr_running++;
3753 	if (se_is_idle(se))
3754 		cfs_rq->idle_nr_running++;
3755 }
3756 
3757 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3758 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3759 {
3760 	update_load_sub(&cfs_rq->load, se->load.weight);
3761 #ifdef CONFIG_SMP
3762 	if (entity_is_task(se)) {
3763 		account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3764 		list_del_init(&se->group_node);
3765 	}
3766 #endif
3767 	cfs_rq->nr_running--;
3768 	if (se_is_idle(se))
3769 		cfs_rq->idle_nr_running--;
3770 }
3771 
3772 /*
3773  * Signed add and clamp on underflow.
3774  *
3775  * Explicitly do a load-store to ensure the intermediate value never hits
3776  * memory. This allows lockless observations without ever seeing the negative
3777  * values.
3778  */
3779 #define add_positive(_ptr, _val) do {                           \
3780 	typeof(_ptr) ptr = (_ptr);                              \
3781 	typeof(_val) val = (_val);                              \
3782 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3783 								\
3784 	res = var + val;                                        \
3785 								\
3786 	if (val < 0 && res > var)                               \
3787 		res = 0;                                        \
3788 								\
3789 	WRITE_ONCE(*ptr, res);                                  \
3790 } while (0)
3791 
3792 /*
3793  * Unsigned subtract and clamp on underflow.
3794  *
3795  * Explicitly do a load-store to ensure the intermediate value never hits
3796  * memory. This allows lockless observations without ever seeing the negative
3797  * values.
3798  */
3799 #define sub_positive(_ptr, _val) do {				\
3800 	typeof(_ptr) ptr = (_ptr);				\
3801 	typeof(*ptr) val = (_val);				\
3802 	typeof(*ptr) res, var = READ_ONCE(*ptr);		\
3803 	res = var - val;					\
3804 	if (res > var)						\
3805 		res = 0;					\
3806 	WRITE_ONCE(*ptr, res);					\
3807 } while (0)
3808 
3809 /*
3810  * Remove and clamp on negative, from a local variable.
3811  *
3812  * A variant of sub_positive(), which does not use explicit load-store
3813  * and is thus optimized for local variable updates.
3814  */
3815 #define lsub_positive(_ptr, _val) do {				\
3816 	typeof(_ptr) ptr = (_ptr);				\
3817 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
3818 } while (0)
3819 
3820 #ifdef CONFIG_SMP
3821 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3822 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3823 {
3824 	cfs_rq->avg.load_avg += se->avg.load_avg;
3825 	cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3826 }
3827 
3828 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3829 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3830 {
3831 	sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3832 	sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3833 	/* See update_cfs_rq_load_avg() */
3834 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3835 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3836 }
3837 #else
3838 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3839 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3840 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3841 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3842 #endif
3843 
reweight_eevdf(struct sched_entity * se,u64 avruntime,unsigned long weight)3844 static void reweight_eevdf(struct sched_entity *se, u64 avruntime,
3845 			   unsigned long weight)
3846 {
3847 	unsigned long old_weight = se->load.weight;
3848 	s64 vlag, vslice;
3849 
3850 	/*
3851 	 * VRUNTIME
3852 	 * --------
3853 	 *
3854 	 * COROLLARY #1: The virtual runtime of the entity needs to be
3855 	 * adjusted if re-weight at !0-lag point.
3856 	 *
3857 	 * Proof: For contradiction assume this is not true, so we can
3858 	 * re-weight without changing vruntime at !0-lag point.
3859 	 *
3860 	 *             Weight	VRuntime   Avg-VRuntime
3861 	 *     before    w          v            V
3862 	 *      after    w'         v'           V'
3863 	 *
3864 	 * Since lag needs to be preserved through re-weight:
3865 	 *
3866 	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
3867 	 *	==>	V' = (V - v)*w/w' + v		(1)
3868 	 *
3869 	 * Let W be the total weight of the entities before reweight,
3870 	 * since V' is the new weighted average of entities:
3871 	 *
3872 	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
3873 	 *
3874 	 * by using (1) & (2) we obtain:
3875 	 *
3876 	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
3877 	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
3878 	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
3879 	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
3880 	 *
3881 	 * Since we are doing at !0-lag point which means V != v, we
3882 	 * can simplify (3):
3883 	 *
3884 	 *	==>	W / (W + w' - w) = w / w'
3885 	 *	==>	Ww' = Ww + ww' - ww
3886 	 *	==>	W * (w' - w) = w * (w' - w)
3887 	 *	==>	W = w	(re-weight indicates w' != w)
3888 	 *
3889 	 * So the cfs_rq contains only one entity, hence vruntime of
3890 	 * the entity @v should always equal to the cfs_rq's weighted
3891 	 * average vruntime @V, which means we will always re-weight
3892 	 * at 0-lag point, thus breach assumption. Proof completed.
3893 	 *
3894 	 *
3895 	 * COROLLARY #2: Re-weight does NOT affect weighted average
3896 	 * vruntime of all the entities.
3897 	 *
3898 	 * Proof: According to corollary #1, Eq. (1) should be:
3899 	 *
3900 	 *	(V - v)*w = (V' - v')*w'
3901 	 *	==>    v' = V' - (V - v)*w/w'		(4)
3902 	 *
3903 	 * According to the weighted average formula, we have:
3904 	 *
3905 	 *	V' = (WV - wv + w'v') / (W - w + w')
3906 	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
3907 	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
3908 	 *	   = (WV + w'V' - Vw) / (W - w + w')
3909 	 *
3910 	 *	==>  V'*(W - w + w') = WV + w'V' - Vw
3911 	 *	==>	V' * (W - w) = (W - w) * V	(5)
3912 	 *
3913 	 * If the entity is the only one in the cfs_rq, then reweight
3914 	 * always occurs at 0-lag point, so V won't change. Or else
3915 	 * there are other entities, hence W != w, then Eq. (5) turns
3916 	 * into V' = V. So V won't change in either case, proof done.
3917 	 *
3918 	 *
3919 	 * So according to corollary #1 & #2, the effect of re-weight
3920 	 * on vruntime should be:
3921 	 *
3922 	 *	v' = V' - (V - v) * w / w'		(4)
3923 	 *	   = V  - (V - v) * w / w'
3924 	 *	   = V  - vl * w / w'
3925 	 *	   = V  - vl'
3926 	 */
3927 	if (avruntime != se->vruntime) {
3928 		vlag = entity_lag(avruntime, se);
3929 		vlag = div_s64(vlag * old_weight, weight);
3930 		se->vruntime = avruntime - vlag;
3931 	}
3932 
3933 	/*
3934 	 * DEADLINE
3935 	 * --------
3936 	 *
3937 	 * When the weight changes, the virtual time slope changes and
3938 	 * we should adjust the relative virtual deadline accordingly.
3939 	 *
3940 	 *	d' = v' + (d - v)*w/w'
3941 	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
3942 	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
3943 	 *	   = V  + (d - V)*w/w'
3944 	 */
3945 	vslice = (s64)(se->deadline - avruntime);
3946 	vslice = div_s64(vslice * old_weight, weight);
3947 	se->deadline = avruntime + vslice;
3948 }
3949 
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3950 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3951 			    unsigned long weight)
3952 {
3953 	bool curr = cfs_rq->curr == se;
3954 	u64 avruntime;
3955 
3956 	if (se->on_rq) {
3957 		/* commit outstanding execution time */
3958 		update_curr(cfs_rq);
3959 		avruntime = avg_vruntime(cfs_rq);
3960 		if (!curr)
3961 			__dequeue_entity(cfs_rq, se);
3962 		update_load_sub(&cfs_rq->load, se->load.weight);
3963 	}
3964 	dequeue_load_avg(cfs_rq, se);
3965 
3966 	trace_android_vh_reweight_entity(se, &weight);
3967 
3968 	if (se->on_rq) {
3969 		reweight_eevdf(se, avruntime, weight);
3970 	} else {
3971 		/*
3972 		 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3973 		 * we need to scale se->vlag when w_i changes.
3974 		 */
3975 		se->vlag = div_s64(se->vlag * se->load.weight, weight);
3976 	}
3977 
3978 	update_load_set(&se->load, weight);
3979 
3980 #ifdef CONFIG_SMP
3981 	do {
3982 		u32 divider = get_pelt_divider(&se->avg);
3983 
3984 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3985 	} while (0);
3986 #endif
3987 
3988 	enqueue_load_avg(cfs_rq, se);
3989 	if (se->on_rq) {
3990 		update_load_add(&cfs_rq->load, se->load.weight);
3991 		if (!curr)
3992 			__enqueue_entity(cfs_rq, se);
3993 
3994 		/*
3995 		 * The entity's vruntime has been adjusted, so let's check
3996 		 * whether the rq-wide min_vruntime needs updated too. Since
3997 		 * the calculations above require stable min_vruntime rather
3998 		 * than up-to-date one, we do the update at the end of the
3999 		 * reweight process.
4000 		 */
4001 		update_min_vruntime(cfs_rq);
4002 	}
4003 }
4004 
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)4005 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
4006 			       const struct load_weight *lw)
4007 {
4008 	struct sched_entity *se = &p->se;
4009 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4010 	struct load_weight *load = &se->load;
4011 
4012 	reweight_entity(cfs_rq, se, lw->weight);
4013 	load->inv_weight = lw->inv_weight;
4014 }
4015 
4016 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
4017 
4018 #ifdef CONFIG_FAIR_GROUP_SCHED
4019 #ifdef CONFIG_SMP
4020 /*
4021  * All this does is approximate the hierarchical proportion which includes that
4022  * global sum we all love to hate.
4023  *
4024  * That is, the weight of a group entity, is the proportional share of the
4025  * group weight based on the group runqueue weights. That is:
4026  *
4027  *                     tg->weight * grq->load.weight
4028  *   ge->load.weight = -----------------------------               (1)
4029  *                       \Sum grq->load.weight
4030  *
4031  * Now, because computing that sum is prohibitively expensive to compute (been
4032  * there, done that) we approximate it with this average stuff. The average
4033  * moves slower and therefore the approximation is cheaper and more stable.
4034  *
4035  * So instead of the above, we substitute:
4036  *
4037  *   grq->load.weight -> grq->avg.load_avg                         (2)
4038  *
4039  * which yields the following:
4040  *
4041  *                     tg->weight * grq->avg.load_avg
4042  *   ge->load.weight = ------------------------------              (3)
4043  *                             tg->load_avg
4044  *
4045  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
4046  *
4047  * That is shares_avg, and it is right (given the approximation (2)).
4048  *
4049  * The problem with it is that because the average is slow -- it was designed
4050  * to be exactly that of course -- this leads to transients in boundary
4051  * conditions. In specific, the case where the group was idle and we start the
4052  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
4053  * yielding bad latency etc..
4054  *
4055  * Now, in that special case (1) reduces to:
4056  *
4057  *                     tg->weight * grq->load.weight
4058  *   ge->load.weight = ----------------------------- = tg->weight   (4)
4059  *                         grp->load.weight
4060  *
4061  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
4062  *
4063  * So what we do is modify our approximation (3) to approach (4) in the (near)
4064  * UP case, like:
4065  *
4066  *   ge->load.weight =
4067  *
4068  *              tg->weight * grq->load.weight
4069  *     ---------------------------------------------------         (5)
4070  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
4071  *
4072  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
4073  * we need to use grq->avg.load_avg as its lower bound, which then gives:
4074  *
4075  *
4076  *                     tg->weight * grq->load.weight
4077  *   ge->load.weight = -----------------------------		   (6)
4078  *                             tg_load_avg'
4079  *
4080  * Where:
4081  *
4082  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
4083  *                  max(grq->load.weight, grq->avg.load_avg)
4084  *
4085  * And that is shares_weight and is icky. In the (near) UP case it approaches
4086  * (4) while in the normal case it approaches (3). It consistently
4087  * overestimates the ge->load.weight and therefore:
4088  *
4089  *   \Sum ge->load.weight >= tg->weight
4090  *
4091  * hence icky!
4092  */
calc_group_shares(struct cfs_rq * cfs_rq)4093 static long calc_group_shares(struct cfs_rq *cfs_rq)
4094 {
4095 	long tg_weight, tg_shares, load, shares;
4096 	struct task_group *tg = cfs_rq->tg;
4097 
4098 	tg_shares = READ_ONCE(tg->shares);
4099 
4100 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
4101 
4102 	tg_weight = atomic_long_read(&tg->load_avg);
4103 
4104 	/* Ensure tg_weight >= load */
4105 	tg_weight -= cfs_rq->tg_load_avg_contrib;
4106 	tg_weight += load;
4107 
4108 	shares = (tg_shares * load);
4109 	if (tg_weight)
4110 		shares /= tg_weight;
4111 
4112 	/*
4113 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
4114 	 * of a group with small tg->shares value. It is a floor value which is
4115 	 * assigned as a minimum load.weight to the sched_entity representing
4116 	 * the group on a CPU.
4117 	 *
4118 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
4119 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
4120 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
4121 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
4122 	 * instead of 0.
4123 	 */
4124 	return clamp_t(long, shares, MIN_SHARES, tg_shares);
4125 }
4126 #endif /* CONFIG_SMP */
4127 
4128 /*
4129  * Recomputes the group entity based on the current state of its group
4130  * runqueue.
4131  */
update_cfs_group(struct sched_entity * se)4132 static void update_cfs_group(struct sched_entity *se)
4133 {
4134 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4135 	long shares;
4136 
4137 	/*
4138 	 * When a group becomes empty, preserve its weight. This matters for
4139 	 * DELAY_DEQUEUE.
4140 	 */
4141 	if (!gcfs_rq || !gcfs_rq->load.weight)
4142 		return;
4143 
4144 	if (throttled_hierarchy(gcfs_rq))
4145 		return;
4146 
4147 #ifndef CONFIG_SMP
4148 	shares = READ_ONCE(gcfs_rq->tg->shares);
4149 #else
4150 	shares = calc_group_shares(gcfs_rq);
4151 #endif
4152 	if (unlikely(se->load.weight != shares))
4153 		reweight_entity(cfs_rq_of(se), se, shares);
4154 }
4155 
4156 #else /* CONFIG_FAIR_GROUP_SCHED */
update_cfs_group(struct sched_entity * se)4157 static inline void update_cfs_group(struct sched_entity *se)
4158 {
4159 }
4160 #endif /* CONFIG_FAIR_GROUP_SCHED */
4161 
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)4162 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
4163 {
4164 	struct rq *rq = rq_of(cfs_rq);
4165 
4166 	if (&rq->cfs == cfs_rq) {
4167 		/*
4168 		 * There are a few boundary cases this might miss but it should
4169 		 * get called often enough that that should (hopefully) not be
4170 		 * a real problem.
4171 		 *
4172 		 * It will not get called when we go idle, because the idle
4173 		 * thread is a different class (!fair), nor will the utilization
4174 		 * number include things like RT tasks.
4175 		 *
4176 		 * As is, the util number is not freq-invariant (we'd have to
4177 		 * implement arch_scale_freq_capacity() for that).
4178 		 *
4179 		 * See cpu_util_cfs().
4180 		 */
4181 		cpufreq_update_util(rq, flags);
4182 	}
4183 }
4184 
4185 #ifdef CONFIG_SMP
load_avg_is_decayed(struct sched_avg * sa)4186 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4187 {
4188 	if (sa->load_sum)
4189 		return false;
4190 
4191 	if (sa->util_sum)
4192 		return false;
4193 
4194 	if (sa->runnable_sum)
4195 		return false;
4196 
4197 	/*
4198 	 * _avg must be null when _sum are null because _avg = _sum / divider
4199 	 * Make sure that rounding and/or propagation of PELT values never
4200 	 * break this.
4201 	 */
4202 	SCHED_WARN_ON(sa->load_avg ||
4203 		      sa->util_avg ||
4204 		      sa->runnable_avg);
4205 
4206 	return true;
4207 }
4208 
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)4209 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4210 {
4211 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4212 				 cfs_rq->last_update_time_copy);
4213 }
4214 #ifdef CONFIG_FAIR_GROUP_SCHED
4215 /*
4216  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4217  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4218  * bottom-up, we only have to test whether the cfs_rq before us on the list
4219  * is our child.
4220  * If cfs_rq is not on the list, test whether a child needs its to be added to
4221  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
4222  */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4223 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4224 {
4225 	struct cfs_rq *prev_cfs_rq;
4226 	struct list_head *prev;
4227 	struct rq *rq = rq_of(cfs_rq);
4228 
4229 	if (cfs_rq->on_list) {
4230 		prev = cfs_rq->leaf_cfs_rq_list.prev;
4231 	} else {
4232 		prev = rq->tmp_alone_branch;
4233 	}
4234 
4235 	if (prev == &rq->leaf_cfs_rq_list)
4236 		return false;
4237 
4238 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4239 
4240 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4241 }
4242 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4243 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4244 {
4245 	if (cfs_rq->load.weight)
4246 		return false;
4247 
4248 	if (!load_avg_is_decayed(&cfs_rq->avg))
4249 		return false;
4250 
4251 	if (child_cfs_rq_on_list(cfs_rq))
4252 		return false;
4253 
4254 	return true;
4255 }
4256 
4257 /**
4258  * update_tg_load_avg - update the tg's load avg
4259  * @cfs_rq: the cfs_rq whose avg changed
4260  *
4261  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4262  * However, because tg->load_avg is a global value there are performance
4263  * considerations.
4264  *
4265  * In order to avoid having to look at the other cfs_rq's, we use a
4266  * differential update where we store the last value we propagated. This in
4267  * turn allows skipping updates if the differential is 'small'.
4268  *
4269  * Updating tg's load_avg is necessary before update_cfs_share().
4270  */
update_tg_load_avg(struct cfs_rq * cfs_rq)4271 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4272 {
4273 	long delta;
4274 	u64 now;
4275 
4276 	/*
4277 	 * No need to update load_avg for root_task_group as it is not used.
4278 	 */
4279 	if (cfs_rq->tg == &root_task_group)
4280 		return;
4281 
4282 	/* rq has been offline and doesn't contribute to the share anymore: */
4283 	if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4284 		return;
4285 
4286 	/*
4287 	 * For migration heavy workloads, access to tg->load_avg can be
4288 	 * unbound. Limit the update rate to at most once per ms.
4289 	 */
4290 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4291 	if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4292 		return;
4293 
4294 	delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4295 	if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4296 		atomic_long_add(delta, &cfs_rq->tg->load_avg);
4297 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4298 		cfs_rq->last_update_tg_load_avg = now;
4299 	}
4300 }
4301 
clear_tg_load_avg(struct cfs_rq * cfs_rq)4302 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4303 {
4304 	long delta;
4305 	u64 now;
4306 
4307 	/*
4308 	 * No need to update load_avg for root_task_group, as it is not used.
4309 	 */
4310 	if (cfs_rq->tg == &root_task_group)
4311 		return;
4312 
4313 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4314 	delta = 0 - cfs_rq->tg_load_avg_contrib;
4315 	atomic_long_add(delta, &cfs_rq->tg->load_avg);
4316 	cfs_rq->tg_load_avg_contrib = 0;
4317 	cfs_rq->last_update_tg_load_avg = now;
4318 }
4319 
4320 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4321 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4322 {
4323 	struct task_group *tg;
4324 
4325 	lockdep_assert_rq_held(rq);
4326 
4327 	/*
4328 	 * The rq clock has already been updated in
4329 	 * set_rq_offline(), so we should skip updating
4330 	 * the rq clock again in unthrottle_cfs_rq().
4331 	 */
4332 	rq_clock_start_loop_update(rq);
4333 
4334 	rcu_read_lock();
4335 	list_for_each_entry_rcu(tg, &task_groups, list) {
4336 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4337 
4338 		clear_tg_load_avg(cfs_rq);
4339 	}
4340 	rcu_read_unlock();
4341 
4342 	rq_clock_stop_loop_update(rq);
4343 }
4344 
4345 /*
4346  * Called within set_task_rq() right before setting a task's CPU. The
4347  * caller only guarantees p->pi_lock is held; no other assumptions,
4348  * including the state of rq->lock, should be made.
4349  */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4350 void set_task_rq_fair(struct sched_entity *se,
4351 		      struct cfs_rq *prev, struct cfs_rq *next)
4352 {
4353 	u64 p_last_update_time;
4354 	u64 n_last_update_time;
4355 
4356 	if (!sched_feat(ATTACH_AGE_LOAD))
4357 		return;
4358 
4359 	/*
4360 	 * We are supposed to update the task to "current" time, then its up to
4361 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4362 	 * getting what current time is, so simply throw away the out-of-date
4363 	 * time. This will result in the wakee task is less decayed, but giving
4364 	 * the wakee more load sounds not bad.
4365 	 */
4366 	if (!(se->avg.last_update_time && prev))
4367 		return;
4368 
4369 	p_last_update_time = cfs_rq_last_update_time(prev);
4370 	n_last_update_time = cfs_rq_last_update_time(next);
4371 
4372 	__update_load_avg_blocked_se(p_last_update_time, se);
4373 	se->avg.last_update_time = n_last_update_time;
4374 }
4375 
4376 /*
4377  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4378  * propagate its contribution. The key to this propagation is the invariant
4379  * that for each group:
4380  *
4381  *   ge->avg == grq->avg						(1)
4382  *
4383  * _IFF_ we look at the pure running and runnable sums. Because they
4384  * represent the very same entity, just at different points in the hierarchy.
4385  *
4386  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4387  * and simply copies the running/runnable sum over (but still wrong, because
4388  * the group entity and group rq do not have their PELT windows aligned).
4389  *
4390  * However, update_tg_cfs_load() is more complex. So we have:
4391  *
4392  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
4393  *
4394  * And since, like util, the runnable part should be directly transferable,
4395  * the following would _appear_ to be the straight forward approach:
4396  *
4397  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
4398  *
4399  * And per (1) we have:
4400  *
4401  *   ge->avg.runnable_avg == grq->avg.runnable_avg
4402  *
4403  * Which gives:
4404  *
4405  *                      ge->load.weight * grq->avg.load_avg
4406  *   ge->avg.load_avg = -----------------------------------		(4)
4407  *                               grq->load.weight
4408  *
4409  * Except that is wrong!
4410  *
4411  * Because while for entities historical weight is not important and we
4412  * really only care about our future and therefore can consider a pure
4413  * runnable sum, runqueues can NOT do this.
4414  *
4415  * We specifically want runqueues to have a load_avg that includes
4416  * historical weights. Those represent the blocked load, the load we expect
4417  * to (shortly) return to us. This only works by keeping the weights as
4418  * integral part of the sum. We therefore cannot decompose as per (3).
4419  *
4420  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4421  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4422  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4423  * runnable section of these tasks overlap (or not). If they were to perfectly
4424  * align the rq as a whole would be runnable 2/3 of the time. If however we
4425  * always have at least 1 runnable task, the rq as a whole is always runnable.
4426  *
4427  * So we'll have to approximate.. :/
4428  *
4429  * Given the constraint:
4430  *
4431  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4432  *
4433  * We can construct a rule that adds runnable to a rq by assuming minimal
4434  * overlap.
4435  *
4436  * On removal, we'll assume each task is equally runnable; which yields:
4437  *
4438  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4439  *
4440  * XXX: only do this for the part of runnable > running ?
4441  *
4442  */
4443 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4444 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4445 {
4446 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4447 	u32 new_sum, divider;
4448 
4449 	/* Nothing to update */
4450 	if (!delta_avg)
4451 		return;
4452 
4453 	/*
4454 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4455 	 * See ___update_load_avg() for details.
4456 	 */
4457 	divider = get_pelt_divider(&cfs_rq->avg);
4458 
4459 
4460 	/* Set new sched_entity's utilization */
4461 	se->avg.util_avg = gcfs_rq->avg.util_avg;
4462 	new_sum = se->avg.util_avg * divider;
4463 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
4464 	se->avg.util_sum = new_sum;
4465 
4466 	/* Update parent cfs_rq utilization */
4467 	add_positive(&cfs_rq->avg.util_avg, delta_avg);
4468 	add_positive(&cfs_rq->avg.util_sum, delta_sum);
4469 
4470 	/* See update_cfs_rq_load_avg() */
4471 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4472 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4473 }
4474 
4475 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4476 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4477 {
4478 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4479 	u32 new_sum, divider;
4480 
4481 	/* Nothing to update */
4482 	if (!delta_avg)
4483 		return;
4484 
4485 	/*
4486 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4487 	 * See ___update_load_avg() for details.
4488 	 */
4489 	divider = get_pelt_divider(&cfs_rq->avg);
4490 
4491 	/* Set new sched_entity's runnable */
4492 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4493 	new_sum = se->avg.runnable_avg * divider;
4494 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4495 	se->avg.runnable_sum = new_sum;
4496 
4497 	/* Update parent cfs_rq runnable */
4498 	add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4499 	add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4500 	/* See update_cfs_rq_load_avg() */
4501 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4502 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4503 }
4504 
4505 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4506 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4507 {
4508 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4509 	unsigned long load_avg;
4510 	u64 load_sum = 0;
4511 	s64 delta_sum;
4512 	u32 divider;
4513 
4514 	if (!runnable_sum)
4515 		return;
4516 
4517 	gcfs_rq->prop_runnable_sum = 0;
4518 
4519 	/*
4520 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4521 	 * See ___update_load_avg() for details.
4522 	 */
4523 	divider = get_pelt_divider(&cfs_rq->avg);
4524 
4525 	if (runnable_sum >= 0) {
4526 		/*
4527 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4528 		 * the CPU is saturated running == runnable.
4529 		 */
4530 		runnable_sum += se->avg.load_sum;
4531 		runnable_sum = min_t(long, runnable_sum, divider);
4532 	} else {
4533 		/*
4534 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4535 		 * assuming all tasks are equally runnable.
4536 		 */
4537 		if (scale_load_down(gcfs_rq->load.weight)) {
4538 			load_sum = div_u64(gcfs_rq->avg.load_sum,
4539 				scale_load_down(gcfs_rq->load.weight));
4540 		}
4541 
4542 		/* But make sure to not inflate se's runnable */
4543 		runnable_sum = min(se->avg.load_sum, load_sum);
4544 	}
4545 
4546 	/*
4547 	 * runnable_sum can't be lower than running_sum
4548 	 * Rescale running sum to be in the same range as runnable sum
4549 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
4550 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
4551 	 */
4552 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4553 	runnable_sum = max(runnable_sum, running_sum);
4554 
4555 	load_sum = se_weight(se) * runnable_sum;
4556 	load_avg = div_u64(load_sum, divider);
4557 
4558 	delta_avg = load_avg - se->avg.load_avg;
4559 	if (!delta_avg)
4560 		return;
4561 
4562 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4563 
4564 	se->avg.load_sum = runnable_sum;
4565 	se->avg.load_avg = load_avg;
4566 	add_positive(&cfs_rq->avg.load_avg, delta_avg);
4567 	add_positive(&cfs_rq->avg.load_sum, delta_sum);
4568 	/* See update_cfs_rq_load_avg() */
4569 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4570 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4571 }
4572 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4573 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4574 {
4575 	cfs_rq->propagate = 1;
4576 	cfs_rq->prop_runnable_sum += runnable_sum;
4577 }
4578 
4579 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4580 static inline int propagate_entity_load_avg(struct sched_entity *se)
4581 {
4582 	struct cfs_rq *cfs_rq, *gcfs_rq;
4583 
4584 	if (entity_is_task(se))
4585 		return 0;
4586 
4587 	gcfs_rq = group_cfs_rq(se);
4588 	if (!gcfs_rq->propagate)
4589 		return 0;
4590 
4591 	gcfs_rq->propagate = 0;
4592 
4593 	cfs_rq = cfs_rq_of(se);
4594 
4595 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4596 
4597 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4598 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4599 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4600 
4601 	trace_pelt_cfs_tp(cfs_rq);
4602 	trace_pelt_se_tp(se);
4603 
4604 	return 1;
4605 }
4606 
4607 /*
4608  * Check if we need to update the load and the utilization of a blocked
4609  * group_entity:
4610  */
skip_blocked_update(struct sched_entity * se)4611 static inline bool skip_blocked_update(struct sched_entity *se)
4612 {
4613 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4614 
4615 	/*
4616 	 * If sched_entity still have not zero load or utilization, we have to
4617 	 * decay it:
4618 	 */
4619 	if (se->avg.load_avg || se->avg.util_avg)
4620 		return false;
4621 
4622 	/*
4623 	 * If there is a pending propagation, we have to update the load and
4624 	 * the utilization of the sched_entity:
4625 	 */
4626 	if (gcfs_rq->propagate)
4627 		return false;
4628 
4629 	/*
4630 	 * Otherwise, the load and the utilization of the sched_entity is
4631 	 * already zero and there is no pending propagation, so it will be a
4632 	 * waste of time to try to decay it:
4633 	 */
4634 	return true;
4635 }
4636 
4637 #else /* CONFIG_FAIR_GROUP_SCHED */
4638 
update_tg_load_avg(struct cfs_rq * cfs_rq)4639 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4640 
clear_tg_offline_cfs_rqs(struct rq * rq)4641 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4642 
propagate_entity_load_avg(struct sched_entity * se)4643 static inline int propagate_entity_load_avg(struct sched_entity *se)
4644 {
4645 	return 0;
4646 }
4647 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4648 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4649 
4650 #endif /* CONFIG_FAIR_GROUP_SCHED */
4651 
4652 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4653 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4654 {
4655 	u64 throttled = 0, now, lut;
4656 	struct cfs_rq *cfs_rq;
4657 	struct rq *rq;
4658 	bool is_idle;
4659 
4660 	if (load_avg_is_decayed(&se->avg))
4661 		return;
4662 
4663 	cfs_rq = cfs_rq_of(se);
4664 	rq = rq_of(cfs_rq);
4665 
4666 	rcu_read_lock();
4667 	is_idle = is_idle_task(rcu_dereference(rq->curr));
4668 	rcu_read_unlock();
4669 
4670 	/*
4671 	 * The lag estimation comes with a cost we don't want to pay all the
4672 	 * time. Hence, limiting to the case where the source CPU is idle and
4673 	 * we know we are at the greatest risk to have an outdated clock.
4674 	 */
4675 	if (!is_idle)
4676 		return;
4677 
4678 	/*
4679 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4680 	 *
4681 	 *   last_update_time (the cfs_rq's last_update_time)
4682 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
4683 	 *      = rq_clock_pelt()@cfs_rq_idle
4684 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
4685 	 *
4686 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
4687 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4688 	 *
4689 	 *   rq_idle_lag (delta between now and rq's update)
4690 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
4691 	 *
4692 	 * We can then write:
4693 	 *
4694 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4695 	 *          sched_clock_cpu() - rq_clock()@rq_idle
4696 	 * Where:
4697 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4698 	 *      rq_clock()@rq_idle      is rq->clock_idle
4699 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
4700 	 *                              is cfs_rq->throttled_pelt_idle
4701 	 */
4702 
4703 #ifdef CONFIG_CFS_BANDWIDTH
4704 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4705 	/* The clock has been stopped for throttling */
4706 	if (throttled == U64_MAX)
4707 		return;
4708 #endif
4709 	now = u64_u32_load(rq->clock_pelt_idle);
4710 	/*
4711 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4712 	 * is observed the old clock_pelt_idle value and the new clock_idle,
4713 	 * which lead to an underestimation. The opposite would lead to an
4714 	 * overestimation.
4715 	 */
4716 	smp_rmb();
4717 	lut = cfs_rq_last_update_time(cfs_rq);
4718 
4719 	now -= throttled;
4720 	if (now < lut)
4721 		/*
4722 		 * cfs_rq->avg.last_update_time is more recent than our
4723 		 * estimation, let's use it.
4724 		 */
4725 		now = lut;
4726 	else
4727 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4728 
4729 	__update_load_avg_blocked_se(now, se);
4730 }
4731 #else
migrate_se_pelt_lag(struct sched_entity * se)4732 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4733 #endif
4734 
4735 /**
4736  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4737  * @now: current time, as per cfs_rq_clock_pelt()
4738  * @cfs_rq: cfs_rq to update
4739  *
4740  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4741  * avg. The immediate corollary is that all (fair) tasks must be attached.
4742  *
4743  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4744  *
4745  * Return: true if the load decayed or we removed load.
4746  *
4747  * Since both these conditions indicate a changed cfs_rq->avg.load we should
4748  * call update_tg_load_avg() when this function returns true.
4749  */
4750 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4751 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4752 {
4753 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4754 	struct sched_avg *sa = &cfs_rq->avg;
4755 	int decayed = 0;
4756 
4757 	if (cfs_rq->removed.nr) {
4758 		unsigned long r;
4759 		u32 divider = get_pelt_divider(&cfs_rq->avg);
4760 
4761 		raw_spin_lock(&cfs_rq->removed.lock);
4762 		swap(cfs_rq->removed.util_avg, removed_util);
4763 		swap(cfs_rq->removed.load_avg, removed_load);
4764 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
4765 		cfs_rq->removed.nr = 0;
4766 		raw_spin_unlock(&cfs_rq->removed.lock);
4767 
4768 		r = removed_load;
4769 		sub_positive(&sa->load_avg, r);
4770 		sub_positive(&sa->load_sum, r * divider);
4771 		/* See sa->util_sum below */
4772 		sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4773 
4774 		r = removed_util;
4775 		sub_positive(&sa->util_avg, r);
4776 		sub_positive(&sa->util_sum, r * divider);
4777 		/*
4778 		 * Because of rounding, se->util_sum might ends up being +1 more than
4779 		 * cfs->util_sum. Although this is not a problem by itself, detaching
4780 		 * a lot of tasks with the rounding problem between 2 updates of
4781 		 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4782 		 * cfs_util_avg is not.
4783 		 * Check that util_sum is still above its lower bound for the new
4784 		 * util_avg. Given that period_contrib might have moved since the last
4785 		 * sync, we are only sure that util_sum must be above or equal to
4786 		 *    util_avg * minimum possible divider
4787 		 */
4788 		sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4789 
4790 		r = removed_runnable;
4791 		sub_positive(&sa->runnable_avg, r);
4792 		sub_positive(&sa->runnable_sum, r * divider);
4793 		/* See sa->util_sum above */
4794 		sa->runnable_sum = max_t(u32, sa->runnable_sum,
4795 					      sa->runnable_avg * PELT_MIN_DIVIDER);
4796 
4797 		/*
4798 		 * removed_runnable is the unweighted version of removed_load so we
4799 		 * can use it to estimate removed_load_sum.
4800 		 */
4801 		add_tg_cfs_propagate(cfs_rq,
4802 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4803 
4804 		decayed = 1;
4805 	}
4806 
4807 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4808 	u64_u32_store_copy(sa->last_update_time,
4809 			   cfs_rq->last_update_time_copy,
4810 			   sa->last_update_time);
4811 	return decayed;
4812 }
4813 
4814 /**
4815  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4816  * @cfs_rq: cfs_rq to attach to
4817  * @se: sched_entity to attach
4818  *
4819  * Must call update_cfs_rq_load_avg() before this, since we rely on
4820  * cfs_rq->avg.last_update_time being current.
4821  */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4822 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4823 {
4824 	/*
4825 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4826 	 * See ___update_load_avg() for details.
4827 	 */
4828 	u32 divider = get_pelt_divider(&cfs_rq->avg);
4829 
4830 	/*
4831 	 * When we attach the @se to the @cfs_rq, we must align the decay
4832 	 * window because without that, really weird and wonderful things can
4833 	 * happen.
4834 	 *
4835 	 * XXX illustrate
4836 	 */
4837 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
4838 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
4839 
4840 	/*
4841 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4842 	 * period_contrib. This isn't strictly correct, but since we're
4843 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4844 	 * _sum a little.
4845 	 */
4846 	se->avg.util_sum = se->avg.util_avg * divider;
4847 
4848 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
4849 
4850 	se->avg.load_sum = se->avg.load_avg * divider;
4851 	if (se_weight(se) < se->avg.load_sum)
4852 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4853 	else
4854 		se->avg.load_sum = 1;
4855 
4856 	trace_android_rvh_attach_entity_load_avg(cfs_rq, se);
4857 
4858 	enqueue_load_avg(cfs_rq, se);
4859 	cfs_rq->avg.util_avg += se->avg.util_avg;
4860 	cfs_rq->avg.util_sum += se->avg.util_sum;
4861 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4862 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4863 
4864 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4865 
4866 	cfs_rq_util_change(cfs_rq, 0);
4867 
4868 	trace_pelt_cfs_tp(cfs_rq);
4869 }
4870 
4871 /**
4872  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4873  * @cfs_rq: cfs_rq to detach from
4874  * @se: sched_entity to detach
4875  *
4876  * Must call update_cfs_rq_load_avg() before this, since we rely on
4877  * cfs_rq->avg.last_update_time being current.
4878  */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4879 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4880 {
4881 	trace_android_rvh_detach_entity_load_avg(cfs_rq, se);
4882 
4883 	dequeue_load_avg(cfs_rq, se);
4884 	sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4885 	sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4886 	/* See update_cfs_rq_load_avg() */
4887 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4888 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4889 
4890 	sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4891 	sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4892 	/* See update_cfs_rq_load_avg() */
4893 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4894 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4895 
4896 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4897 
4898 	cfs_rq_util_change(cfs_rq, 0);
4899 
4900 	trace_pelt_cfs_tp(cfs_rq);
4901 }
4902 
4903 /*
4904  * Optional action to be done while updating the load average
4905  */
4906 #define UPDATE_TG	0x1
4907 #define SKIP_AGE_LOAD	0x2
4908 #define DO_ATTACH	0x4
4909 #define DO_DETACH	0x8
4910 
4911 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4912 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4913 {
4914 	u64 now = cfs_rq_clock_pelt(cfs_rq);
4915 	int decayed;
4916 
4917 	/*
4918 	 * Track task load average for carrying it to new CPU after migrated, and
4919 	 * track group sched_entity load average for task_h_load calculation in migration
4920 	 */
4921 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4922 		__update_load_avg_se(now, cfs_rq, se);
4923 
4924 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
4925 	decayed |= propagate_entity_load_avg(se);
4926 
4927 	trace_android_rvh_update_load_avg(now, cfs_rq, se);
4928 
4929 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4930 
4931 		/*
4932 		 * DO_ATTACH means we're here from enqueue_entity().
4933 		 * !last_update_time means we've passed through
4934 		 * migrate_task_rq_fair() indicating we migrated.
4935 		 *
4936 		 * IOW we're enqueueing a task on a new CPU.
4937 		 */
4938 		attach_entity_load_avg(cfs_rq, se);
4939 		update_tg_load_avg(cfs_rq);
4940 
4941 	} else if (flags & DO_DETACH) {
4942 		/*
4943 		 * DO_DETACH means we're here from dequeue_entity()
4944 		 * and we are migrating task out of the CPU.
4945 		 */
4946 		detach_entity_load_avg(cfs_rq, se);
4947 		update_tg_load_avg(cfs_rq);
4948 	} else if (decayed) {
4949 		cfs_rq_util_change(cfs_rq, 0);
4950 
4951 		if (flags & UPDATE_TG)
4952 			update_tg_load_avg(cfs_rq);
4953 	}
4954 }
4955 
4956 /*
4957  * Synchronize entity load avg of dequeued entity without locking
4958  * the previous rq.
4959  */
sync_entity_load_avg(struct sched_entity * se)4960 static void sync_entity_load_avg(struct sched_entity *se)
4961 {
4962 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4963 	u64 last_update_time;
4964 
4965 	last_update_time = cfs_rq_last_update_time(cfs_rq);
4966 	__update_load_avg_blocked_se(last_update_time, se);
4967 }
4968 
4969 /*
4970  * Task first catches up with cfs_rq, and then subtract
4971  * itself from the cfs_rq (task must be off the queue now).
4972  */
remove_entity_load_avg(struct sched_entity * se)4973 static void remove_entity_load_avg(struct sched_entity *se)
4974 {
4975 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4976 	unsigned long flags;
4977 
4978 	/*
4979 	 * tasks cannot exit without having gone through wake_up_new_task() ->
4980 	 * enqueue_task_fair() which will have added things to the cfs_rq,
4981 	 * so we can remove unconditionally.
4982 	 */
4983 
4984 	sync_entity_load_avg(se);
4985 
4986 	trace_android_rvh_remove_entity_load_avg(cfs_rq, se);
4987 
4988 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4989 	++cfs_rq->removed.nr;
4990 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
4991 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
4992 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
4993 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4994 }
4995 
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4996 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4997 {
4998 	return cfs_rq->avg.runnable_avg;
4999 }
5000 
cfs_rq_load_avg(struct cfs_rq * cfs_rq)5001 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
5002 {
5003 	return cfs_rq->avg.load_avg;
5004 }
5005 
5006 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
5007 
task_util(struct task_struct * p)5008 static inline unsigned long task_util(struct task_struct *p)
5009 {
5010 	return READ_ONCE(p->se.avg.util_avg);
5011 }
5012 
task_runnable(struct task_struct * p)5013 static inline unsigned long task_runnable(struct task_struct *p)
5014 {
5015 	return READ_ONCE(p->se.avg.runnable_avg);
5016 }
5017 
_task_util_est(struct task_struct * p)5018 static inline unsigned long _task_util_est(struct task_struct *p)
5019 {
5020 	return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
5021 }
5022 
task_util_est(struct task_struct * p)5023 static inline unsigned long task_util_est(struct task_struct *p)
5024 {
5025 	return max(task_util(p), _task_util_est(p));
5026 }
5027 
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5028 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
5029 				    struct task_struct *p)
5030 {
5031 	unsigned int enqueued;
5032 
5033 	if (!sched_feat(UTIL_EST))
5034 		return;
5035 
5036 	/* Update root cfs_rq's estimated utilization */
5037 	enqueued  = cfs_rq->avg.util_est;
5038 	enqueued += _task_util_est(p);
5039 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5040 
5041 	trace_sched_util_est_cfs_tp(cfs_rq);
5042 }
5043 
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5044 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
5045 				    struct task_struct *p)
5046 {
5047 	unsigned int enqueued;
5048 
5049 	if (!sched_feat(UTIL_EST))
5050 		return;
5051 
5052 	/* Update root cfs_rq's estimated utilization */
5053 	enqueued  = cfs_rq->avg.util_est;
5054 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
5055 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5056 
5057 	trace_sched_util_est_cfs_tp(cfs_rq);
5058 }
5059 
5060 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
5061 
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5062 static inline void util_est_update(struct cfs_rq *cfs_rq,
5063 				   struct task_struct *p,
5064 				   bool task_sleep)
5065 {
5066 	unsigned int ewma, dequeued, last_ewma_diff;
5067 	int ret = 0;
5068 
5069 	trace_android_rvh_util_est_update(cfs_rq, p, task_sleep, &ret);
5070 	if (ret)
5071 		return;
5072 
5073 	if (!sched_feat(UTIL_EST))
5074 		return;
5075 
5076 	/*
5077 	 * Skip update of task's estimated utilization when the task has not
5078 	 * yet completed an activation, e.g. being migrated.
5079 	 */
5080 	if (!task_sleep)
5081 		return;
5082 
5083 	/* Get current estimate of utilization */
5084 	ewma = READ_ONCE(p->se.avg.util_est);
5085 
5086 	/*
5087 	 * If the PELT values haven't changed since enqueue time,
5088 	 * skip the util_est update.
5089 	 */
5090 	if (ewma & UTIL_AVG_UNCHANGED)
5091 		return;
5092 
5093 	/* Get utilization at dequeue */
5094 	dequeued = task_util(p);
5095 
5096 	/*
5097 	 * Reset EWMA on utilization increases, the moving average is used only
5098 	 * to smooth utilization decreases.
5099 	 */
5100 	if (ewma <= dequeued) {
5101 		ewma = dequeued;
5102 		goto done;
5103 	}
5104 
5105 	/*
5106 	 * Skip update of task's estimated utilization when its members are
5107 	 * already ~1% close to its last activation value.
5108 	 */
5109 	last_ewma_diff = ewma - dequeued;
5110 	if (last_ewma_diff < UTIL_EST_MARGIN)
5111 		goto done;
5112 
5113 	/*
5114 	 * To avoid overestimation of actual task utilization, skip updates if
5115 	 * we cannot grant there is idle time in this CPU.
5116 	 */
5117 	if (dequeued > arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))))
5118 		return;
5119 
5120 	/*
5121 	 * To avoid underestimate of task utilization, skip updates of EWMA if
5122 	 * we cannot grant that thread got all CPU time it wanted.
5123 	 */
5124 	if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
5125 		goto done;
5126 
5127 
5128 	/*
5129 	 * Update Task's estimated utilization
5130 	 *
5131 	 * When *p completes an activation we can consolidate another sample
5132 	 * of the task size. This is done by using this value to update the
5133 	 * Exponential Weighted Moving Average (EWMA):
5134 	 *
5135 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
5136 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
5137 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
5138 	 *          = w * (      -last_ewma_diff           ) +     ewma(t-1)
5139 	 *          = w * (-last_ewma_diff +  ewma(t-1) / w)
5140 	 *
5141 	 * Where 'w' is the weight of new samples, which is configured to be
5142 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5143 	 */
5144 	ewma <<= UTIL_EST_WEIGHT_SHIFT;
5145 	ewma  -= last_ewma_diff;
5146 	ewma >>= UTIL_EST_WEIGHT_SHIFT;
5147 done:
5148 	ewma |= UTIL_AVG_UNCHANGED;
5149 	WRITE_ONCE(p->se.avg.util_est, ewma);
5150 
5151 	trace_sched_util_est_se_tp(&p->se);
5152 }
5153 
get_actual_cpu_capacity(int cpu)5154 static inline unsigned long get_actual_cpu_capacity(int cpu)
5155 {
5156 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
5157 
5158 	capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
5159 
5160 	return capacity;
5161 }
5162 
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)5163 static inline int util_fits_cpu(unsigned long util,
5164 				unsigned long uclamp_min,
5165 				unsigned long uclamp_max,
5166 				int cpu)
5167 {
5168 	unsigned long capacity = capacity_of(cpu);
5169 	unsigned long capacity_orig;
5170 	bool fits, uclamp_max_fits, done = false;
5171 
5172 	trace_android_rvh_util_fits_cpu(util, uclamp_min, uclamp_max, cpu, &fits, &done);
5173 
5174 	if (done)
5175 		return fits;
5176 
5177 	/*
5178 	 * Check if the real util fits without any uclamp boost/cap applied.
5179 	 */
5180 	fits = fits_capacity(util, capacity);
5181 
5182 	if (!uclamp_is_used())
5183 		return fits;
5184 
5185 	/*
5186 	 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
5187 	 * uclamp_max. We only care about capacity pressure (by using
5188 	 * capacity_of()) for comparing against the real util.
5189 	 *
5190 	 * If a task is boosted to 1024 for example, we don't want a tiny
5191 	 * pressure to skew the check whether it fits a CPU or not.
5192 	 *
5193 	 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
5194 	 * should fit a little cpu even if there's some pressure.
5195 	 *
5196 	 * Only exception is for HW or cpufreq pressure since it has a direct impact
5197 	 * on available OPP of the system.
5198 	 *
5199 	 * We honour it for uclamp_min only as a drop in performance level
5200 	 * could result in not getting the requested minimum performance level.
5201 	 *
5202 	 * For uclamp_max, we can tolerate a drop in performance level as the
5203 	 * goal is to cap the task. So it's okay if it's getting less.
5204 	 */
5205 	capacity_orig = arch_scale_cpu_capacity(cpu);
5206 
5207 	/*
5208 	 * We want to force a task to fit a cpu as implied by uclamp_max.
5209 	 * But we do have some corner cases to cater for..
5210 	 *
5211 	 *
5212 	 *                                 C=z
5213 	 *   |                             ___
5214 	 *   |                  C=y       |   |
5215 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
5216 	 *   |      C=x        |   |      |   |
5217 	 *   |      ___        |   |      |   |
5218 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
5219 	 *   |     |   |       |   |      |   |
5220 	 *   |     |   |       |   |      |   |
5221 	 *   +----------------------------------------
5222 	 *         CPU0        CPU1       CPU2
5223 	 *
5224 	 *   In the above example if a task is capped to a specific performance
5225 	 *   point, y, then when:
5226 	 *
5227 	 *   * util = 80% of x then it does not fit on CPU0 and should migrate
5228 	 *     to CPU1
5229 	 *   * util = 80% of y then it is forced to fit on CPU1 to honour
5230 	 *     uclamp_max request.
5231 	 *
5232 	 *   which is what we're enforcing here. A task always fits if
5233 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
5234 	 *   the normal upmigration rules should withhold still.
5235 	 *
5236 	 *   Only exception is when we are on max capacity, then we need to be
5237 	 *   careful not to block overutilized state. This is so because:
5238 	 *
5239 	 *     1. There's no concept of capping at max_capacity! We can't go
5240 	 *        beyond this performance level anyway.
5241 	 *     2. The system is being saturated when we're operating near
5242 	 *        max capacity, it doesn't make sense to block overutilized.
5243 	 */
5244 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5245 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5246 	fits = fits || uclamp_max_fits;
5247 
5248 	/*
5249 	 *
5250 	 *                                 C=z
5251 	 *   |                             ___       (region a, capped, util >= uclamp_max)
5252 	 *   |                  C=y       |   |
5253 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5254 	 *   |      C=x        |   |      |   |
5255 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
5256 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5257 	 *   |     |   |       |   |      |   |
5258 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
5259 	 *   +----------------------------------------
5260 	 *         CPU0        CPU1       CPU2
5261 	 *
5262 	 * a) If util > uclamp_max, then we're capped, we don't care about
5263 	 *    actual fitness value here. We only care if uclamp_max fits
5264 	 *    capacity without taking margin/pressure into account.
5265 	 *    See comment above.
5266 	 *
5267 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
5268 	 *    fits_capacity() rules apply. Except we need to ensure that we
5269 	 *    enforce we remain within uclamp_max, see comment above.
5270 	 *
5271 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5272 	 *    need to take into account the boosted value fits the CPU without
5273 	 *    taking margin/pressure into account.
5274 	 *
5275 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
5276 	 * just need to consider an extra check for case (c) after ensuring we
5277 	 * handle the case uclamp_min > uclamp_max.
5278 	 */
5279 	uclamp_min = min(uclamp_min, uclamp_max);
5280 	if (fits && (util < uclamp_min) &&
5281 	    (uclamp_min > get_actual_cpu_capacity(cpu)))
5282 		return -1;
5283 
5284 	return fits;
5285 }
5286 
task_fits_cpu(struct task_struct * p,int cpu)5287 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5288 {
5289 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5290 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5291 	unsigned long util = task_util_est(p);
5292 	/*
5293 	 * Return true only if the cpu fully fits the task requirements, which
5294 	 * include the utilization but also the performance hints.
5295 	 */
5296 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5297 }
5298 
is_misfit_task(struct task_struct * p,struct rq * rq,misfit_reason_t * reason)5299 static inline int is_misfit_task(struct task_struct *p, struct rq *rq,
5300 				 misfit_reason_t *reason)
5301 {
5302 	int cpu = cpu_of(rq);
5303 
5304 	if (!p || p->nr_cpus_allowed == 1)
5305 		return 0;
5306 
5307 	if (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity)
5308 		return 0;
5309 
5310 	if (task_fits_cpu(p, cpu_of(rq)))
5311 		return 0;
5312 
5313 	if (reason)
5314 		*reason = MISFIT_PERF;
5315 
5316 	return 1;
5317 }
5318 
update_misfit_status(struct task_struct * p,struct rq * rq)5319 inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5320 {
5321 	bool need_update = true;
5322 	misfit_reason_t reason;
5323 
5324 	rq->misfit_task_load = 0;
5325 	rq->misfit_reason = -1;
5326 
5327 	trace_android_rvh_update_misfit_status(p, rq, &need_update);
5328 	if (!sched_asym_cpucap_active() || !need_update)
5329 		return;
5330 
5331 	/*
5332 	 * Affinity allows us to go somewhere higher?  Or are we on biggest
5333 	 * available CPU already? Or do we fit into this CPU ?
5334 	 */
5335 	if (is_misfit_task(p, rq, &reason)) {
5336 		/*
5337 		 * Make sure that misfit_task_load will not be null even if
5338 		 * task_h_load() returns 0.
5339 		 */
5340 		rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5341 		rq->misfit_reason = reason;
5342 	}
5343 
5344 }
5345 EXPORT_SYMBOL_GPL(update_misfit_status);
5346 
5347 #else /* CONFIG_SMP */
5348 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)5349 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5350 {
5351 	return !cfs_rq->nr_running;
5352 }
5353 
5354 #define UPDATE_TG	0x0
5355 #define SKIP_AGE_LOAD	0x0
5356 #define DO_ATTACH	0x0
5357 #define DO_DETACH	0x0
5358 
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)5359 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
5360 {
5361 	cfs_rq_util_change(cfs_rq, 0);
5362 }
5363 
remove_entity_load_avg(struct sched_entity * se)5364 static inline void remove_entity_load_avg(struct sched_entity *se) {}
5365 
5366 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5367 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5368 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5369 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5370 
sched_balance_newidle(struct rq * rq,struct rq_flags * rf)5371 static inline int sched_balance_newidle(struct rq *rq, struct rq_flags *rf)
5372 {
5373 	return 0;
5374 }
5375 
5376 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5377 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5378 
5379 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5380 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5381 
5382 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5383 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
5384 		bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)5385 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
5386 
5387 #endif /* CONFIG_SMP */
5388 
5389 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5390 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5391 {
5392 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
5393 	s64 lag = 0;
5394 
5395 	if (!se->custom_slice)
5396 		se->slice = sysctl_sched_base_slice;
5397 	vslice = calc_delta_fair(se->slice, se);
5398 
5399 	/*
5400 	 * Due to how V is constructed as the weighted average of entities,
5401 	 * adding tasks with positive lag, or removing tasks with negative lag
5402 	 * will move 'time' backwards, this can screw around with the lag of
5403 	 * other tasks.
5404 	 *
5405 	 * EEVDF: placement strategy #1 / #2
5406 	 */
5407 	if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
5408 		struct sched_entity *curr = cfs_rq->curr;
5409 		unsigned long load;
5410 
5411 		lag = se->vlag;
5412 
5413 		/*
5414 		 * If we want to place a task and preserve lag, we have to
5415 		 * consider the effect of the new entity on the weighted
5416 		 * average and compensate for this, otherwise lag can quickly
5417 		 * evaporate.
5418 		 *
5419 		 * Lag is defined as:
5420 		 *
5421 		 *   lag_i = S - s_i = w_i * (V - v_i)
5422 		 *
5423 		 * To avoid the 'w_i' term all over the place, we only track
5424 		 * the virtual lag:
5425 		 *
5426 		 *   vl_i = V - v_i <=> v_i = V - vl_i
5427 		 *
5428 		 * And we take V to be the weighted average of all v:
5429 		 *
5430 		 *   V = (\Sum w_j*v_j) / W
5431 		 *
5432 		 * Where W is: \Sum w_j
5433 		 *
5434 		 * Then, the weighted average after adding an entity with lag
5435 		 * vl_i is given by:
5436 		 *
5437 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5438 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
5439 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5440 		 *      = (V*(W + w_i) - w_i*l) / (W + w_i)
5441 		 *      = V - w_i*vl_i / (W + w_i)
5442 		 *
5443 		 * And the actual lag after adding an entity with vl_i is:
5444 		 *
5445 		 *   vl'_i = V' - v_i
5446 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5447 		 *         = vl_i - w_i*vl_i / (W + w_i)
5448 		 *
5449 		 * Which is strictly less than vl_i. So in order to preserve lag
5450 		 * we should inflate the lag before placement such that the
5451 		 * effective lag after placement comes out right.
5452 		 *
5453 		 * As such, invert the above relation for vl'_i to get the vl_i
5454 		 * we need to use such that the lag after placement is the lag
5455 		 * we computed before dequeue.
5456 		 *
5457 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
5458 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5459 		 *
5460 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5461 		 *                   = W*vl_i
5462 		 *
5463 		 *   vl_i = (W + w_i)*vl'_i / W
5464 		 */
5465 		load = cfs_rq->avg_load;
5466 		if (curr && curr->on_rq)
5467 			load += scale_load_down(curr->load.weight);
5468 
5469 		lag *= load + scale_load_down(se->load.weight);
5470 		if (WARN_ON_ONCE(!load))
5471 			load = 1;
5472 		lag = div_s64(lag, load);
5473 	}
5474 
5475 	se->vruntime = vruntime - lag;
5476 
5477 	if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
5478 		se->deadline += se->vruntime;
5479 		se->rel_deadline = 0;
5480 		return;
5481 	}
5482 
5483 	/*
5484 	 * When joining the competition; the existing tasks will be,
5485 	 * on average, halfway through their slice, as such start tasks
5486 	 * off with half a slice to ease into the competition.
5487 	 */
5488 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5489 		vslice /= 2;
5490 
5491 	/*
5492 	 * EEVDF: vd_i = ve_i + r_i/w_i
5493 	 */
5494 	se->deadline = se->vruntime + vslice;
5495 	trace_android_rvh_place_entity(cfs_rq, se, flags, &vruntime);
5496 }
5497 
5498 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5499 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5500 
5501 static inline bool cfs_bandwidth_used(void);
5502 
5503 static void
5504 requeue_delayed_entity(struct sched_entity *se);
5505 
5506 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5507 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5508 {
5509 	bool curr = cfs_rq->curr == se;
5510 
5511 	/*
5512 	 * If we're the current task, we must renormalise before calling
5513 	 * update_curr().
5514 	 */
5515 	if (curr)
5516 		place_entity(cfs_rq, se, flags);
5517 
5518 	update_curr(cfs_rq);
5519 
5520 	/*
5521 	 * When enqueuing a sched_entity, we must:
5522 	 *   - Update loads to have both entity and cfs_rq synced with now.
5523 	 *   - For group_entity, update its runnable_weight to reflect the new
5524 	 *     h_nr_running of its group cfs_rq.
5525 	 *   - For group_entity, update its weight to reflect the new share of
5526 	 *     its group cfs_rq
5527 	 *   - Add its new weight to cfs_rq->load.weight
5528 	 */
5529 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5530 	se_update_runnable(se);
5531 	/*
5532 	 * XXX update_load_avg() above will have attached us to the pelt sum;
5533 	 * but update_cfs_group() here will re-adjust the weight and have to
5534 	 * undo/redo all that. Seems wasteful.
5535 	 */
5536 	update_cfs_group(se);
5537 
5538 	/*
5539 	 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5540 	 * we can place the entity.
5541 	 */
5542 	if (!curr)
5543 		place_entity(cfs_rq, se, flags);
5544 
5545 	account_entity_enqueue(cfs_rq, se);
5546 
5547 	/* Entity has migrated, no longer consider this task hot */
5548 	if (flags & ENQUEUE_MIGRATED)
5549 		se->exec_start = 0;
5550 
5551 	check_schedstat_required();
5552 	update_stats_enqueue_fair(cfs_rq, se, flags);
5553 	if (!curr)
5554 		__enqueue_entity(cfs_rq, se);
5555 	se->on_rq = 1;
5556 
5557 	if (cfs_rq->nr_running == 1) {
5558 		check_enqueue_throttle(cfs_rq);
5559 		if (!throttled_hierarchy(cfs_rq)) {
5560 			list_add_leaf_cfs_rq(cfs_rq);
5561 		} else {
5562 #ifdef CONFIG_CFS_BANDWIDTH
5563 			struct rq *rq = rq_of(cfs_rq);
5564 
5565 			if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5566 				cfs_rq->throttled_clock = rq_clock(rq);
5567 			if (!cfs_rq->throttled_clock_self)
5568 				cfs_rq->throttled_clock_self = rq_clock(rq);
5569 #endif
5570 		}
5571 	}
5572 }
5573 
__clear_buddies_next(struct sched_entity * se)5574 static void __clear_buddies_next(struct sched_entity *se)
5575 {
5576 	for_each_sched_entity(se) {
5577 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5578 		if (cfs_rq->next != se)
5579 			break;
5580 
5581 		cfs_rq->next = NULL;
5582 	}
5583 }
5584 
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5585 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5586 {
5587 	if (cfs_rq->next == se)
5588 		__clear_buddies_next(se);
5589 }
5590 
5591 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5592 
set_delayed(struct sched_entity * se)5593 static void set_delayed(struct sched_entity *se)
5594 {
5595 	se->sched_delayed = 1;
5596 
5597 	/*
5598 	 * Delayed se of cfs_rq have no tasks queued on them.
5599 	 * Do not adjust h_nr_runnable since dequeue_entities()
5600 	 * will account it for blocked tasks.
5601 	 */
5602 	if (!entity_is_task(se))
5603 		return;
5604 
5605 	for_each_sched_entity(se) {
5606 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5607 
5608 		cfs_rq->h_nr_delayed++;
5609 		if (cfs_rq_throttled(cfs_rq))
5610 			break;
5611 	}
5612 }
5613 
clear_delayed(struct sched_entity * se)5614 static void clear_delayed(struct sched_entity *se)
5615 {
5616 	se->sched_delayed = 0;
5617 
5618 	/*
5619 	 * Delayed se of cfs_rq have no tasks queued on them.
5620 	 * Do not adjust h_nr_runnable since a dequeue has
5621 	 * already accounted for it or an enqueue of a task
5622 	 * below it will account for it in enqueue_task_fair().
5623 	 */
5624 	if (!entity_is_task(se))
5625 		return;
5626 
5627 	for_each_sched_entity(se) {
5628 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5629 
5630 		cfs_rq->h_nr_delayed--;
5631 		if (cfs_rq_throttled(cfs_rq))
5632 			break;
5633 	}
5634 }
5635 
finish_delayed_dequeue_entity(struct sched_entity * se)5636 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5637 {
5638 	clear_delayed(se);
5639 	if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5640 		se->vlag = 0;
5641 }
5642 
5643 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5644 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5645 {
5646 	bool sleep = flags & DEQUEUE_SLEEP;
5647 
5648 	update_curr(cfs_rq);
5649 	clear_buddies(cfs_rq, se);
5650 
5651 	if (flags & DEQUEUE_DELAYED) {
5652 		SCHED_WARN_ON(!se->sched_delayed);
5653 	} else {
5654 		bool delay = sleep;
5655 		/*
5656 		 * DELAY_DEQUEUE relies on spurious wakeups, special task
5657 		 * states must not suffer spurious wakeups, excempt them.
5658 		 */
5659 		if (flags & DEQUEUE_SPECIAL)
5660 			delay = false;
5661 
5662 		SCHED_WARN_ON(delay && se->sched_delayed);
5663 
5664 		trace_android_rvh_dequeue_entity_delayed(cfs_rq, se, &delay);
5665 		if (sched_feat(DELAY_DEQUEUE) && delay &&
5666 		    !entity_eligible(cfs_rq, se)) {
5667 			update_load_avg(cfs_rq, se, 0);
5668 			set_delayed(se);
5669 			return false;
5670 		}
5671 	}
5672 
5673 	int action = UPDATE_TG;
5674 	if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5675 		action |= DO_DETACH;
5676 
5677 	/*
5678 	 * When dequeuing a sched_entity, we must:
5679 	 *   - Update loads to have both entity and cfs_rq synced with now.
5680 	 *   - For group_entity, update its runnable_weight to reflect the new
5681 	 *     h_nr_running of its group cfs_rq.
5682 	 *   - Subtract its previous weight from cfs_rq->load.weight.
5683 	 *   - For group entity, update its weight to reflect the new share
5684 	 *     of its group cfs_rq.
5685 	 */
5686 	update_load_avg(cfs_rq, se, action);
5687 	se_update_runnable(se);
5688 
5689 	update_stats_dequeue_fair(cfs_rq, se, flags);
5690 
5691 	update_entity_lag(cfs_rq, se);
5692 	if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5693 		se->deadline -= se->vruntime;
5694 		se->rel_deadline = 1;
5695 	}
5696 
5697 	if (se != cfs_rq->curr)
5698 		__dequeue_entity(cfs_rq, se);
5699 	se->on_rq = 0;
5700 	account_entity_dequeue(cfs_rq, se);
5701 
5702 	/* return excess runtime on last dequeue */
5703 	return_cfs_rq_runtime(cfs_rq);
5704 
5705 	update_cfs_group(se);
5706 
5707 	/*
5708 	 * Now advance min_vruntime if @se was the entity holding it back,
5709 	 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5710 	 * put back on, and if we advance min_vruntime, we'll be placed back
5711 	 * further than we started -- i.e. we'll be penalized.
5712 	 */
5713 	if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5714 		update_min_vruntime(cfs_rq);
5715 
5716 	if (flags & DEQUEUE_DELAYED)
5717 		finish_delayed_dequeue_entity(se);
5718 
5719 	if (cfs_rq->nr_running == 0)
5720 		update_idle_cfs_rq_clock_pelt(cfs_rq);
5721 
5722 	return true;
5723 }
5724 
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5725 void set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5726 {
5727 	clear_buddies(cfs_rq, se);
5728 
5729 	/* 'current' is not kept within the tree. */
5730 	if (se->on_rq) {
5731 		/*
5732 		 * Any task has to be enqueued before it get to execute on
5733 		 * a CPU. So account for the time it spent waiting on the
5734 		 * runqueue.
5735 		 */
5736 		update_stats_wait_end_fair(cfs_rq, se);
5737 		__dequeue_entity(cfs_rq, se);
5738 		update_load_avg(cfs_rq, se, UPDATE_TG);
5739 
5740 		set_protect_slice(se);
5741 	}
5742 
5743 	update_stats_curr_start(cfs_rq, se);
5744 	SCHED_WARN_ON(cfs_rq->curr);
5745 	cfs_rq->curr = se;
5746 
5747 	/*
5748 	 * Track our maximum slice length, if the CPU's load is at
5749 	 * least twice that of our own weight (i.e. don't track it
5750 	 * when there are only lesser-weight tasks around):
5751 	 */
5752 	if (schedstat_enabled() &&
5753 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5754 		struct sched_statistics *stats;
5755 
5756 		stats = __schedstats_from_se(se);
5757 		__schedstat_set(stats->slice_max,
5758 				max((u64)stats->slice_max,
5759 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
5760 	}
5761 
5762 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
5763 }
5764 EXPORT_SYMBOL_GPL(set_next_entity);
5765 
5766 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5767 
5768 /*
5769  * Pick the next process, keeping these things in mind, in this order:
5770  * 1) keep things fair between processes/task groups
5771  * 2) pick the "next" process, since someone really wants that to run
5772  * 3) pick the "last" process, for cache locality
5773  * 4) do not run the "skip" process, if something else is available
5774  */
5775 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5776 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5777 {
5778 	/*
5779 	 * Picking the ->next buddy will affect latency but not fairness.
5780 	 */
5781 	if (sched_feat(PICK_BUDDY) &&
5782 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
5783 		/* ->next will never be delayed */
5784 		SCHED_WARN_ON(cfs_rq->next->sched_delayed);
5785 		return cfs_rq->next;
5786 	}
5787 
5788 	struct sched_entity *se = pick_eevdf(cfs_rq);
5789 	if (se->sched_delayed) {
5790 		dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5791 		/*
5792 		 * Must not reference @se again, see __block_task().
5793 		 */
5794 		return NULL;
5795 	}
5796 	return se;
5797 }
5798 
5799 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5800 
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5801 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5802 {
5803 	/*
5804 	 * If still on the runqueue then deactivate_task()
5805 	 * was not called and update_curr() has to be done:
5806 	 */
5807 	if (prev->on_rq)
5808 		update_curr(cfs_rq);
5809 
5810 	/* throttle cfs_rqs exceeding runtime */
5811 	check_cfs_rq_runtime(cfs_rq);
5812 
5813 	if (prev->on_rq) {
5814 		update_stats_wait_start_fair(cfs_rq, prev);
5815 		/* Put 'current' back into the tree. */
5816 		__enqueue_entity(cfs_rq, prev);
5817 		/* in !on_rq case, update occurred at dequeue */
5818 		update_load_avg(cfs_rq, prev, 0);
5819 	}
5820 	SCHED_WARN_ON(cfs_rq->curr != prev);
5821 	cfs_rq->curr = NULL;
5822 }
5823 
5824 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5825 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5826 {
5827 	/*
5828 	 * Update run-time statistics of the 'current'.
5829 	 */
5830 	update_curr(cfs_rq);
5831 
5832 	/*
5833 	 * Ensure that runnable average is periodically updated.
5834 	 */
5835 	update_load_avg(cfs_rq, curr, UPDATE_TG);
5836 	update_cfs_group(curr);
5837 
5838 #ifdef CONFIG_SCHED_HRTICK
5839 	/*
5840 	 * queued ticks are scheduled to match the slice, so don't bother
5841 	 * validating it and just reschedule.
5842 	 */
5843 	if (queued) {
5844 		resched_curr(rq_of(cfs_rq));
5845 		return;
5846 	}
5847 	/*
5848 	 * don't let the period tick interfere with the hrtick preemption
5849 	 */
5850 	if (!sched_feat(DOUBLE_TICK) &&
5851 			hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5852 		return;
5853 #endif
5854 	trace_android_rvh_entity_tick(cfs_rq, curr);
5855 }
5856 
5857 
5858 /**************************************************
5859  * CFS bandwidth control machinery
5860  */
5861 
5862 #ifdef CONFIG_CFS_BANDWIDTH
5863 
5864 #ifdef CONFIG_JUMP_LABEL
5865 static struct static_key __cfs_bandwidth_used;
5866 
cfs_bandwidth_used(void)5867 static inline bool cfs_bandwidth_used(void)
5868 {
5869 	return static_key_false(&__cfs_bandwidth_used);
5870 }
5871 
cfs_bandwidth_usage_inc(void)5872 void cfs_bandwidth_usage_inc(void)
5873 {
5874 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5875 }
5876 
cfs_bandwidth_usage_dec(void)5877 void cfs_bandwidth_usage_dec(void)
5878 {
5879 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5880 }
5881 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)5882 static bool cfs_bandwidth_used(void)
5883 {
5884 	return true;
5885 }
5886 
cfs_bandwidth_usage_inc(void)5887 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5888 void cfs_bandwidth_usage_dec(void) {}
5889 #endif /* CONFIG_JUMP_LABEL */
5890 
5891 /*
5892  * default period for cfs group bandwidth.
5893  * default: 0.1s, units: nanoseconds
5894  */
default_cfs_period(void)5895 static inline u64 default_cfs_period(void)
5896 {
5897 	return 100000000ULL;
5898 }
5899 
sched_cfs_bandwidth_slice(void)5900 static inline u64 sched_cfs_bandwidth_slice(void)
5901 {
5902 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5903 }
5904 
5905 /*
5906  * Replenish runtime according to assigned quota. We use sched_clock_cpu
5907  * directly instead of rq->clock to avoid adding additional synchronization
5908  * around rq->lock.
5909  *
5910  * requires cfs_b->lock
5911  */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5912 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5913 {
5914 	s64 runtime;
5915 
5916 	if (unlikely(cfs_b->quota == RUNTIME_INF))
5917 		return;
5918 
5919 	cfs_b->runtime += cfs_b->quota;
5920 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
5921 	if (runtime > 0) {
5922 		cfs_b->burst_time += runtime;
5923 		cfs_b->nr_burst++;
5924 	}
5925 
5926 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5927 	cfs_b->runtime_snap = cfs_b->runtime;
5928 }
5929 
tg_cfs_bandwidth(struct task_group * tg)5930 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5931 {
5932 	return &tg->cfs_bandwidth;
5933 }
5934 
5935 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5936 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5937 				   struct cfs_rq *cfs_rq, u64 target_runtime)
5938 {
5939 	u64 min_amount, amount = 0;
5940 
5941 	lockdep_assert_held(&cfs_b->lock);
5942 
5943 	/* note: this is a positive sum as runtime_remaining <= 0 */
5944 	min_amount = target_runtime - cfs_rq->runtime_remaining;
5945 
5946 	if (cfs_b->quota == RUNTIME_INF)
5947 		amount = min_amount;
5948 	else {
5949 		start_cfs_bandwidth(cfs_b);
5950 
5951 		if (cfs_b->runtime > 0) {
5952 			amount = min(cfs_b->runtime, min_amount);
5953 			cfs_b->runtime -= amount;
5954 			cfs_b->idle = 0;
5955 		}
5956 	}
5957 
5958 	cfs_rq->runtime_remaining += amount;
5959 
5960 	return cfs_rq->runtime_remaining > 0;
5961 }
5962 
5963 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5964 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5965 {
5966 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5967 	int ret;
5968 
5969 	raw_spin_lock(&cfs_b->lock);
5970 	ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5971 	raw_spin_unlock(&cfs_b->lock);
5972 
5973 	return ret;
5974 }
5975 
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5976 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5977 {
5978 	/* dock delta_exec before expiring quota (as it could span periods) */
5979 	cfs_rq->runtime_remaining -= delta_exec;
5980 
5981 	if (likely(cfs_rq->runtime_remaining > 0))
5982 		return;
5983 
5984 	if (cfs_rq->throttled)
5985 		return;
5986 	/*
5987 	 * if we're unable to extend our runtime we resched so that the active
5988 	 * hierarchy can be throttled
5989 	 */
5990 	if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5991 		resched_curr(rq_of(cfs_rq));
5992 }
5993 
5994 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5995 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5996 {
5997 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5998 		return;
5999 
6000 	__account_cfs_rq_runtime(cfs_rq, delta_exec);
6001 }
6002 
cfs_rq_throttled(struct cfs_rq * cfs_rq)6003 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6004 {
6005 	return cfs_bandwidth_used() && cfs_rq->throttled;
6006 }
6007 
6008 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)6009 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6010 {
6011 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
6012 }
6013 
6014 /*
6015  * Ensure that neither of the group entities corresponding to src_cpu or
6016  * dest_cpu are members of a throttled hierarchy when performing group
6017  * load-balance operations.
6018  */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)6019 static inline int throttled_lb_pair(struct task_group *tg,
6020 				    int src_cpu, int dest_cpu)
6021 {
6022 	struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
6023 
6024 	src_cfs_rq = tg->cfs_rq[src_cpu];
6025 	dest_cfs_rq = tg->cfs_rq[dest_cpu];
6026 
6027 	return throttled_hierarchy(src_cfs_rq) ||
6028 	       throttled_hierarchy(dest_cfs_rq);
6029 }
6030 
tg_unthrottle_up(struct task_group * tg,void * data)6031 static int tg_unthrottle_up(struct task_group *tg, void *data)
6032 {
6033 	struct rq *rq = data;
6034 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6035 
6036 	cfs_rq->throttle_count--;
6037 	if (!cfs_rq->throttle_count) {
6038 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6039 					     cfs_rq->throttled_clock_pelt;
6040 
6041 		/* Add cfs_rq with load or one or more already running entities to the list */
6042 		if (!cfs_rq_is_decayed(cfs_rq))
6043 			list_add_leaf_cfs_rq(cfs_rq);
6044 
6045 		if (cfs_rq->throttled_clock_self) {
6046 			u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
6047 
6048 			cfs_rq->throttled_clock_self = 0;
6049 
6050 			if (SCHED_WARN_ON((s64)delta < 0))
6051 				delta = 0;
6052 
6053 			cfs_rq->throttled_clock_self_time += delta;
6054 		}
6055 	}
6056 
6057 	return 0;
6058 }
6059 
tg_throttle_down(struct task_group * tg,void * data)6060 static int tg_throttle_down(struct task_group *tg, void *data)
6061 {
6062 	struct rq *rq = data;
6063 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6064 
6065 	/* group is entering throttled state, stop time */
6066 	if (!cfs_rq->throttle_count) {
6067 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6068 		list_del_leaf_cfs_rq(cfs_rq);
6069 
6070 		SCHED_WARN_ON(cfs_rq->throttled_clock_self);
6071 		if (cfs_rq->nr_running)
6072 			cfs_rq->throttled_clock_self = rq_clock(rq);
6073 	}
6074 	cfs_rq->throttle_count++;
6075 
6076 	return 0;
6077 }
6078 
throttle_cfs_rq(struct cfs_rq * cfs_rq)6079 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
6080 {
6081 	struct rq *rq = rq_of(cfs_rq);
6082 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6083 	struct sched_entity *se;
6084 	long task_delta, idle_task_delta, delayed_delta, dequeue = 1;
6085 
6086 	raw_spin_lock(&cfs_b->lock);
6087 	/* This will start the period timer if necessary */
6088 	if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
6089 		/*
6090 		 * We have raced with bandwidth becoming available, and if we
6091 		 * actually throttled the timer might not unthrottle us for an
6092 		 * entire period. We additionally needed to make sure that any
6093 		 * subsequent check_cfs_rq_runtime calls agree not to throttle
6094 		 * us, as we may commit to do cfs put_prev+pick_next, so we ask
6095 		 * for 1ns of runtime rather than just check cfs_b.
6096 		 */
6097 		dequeue = 0;
6098 	} else {
6099 		list_add_tail_rcu(&cfs_rq->throttled_list,
6100 				  &cfs_b->throttled_cfs_rq);
6101 	}
6102 	raw_spin_unlock(&cfs_b->lock);
6103 
6104 	if (!dequeue)
6105 		return false;  /* Throttle no longer required. */
6106 
6107 	se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
6108 
6109 	/* freeze hierarchy runnable averages while throttled */
6110 	rcu_read_lock();
6111 	walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
6112 	rcu_read_unlock();
6113 
6114 	task_delta = cfs_rq->h_nr_running;
6115 	idle_task_delta = cfs_rq->idle_h_nr_running;
6116 	delayed_delta = cfs_rq->h_nr_delayed;
6117 	for_each_sched_entity(se) {
6118 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6119 		int flags;
6120 
6121 		/* throttled entity or throttle-on-deactivate */
6122 		if (!se->on_rq)
6123 			goto done;
6124 
6125 		/*
6126 		 * Abuse SPECIAL to avoid delayed dequeue in this instance.
6127 		 * This avoids teaching dequeue_entities() about throttled
6128 		 * entities and keeps things relatively simple.
6129 		 */
6130 		flags = DEQUEUE_SLEEP | DEQUEUE_SPECIAL;
6131 		if (se->sched_delayed)
6132 			flags |= DEQUEUE_DELAYED;
6133 		dequeue_entity(qcfs_rq, se, flags);
6134 
6135 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6136 			idle_task_delta = cfs_rq->h_nr_running;
6137 
6138 		qcfs_rq->h_nr_running -= task_delta;
6139 		qcfs_rq->idle_h_nr_running -= idle_task_delta;
6140 		qcfs_rq->h_nr_delayed -= delayed_delta;
6141 
6142 		if (qcfs_rq->load.weight) {
6143 			/* Avoid re-evaluating load for this entity: */
6144 			se = parent_entity(se);
6145 			break;
6146 		}
6147 	}
6148 
6149 	for_each_sched_entity(se) {
6150 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6151 		/* throttled entity or throttle-on-deactivate */
6152 		if (!se->on_rq)
6153 			goto done;
6154 
6155 		update_load_avg(qcfs_rq, se, 0);
6156 		se_update_runnable(se);
6157 
6158 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6159 			idle_task_delta = cfs_rq->h_nr_running;
6160 
6161 		qcfs_rq->h_nr_running -= task_delta;
6162 		qcfs_rq->idle_h_nr_running -= idle_task_delta;
6163 		qcfs_rq->h_nr_delayed -= delayed_delta;
6164 	}
6165 
6166 	/* At this point se is NULL and we are at root level*/
6167 	sub_nr_running(rq, task_delta);
6168 
6169 done:
6170 	/*
6171 	 * Note: distribution will already see us throttled via the
6172 	 * throttled-list.  rq->lock protects completion.
6173 	 */
6174 	cfs_rq->throttled = 1;
6175 	SCHED_WARN_ON(cfs_rq->throttled_clock);
6176 	if (cfs_rq->nr_running)
6177 		cfs_rq->throttled_clock = rq_clock(rq);
6178 	return true;
6179 }
6180 
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)6181 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
6182 {
6183 	struct rq *rq = rq_of(cfs_rq);
6184 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6185 	struct sched_entity *se;
6186 	long task_delta, idle_task_delta, delayed_delta;
6187 	long rq_h_nr_running = rq->cfs.h_nr_running;
6188 
6189 	se = cfs_rq->tg->se[cpu_of(rq)];
6190 
6191 	cfs_rq->throttled = 0;
6192 
6193 	update_rq_clock(rq);
6194 
6195 	raw_spin_lock(&cfs_b->lock);
6196 	if (cfs_rq->throttled_clock) {
6197 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6198 		cfs_rq->throttled_clock = 0;
6199 	}
6200 	list_del_rcu(&cfs_rq->throttled_list);
6201 	raw_spin_unlock(&cfs_b->lock);
6202 
6203 	/* update hierarchical throttle state */
6204 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6205 
6206 	if (!cfs_rq->load.weight) {
6207 		if (!cfs_rq->on_list)
6208 			return;
6209 		/*
6210 		 * Nothing to run but something to decay (on_list)?
6211 		 * Complete the branch.
6212 		 */
6213 		for_each_sched_entity(se) {
6214 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6215 				break;
6216 		}
6217 		goto unthrottle_throttle;
6218 	}
6219 
6220 	task_delta = cfs_rq->h_nr_running;
6221 	idle_task_delta = cfs_rq->idle_h_nr_running;
6222 	delayed_delta = cfs_rq->h_nr_delayed;
6223 	for_each_sched_entity(se) {
6224 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6225 
6226 		/* Handle any unfinished DELAY_DEQUEUE business first. */
6227 		if (se->sched_delayed) {
6228 			int flags = DEQUEUE_SLEEP | DEQUEUE_DELAYED;
6229 
6230 			dequeue_entity(qcfs_rq, se, flags);
6231 		} else if (se->on_rq)
6232 			break;
6233 		enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
6234 
6235 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6236 			idle_task_delta = cfs_rq->h_nr_running;
6237 
6238 		qcfs_rq->h_nr_running += task_delta;
6239 		qcfs_rq->idle_h_nr_running += idle_task_delta;
6240 		qcfs_rq->h_nr_delayed += delayed_delta;
6241 
6242 		/* end evaluation on encountering a throttled cfs_rq */
6243 		if (cfs_rq_throttled(qcfs_rq))
6244 			goto unthrottle_throttle;
6245 	}
6246 
6247 	for_each_sched_entity(se) {
6248 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6249 
6250 		update_load_avg(qcfs_rq, se, UPDATE_TG);
6251 		se_update_runnable(se);
6252 
6253 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6254 			idle_task_delta = cfs_rq->h_nr_running;
6255 
6256 		qcfs_rq->h_nr_running += task_delta;
6257 		qcfs_rq->idle_h_nr_running += idle_task_delta;
6258 		qcfs_rq->h_nr_delayed += delayed_delta;
6259 
6260 		/* end evaluation on encountering a throttled cfs_rq */
6261 		if (cfs_rq_throttled(qcfs_rq))
6262 			goto unthrottle_throttle;
6263 	}
6264 
6265 	/* Start the fair server if un-throttling resulted in new runnable tasks */
6266 	if (!rq_h_nr_running && rq->cfs.h_nr_running)
6267 		dl_server_start(&rq->fair_server);
6268 
6269 	/* At this point se is NULL and we are at root level*/
6270 	add_nr_running(rq, task_delta);
6271 
6272 unthrottle_throttle:
6273 	assert_list_leaf_cfs_rq(rq);
6274 
6275 	/* Determine whether we need to wake up potentially idle CPU: */
6276 	if (rq->curr == rq->idle && rq->cfs.nr_running)
6277 		resched_curr(rq);
6278 }
6279 
6280 #ifdef CONFIG_SMP
__cfsb_csd_unthrottle(void * arg)6281 static void __cfsb_csd_unthrottle(void *arg)
6282 {
6283 	struct cfs_rq *cursor, *tmp;
6284 	struct rq *rq = arg;
6285 	struct rq_flags rf;
6286 
6287 	rq_lock(rq, &rf);
6288 
6289 	/*
6290 	 * Iterating over the list can trigger several call to
6291 	 * update_rq_clock() in unthrottle_cfs_rq().
6292 	 * Do it once and skip the potential next ones.
6293 	 */
6294 	update_rq_clock(rq);
6295 	rq_clock_start_loop_update(rq);
6296 
6297 	/*
6298 	 * Since we hold rq lock we're safe from concurrent manipulation of
6299 	 * the CSD list. However, this RCU critical section annotates the
6300 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
6301 	 * race with group being freed in the window between removing it
6302 	 * from the list and advancing to the next entry in the list.
6303 	 */
6304 	rcu_read_lock();
6305 
6306 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6307 				 throttled_csd_list) {
6308 		list_del_init(&cursor->throttled_csd_list);
6309 
6310 		if (cfs_rq_throttled(cursor))
6311 			unthrottle_cfs_rq(cursor);
6312 	}
6313 
6314 	rcu_read_unlock();
6315 
6316 	rq_clock_stop_loop_update(rq);
6317 	rq_unlock(rq, &rf);
6318 }
6319 
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6320 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6321 {
6322 	struct rq *rq = rq_of(cfs_rq);
6323 	bool first;
6324 
6325 	if (rq == this_rq()) {
6326 		unthrottle_cfs_rq(cfs_rq);
6327 		return;
6328 	}
6329 
6330 	/* Already enqueued */
6331 	if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
6332 		return;
6333 
6334 	first = list_empty(&rq->cfsb_csd_list);
6335 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6336 	if (first)
6337 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6338 }
6339 #else
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6340 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6341 {
6342 	unthrottle_cfs_rq(cfs_rq);
6343 }
6344 #endif
6345 
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6346 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6347 {
6348 	lockdep_assert_rq_held(rq_of(cfs_rq));
6349 
6350 	if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
6351 	    cfs_rq->runtime_remaining <= 0))
6352 		return;
6353 
6354 	__unthrottle_cfs_rq_async(cfs_rq);
6355 }
6356 
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6357 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6358 {
6359 	int this_cpu = smp_processor_id();
6360 	u64 runtime, remaining = 1;
6361 	bool throttled = false;
6362 	struct cfs_rq *cfs_rq, *tmp;
6363 	struct rq_flags rf;
6364 	struct rq *rq;
6365 	LIST_HEAD(local_unthrottle);
6366 
6367 	rcu_read_lock();
6368 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6369 				throttled_list) {
6370 		rq = rq_of(cfs_rq);
6371 
6372 		if (!remaining) {
6373 			throttled = true;
6374 			break;
6375 		}
6376 
6377 		rq_lock_irqsave(rq, &rf);
6378 		if (!cfs_rq_throttled(cfs_rq))
6379 			goto next;
6380 
6381 		/* Already queued for async unthrottle */
6382 		if (!list_empty(&cfs_rq->throttled_csd_list))
6383 			goto next;
6384 
6385 		/* By the above checks, this should never be true */
6386 		SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
6387 
6388 		raw_spin_lock(&cfs_b->lock);
6389 		runtime = -cfs_rq->runtime_remaining + 1;
6390 		if (runtime > cfs_b->runtime)
6391 			runtime = cfs_b->runtime;
6392 		cfs_b->runtime -= runtime;
6393 		remaining = cfs_b->runtime;
6394 		raw_spin_unlock(&cfs_b->lock);
6395 
6396 		cfs_rq->runtime_remaining += runtime;
6397 
6398 		/* we check whether we're throttled above */
6399 		if (cfs_rq->runtime_remaining > 0) {
6400 			if (cpu_of(rq) != this_cpu) {
6401 				unthrottle_cfs_rq_async(cfs_rq);
6402 			} else {
6403 				/*
6404 				 * We currently only expect to be unthrottling
6405 				 * a single cfs_rq locally.
6406 				 */
6407 				SCHED_WARN_ON(!list_empty(&local_unthrottle));
6408 				list_add_tail(&cfs_rq->throttled_csd_list,
6409 					      &local_unthrottle);
6410 			}
6411 		} else {
6412 			throttled = true;
6413 		}
6414 
6415 next:
6416 		rq_unlock_irqrestore(rq, &rf);
6417 	}
6418 
6419 	list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6420 				 throttled_csd_list) {
6421 		struct rq *rq = rq_of(cfs_rq);
6422 
6423 		rq_lock_irqsave(rq, &rf);
6424 
6425 		list_del_init(&cfs_rq->throttled_csd_list);
6426 
6427 		if (cfs_rq_throttled(cfs_rq))
6428 			unthrottle_cfs_rq(cfs_rq);
6429 
6430 		rq_unlock_irqrestore(rq, &rf);
6431 	}
6432 	SCHED_WARN_ON(!list_empty(&local_unthrottle));
6433 
6434 	rcu_read_unlock();
6435 
6436 	return throttled;
6437 }
6438 
6439 /*
6440  * Responsible for refilling a task_group's bandwidth and unthrottling its
6441  * cfs_rqs as appropriate. If there has been no activity within the last
6442  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6443  * used to track this state.
6444  */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6445 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6446 {
6447 	int throttled;
6448 
6449 	/* no need to continue the timer with no bandwidth constraint */
6450 	if (cfs_b->quota == RUNTIME_INF)
6451 		goto out_deactivate;
6452 
6453 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6454 	cfs_b->nr_periods += overrun;
6455 
6456 	/* Refill extra burst quota even if cfs_b->idle */
6457 	__refill_cfs_bandwidth_runtime(cfs_b);
6458 
6459 	/*
6460 	 * idle depends on !throttled (for the case of a large deficit), and if
6461 	 * we're going inactive then everything else can be deferred
6462 	 */
6463 	if (cfs_b->idle && !throttled)
6464 		goto out_deactivate;
6465 
6466 	if (!throttled) {
6467 		/* mark as potentially idle for the upcoming period */
6468 		cfs_b->idle = 1;
6469 		return 0;
6470 	}
6471 
6472 	/* account preceding periods in which throttling occurred */
6473 	cfs_b->nr_throttled += overrun;
6474 
6475 	/*
6476 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
6477 	 */
6478 	while (throttled && cfs_b->runtime > 0) {
6479 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6480 		/* we can't nest cfs_b->lock while distributing bandwidth */
6481 		throttled = distribute_cfs_runtime(cfs_b);
6482 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
6483 	}
6484 
6485 	/*
6486 	 * While we are ensured activity in the period following an
6487 	 * unthrottle, this also covers the case in which the new bandwidth is
6488 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
6489 	 * timer to remain active while there are any throttled entities.)
6490 	 */
6491 	cfs_b->idle = 0;
6492 
6493 	return 0;
6494 
6495 out_deactivate:
6496 	return 1;
6497 }
6498 
6499 /* a cfs_rq won't donate quota below this amount */
6500 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6501 /* minimum remaining period time to redistribute slack quota */
6502 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6503 /* how long we wait to gather additional slack before distributing */
6504 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6505 
6506 /*
6507  * Are we near the end of the current quota period?
6508  *
6509  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6510  * hrtimer base being cleared by hrtimer_start. In the case of
6511  * migrate_hrtimers, base is never cleared, so we are fine.
6512  */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6513 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6514 {
6515 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
6516 	s64 remaining;
6517 
6518 	/* if the call-back is running a quota refresh is already occurring */
6519 	if (hrtimer_callback_running(refresh_timer))
6520 		return 1;
6521 
6522 	/* is a quota refresh about to occur? */
6523 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6524 	if (remaining < (s64)min_expire)
6525 		return 1;
6526 
6527 	return 0;
6528 }
6529 
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6530 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6531 {
6532 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6533 
6534 	/* if there's a quota refresh soon don't bother with slack */
6535 	if (runtime_refresh_within(cfs_b, min_left))
6536 		return;
6537 
6538 	/* don't push forwards an existing deferred unthrottle */
6539 	if (cfs_b->slack_started)
6540 		return;
6541 	cfs_b->slack_started = true;
6542 
6543 	hrtimer_start(&cfs_b->slack_timer,
6544 			ns_to_ktime(cfs_bandwidth_slack_period),
6545 			HRTIMER_MODE_REL);
6546 }
6547 
6548 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6549 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6550 {
6551 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6552 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6553 
6554 	if (slack_runtime <= 0)
6555 		return;
6556 
6557 	raw_spin_lock(&cfs_b->lock);
6558 	if (cfs_b->quota != RUNTIME_INF) {
6559 		cfs_b->runtime += slack_runtime;
6560 
6561 		/* we are under rq->lock, defer unthrottling using a timer */
6562 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6563 		    !list_empty(&cfs_b->throttled_cfs_rq))
6564 			start_cfs_slack_bandwidth(cfs_b);
6565 	}
6566 	raw_spin_unlock(&cfs_b->lock);
6567 
6568 	/* even if it's not valid for return we don't want to try again */
6569 	cfs_rq->runtime_remaining -= slack_runtime;
6570 }
6571 
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6572 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6573 {
6574 	if (!cfs_bandwidth_used())
6575 		return;
6576 
6577 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6578 		return;
6579 
6580 	__return_cfs_rq_runtime(cfs_rq);
6581 }
6582 
6583 /*
6584  * This is done with a timer (instead of inline with bandwidth return) since
6585  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6586  */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6587 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6588 {
6589 	u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6590 	unsigned long flags;
6591 
6592 	/* confirm we're still not at a refresh boundary */
6593 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6594 	cfs_b->slack_started = false;
6595 
6596 	if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6597 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6598 		return;
6599 	}
6600 
6601 	if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6602 		runtime = cfs_b->runtime;
6603 
6604 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6605 
6606 	if (!runtime)
6607 		return;
6608 
6609 	distribute_cfs_runtime(cfs_b);
6610 }
6611 
6612 /*
6613  * When a group wakes up we want to make sure that its quota is not already
6614  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6615  * runtime as update_curr() throttling can not trigger until it's on-rq.
6616  */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6617 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6618 {
6619 	if (!cfs_bandwidth_used())
6620 		return;
6621 
6622 	/* an active group must be handled by the update_curr()->put() path */
6623 	if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6624 		return;
6625 
6626 	/* ensure the group is not already throttled */
6627 	if (cfs_rq_throttled(cfs_rq))
6628 		return;
6629 
6630 	/* update runtime allocation */
6631 	account_cfs_rq_runtime(cfs_rq, 0);
6632 	if (cfs_rq->runtime_remaining <= 0)
6633 		throttle_cfs_rq(cfs_rq);
6634 }
6635 
sync_throttle(struct task_group * tg,int cpu)6636 static void sync_throttle(struct task_group *tg, int cpu)
6637 {
6638 	struct cfs_rq *pcfs_rq, *cfs_rq;
6639 
6640 	if (!cfs_bandwidth_used())
6641 		return;
6642 
6643 	if (!tg->parent)
6644 		return;
6645 
6646 	cfs_rq = tg->cfs_rq[cpu];
6647 	pcfs_rq = tg->parent->cfs_rq[cpu];
6648 
6649 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
6650 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6651 }
6652 
6653 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6654 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6655 {
6656 	if (!cfs_bandwidth_used())
6657 		return false;
6658 
6659 	if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6660 		return false;
6661 
6662 	/*
6663 	 * it's possible for a throttled entity to be forced into a running
6664 	 * state (e.g. set_curr_task), in this case we're finished.
6665 	 */
6666 	if (cfs_rq_throttled(cfs_rq))
6667 		return true;
6668 
6669 	return throttle_cfs_rq(cfs_rq);
6670 }
6671 
sched_cfs_slack_timer(struct hrtimer * timer)6672 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6673 {
6674 	struct cfs_bandwidth *cfs_b =
6675 		container_of(timer, struct cfs_bandwidth, slack_timer);
6676 
6677 	do_sched_cfs_slack_timer(cfs_b);
6678 
6679 	return HRTIMER_NORESTART;
6680 }
6681 
6682 extern const u64 max_cfs_quota_period;
6683 
sched_cfs_period_timer(struct hrtimer * timer)6684 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6685 {
6686 	struct cfs_bandwidth *cfs_b =
6687 		container_of(timer, struct cfs_bandwidth, period_timer);
6688 	unsigned long flags;
6689 	int overrun;
6690 	int idle = 0;
6691 	int count = 0;
6692 
6693 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6694 	for (;;) {
6695 		overrun = hrtimer_forward_now(timer, cfs_b->period);
6696 		if (!overrun)
6697 			break;
6698 
6699 		idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6700 
6701 		if (++count > 3) {
6702 			u64 new, old = ktime_to_ns(cfs_b->period);
6703 
6704 			/*
6705 			 * Grow period by a factor of 2 to avoid losing precision.
6706 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6707 			 * to fail.
6708 			 */
6709 			new = old * 2;
6710 			if (new < max_cfs_quota_period) {
6711 				cfs_b->period = ns_to_ktime(new);
6712 				cfs_b->quota *= 2;
6713 				cfs_b->burst *= 2;
6714 
6715 				pr_warn_ratelimited(
6716 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6717 					smp_processor_id(),
6718 					div_u64(new, NSEC_PER_USEC),
6719 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6720 			} else {
6721 				pr_warn_ratelimited(
6722 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6723 					smp_processor_id(),
6724 					div_u64(old, NSEC_PER_USEC),
6725 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6726 			}
6727 
6728 			/* reset count so we don't come right back in here */
6729 			count = 0;
6730 		}
6731 	}
6732 	if (idle)
6733 		cfs_b->period_active = 0;
6734 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6735 
6736 	return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6737 }
6738 
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6739 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6740 {
6741 	raw_spin_lock_init(&cfs_b->lock);
6742 	cfs_b->runtime = 0;
6743 	cfs_b->quota = RUNTIME_INF;
6744 	cfs_b->period = ns_to_ktime(default_cfs_period());
6745 	cfs_b->burst = 0;
6746 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6747 
6748 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6749 	hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6750 	cfs_b->period_timer.function = sched_cfs_period_timer;
6751 
6752 	/* Add a random offset so that timers interleave */
6753 	hrtimer_set_expires(&cfs_b->period_timer,
6754 			    get_random_u32_below(cfs_b->period));
6755 	hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6756 	cfs_b->slack_timer.function = sched_cfs_slack_timer;
6757 	cfs_b->slack_started = false;
6758 }
6759 
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6760 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6761 {
6762 	cfs_rq->runtime_enabled = 0;
6763 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
6764 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6765 }
6766 
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6767 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6768 {
6769 	lockdep_assert_held(&cfs_b->lock);
6770 
6771 	if (cfs_b->period_active)
6772 		return;
6773 
6774 	cfs_b->period_active = 1;
6775 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6776 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6777 }
6778 
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6779 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6780 {
6781 	int __maybe_unused i;
6782 
6783 	/* init_cfs_bandwidth() was not called */
6784 	if (!cfs_b->throttled_cfs_rq.next)
6785 		return;
6786 
6787 	hrtimer_cancel(&cfs_b->period_timer);
6788 	hrtimer_cancel(&cfs_b->slack_timer);
6789 
6790 	/*
6791 	 * It is possible that we still have some cfs_rq's pending on a CSD
6792 	 * list, though this race is very rare. In order for this to occur, we
6793 	 * must have raced with the last task leaving the group while there
6794 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
6795 	 * CSD item but the remote cpu has not yet processed it. To handle this,
6796 	 * we can simply flush all pending CSD work inline here. We're
6797 	 * guaranteed at this point that no additional cfs_rq of this group can
6798 	 * join a CSD list.
6799 	 */
6800 #ifdef CONFIG_SMP
6801 	for_each_possible_cpu(i) {
6802 		struct rq *rq = cpu_rq(i);
6803 		unsigned long flags;
6804 
6805 		if (list_empty(&rq->cfsb_csd_list))
6806 			continue;
6807 
6808 		local_irq_save(flags);
6809 		__cfsb_csd_unthrottle(rq);
6810 		local_irq_restore(flags);
6811 	}
6812 #endif
6813 }
6814 
6815 /*
6816  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6817  *
6818  * The race is harmless, since modifying bandwidth settings of unhooked group
6819  * bits doesn't do much.
6820  */
6821 
6822 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6823 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6824 {
6825 	struct task_group *tg;
6826 
6827 	lockdep_assert_rq_held(rq);
6828 
6829 	rcu_read_lock();
6830 	list_for_each_entry_rcu(tg, &task_groups, list) {
6831 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6832 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6833 
6834 		raw_spin_lock(&cfs_b->lock);
6835 		cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6836 		raw_spin_unlock(&cfs_b->lock);
6837 	}
6838 	rcu_read_unlock();
6839 }
6840 
6841 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6842 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6843 {
6844 	struct task_group *tg;
6845 
6846 	lockdep_assert_rq_held(rq);
6847 
6848 	/*
6849 	 * The rq clock has already been updated in the
6850 	 * set_rq_offline(), so we should skip updating
6851 	 * the rq clock again in unthrottle_cfs_rq().
6852 	 */
6853 	rq_clock_start_loop_update(rq);
6854 
6855 	rcu_read_lock();
6856 	list_for_each_entry_rcu(tg, &task_groups, list) {
6857 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6858 
6859 		if (!cfs_rq->runtime_enabled)
6860 			continue;
6861 
6862 		/*
6863 		 * clock_task is not advancing so we just need to make sure
6864 		 * there's some valid quota amount
6865 		 */
6866 		cfs_rq->runtime_remaining = 1;
6867 		/*
6868 		 * Offline rq is schedulable till CPU is completely disabled
6869 		 * in take_cpu_down(), so we prevent new cfs throttling here.
6870 		 */
6871 		cfs_rq->runtime_enabled = 0;
6872 
6873 		if (cfs_rq_throttled(cfs_rq))
6874 			unthrottle_cfs_rq(cfs_rq);
6875 	}
6876 	rcu_read_unlock();
6877 
6878 	rq_clock_stop_loop_update(rq);
6879 }
6880 
cfs_task_bw_constrained(struct task_struct * p)6881 bool cfs_task_bw_constrained(struct task_struct *p)
6882 {
6883 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
6884 
6885 	if (!cfs_bandwidth_used())
6886 		return false;
6887 
6888 	if (cfs_rq->runtime_enabled ||
6889 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6890 		return true;
6891 
6892 	return false;
6893 }
6894 
6895 #ifdef CONFIG_NO_HZ_FULL
6896 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6897 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6898 {
6899 	int cpu = cpu_of(rq);
6900 
6901 	if (!cfs_bandwidth_used())
6902 		return;
6903 
6904 	if (!tick_nohz_full_cpu(cpu))
6905 		return;
6906 
6907 	if (rq->nr_running != 1)
6908 		return;
6909 
6910 	/*
6911 	 *  We know there is only one task runnable and we've just picked it. The
6912 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6913 	 *  be otherwise able to stop the tick. Just need to check if we are using
6914 	 *  bandwidth control.
6915 	 */
6916 	if (cfs_task_bw_constrained(p))
6917 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6918 }
6919 #endif
6920 
6921 #else /* CONFIG_CFS_BANDWIDTH */
6922 
cfs_bandwidth_used(void)6923 static inline bool cfs_bandwidth_used(void)
6924 {
6925 	return false;
6926 }
6927 
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6928 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6929 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6930 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6931 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6932 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6933 
cfs_rq_throttled(struct cfs_rq * cfs_rq)6934 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6935 {
6936 	return 0;
6937 }
6938 
throttled_hierarchy(struct cfs_rq * cfs_rq)6939 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6940 {
6941 	return 0;
6942 }
6943 
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)6944 static inline int throttled_lb_pair(struct task_group *tg,
6945 				    int src_cpu, int dest_cpu)
6946 {
6947 	return 0;
6948 }
6949 
6950 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6951 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6952 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6953 #endif
6954 
tg_cfs_bandwidth(struct task_group * tg)6955 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6956 {
6957 	return NULL;
6958 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6959 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6960 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6961 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6962 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6963 bool cfs_task_bw_constrained(struct task_struct *p)
6964 {
6965 	return false;
6966 }
6967 #endif
6968 #endif /* CONFIG_CFS_BANDWIDTH */
6969 
6970 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6971 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6972 #endif
6973 
6974 /**************************************************
6975  * CFS operations on tasks:
6976  */
6977 
6978 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6979 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6980 {
6981 	struct sched_entity *se = &p->se;
6982 
6983 	SCHED_WARN_ON(task_rq(p) != rq);
6984 
6985 	if (rq->cfs.h_nr_running > 1) {
6986 		u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6987 		u64 slice = se->slice;
6988 		s64 delta = slice - ran;
6989 
6990 		if (delta < 0) {
6991 			if (task_current_donor(rq, p))
6992 				resched_curr(rq);
6993 			return;
6994 		}
6995 		hrtick_start(rq, delta);
6996 	}
6997 }
6998 
6999 /*
7000  * called from enqueue/dequeue and updates the hrtick when the
7001  * current task is from our class and nr_running is low enough
7002  * to matter.
7003  */
hrtick_update(struct rq * rq)7004 static void hrtick_update(struct rq *rq)
7005 {
7006 	struct task_struct *donor = rq->donor;
7007 
7008 	if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
7009 		return;
7010 
7011 	hrtick_start_fair(rq, donor);
7012 }
7013 #else /* !CONFIG_SCHED_HRTICK */
7014 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)7015 hrtick_start_fair(struct rq *rq, struct task_struct *p)
7016 {
7017 }
7018 
hrtick_update(struct rq * rq)7019 static inline void hrtick_update(struct rq *rq)
7020 {
7021 }
7022 #endif
7023 
7024 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)7025 static inline bool cpu_overutilized(int cpu)
7026 {
7027 	unsigned long  rq_util_min, rq_util_max;
7028 	int overutilized = -1;
7029 
7030 	trace_android_rvh_cpu_overutilized(cpu, &overutilized);
7031 	if (overutilized != -1)
7032 		return overutilized;
7033 
7034 	if (!sched_energy_enabled())
7035 		return false;
7036 
7037 	rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
7038 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
7039 
7040 	/* Return true only if the utilization doesn't fit CPU's capacity */
7041 	return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
7042 }
7043 
7044 /*
7045  * overutilized value make sense only if EAS is enabled
7046  */
is_rd_overutilized(struct root_domain * rd)7047 static inline bool is_rd_overutilized(struct root_domain *rd)
7048 {
7049 	return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
7050 }
7051 
set_rd_overutilized(struct root_domain * rd,bool flag)7052 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
7053 {
7054 	if (!sched_energy_enabled())
7055 		return;
7056 
7057 	WRITE_ONCE(rd->overutilized, flag);
7058 	trace_sched_overutilized_tp(rd, flag);
7059 }
7060 
check_update_overutilized_status(struct rq * rq)7061 static inline void check_update_overutilized_status(struct rq *rq)
7062 {
7063 	/*
7064 	 * overutilized field is used for load balancing decisions only
7065 	 * if energy aware scheduler is being used
7066 	 */
7067 
7068 	if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
7069 		set_rd_overutilized(rq->rd, 1);
7070 }
7071 #else
check_update_overutilized_status(struct rq * rq)7072 static inline void check_update_overutilized_status(struct rq *rq) { }
7073 #endif
7074 
7075 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)7076 static int sched_idle_rq(struct rq *rq)
7077 {
7078 	return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
7079 			rq->nr_running);
7080 }
7081 
7082 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)7083 static int sched_idle_cpu(int cpu)
7084 {
7085 	return sched_idle_rq(cpu_rq(cpu));
7086 }
7087 #endif
7088 
7089 static void
requeue_delayed_entity(struct sched_entity * se)7090 requeue_delayed_entity(struct sched_entity *se)
7091 {
7092 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
7093 
7094 	/*
7095 	 * se->sched_delayed should imply: se->on_rq == 1.
7096 	 * Because a delayed entity is one that is still on
7097 	 * the runqueue competing until elegibility.
7098 	 */
7099 	SCHED_WARN_ON(!se->sched_delayed);
7100 	SCHED_WARN_ON(!se->on_rq);
7101 
7102 	if (sched_feat(DELAY_ZERO)) {
7103 		update_entity_lag(cfs_rq, se);
7104 		if (se->vlag > 0) {
7105 			cfs_rq->nr_running--;
7106 			if (se != cfs_rq->curr)
7107 				__dequeue_entity(cfs_rq, se);
7108 			se->vlag = 0;
7109 			place_entity(cfs_rq, se, 0);
7110 			if (se != cfs_rq->curr)
7111 				__enqueue_entity(cfs_rq, se);
7112 			cfs_rq->nr_running++;
7113 		}
7114 	}
7115 
7116 	update_load_avg(cfs_rq, se, 0);
7117 	clear_delayed(se);
7118 }
7119 
7120 /*
7121  * The enqueue_task method is called before nr_running is
7122  * increased. Here we update the fair scheduling stats and
7123  * then put the task into the rbtree:
7124  */
7125 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)7126 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7127 {
7128 	struct cfs_rq *cfs_rq;
7129 	struct sched_entity *se = &p->se;
7130 	int idle_h_nr_running = task_has_idle_policy(p);
7131 	int h_nr_delayed = 0;
7132 	int task_new = !(flags & ENQUEUE_WAKEUP);
7133 	int rq_h_nr_running = rq->cfs.h_nr_running;
7134 	u64 slice = 0;
7135 	int should_iowait_boost;
7136 
7137 	/*
7138 	 * The code below (indirectly) updates schedutil which looks at
7139 	 * the cfs_rq utilization to select a frequency.
7140 	 * Let's add the task's estimated utilization to the cfs_rq's
7141 	 * estimated utilization, before we update schedutil.
7142 	 */
7143 	if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
7144 		util_est_enqueue(&rq->cfs, p);
7145 
7146 	if (flags & ENQUEUE_DELAYED) {
7147 		requeue_delayed_entity(se);
7148 		return;
7149 	}
7150 
7151 	/*
7152 	 * If in_iowait is set, the code below may not trigger any cpufreq
7153 	 * utilization updates, so do it here explicitly with the IOWAIT flag
7154 	 * passed.
7155 	 */
7156 	should_iowait_boost = p->in_iowait;
7157 	trace_android_rvh_set_iowait(p, rq, &should_iowait_boost);
7158 	if (should_iowait_boost)
7159 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
7160 
7161 	if (task_new)
7162 		h_nr_delayed = !!se->sched_delayed;
7163 
7164 	for_each_sched_entity(se) {
7165 		if (se->on_rq) {
7166 			if (se->sched_delayed)
7167 				requeue_delayed_entity(se);
7168 			break;
7169 		}
7170 		cfs_rq = cfs_rq_of(se);
7171 
7172 		/*
7173 		 * Basically set the slice of group entries to the min_slice of
7174 		 * their respective cfs_rq. This ensures the group can service
7175 		 * its entities in the desired time-frame.
7176 		 */
7177 		if (slice) {
7178 			se->slice = slice;
7179 			se->custom_slice = 1;
7180 		}
7181 		enqueue_entity(cfs_rq, se, flags);
7182 		slice = cfs_rq_min_slice(cfs_rq);
7183 
7184 		cfs_rq->h_nr_running++;
7185 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
7186 		cfs_rq->h_nr_delayed += h_nr_delayed;
7187 
7188 		if (cfs_rq_is_idle(cfs_rq))
7189 			idle_h_nr_running = 1;
7190 
7191 		/* end evaluation on encountering a throttled cfs_rq */
7192 		if (cfs_rq_throttled(cfs_rq))
7193 			goto enqueue_throttle;
7194 
7195 		flags = ENQUEUE_WAKEUP;
7196 	}
7197 
7198 	trace_android_rvh_enqueue_task_fair(rq, p, flags);
7199 	for_each_sched_entity(se) {
7200 		cfs_rq = cfs_rq_of(se);
7201 
7202 		update_load_avg(cfs_rq, se, UPDATE_TG);
7203 		se_update_runnable(se);
7204 		update_cfs_group(se);
7205 
7206 		se->slice = slice;
7207 		if (se != cfs_rq->curr)
7208 			min_vruntime_cb_propagate(&se->run_node, NULL);
7209 		slice = cfs_rq_min_slice(cfs_rq);
7210 
7211 		cfs_rq->h_nr_running++;
7212 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
7213 		cfs_rq->h_nr_delayed += h_nr_delayed;
7214 
7215 		if (cfs_rq_is_idle(cfs_rq))
7216 			idle_h_nr_running = 1;
7217 
7218 		/* end evaluation on encountering a throttled cfs_rq */
7219 		if (cfs_rq_throttled(cfs_rq))
7220 			goto enqueue_throttle;
7221 	}
7222 
7223 	if (!rq_h_nr_running && rq->cfs.h_nr_running) {
7224 		/* Account for idle runtime */
7225 		if (!rq->nr_running)
7226 			dl_server_update_idle_time(rq, rq->curr);
7227 		dl_server_start(&rq->fair_server);
7228 	}
7229 
7230 	/* At this point se is NULL and we are at root level*/
7231 	add_nr_running(rq, 1);
7232 
7233 	/*
7234 	 * Since new tasks are assigned an initial util_avg equal to
7235 	 * half of the spare capacity of their CPU, tiny tasks have the
7236 	 * ability to cross the overutilized threshold, which will
7237 	 * result in the load balancer ruining all the task placement
7238 	 * done by EAS. As a way to mitigate that effect, do not account
7239 	 * for the first enqueue operation of new tasks during the
7240 	 * overutilized flag detection.
7241 	 *
7242 	 * A better way of solving this problem would be to wait for
7243 	 * the PELT signals of tasks to converge before taking them
7244 	 * into account, but that is not straightforward to implement,
7245 	 * and the following generally works well enough in practice.
7246 	 */
7247 	if (!task_new)
7248 		check_update_overutilized_status(rq);
7249 
7250 enqueue_throttle:
7251 	assert_list_leaf_cfs_rq(rq);
7252 
7253 	hrtick_update(rq);
7254 }
7255 
7256 static void set_next_buddy(struct sched_entity *se);
7257 
7258 /*
7259  * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
7260  * failing half-way through and resume the dequeue later.
7261  *
7262  * Returns:
7263  * -1 - dequeue delayed
7264  *  0 - dequeue throttled
7265  *  1 - dequeue complete
7266  */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)7267 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7268 {
7269 	bool was_sched_idle = sched_idle_rq(rq);
7270 	bool task_sleep = flags & DEQUEUE_SLEEP;
7271 	bool task_delayed = flags & DEQUEUE_DELAYED;
7272 	struct task_struct *p = NULL;
7273 	int idle_h_nr_running = 0;
7274 	int h_nr_running = 0;
7275 	int h_nr_delayed = 0;
7276 	struct cfs_rq *cfs_rq;
7277 	u64 slice = 0;
7278 
7279 	if (entity_is_task(se)) {
7280 		p = task_of(se);
7281 		h_nr_running = 1;
7282 		idle_h_nr_running = task_has_idle_policy(p);
7283 		if (!task_sleep && !task_delayed)
7284 			h_nr_delayed = !!se->sched_delayed;
7285 	}
7286 
7287 	for_each_sched_entity(se) {
7288 		cfs_rq = cfs_rq_of(se);
7289 
7290 		if (!dequeue_entity(cfs_rq, se, flags)) {
7291 			if (p && &p->se == se)
7292 				return -1;
7293 
7294 			slice = cfs_rq_min_slice(cfs_rq);
7295 			break;
7296 		}
7297 
7298 		cfs_rq->h_nr_running -= h_nr_running;
7299 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
7300 		cfs_rq->h_nr_delayed -= h_nr_delayed;
7301 
7302 		if (cfs_rq_is_idle(cfs_rq))
7303 			idle_h_nr_running = h_nr_running;
7304 
7305 		/* end evaluation on encountering a throttled cfs_rq */
7306 		if (cfs_rq_throttled(cfs_rq))
7307 			return 0;
7308 
7309 		/* Don't dequeue parent if it has other entities besides us */
7310 		if (cfs_rq->load.weight) {
7311 			slice = cfs_rq_min_slice(cfs_rq);
7312 
7313 			/* Avoid re-evaluating load for this entity: */
7314 			se = parent_entity(se);
7315 			/*
7316 			 * Bias pick_next to pick a task from this cfs_rq, as
7317 			 * p is sleeping when it is within its sched_slice.
7318 			 */
7319 			if (task_sleep && se && !throttled_hierarchy(cfs_rq))
7320 				set_next_buddy(se);
7321 			break;
7322 		}
7323 		flags |= DEQUEUE_SLEEP;
7324 		flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7325 	}
7326 
7327 	trace_android_rvh_dequeue_task_fair(rq, p, flags);
7328 	for_each_sched_entity(se) {
7329 		cfs_rq = cfs_rq_of(se);
7330 
7331 		update_load_avg(cfs_rq, se, UPDATE_TG);
7332 		se_update_runnable(se);
7333 		update_cfs_group(se);
7334 
7335 		se->slice = slice;
7336 		if (se != cfs_rq->curr)
7337 			min_vruntime_cb_propagate(&se->run_node, NULL);
7338 		slice = cfs_rq_min_slice(cfs_rq);
7339 
7340 		cfs_rq->h_nr_running -= h_nr_running;
7341 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
7342 		cfs_rq->h_nr_delayed -= h_nr_delayed;
7343 
7344 		if (cfs_rq_is_idle(cfs_rq))
7345 			idle_h_nr_running = h_nr_running;
7346 
7347 		/* end evaluation on encountering a throttled cfs_rq */
7348 		if (cfs_rq_throttled(cfs_rq))
7349 			return 0;
7350 	}
7351 
7352 	sub_nr_running(rq, h_nr_running);
7353 
7354 	/* balance early to pull high priority tasks */
7355 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7356 		rq->next_balance = jiffies;
7357 
7358 	if (p && task_delayed) {
7359 		SCHED_WARN_ON(!task_sleep);
7360 		SCHED_WARN_ON(p->on_rq != 1);
7361 
7362 		/* Fix-up what dequeue_task_fair() skipped */
7363 		hrtick_update(rq);
7364 
7365 		/*
7366 		 * Fix-up what block_task() skipped.
7367 		 *
7368 		 * Must be last, @p might not be valid after this.
7369 		 */
7370 		__block_task(rq, p);
7371 	}
7372 
7373 	return 1;
7374 }
7375 
7376 /*
7377  * The dequeue_task method is called before nr_running is
7378  * decreased. We remove the task from the rbtree and
7379  * update the fair scheduling stats:
7380  */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7381 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7382 {
7383 	if (!p->se.sched_delayed)
7384 		util_est_dequeue(&rq->cfs, p);
7385 
7386 	util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7387 	if (dequeue_entities(rq, &p->se, flags) < 0)
7388 		return false;
7389 
7390 	/*
7391 	 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7392 	 */
7393 
7394 	hrtick_update(rq);
7395 	return true;
7396 }
7397 
7398 #ifdef CONFIG_SMP
7399 
7400 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7401 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7402 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7403 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7404 
7405 #ifdef CONFIG_NO_HZ_COMMON
7406 
7407 static struct {
7408 	cpumask_var_t idle_cpus_mask;
7409 	atomic_t nr_cpus;
7410 	int has_blocked;		/* Idle CPUS has blocked load */
7411 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
7412 	unsigned long next_balance;     /* in jiffy units */
7413 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
7414 } nohz ____cacheline_aligned;
7415 
7416 #endif /* CONFIG_NO_HZ_COMMON */
7417 
cpu_load(struct rq * rq)7418 static unsigned long cpu_load(struct rq *rq)
7419 {
7420 	return cfs_rq_load_avg(&rq->cfs);
7421 }
7422 
7423 /*
7424  * cpu_load_without - compute CPU load without any contributions from *p
7425  * @cpu: the CPU which load is requested
7426  * @p: the task which load should be discounted
7427  *
7428  * The load of a CPU is defined by the load of tasks currently enqueued on that
7429  * CPU as well as tasks which are currently sleeping after an execution on that
7430  * CPU.
7431  *
7432  * This method returns the load of the specified CPU by discounting the load of
7433  * the specified task, whenever the task is currently contributing to the CPU
7434  * load.
7435  */
cpu_load_without(struct rq * rq,struct task_struct * p)7436 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7437 {
7438 	struct cfs_rq *cfs_rq;
7439 	unsigned int load;
7440 
7441 	/* Task has no contribution or is new */
7442 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7443 		return cpu_load(rq);
7444 
7445 	cfs_rq = &rq->cfs;
7446 	load = READ_ONCE(cfs_rq->avg.load_avg);
7447 
7448 	/* Discount task's util from CPU's util */
7449 	lsub_positive(&load, task_h_load(p));
7450 
7451 	return load;
7452 }
7453 
cpu_runnable(struct rq * rq)7454 static unsigned long cpu_runnable(struct rq *rq)
7455 {
7456 	return cfs_rq_runnable_avg(&rq->cfs);
7457 }
7458 
cpu_runnable_without(struct rq * rq,struct task_struct * p)7459 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7460 {
7461 	struct cfs_rq *cfs_rq;
7462 	unsigned int runnable;
7463 
7464 	/* Task has no contribution or is new */
7465 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7466 		return cpu_runnable(rq);
7467 
7468 	cfs_rq = &rq->cfs;
7469 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7470 
7471 	/* Discount task's runnable from CPU's runnable */
7472 	lsub_positive(&runnable, p->se.avg.runnable_avg);
7473 
7474 	return runnable;
7475 }
7476 
capacity_of(int cpu)7477 static unsigned long capacity_of(int cpu)
7478 {
7479 	return cpu_rq(cpu)->cpu_capacity;
7480 }
7481 
record_wakee(struct task_struct * p)7482 static void record_wakee(struct task_struct *p)
7483 {
7484 	/*
7485 	 * Only decay a single time; tasks that have less then 1 wakeup per
7486 	 * jiffy will not have built up many flips.
7487 	 */
7488 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7489 		current->wakee_flips >>= 1;
7490 		current->wakee_flip_decay_ts = jiffies;
7491 	}
7492 
7493 	if (current->last_wakee != p) {
7494 		current->last_wakee = p;
7495 		current->wakee_flips++;
7496 	}
7497 }
7498 
7499 /*
7500  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7501  *
7502  * A waker of many should wake a different task than the one last awakened
7503  * at a frequency roughly N times higher than one of its wakees.
7504  *
7505  * In order to determine whether we should let the load spread vs consolidating
7506  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7507  * partner, and a factor of lls_size higher frequency in the other.
7508  *
7509  * With both conditions met, we can be relatively sure that the relationship is
7510  * non-monogamous, with partner count exceeding socket size.
7511  *
7512  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7513  * whatever is irrelevant, spread criteria is apparent partner count exceeds
7514  * socket size.
7515  */
wake_wide(struct task_struct * p)7516 static int wake_wide(struct task_struct *p)
7517 {
7518 	unsigned int master = current->wakee_flips;
7519 	unsigned int slave = p->wakee_flips;
7520 	int factor = __this_cpu_read(sd_llc_size);
7521 
7522 	if (master < slave)
7523 		swap(master, slave);
7524 	if (slave < factor || master < slave * factor)
7525 		return 0;
7526 	return 1;
7527 }
7528 
7529 /*
7530  * The purpose of wake_affine() is to quickly determine on which CPU we can run
7531  * soonest. For the purpose of speed we only consider the waking and previous
7532  * CPU.
7533  *
7534  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7535  *			cache-affine and is (or	will be) idle.
7536  *
7537  * wake_affine_weight() - considers the weight to reflect the average
7538  *			  scheduling latency of the CPUs. This seems to work
7539  *			  for the overloaded case.
7540  */
7541 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7542 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7543 {
7544 	/*
7545 	 * If this_cpu is idle, it implies the wakeup is from interrupt
7546 	 * context. Only allow the move if cache is shared. Otherwise an
7547 	 * interrupt intensive workload could force all tasks onto one
7548 	 * node depending on the IO topology or IRQ affinity settings.
7549 	 *
7550 	 * If the prev_cpu is idle and cache affine then avoid a migration.
7551 	 * There is no guarantee that the cache hot data from an interrupt
7552 	 * is more important than cache hot data on the prev_cpu and from
7553 	 * a cpufreq perspective, it's better to have higher utilisation
7554 	 * on one CPU.
7555 	 */
7556 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7557 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7558 
7559 	if (sync && cpu_rq(this_cpu)->nr_running == 1)
7560 		return this_cpu;
7561 
7562 	if (available_idle_cpu(prev_cpu))
7563 		return prev_cpu;
7564 
7565 	return nr_cpumask_bits;
7566 }
7567 
7568 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7569 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7570 		   int this_cpu, int prev_cpu, int sync)
7571 {
7572 	s64 this_eff_load, prev_eff_load;
7573 	unsigned long task_load;
7574 
7575 	this_eff_load = cpu_load(cpu_rq(this_cpu));
7576 
7577 	if (sync) {
7578 		unsigned long current_load = task_h_load(current);
7579 
7580 		if (current_load > this_eff_load)
7581 			return this_cpu;
7582 
7583 		this_eff_load -= current_load;
7584 	}
7585 
7586 	task_load = task_h_load(p);
7587 
7588 	this_eff_load += task_load;
7589 	if (sched_feat(WA_BIAS))
7590 		this_eff_load *= 100;
7591 	this_eff_load *= capacity_of(prev_cpu);
7592 
7593 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7594 	prev_eff_load -= task_load;
7595 	if (sched_feat(WA_BIAS))
7596 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7597 	prev_eff_load *= capacity_of(this_cpu);
7598 
7599 	/*
7600 	 * If sync, adjust the weight of prev_eff_load such that if
7601 	 * prev_eff == this_eff that select_idle_sibling() will consider
7602 	 * stacking the wakee on top of the waker if no other CPU is
7603 	 * idle.
7604 	 */
7605 	if (sync)
7606 		prev_eff_load += 1;
7607 
7608 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7609 }
7610 
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7611 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7612 		       int this_cpu, int prev_cpu, int sync)
7613 {
7614 	int target = nr_cpumask_bits;
7615 
7616 	if (sched_feat(WA_IDLE))
7617 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
7618 
7619 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7620 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7621 
7622 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7623 	if (target != this_cpu)
7624 		return prev_cpu;
7625 
7626 	schedstat_inc(sd->ttwu_move_affine);
7627 	schedstat_inc(p->stats.nr_wakeups_affine);
7628 	return target;
7629 }
7630 
7631 static struct sched_group *
7632 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7633 
7634 /*
7635  * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7636  */
7637 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7638 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7639 {
7640 	unsigned long load, min_load = ULONG_MAX;
7641 	unsigned int min_exit_latency = UINT_MAX;
7642 	u64 latest_idle_timestamp = 0;
7643 	int least_loaded_cpu = this_cpu;
7644 	int shallowest_idle_cpu = -1;
7645 	int i;
7646 
7647 	/* Check if we have any choice: */
7648 	if (group->group_weight == 1)
7649 		return cpumask_first(sched_group_span(group));
7650 
7651 	/* Traverse only the allowed CPUs */
7652 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7653 		struct rq *rq = cpu_rq(i);
7654 
7655 		if (!sched_core_cookie_match(rq, p))
7656 			continue;
7657 
7658 		if (sched_idle_cpu(i))
7659 			return i;
7660 
7661 		if (available_idle_cpu(i)) {
7662 			struct cpuidle_state *idle = idle_get_state(rq);
7663 			if (idle && idle->exit_latency < min_exit_latency) {
7664 				/*
7665 				 * We give priority to a CPU whose idle state
7666 				 * has the smallest exit latency irrespective
7667 				 * of any idle timestamp.
7668 				 */
7669 				min_exit_latency = idle->exit_latency;
7670 				latest_idle_timestamp = rq->idle_stamp;
7671 				shallowest_idle_cpu = i;
7672 			} else if ((!idle || idle->exit_latency == min_exit_latency) &&
7673 				   rq->idle_stamp > latest_idle_timestamp) {
7674 				/*
7675 				 * If equal or no active idle state, then
7676 				 * the most recently idled CPU might have
7677 				 * a warmer cache.
7678 				 */
7679 				latest_idle_timestamp = rq->idle_stamp;
7680 				shallowest_idle_cpu = i;
7681 			}
7682 		} else if (shallowest_idle_cpu == -1) {
7683 			load = cpu_load(cpu_rq(i));
7684 			if (load < min_load) {
7685 				min_load = load;
7686 				least_loaded_cpu = i;
7687 			}
7688 		}
7689 	}
7690 
7691 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7692 }
7693 
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7694 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7695 				  int cpu, int prev_cpu, int sd_flag)
7696 {
7697 	int new_cpu = cpu;
7698 
7699 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7700 		return prev_cpu;
7701 
7702 	/*
7703 	 * We need task's util for cpu_util_without, sync it up to
7704 	 * prev_cpu's last_update_time.
7705 	 */
7706 	if (!(sd_flag & SD_BALANCE_FORK))
7707 		sync_entity_load_avg(&p->se);
7708 
7709 	while (sd) {
7710 		struct sched_group *group;
7711 		struct sched_domain *tmp;
7712 		int weight;
7713 
7714 		if (!(sd->flags & sd_flag)) {
7715 			sd = sd->child;
7716 			continue;
7717 		}
7718 
7719 		group = sched_balance_find_dst_group(sd, p, cpu);
7720 		if (!group) {
7721 			sd = sd->child;
7722 			continue;
7723 		}
7724 
7725 		new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7726 		if (new_cpu == cpu) {
7727 			/* Now try balancing at a lower domain level of 'cpu': */
7728 			sd = sd->child;
7729 			continue;
7730 		}
7731 
7732 		/* Now try balancing at a lower domain level of 'new_cpu': */
7733 		cpu = new_cpu;
7734 		weight = sd->span_weight;
7735 		sd = NULL;
7736 		for_each_domain(cpu, tmp) {
7737 			if (weight <= tmp->span_weight)
7738 				break;
7739 			if (tmp->flags & sd_flag)
7740 				sd = tmp;
7741 		}
7742 	}
7743 
7744 	return new_cpu;
7745 }
7746 
__select_idle_cpu(int cpu,struct task_struct * p)7747 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7748 {
7749 	if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7750 	    sched_cpu_cookie_match(cpu_rq(cpu), p))
7751 		return cpu;
7752 
7753 	return -1;
7754 }
7755 
7756 #ifdef CONFIG_SCHED_SMT
7757 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7758 EXPORT_SYMBOL_GPL(sched_smt_present);
7759 
set_idle_cores(int cpu,int val)7760 static inline void set_idle_cores(int cpu, int val)
7761 {
7762 	struct sched_domain_shared *sds;
7763 
7764 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7765 	if (sds)
7766 		WRITE_ONCE(sds->has_idle_cores, val);
7767 }
7768 
test_idle_cores(int cpu)7769 static inline bool test_idle_cores(int cpu)
7770 {
7771 	struct sched_domain_shared *sds;
7772 
7773 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7774 	if (sds)
7775 		return READ_ONCE(sds->has_idle_cores);
7776 
7777 	return false;
7778 }
7779 
7780 /*
7781  * Scans the local SMT mask to see if the entire core is idle, and records this
7782  * information in sd_llc_shared->has_idle_cores.
7783  *
7784  * Since SMT siblings share all cache levels, inspecting this limited remote
7785  * state should be fairly cheap.
7786  */
__update_idle_core(struct rq * rq)7787 void __update_idle_core(struct rq *rq)
7788 {
7789 	int core = cpu_of(rq);
7790 	int cpu;
7791 
7792 	rcu_read_lock();
7793 	if (test_idle_cores(core))
7794 		goto unlock;
7795 
7796 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7797 		if (cpu == core)
7798 			continue;
7799 
7800 		if (!available_idle_cpu(cpu))
7801 			goto unlock;
7802 	}
7803 
7804 	set_idle_cores(core, 1);
7805 unlock:
7806 	rcu_read_unlock();
7807 }
7808 
7809 /*
7810  * Scan the entire LLC domain for idle cores; this dynamically switches off if
7811  * there are no idle cores left in the system; tracked through
7812  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7813  */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7814 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7815 {
7816 	bool idle = true;
7817 	int cpu;
7818 
7819 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7820 		if (!available_idle_cpu(cpu)) {
7821 			idle = false;
7822 			if (*idle_cpu == -1) {
7823 				if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7824 					*idle_cpu = cpu;
7825 					break;
7826 				}
7827 				continue;
7828 			}
7829 			break;
7830 		}
7831 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7832 			*idle_cpu = cpu;
7833 	}
7834 
7835 	if (idle)
7836 		return core;
7837 
7838 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7839 	return -1;
7840 }
7841 
7842 /*
7843  * Scan the local SMT mask for idle CPUs.
7844  */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7845 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7846 {
7847 	int cpu;
7848 
7849 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7850 		if (cpu == target)
7851 			continue;
7852 		/*
7853 		 * Check if the CPU is in the LLC scheduling domain of @target.
7854 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7855 		 */
7856 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7857 			continue;
7858 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7859 			return cpu;
7860 	}
7861 
7862 	return -1;
7863 }
7864 
7865 #else /* CONFIG_SCHED_SMT */
7866 
set_idle_cores(int cpu,int val)7867 static inline void set_idle_cores(int cpu, int val)
7868 {
7869 }
7870 
test_idle_cores(int cpu)7871 static inline bool test_idle_cores(int cpu)
7872 {
7873 	return false;
7874 }
7875 
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7876 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7877 {
7878 	return __select_idle_cpu(core, p);
7879 }
7880 
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7881 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7882 {
7883 	return -1;
7884 }
7885 
7886 #endif /* CONFIG_SCHED_SMT */
7887 
7888 /*
7889  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7890  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7891  * average idle time for this rq (as found in rq->avg_idle).
7892  */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7893 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7894 {
7895 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7896 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
7897 	struct sched_domain_shared *sd_share;
7898 
7899 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7900 
7901 	if (sched_feat(SIS_UTIL)) {
7902 		sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7903 		if (sd_share) {
7904 			/* because !--nr is the condition to stop scan */
7905 			nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7906 			/* overloaded LLC is unlikely to have idle cpu/core */
7907 			if (nr == 1)
7908 				return -1;
7909 		}
7910 	}
7911 
7912 	if (static_branch_unlikely(&sched_cluster_active)) {
7913 		struct sched_group *sg = sd->groups;
7914 
7915 		if (sg->flags & SD_CLUSTER) {
7916 			for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7917 				if (!cpumask_test_cpu(cpu, cpus))
7918 					continue;
7919 
7920 				if (has_idle_core) {
7921 					i = select_idle_core(p, cpu, cpus, &idle_cpu);
7922 					if ((unsigned int)i < nr_cpumask_bits)
7923 						return i;
7924 				} else {
7925 					if (--nr <= 0)
7926 						return -1;
7927 					idle_cpu = __select_idle_cpu(cpu, p);
7928 					if ((unsigned int)idle_cpu < nr_cpumask_bits)
7929 						return idle_cpu;
7930 				}
7931 			}
7932 			cpumask_andnot(cpus, cpus, sched_group_span(sg));
7933 		}
7934 	}
7935 
7936 	for_each_cpu_wrap(cpu, cpus, target + 1) {
7937 		if (has_idle_core) {
7938 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
7939 			if ((unsigned int)i < nr_cpumask_bits)
7940 				return i;
7941 
7942 		} else {
7943 			if (--nr <= 0)
7944 				return -1;
7945 			idle_cpu = __select_idle_cpu(cpu, p);
7946 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
7947 				break;
7948 		}
7949 	}
7950 
7951 	if (has_idle_core)
7952 		set_idle_cores(target, false);
7953 
7954 	return idle_cpu;
7955 }
7956 
7957 /*
7958  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7959  * the task fits. If no CPU is big enough, but there are idle ones, try to
7960  * maximize capacity.
7961  */
7962 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7963 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7964 {
7965 	unsigned long task_util, util_min, util_max, best_cap = 0;
7966 	int fits, best_fits = 0;
7967 	int cpu, best_cpu = -1;
7968 	struct cpumask *cpus;
7969 
7970 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7971 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7972 
7973 	task_util = task_util_est(p);
7974 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
7975 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
7976 
7977 	for_each_cpu_wrap(cpu, cpus, target) {
7978 		unsigned long cpu_cap = capacity_of(cpu);
7979 
7980 		if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7981 			continue;
7982 
7983 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7984 
7985 		/* This CPU fits with all requirements */
7986 		if (fits > 0)
7987 			return cpu;
7988 		/*
7989 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7990 		 * Look for the CPU with best capacity.
7991 		 */
7992 		else if (fits < 0)
7993 			cpu_cap = get_actual_cpu_capacity(cpu);
7994 
7995 		/*
7996 		 * First, select CPU which fits better (-1 being better than 0).
7997 		 * Then, select the one with best capacity at same level.
7998 		 */
7999 		if ((fits < best_fits) ||
8000 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
8001 			best_cap = cpu_cap;
8002 			best_cpu = cpu;
8003 			best_fits = fits;
8004 		}
8005 	}
8006 
8007 	return best_cpu;
8008 }
8009 
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)8010 static inline bool asym_fits_cpu(unsigned long util,
8011 				 unsigned long util_min,
8012 				 unsigned long util_max,
8013 				 int cpu)
8014 {
8015 	if (sched_asym_cpucap_active())
8016 		/*
8017 		 * Return true only if the cpu fully fits the task requirements
8018 		 * which include the utilization and the performance hints.
8019 		 */
8020 		return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
8021 
8022 	return true;
8023 }
8024 
8025 /*
8026  * Try and locate an idle core/thread in the LLC cache domain.
8027  */
select_idle_sibling(struct task_struct * p,int prev,int target)8028 static int select_idle_sibling(struct task_struct *p, int prev, int target)
8029 {
8030 	bool has_idle_core = false;
8031 	struct sched_domain *sd;
8032 	unsigned long task_util, util_min, util_max;
8033 	int i, recent_used_cpu, prev_aff = -1;
8034 
8035 	/*
8036 	 * On asymmetric system, update task utilization because we will check
8037 	 * that the task fits with CPU's capacity.
8038 	 */
8039 	if (sched_asym_cpucap_active()) {
8040 		sync_entity_load_avg(&p->se);
8041 		task_util = task_util_est(p);
8042 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
8043 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
8044 	}
8045 
8046 	/*
8047 	 * per-cpu select_rq_mask usage
8048 	 */
8049 	lockdep_assert_irqs_disabled();
8050 
8051 	if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
8052 	    asym_fits_cpu(task_util, util_min, util_max, target))
8053 		return target;
8054 
8055 	/*
8056 	 * If the previous CPU is cache affine and idle, don't be stupid:
8057 	 */
8058 	if (prev != target && cpus_share_cache(prev, target) &&
8059 	    (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
8060 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
8061 
8062 		if (!static_branch_unlikely(&sched_cluster_active) ||
8063 		    cpus_share_resources(prev, target))
8064 			return prev;
8065 
8066 		prev_aff = prev;
8067 	}
8068 
8069 	/*
8070 	 * Allow a per-cpu kthread to stack with the wakee if the
8071 	 * kworker thread and the tasks previous CPUs are the same.
8072 	 * The assumption is that the wakee queued work for the
8073 	 * per-cpu kthread that is now complete and the wakeup is
8074 	 * essentially a sync wakeup. An obvious example of this
8075 	 * pattern is IO completions.
8076 	 */
8077 	if (is_per_cpu_kthread(current) &&
8078 	    in_task() &&
8079 	    prev == smp_processor_id() &&
8080 	    this_rq()->nr_running <= 1 &&
8081 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
8082 		return prev;
8083 	}
8084 
8085 	/* Check a recently used CPU as a potential idle candidate: */
8086 	recent_used_cpu = p->recent_used_cpu;
8087 	p->recent_used_cpu = prev;
8088 	if (recent_used_cpu != prev &&
8089 	    recent_used_cpu != target &&
8090 	    cpus_share_cache(recent_used_cpu, target) &&
8091 	    (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
8092 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
8093 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
8094 
8095 		if (!static_branch_unlikely(&sched_cluster_active) ||
8096 		    cpus_share_resources(recent_used_cpu, target))
8097 			return recent_used_cpu;
8098 
8099 	} else {
8100 		recent_used_cpu = -1;
8101 	}
8102 
8103 	/*
8104 	 * For asymmetric CPU capacity systems, our domain of interest is
8105 	 * sd_asym_cpucapacity rather than sd_llc.
8106 	 */
8107 	if (sched_asym_cpucap_active()) {
8108 		sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
8109 		/*
8110 		 * On an asymmetric CPU capacity system where an exclusive
8111 		 * cpuset defines a symmetric island (i.e. one unique
8112 		 * capacity_orig value through the cpuset), the key will be set
8113 		 * but the CPUs within that cpuset will not have a domain with
8114 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
8115 		 * capacity path.
8116 		 */
8117 		if (sd) {
8118 			i = select_idle_capacity(p, sd, target);
8119 			return ((unsigned)i < nr_cpumask_bits) ? i : target;
8120 		}
8121 	}
8122 
8123 	sd = rcu_dereference(per_cpu(sd_llc, target));
8124 	if (!sd)
8125 		return target;
8126 
8127 	if (sched_smt_active()) {
8128 		has_idle_core = test_idle_cores(target);
8129 
8130 		if (!has_idle_core && cpus_share_cache(prev, target)) {
8131 			i = select_idle_smt(p, sd, prev);
8132 			if ((unsigned int)i < nr_cpumask_bits)
8133 				return i;
8134 		}
8135 	}
8136 
8137 	i = select_idle_cpu(p, sd, has_idle_core, target);
8138 	if ((unsigned)i < nr_cpumask_bits)
8139 		return i;
8140 
8141 	/*
8142 	 * For cluster machines which have lower sharing cache like L2 or
8143 	 * LLC Tag, we tend to find an idle CPU in the target's cluster
8144 	 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
8145 	 * use them if possible when no idle CPU found in select_idle_cpu().
8146 	 */
8147 	if ((unsigned int)prev_aff < nr_cpumask_bits)
8148 		return prev_aff;
8149 	if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
8150 		return recent_used_cpu;
8151 
8152 	return target;
8153 }
8154 
8155 /**
8156  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
8157  * @cpu: the CPU to get the utilization for
8158  * @p: task for which the CPU utilization should be predicted or NULL
8159  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
8160  * @boost: 1 to enable boosting, otherwise 0
8161  *
8162  * The unit of the return value must be the same as the one of CPU capacity
8163  * so that CPU utilization can be compared with CPU capacity.
8164  *
8165  * CPU utilization is the sum of running time of runnable tasks plus the
8166  * recent utilization of currently non-runnable tasks on that CPU.
8167  * It represents the amount of CPU capacity currently used by CFS tasks in
8168  * the range [0..max CPU capacity] with max CPU capacity being the CPU
8169  * capacity at f_max.
8170  *
8171  * The estimated CPU utilization is defined as the maximum between CPU
8172  * utilization and sum of the estimated utilization of the currently
8173  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
8174  * previously-executed tasks, which helps better deduce how busy a CPU will
8175  * be when a long-sleeping task wakes up. The contribution to CPU utilization
8176  * of such a task would be significantly decayed at this point of time.
8177  *
8178  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
8179  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
8180  * utilization. Boosting is implemented in cpu_util() so that internal
8181  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
8182  * latter via cpu_util_cfs_boost().
8183  *
8184  * CPU utilization can be higher than the current CPU capacity
8185  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
8186  * of rounding errors as well as task migrations or wakeups of new tasks.
8187  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
8188  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
8189  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
8190  * capacity. CPU utilization is allowed to overshoot current CPU capacity
8191  * though since this is useful for predicting the CPU capacity required
8192  * after task migrations (scheduler-driven DVFS).
8193  *
8194  * Return: (Boosted) (estimated) utilization for the specified CPU.
8195  */
8196 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)8197 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
8198 {
8199 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
8200 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
8201 	unsigned long runnable;
8202 
8203 	if (boost) {
8204 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
8205 		util = max(util, runnable);
8206 	}
8207 
8208 	/*
8209 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
8210 	 * contribution. If @p migrates from another CPU to @cpu add its
8211 	 * contribution. In all the other cases @cpu is not impacted by the
8212 	 * migration so its util_avg is already correct.
8213 	 */
8214 	if (p && task_cpu(p) == cpu && dst_cpu != cpu)
8215 		lsub_positive(&util, task_util(p));
8216 	else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
8217 		util += task_util(p);
8218 
8219 	if (sched_feat(UTIL_EST)) {
8220 		unsigned long util_est;
8221 
8222 		util_est = READ_ONCE(cfs_rq->avg.util_est);
8223 
8224 		/*
8225 		 * During wake-up @p isn't enqueued yet and doesn't contribute
8226 		 * to any cpu_rq(cpu)->cfs.avg.util_est.
8227 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
8228 		 * has been enqueued.
8229 		 *
8230 		 * During exec (@dst_cpu = -1) @p is enqueued and does
8231 		 * contribute to cpu_rq(cpu)->cfs.util_est.
8232 		 * Remove it to "simulate" cpu_util without @p's contribution.
8233 		 *
8234 		 * Despite the task_on_rq_queued(@p) check there is still a
8235 		 * small window for a possible race when an exec
8236 		 * select_task_rq_fair() races with LB's detach_task().
8237 		 *
8238 		 *   detach_task()
8239 		 *     deactivate_task()
8240 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
8241 		 *       -------------------------------- A
8242 		 *       dequeue_task()                    \
8243 		 *         dequeue_task_fair()              + Race Time
8244 		 *           util_est_dequeue()            /
8245 		 *       -------------------------------- B
8246 		 *
8247 		 * The additional check "current == p" is required to further
8248 		 * reduce the race window.
8249 		 */
8250 		if (dst_cpu == cpu)
8251 			util_est += _task_util_est(p);
8252 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
8253 			lsub_positive(&util_est, _task_util_est(p));
8254 
8255 		util = max(util, util_est);
8256 	}
8257 
8258 	return min(util, arch_scale_cpu_capacity(cpu));
8259 }
8260 
cpu_util_cfs(int cpu)8261 unsigned long cpu_util_cfs(int cpu)
8262 {
8263 	return cpu_util(cpu, NULL, -1, 0);
8264 }
8265 
cpu_util_cfs_boost(int cpu)8266 unsigned long cpu_util_cfs_boost(int cpu)
8267 {
8268 	unsigned long util = INT_MAX;
8269 
8270 	trace_android_rvh_cpu_util_cfs_boost(cpu, &util);
8271 	if (util != INT_MAX)
8272 		return util;
8273 
8274 	return cpu_util(cpu, NULL, -1, 1);
8275 }
8276 
8277 /*
8278  * cpu_util_without: compute cpu utilization without any contributions from *p
8279  * @cpu: the CPU which utilization is requested
8280  * @p: the task which utilization should be discounted
8281  *
8282  * The utilization of a CPU is defined by the utilization of tasks currently
8283  * enqueued on that CPU as well as tasks which are currently sleeping after an
8284  * execution on that CPU.
8285  *
8286  * This method returns the utilization of the specified CPU by discounting the
8287  * utilization of the specified task, whenever the task is currently
8288  * contributing to the CPU utilization.
8289  */
cpu_util_without(int cpu,struct task_struct * p)8290 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8291 {
8292 	/* Task has no contribution or is new */
8293 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8294 		p = NULL;
8295 
8296 	return cpu_util(cpu, p, -1, 0);
8297 }
8298 
8299 /*
8300  * This function computes an effective utilization for the given CPU, to be
8301  * used for frequency selection given the linear relation: f = u * f_max.
8302  *
8303  * The scheduler tracks the following metrics:
8304  *
8305  *   cpu_util_{cfs,rt,dl,irq}()
8306  *   cpu_bw_dl()
8307  *
8308  * Where the cfs,rt and dl util numbers are tracked with the same metric and
8309  * synchronized windows and are thus directly comparable.
8310  *
8311  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8312  * which excludes things like IRQ and steal-time. These latter are then accrued
8313  * in the IRQ utilization.
8314  *
8315  * The DL bandwidth number OTOH is not a measured metric but a value computed
8316  * based on the task model parameters and gives the minimal utilization
8317  * required to meet deadlines.
8318  */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8319 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8320 				 unsigned long *min,
8321 				 unsigned long *max)
8322 {
8323 	unsigned long util, irq, scale;
8324 	struct rq *rq = cpu_rq(cpu);
8325 
8326 	scale = arch_scale_cpu_capacity(cpu);
8327 
8328 	/*
8329 	 * Early check to see if IRQ/steal time saturates the CPU, can be
8330 	 * because of inaccuracies in how we track these -- see
8331 	 * update_irq_load_avg().
8332 	 */
8333 	irq = cpu_util_irq(rq);
8334 	if (unlikely(irq >= scale)) {
8335 		if (min)
8336 			*min = scale;
8337 		if (max)
8338 			*max = scale;
8339 		return scale;
8340 	}
8341 
8342 	if (min) {
8343 		/*
8344 		 * The minimum utilization returns the highest level between:
8345 		 * - the computed DL bandwidth needed with the IRQ pressure which
8346 		 *   steals time to the deadline task.
8347 		 * - The minimum performance requirement for CFS and/or RT.
8348 		 */
8349 		*min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8350 
8351 		/*
8352 		 * When an RT task is runnable and uclamp is not used, we must
8353 		 * ensure that the task will run at maximum compute capacity.
8354 		 */
8355 		if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8356 			*min = max(*min, scale);
8357 	}
8358 
8359 	/*
8360 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8361 	 * CFS tasks and we use the same metric to track the effective
8362 	 * utilization (PELT windows are synchronized) we can directly add them
8363 	 * to obtain the CPU's actual utilization.
8364 	 */
8365 	util = util_cfs + cpu_util_rt(rq);
8366 	util += cpu_util_dl(rq);
8367 
8368 	/*
8369 	 * The maximum hint is a soft bandwidth requirement, which can be lower
8370 	 * than the actual utilization because of uclamp_max requirements.
8371 	 */
8372 	if (max)
8373 		*max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8374 
8375 	if (util >= scale)
8376 		return scale;
8377 
8378 	/*
8379 	 * There is still idle time; further improve the number by using the
8380 	 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8381 	 * need to scale the task numbers:
8382 	 *
8383 	 *              max - irq
8384 	 *   U' = irq + --------- * U
8385 	 *                 max
8386 	 */
8387 	util = scale_irq_capacity(util, irq, scale);
8388 	util += irq;
8389 
8390 	return min(scale, util);
8391 }
8392 
sched_cpu_util(int cpu)8393 unsigned long sched_cpu_util(int cpu)
8394 {
8395 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8396 }
8397 
8398 /*
8399  * energy_env - Utilization landscape for energy estimation.
8400  * @task_busy_time: Utilization contribution by the task for which we test the
8401  *                  placement. Given by eenv_task_busy_time().
8402  * @pd_busy_time:   Utilization of the whole perf domain without the task
8403  *                  contribution. Given by eenv_pd_busy_time().
8404  * @cpu_cap:        Maximum CPU capacity for the perf domain.
8405  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8406  */
8407 struct energy_env {
8408 	unsigned long task_busy_time;
8409 	unsigned long pd_busy_time;
8410 	unsigned long cpu_cap;
8411 	unsigned long pd_cap;
8412 };
8413 
8414 /*
8415  * Compute the task busy time for compute_energy(). This time cannot be
8416  * injected directly into effective_cpu_util() because of the IRQ scaling.
8417  * The latter only makes sense with the most recent CPUs where the task has
8418  * run.
8419  */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8420 static inline void eenv_task_busy_time(struct energy_env *eenv,
8421 				       struct task_struct *p, int prev_cpu)
8422 {
8423 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8424 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8425 
8426 	if (unlikely(irq >= max_cap))
8427 		busy_time = max_cap;
8428 	else
8429 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8430 
8431 	eenv->task_busy_time = busy_time;
8432 }
8433 
8434 /*
8435  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8436  * utilization for each @pd_cpus, it however doesn't take into account
8437  * clamping since the ratio (utilization / cpu_capacity) is already enough to
8438  * scale the EM reported power consumption at the (eventually clamped)
8439  * cpu_capacity.
8440  *
8441  * The contribution of the task @p for which we want to estimate the
8442  * energy cost is removed (by cpu_util()) and must be calculated
8443  * separately (see eenv_task_busy_time). This ensures:
8444  *
8445  *   - A stable PD utilization, no matter which CPU of that PD we want to place
8446  *     the task on.
8447  *
8448  *   - A fair comparison between CPUs as the task contribution (task_util())
8449  *     will always be the same no matter which CPU utilization we rely on
8450  *     (util_avg or util_est).
8451  *
8452  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8453  * exceed @eenv->pd_cap.
8454  */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8455 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8456 				     struct cpumask *pd_cpus,
8457 				     struct task_struct *p)
8458 {
8459 	unsigned long busy_time = 0;
8460 	int cpu;
8461 
8462 	for_each_cpu(cpu, pd_cpus) {
8463 		unsigned long util = cpu_util(cpu, p, -1, 0);
8464 
8465 		busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8466 	}
8467 
8468 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8469 }
8470 
8471 /*
8472  * Compute the maximum utilization for compute_energy() when the task @p
8473  * is placed on the cpu @dst_cpu.
8474  *
8475  * Returns the maximum utilization among @eenv->cpus. This utilization can't
8476  * exceed @eenv->cpu_cap.
8477  */
8478 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8479 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8480 		 struct task_struct *p, int dst_cpu)
8481 {
8482 	unsigned long max_util = 0;
8483 	int cpu;
8484 
8485 	for_each_cpu(cpu, pd_cpus) {
8486 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8487 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8488 		unsigned long eff_util, min, max;
8489 
8490 		/*
8491 		 * Performance domain frequency: utilization clamping
8492 		 * must be considered since it affects the selection
8493 		 * of the performance domain frequency.
8494 		 * NOTE: in case RT tasks are running, by default the min
8495 		 * utilization can be max OPP.
8496 		 */
8497 		eff_util = effective_cpu_util(cpu, util, &min, &max);
8498 
8499 		/* Task's uclamp can modify min and max value */
8500 		if (tsk && uclamp_is_used()) {
8501 			min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8502 
8503 			/*
8504 			 * If there is no active max uclamp constraint,
8505 			 * directly use task's one, otherwise keep max.
8506 			 */
8507 			if (uclamp_rq_is_idle(cpu_rq(cpu)))
8508 				max = uclamp_eff_value(p, UCLAMP_MAX);
8509 			else
8510 				max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8511 		}
8512 
8513 		eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8514 		max_util = max(max_util, eff_util);
8515 	}
8516 
8517 	return min(max_util, eenv->cpu_cap);
8518 }
8519 
8520 /*
8521  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8522  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8523  * contribution is ignored.
8524  */
8525 static inline unsigned long
compute_energy(struct energy_env * eenv,struct perf_domain * pd,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8526 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8527 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8528 {
8529 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8530 	unsigned long busy_time = eenv->pd_busy_time;
8531 	unsigned long energy;
8532 
8533 	if (dst_cpu >= 0)
8534 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8535 
8536 	energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8537 
8538 	trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8539 
8540 	return energy;
8541 }
8542 
8543 /*
8544  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8545  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8546  * spare capacity in each performance domain and uses it as a potential
8547  * candidate to execute the task. Then, it uses the Energy Model to figure
8548  * out which of the CPU candidates is the most energy-efficient.
8549  *
8550  * The rationale for this heuristic is as follows. In a performance domain,
8551  * all the most energy efficient CPU candidates (according to the Energy
8552  * Model) are those for which we'll request a low frequency. When there are
8553  * several CPUs for which the frequency request will be the same, we don't
8554  * have enough data to break the tie between them, because the Energy Model
8555  * only includes active power costs. With this model, if we assume that
8556  * frequency requests follow utilization (e.g. using schedutil), the CPU with
8557  * the maximum spare capacity in a performance domain is guaranteed to be among
8558  * the best candidates of the performance domain.
8559  *
8560  * In practice, it could be preferable from an energy standpoint to pack
8561  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8562  * but that could also hurt our chances to go cluster idle, and we have no
8563  * ways to tell with the current Energy Model if this is actually a good
8564  * idea or not. So, find_energy_efficient_cpu() basically favors
8565  * cluster-packing, and spreading inside a cluster. That should at least be
8566  * a good thing for latency, and this is consistent with the idea that most
8567  * of the energy savings of EAS come from the asymmetry of the system, and
8568  * not so much from breaking the tie between identical CPUs. That's also the
8569  * reason why EAS is enabled in the topology code only for systems where
8570  * SD_ASYM_CPUCAPACITY is set.
8571  *
8572  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8573  * they don't have any useful utilization data yet and it's not possible to
8574  * forecast their impact on energy consumption. Consequently, they will be
8575  * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8576  * to be energy-inefficient in some use-cases. The alternative would be to
8577  * bias new tasks towards specific types of CPUs first, or to try to infer
8578  * their util_avg from the parent task, but those heuristics could hurt
8579  * other use-cases too. So, until someone finds a better way to solve this,
8580  * let's keep things simple by re-using the existing slow path.
8581  */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu,int sync)8582 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu, int sync)
8583 {
8584 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8585 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8586 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8587 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8588 	struct root_domain *rd = this_rq()->rd;
8589 	int cpu, best_energy_cpu, target = -1;
8590 	int prev_fits = -1, best_fits = -1;
8591 	unsigned long best_actual_cap = 0;
8592 	unsigned long prev_actual_cap = 0;
8593 	struct sched_domain *sd;
8594 	struct perf_domain *pd;
8595 	struct energy_env eenv;
8596 	int new_cpu = INT_MAX;
8597 
8598 	trace_android_rvh_find_energy_efficient_cpu(p, prev_cpu, sync, &new_cpu);
8599 	if (new_cpu != INT_MAX)
8600 		return new_cpu;
8601 
8602 	sync_entity_load_avg(&p->se);
8603 
8604 	rcu_read_lock();
8605 	pd = rcu_dereference(rd->pd);
8606 	if (!pd)
8607 		goto unlock;
8608 
8609 	cpu = smp_processor_id();
8610 	if (sync && cpu_rq(cpu)->nr_running == 1 &&
8611 	    cpumask_test_cpu(cpu, p->cpus_ptr) &&
8612 	    task_fits_cpu(p, cpu)) {
8613 		rcu_read_unlock();
8614 		return cpu;
8615 	}
8616 
8617 	/*
8618 	 * Energy-aware wake-up happens on the lowest sched_domain starting
8619 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8620 	 */
8621 	sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8622 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8623 		sd = sd->parent;
8624 	if (!sd)
8625 		goto unlock;
8626 
8627 	target = prev_cpu;
8628 
8629 	sync_entity_load_avg(&p->se);
8630 	if (!task_util_est(p) && p_util_min == 0)
8631 		goto unlock;
8632 
8633 	eenv_task_busy_time(&eenv, p, prev_cpu);
8634 
8635 	for (; pd; pd = pd->next) {
8636 		unsigned long util_min = p_util_min, util_max = p_util_max;
8637 		unsigned long cpu_cap, cpu_actual_cap, util;
8638 		long prev_spare_cap = -1, max_spare_cap = -1;
8639 		unsigned long rq_util_min, rq_util_max;
8640 		unsigned long cur_delta, base_energy;
8641 		int max_spare_cap_cpu = -1;
8642 		int fits, max_fits = -1;
8643 
8644 		cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8645 
8646 		if (cpumask_empty(cpus))
8647 			continue;
8648 
8649 		/* Account external pressure for the energy estimation */
8650 		cpu = cpumask_first(cpus);
8651 		cpu_actual_cap = get_actual_cpu_capacity(cpu);
8652 
8653 		eenv.cpu_cap = cpu_actual_cap;
8654 		eenv.pd_cap = 0;
8655 
8656 		for_each_cpu(cpu, cpus) {
8657 			struct rq *rq = cpu_rq(cpu);
8658 
8659 			eenv.pd_cap += cpu_actual_cap;
8660 
8661 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8662 				continue;
8663 
8664 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8665 				continue;
8666 
8667 			util = cpu_util(cpu, p, cpu, 0);
8668 			cpu_cap = capacity_of(cpu);
8669 
8670 			/*
8671 			 * Skip CPUs that cannot satisfy the capacity request.
8672 			 * IOW, placing the task there would make the CPU
8673 			 * overutilized. Take uclamp into account to see how
8674 			 * much capacity we can get out of the CPU; this is
8675 			 * aligned with sched_cpu_util().
8676 			 */
8677 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8678 				/*
8679 				 * Open code uclamp_rq_util_with() except for
8680 				 * the clamp() part. I.e.: apply max aggregation
8681 				 * only. util_fits_cpu() logic requires to
8682 				 * operate on non clamped util but must use the
8683 				 * max-aggregated uclamp_{min, max}.
8684 				 */
8685 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8686 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8687 
8688 				util_min = max(rq_util_min, p_util_min);
8689 				util_max = max(rq_util_max, p_util_max);
8690 			}
8691 
8692 			fits = util_fits_cpu(util, util_min, util_max, cpu);
8693 			if (!fits)
8694 				continue;
8695 
8696 			lsub_positive(&cpu_cap, util);
8697 
8698 			if (cpu == prev_cpu) {
8699 				/* Always use prev_cpu as a candidate. */
8700 				prev_spare_cap = cpu_cap;
8701 				prev_fits = fits;
8702 			} else if ((fits > max_fits) ||
8703 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8704 				/*
8705 				 * Find the CPU with the maximum spare capacity
8706 				 * among the remaining CPUs in the performance
8707 				 * domain.
8708 				 */
8709 				max_spare_cap = cpu_cap;
8710 				max_spare_cap_cpu = cpu;
8711 				max_fits = fits;
8712 			}
8713 		}
8714 
8715 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8716 			continue;
8717 
8718 		eenv_pd_busy_time(&eenv, cpus, p);
8719 		/* Compute the 'base' energy of the pd, without @p */
8720 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8721 
8722 		/* Evaluate the energy impact of using prev_cpu. */
8723 		if (prev_spare_cap > -1) {
8724 			prev_delta = compute_energy(&eenv, pd, cpus, p,
8725 						    prev_cpu);
8726 			/* CPU utilization has changed */
8727 			if (prev_delta < base_energy)
8728 				goto unlock;
8729 			prev_delta -= base_energy;
8730 			prev_actual_cap = cpu_actual_cap;
8731 			best_delta = min(best_delta, prev_delta);
8732 		}
8733 
8734 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
8735 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8736 			/* Current best energy cpu fits better */
8737 			if (max_fits < best_fits)
8738 				continue;
8739 
8740 			/*
8741 			 * Both don't fit performance hint (i.e. uclamp_min)
8742 			 * but best energy cpu has better capacity.
8743 			 */
8744 			if ((max_fits < 0) &&
8745 			    (cpu_actual_cap <= best_actual_cap))
8746 				continue;
8747 
8748 			cur_delta = compute_energy(&eenv, pd, cpus, p,
8749 						   max_spare_cap_cpu);
8750 			/* CPU utilization has changed */
8751 			if (cur_delta < base_energy)
8752 				goto unlock;
8753 			cur_delta -= base_energy;
8754 
8755 			/*
8756 			 * Both fit for the task but best energy cpu has lower
8757 			 * energy impact.
8758 			 */
8759 			if ((max_fits > 0) && (best_fits > 0) &&
8760 			    (cur_delta >= best_delta))
8761 				continue;
8762 
8763 			best_delta = cur_delta;
8764 			best_energy_cpu = max_spare_cap_cpu;
8765 			best_fits = max_fits;
8766 			best_actual_cap = cpu_actual_cap;
8767 		}
8768 	}
8769 	rcu_read_unlock();
8770 
8771 	if ((best_fits > prev_fits) ||
8772 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
8773 	    ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8774 		target = best_energy_cpu;
8775 
8776 	return target;
8777 
8778 unlock:
8779 	rcu_read_unlock();
8780 
8781 	return target;
8782 }
8783 
8784 /*
8785  * select_task_rq_fair: Select target runqueue for the waking task in domains
8786  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8787  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8788  *
8789  * Balances load by selecting the idlest CPU in the idlest group, or under
8790  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8791  *
8792  * Returns the target CPU number.
8793  */
8794 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8795 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8796 {
8797 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8798 	struct sched_domain *tmp, *sd = NULL;
8799 	int cpu = smp_processor_id();
8800 	int new_cpu = prev_cpu;
8801 	int want_affine = 0;
8802 	int target_cpu = -1;
8803 	/* SD_flags and WF_flags share the first nibble */
8804 	int sd_flag = wake_flags & 0xF;
8805 
8806 	if (trace_android_rvh_select_task_rq_fair_enabled() &&
8807 	    !(sd_flag & SD_BALANCE_FORK))
8808 		sync_entity_load_avg(&p->se);
8809 	trace_android_rvh_select_task_rq_fair(p, prev_cpu, sd_flag,
8810 			wake_flags, &target_cpu);
8811 	if (target_cpu >= 0)
8812 		return target_cpu;
8813 
8814 	/*
8815 	 * required for stable ->cpus_allowed
8816 	 */
8817 	lockdep_assert_held(&p->pi_lock);
8818 	if (wake_flags & WF_TTWU) {
8819 		record_wakee(p);
8820 
8821 		if ((wake_flags & WF_CURRENT_CPU) &&
8822 		    cpumask_test_cpu(cpu, p->cpus_ptr))
8823 			return cpu;
8824 
8825 		if (!is_rd_overutilized(this_rq()->rd)) {
8826 			new_cpu = find_energy_efficient_cpu(p, prev_cpu, sync);
8827 			if (new_cpu >= 0)
8828 				return new_cpu;
8829 			new_cpu = prev_cpu;
8830 		}
8831 
8832 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8833 	}
8834 
8835 	rcu_read_lock();
8836 	for_each_domain(cpu, tmp) {
8837 		/*
8838 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
8839 		 * cpu is a valid SD_WAKE_AFFINE target.
8840 		 */
8841 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8842 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8843 			if (cpu != prev_cpu)
8844 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8845 
8846 			sd = NULL; /* Prefer wake_affine over balance flags */
8847 			break;
8848 		}
8849 
8850 		/*
8851 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8852 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8853 		 * will usually go to the fast path.
8854 		 */
8855 		if (tmp->flags & sd_flag)
8856 			sd = tmp;
8857 		else if (!want_affine)
8858 			break;
8859 	}
8860 
8861 	if (unlikely(sd)) {
8862 		/* Slow path */
8863 		new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8864 	} else if (wake_flags & WF_TTWU) { /* XXX always ? */
8865 		/* Fast path */
8866 		new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8867 	}
8868 	rcu_read_unlock();
8869 
8870 	return new_cpu;
8871 }
8872 
8873 /*
8874  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8875  * cfs_rq_of(p) references at time of call are still valid and identify the
8876  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8877  */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8878 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8879 {
8880 	struct sched_entity *se = &p->se;
8881 
8882 	if (!task_on_rq_migrating(p)) {
8883 		remove_entity_load_avg(se);
8884 
8885 		/*
8886 		 * Here, the task's PELT values have been updated according to
8887 		 * the current rq's clock. But if that clock hasn't been
8888 		 * updated in a while, a substantial idle time will be missed,
8889 		 * leading to an inflation after wake-up on the new rq.
8890 		 *
8891 		 * Estimate the missing time from the cfs_rq last_update_time
8892 		 * and update sched_avg to improve the PELT continuity after
8893 		 * migration.
8894 		 */
8895 		migrate_se_pelt_lag(se);
8896 	}
8897 
8898 	/* Tell new CPU we are migrated */
8899 	se->avg.last_update_time = 0;
8900 
8901 	update_scan_period(p, new_cpu);
8902 }
8903 
task_dead_fair(struct task_struct * p)8904 static void task_dead_fair(struct task_struct *p)
8905 {
8906 	struct sched_entity *se = &p->se;
8907 
8908 	if (se->sched_delayed) {
8909 		struct rq_flags rf;
8910 		struct rq *rq;
8911 
8912 		rq = task_rq_lock(p, &rf);
8913 		if (se->sched_delayed) {
8914 			update_rq_clock(rq);
8915 			dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8916 		}
8917 		task_rq_unlock(rq, p, &rf);
8918 	}
8919 
8920 	remove_entity_load_avg(se);
8921 }
8922 
8923 /*
8924  * Set the max capacity the task is allowed to run at for misfit detection.
8925  */
set_task_max_allowed_capacity(struct task_struct * p)8926 static void set_task_max_allowed_capacity(struct task_struct *p)
8927 {
8928 	struct asym_cap_data *entry;
8929 
8930 	if (!sched_asym_cpucap_active())
8931 		return;
8932 
8933 	rcu_read_lock();
8934 	list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8935 		cpumask_t *cpumask;
8936 
8937 		cpumask = cpu_capacity_span(entry);
8938 		if (!cpumask_intersects(p->cpus_ptr, cpumask))
8939 			continue;
8940 
8941 		p->max_allowed_capacity = entry->capacity;
8942 		break;
8943 	}
8944 	rcu_read_unlock();
8945 }
8946 
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8947 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8948 {
8949 	set_cpus_allowed_common(p, ctx);
8950 	set_task_max_allowed_capacity(p);
8951 }
8952 
8953 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8954 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8955 {
8956 	trace_android_rvh_balance_fair(rq, prev, rf);
8957 	if (sched_fair_runnable(rq))
8958 		return 1;
8959 
8960 	return sched_balance_newidle(rq, rf) != 0;
8961 }
8962 #else
set_task_max_allowed_capacity(struct task_struct * p)8963 static inline void set_task_max_allowed_capacity(struct task_struct *p) {}
8964 #endif /* CONFIG_SMP */
8965 
set_next_buddy(struct sched_entity * se)8966 static void set_next_buddy(struct sched_entity *se)
8967 {
8968 	for_each_sched_entity(se) {
8969 		if (SCHED_WARN_ON(!se->on_rq))
8970 			return;
8971 		if (se_is_idle(se))
8972 			return;
8973 		cfs_rq_of(se)->next = se;
8974 	}
8975 }
8976 
8977 /*
8978  * Preempt the current task with a newly woken task if needed:
8979  */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8980 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8981 {
8982 	struct task_struct *donor = rq->donor;
8983 	struct sched_entity *se = &donor->se, *pse = &p->se;
8984 	struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8985 	int cse_is_idle, pse_is_idle;
8986 	bool ignore = false;
8987 	bool preempt = false;
8988 
8989 	if (unlikely(se == pse))
8990 		return;
8991 	trace_android_rvh_check_preempt_wakeup_ignore(donor, &ignore);
8992 	if (ignore)
8993 		return;
8994 
8995 	/*
8996 	 * This is possible from callers such as attach_tasks(), in which we
8997 	 * unconditionally wakeup_preempt() after an enqueue (which may have
8998 	 * lead to a throttle).  This both saves work and prevents false
8999 	 * next-buddy nomination below.
9000 	 */
9001 	if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
9002 		return;
9003 
9004 	if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK) && !pse->sched_delayed) {
9005 		set_next_buddy(pse);
9006 	}
9007 
9008 	/*
9009 	 * We can come here with TIF_NEED_RESCHED already set from new task
9010 	 * wake up path.
9011 	 *
9012 	 * Note: this also catches the edge-case of curr being in a throttled
9013 	 * group (e.g. via set_curr_task), since update_curr() (in the
9014 	 * enqueue of curr) will have resulted in resched being set.  This
9015 	 * prevents us from potentially nominating it as a false LAST_BUDDY
9016 	 * below.
9017 	 */
9018 	if (test_tsk_need_resched(rq->curr))
9019 		return;
9020 
9021 	if (!sched_feat(WAKEUP_PREEMPTION))
9022 		return;
9023 
9024 	find_matching_se(&se, &pse);
9025 	WARN_ON_ONCE(!pse);
9026 
9027 	cse_is_idle = se_is_idle(se);
9028 	pse_is_idle = se_is_idle(pse);
9029 
9030 	/*
9031 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
9032 	 * in the inverse case).
9033 	 */
9034 	if (cse_is_idle && !pse_is_idle) {
9035 		/*
9036 		 * When non-idle entity preempt an idle entity,
9037 		 * don't give idle entity slice protection.
9038 		 */
9039 		cancel_protect_slice(se);
9040 		goto preempt;
9041 	}
9042 
9043 	if (cse_is_idle != pse_is_idle)
9044 		return;
9045 
9046 	/*
9047 	 * BATCH and IDLE tasks do not preempt others.
9048 	 */
9049 	if (unlikely(!normal_policy(p->policy)))
9050 		return;
9051 
9052 	cfs_rq = cfs_rq_of(se);
9053 	update_curr(cfs_rq);
9054 	trace_android_rvh_check_preempt_wakeup_fair(rq, p, &preempt, &ignore,
9055 						wake_flags, se, pse);
9056 	if (preempt)
9057 		goto preempt;
9058 	if (ignore)
9059 		return;
9060 	/*
9061 	 * If @p has a shorter slice than current and @p is eligible, override
9062 	 * current's slice protection in order to allow preemption.
9063 	 *
9064 	 * Note that even if @p does not turn out to be the most eligible
9065 	 * task at this moment, current's slice protection will be lost.
9066 	 */
9067 	if (do_preempt_short(cfs_rq, pse, se))
9068 		cancel_protect_slice(se);
9069 
9070 	/*
9071 	 * If @p has become the most eligible task, force preemption.
9072 	 */
9073 	if (pick_eevdf(cfs_rq) == pse)
9074 		goto preempt;
9075 
9076 	return;
9077 
9078 preempt:
9079 	resched_curr(rq);
9080 }
9081 
pick_task_fair(struct rq * rq)9082 static struct task_struct *pick_task_fair(struct rq *rq)
9083 {
9084 	struct sched_entity *se;
9085 	struct cfs_rq *cfs_rq;
9086 
9087 again:
9088 	cfs_rq = &rq->cfs;
9089 	if (!cfs_rq->nr_running)
9090 		return NULL;
9091 
9092 	do {
9093 		/* Might not have done put_prev_entity() */
9094 		if (cfs_rq->curr && cfs_rq->curr->on_rq)
9095 			update_curr(cfs_rq);
9096 
9097 		if (unlikely(check_cfs_rq_runtime(cfs_rq)))
9098 			goto again;
9099 
9100 		se = pick_next_entity(rq, cfs_rq);
9101 		if (!se)
9102 			goto again;
9103 		cfs_rq = group_cfs_rq(se);
9104 	} while (cfs_rq);
9105 
9106 	return task_of(se);
9107 }
9108 
9109 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
9110 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
9111 
9112 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)9113 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
9114 {
9115 	struct sched_entity *se;
9116 	struct task_struct *p = NULL;
9117 	int new_tasks;
9118 
9119 again:
9120 	trace_android_rvh_before_pick_task_fair(rq, &p, prev, rf);
9121 	if (!p) {
9122 		p = pick_task_fair(rq);
9123 		trace_android_rvh_replace_next_task_fair(rq, &p, prev);
9124 	}
9125 
9126 	if (!p)
9127 		goto idle;
9128 	se = &p->se;
9129 
9130 #ifdef CONFIG_FAIR_GROUP_SCHED
9131 	if (prev->sched_class != &fair_sched_class ||
9132 	    rq->curr != rq->donor)
9133 		goto simple;
9134 
9135 	__put_prev_set_next_dl_server(rq, prev, p);
9136 
9137 	/*
9138 	 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
9139 	 * likely that a next task is from the same cgroup as the current.
9140 	 *
9141 	 * Therefore attempt to avoid putting and setting the entire cgroup
9142 	 * hierarchy, only change the part that actually changes.
9143 	 *
9144 	 * Since we haven't yet done put_prev_entity and if the selected task
9145 	 * is a different task than we started out with, try and touch the
9146 	 * least amount of cfs_rqs.
9147 	 */
9148 	if (prev != p) {
9149 		struct sched_entity *pse = &prev->se;
9150 		struct cfs_rq *cfs_rq;
9151 
9152 		while (!(cfs_rq = is_same_group(se, pse))) {
9153 			int se_depth = se->depth;
9154 			int pse_depth = pse->depth;
9155 
9156 			if (se_depth <= pse_depth) {
9157 				put_prev_entity(cfs_rq_of(pse), pse);
9158 				pse = parent_entity(pse);
9159 			}
9160 			if (se_depth >= pse_depth) {
9161 				set_next_entity(cfs_rq_of(se), se);
9162 				se = parent_entity(se);
9163 			}
9164 		}
9165 
9166 		put_prev_entity(cfs_rq, pse);
9167 		set_next_entity(cfs_rq, se);
9168 
9169 		__set_next_task_fair(rq, p, true);
9170 	}
9171 
9172 	return p;
9173 
9174 simple:
9175 #endif
9176 	put_prev_set_next_task(rq, prev, p);
9177 	return p;
9178 
9179 idle:
9180 	if (!rf)
9181 		return NULL;
9182 
9183 	new_tasks = sched_balance_newidle(rq, rf);
9184 
9185 	/*
9186 	 * Because sched_balance_newidle() releases (and re-acquires) rq->lock, it is
9187 	 * possible for any higher priority task to appear. In that case we
9188 	 * must re-start the pick_next_entity() loop.
9189 	 */
9190 	if (new_tasks < 0)
9191 		return RETRY_TASK;
9192 
9193 	if (new_tasks > 0)
9194 		goto again;
9195 
9196 	/*
9197 	 * rq is about to be idle, check if we need to update the
9198 	 * lost_idle_time of clock_pelt
9199 	 */
9200 	update_idle_rq_clock_pelt(rq);
9201 
9202 	return NULL;
9203 }
9204 
__pick_next_task_fair(struct rq * rq,struct task_struct * prev)9205 static struct task_struct *__pick_next_task_fair(struct rq *rq, struct task_struct *prev)
9206 {
9207 	return pick_next_task_fair(rq, prev, NULL);
9208 }
9209 
fair_server_pick_task(struct sched_dl_entity * dl_se)9210 static struct task_struct *fair_server_pick_task(struct sched_dl_entity *dl_se)
9211 {
9212 	return pick_task_fair(dl_se->rq);
9213 }
9214 
fair_server_init(struct rq * rq)9215 void fair_server_init(struct rq *rq)
9216 {
9217 	struct sched_dl_entity *dl_se = &rq->fair_server;
9218 
9219 	init_dl_entity(dl_se);
9220 
9221 	dl_server_init(dl_se, rq, fair_server_pick_task);
9222 }
9223 
9224 /*
9225  * Account for a descheduled task:
9226  */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)9227 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9228 {
9229 	struct sched_entity *se = &prev->se;
9230 	struct cfs_rq *cfs_rq;
9231 
9232 	for_each_sched_entity(se) {
9233 		cfs_rq = cfs_rq_of(se);
9234 		put_prev_entity(cfs_rq, se);
9235 	}
9236 }
9237 
9238 /*
9239  * sched_yield() is very simple
9240  */
yield_task_fair(struct rq * rq)9241 static void yield_task_fair(struct rq *rq)
9242 {
9243 	struct task_struct *curr = rq->curr;
9244 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9245 	struct sched_entity *se = &curr->se;
9246 
9247 	/*
9248 	 * Are we the only task in the tree?
9249 	 */
9250 	if (unlikely(rq->nr_running == 1))
9251 		return;
9252 
9253 	clear_buddies(cfs_rq, se);
9254 
9255 	update_rq_clock(rq);
9256 	/*
9257 	 * Update run-time statistics of the 'current'.
9258 	 */
9259 	update_curr(cfs_rq);
9260 	/*
9261 	 * Tell update_rq_clock() that we've just updated,
9262 	 * so we don't do microscopic update in schedule()
9263 	 * and double the fastpath cost.
9264 	 */
9265 	rq_clock_skip_update(rq);
9266 
9267 	se->deadline += calc_delta_fair(se->slice, se);
9268 }
9269 
yield_to_task_fair(struct rq * rq,struct task_struct * p)9270 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9271 {
9272 	struct sched_entity *se = &p->se;
9273 
9274 	/* throttled hierarchies are not runnable */
9275 	if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
9276 		return false;
9277 
9278 	/* Tell the scheduler that we'd really like se to run next. */
9279 	set_next_buddy(se);
9280 
9281 	yield_task_fair(rq);
9282 
9283 	return true;
9284 }
9285 
9286 #ifdef CONFIG_SMP
9287 /**************************************************
9288  * Fair scheduling class load-balancing methods.
9289  *
9290  * BASICS
9291  *
9292  * The purpose of load-balancing is to achieve the same basic fairness the
9293  * per-CPU scheduler provides, namely provide a proportional amount of compute
9294  * time to each task. This is expressed in the following equation:
9295  *
9296  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
9297  *
9298  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9299  * W_i,0 is defined as:
9300  *
9301  *   W_i,0 = \Sum_j w_i,j                                             (2)
9302  *
9303  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9304  * is derived from the nice value as per sched_prio_to_weight[].
9305  *
9306  * The weight average is an exponential decay average of the instantaneous
9307  * weight:
9308  *
9309  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
9310  *
9311  * C_i is the compute capacity of CPU i, typically it is the
9312  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9313  * can also include other factors [XXX].
9314  *
9315  * To achieve this balance we define a measure of imbalance which follows
9316  * directly from (1):
9317  *
9318  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
9319  *
9320  * We them move tasks around to minimize the imbalance. In the continuous
9321  * function space it is obvious this converges, in the discrete case we get
9322  * a few fun cases generally called infeasible weight scenarios.
9323  *
9324  * [XXX expand on:
9325  *     - infeasible weights;
9326  *     - local vs global optima in the discrete case. ]
9327  *
9328  *
9329  * SCHED DOMAINS
9330  *
9331  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9332  * for all i,j solution, we create a tree of CPUs that follows the hardware
9333  * topology where each level pairs two lower groups (or better). This results
9334  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9335  * tree to only the first of the previous level and we decrease the frequency
9336  * of load-balance at each level inversely proportional to the number of CPUs in
9337  * the groups.
9338  *
9339  * This yields:
9340  *
9341  *     log_2 n     1     n
9342  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
9343  *     i = 0      2^i   2^i
9344  *                               `- size of each group
9345  *         |         |     `- number of CPUs doing load-balance
9346  *         |         `- freq
9347  *         `- sum over all levels
9348  *
9349  * Coupled with a limit on how many tasks we can migrate every balance pass,
9350  * this makes (5) the runtime complexity of the balancer.
9351  *
9352  * An important property here is that each CPU is still (indirectly) connected
9353  * to every other CPU in at most O(log n) steps:
9354  *
9355  * The adjacency matrix of the resulting graph is given by:
9356  *
9357  *             log_2 n
9358  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
9359  *             k = 0
9360  *
9361  * And you'll find that:
9362  *
9363  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
9364  *
9365  * Showing there's indeed a path between every CPU in at most O(log n) steps.
9366  * The task movement gives a factor of O(m), giving a convergence complexity
9367  * of:
9368  *
9369  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
9370  *
9371  *
9372  * WORK CONSERVING
9373  *
9374  * In order to avoid CPUs going idle while there's still work to do, new idle
9375  * balancing is more aggressive and has the newly idle CPU iterate up the domain
9376  * tree itself instead of relying on other CPUs to bring it work.
9377  *
9378  * This adds some complexity to both (5) and (8) but it reduces the total idle
9379  * time.
9380  *
9381  * [XXX more?]
9382  *
9383  *
9384  * CGROUPS
9385  *
9386  * Cgroups make a horror show out of (2), instead of a simple sum we get:
9387  *
9388  *                                s_k,i
9389  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
9390  *                                 S_k
9391  *
9392  * Where
9393  *
9394  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
9395  *
9396  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9397  *
9398  * The big problem is S_k, its a global sum needed to compute a local (W_i)
9399  * property.
9400  *
9401  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9402  *      rewrite all of this once again.]
9403  */
9404 
9405 unsigned long __read_mostly max_load_balance_interval = HZ/10;
9406 EXPORT_SYMBOL_GPL(max_load_balance_interval);
9407 
9408 enum fbq_type { regular, remote, all };
9409 
9410 /*
9411  * 'group_type' describes the group of CPUs at the moment of load balancing.
9412  *
9413  * The enum is ordered by pulling priority, with the group with lowest priority
9414  * first so the group_type can simply be compared when selecting the busiest
9415  * group. See update_sd_pick_busiest().
9416  */
9417 enum group_type {
9418 	/* The group has spare capacity that can be used to run more tasks.  */
9419 	group_has_spare = 0,
9420 	/*
9421 	 * The group is fully used and the tasks don't compete for more CPU
9422 	 * cycles. Nevertheless, some tasks might wait before running.
9423 	 */
9424 	group_fully_busy,
9425 	/*
9426 	 * One task doesn't fit with CPU's capacity and must be migrated to a
9427 	 * more powerful CPU.
9428 	 */
9429 	group_misfit_task,
9430 	/*
9431 	 * Balance SMT group that's fully busy. Can benefit from migration
9432 	 * a task on SMT with busy sibling to another CPU on idle core.
9433 	 */
9434 	group_smt_balance,
9435 	/*
9436 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9437 	 * and the task should be migrated to it instead of running on the
9438 	 * current CPU.
9439 	 */
9440 	group_asym_packing,
9441 	/*
9442 	 * The tasks' affinity constraints previously prevented the scheduler
9443 	 * from balancing the load across the system.
9444 	 */
9445 	group_imbalanced,
9446 	/*
9447 	 * The CPU is overloaded and can't provide expected CPU cycles to all
9448 	 * tasks.
9449 	 */
9450 	group_overloaded
9451 };
9452 
9453 enum migration_type {
9454 	migrate_load = 0,
9455 	migrate_util,
9456 	migrate_task,
9457 	migrate_misfit
9458 };
9459 
9460 #define LBF_ALL_PINNED	0x01
9461 #define LBF_NEED_BREAK	0x02
9462 #define LBF_DST_PINNED  0x04
9463 #define LBF_SOME_PINNED	0x08
9464 #define LBF_ACTIVE_LB	0x10
9465 
9466 struct lb_env {
9467 	struct sched_domain	*sd;
9468 
9469 	struct rq		*src_rq;
9470 	int			src_cpu;
9471 
9472 	int			dst_cpu;
9473 	struct rq		*dst_rq;
9474 
9475 	struct cpumask		*dst_grpmask;
9476 	int			new_dst_cpu;
9477 	enum cpu_idle_type	idle;
9478 	long			imbalance;
9479 	/* The set of CPUs under consideration for load-balancing */
9480 	struct cpumask		*cpus;
9481 
9482 	unsigned int		flags;
9483 
9484 	unsigned int		loop;
9485 	unsigned int		loop_break;
9486 	unsigned int		loop_max;
9487 
9488 	enum fbq_type		fbq_type;
9489 	enum migration_type	migration_type;
9490 	struct list_head	tasks;
9491 	struct rq_flags		*src_rq_rf;
9492 };
9493 
9494 /*
9495  * Is this task likely cache-hot:
9496  */
task_hot(struct task_struct * p,struct lb_env * env)9497 static int task_hot(struct task_struct *p, struct lb_env *env)
9498 {
9499 	s64 delta;
9500 
9501 	lockdep_assert_rq_held(env->src_rq);
9502 
9503 	if (p->sched_class != &fair_sched_class)
9504 		return 0;
9505 
9506 	if (unlikely(task_has_idle_policy(p)))
9507 		return 0;
9508 
9509 	/* SMT siblings share cache */
9510 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9511 		return 0;
9512 
9513 	/*
9514 	 * Buddy candidates are cache hot:
9515 	 */
9516 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9517 	    (&p->se == cfs_rq_of(&p->se)->next))
9518 		return 1;
9519 
9520 	if (sysctl_sched_migration_cost == -1)
9521 		return 1;
9522 
9523 	/*
9524 	 * Don't migrate task if the task's cookie does not match
9525 	 * with the destination CPU's core cookie.
9526 	 */
9527 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9528 		return 1;
9529 
9530 	if (sysctl_sched_migration_cost == 0)
9531 		return 0;
9532 
9533 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9534 
9535 	return delta < (s64)sysctl_sched_migration_cost;
9536 }
9537 
9538 #ifdef CONFIG_NUMA_BALANCING
9539 /*
9540  * Returns 1, if task migration degrades locality
9541  * Returns 0, if task migration improves locality i.e migration preferred.
9542  * Returns -1, if task migration is not affected by locality.
9543  */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9544 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9545 {
9546 	struct numa_group *numa_group = rcu_dereference(p->numa_group);
9547 	unsigned long src_weight, dst_weight;
9548 	int src_nid, dst_nid, dist;
9549 
9550 	if (!static_branch_likely(&sched_numa_balancing))
9551 		return -1;
9552 
9553 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9554 		return -1;
9555 
9556 	src_nid = cpu_to_node(env->src_cpu);
9557 	dst_nid = cpu_to_node(env->dst_cpu);
9558 
9559 	if (src_nid == dst_nid)
9560 		return -1;
9561 
9562 	/* Migrating away from the preferred node is always bad. */
9563 	if (src_nid == p->numa_preferred_nid) {
9564 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9565 			return 1;
9566 		else
9567 			return -1;
9568 	}
9569 
9570 	/* Encourage migration to the preferred node. */
9571 	if (dst_nid == p->numa_preferred_nid)
9572 		return 0;
9573 
9574 	/* Leaving a core idle is often worse than degrading locality. */
9575 	if (env->idle == CPU_IDLE)
9576 		return -1;
9577 
9578 	dist = node_distance(src_nid, dst_nid);
9579 	if (numa_group) {
9580 		src_weight = group_weight(p, src_nid, dist);
9581 		dst_weight = group_weight(p, dst_nid, dist);
9582 	} else {
9583 		src_weight = task_weight(p, src_nid, dist);
9584 		dst_weight = task_weight(p, dst_nid, dist);
9585 	}
9586 
9587 	return dst_weight < src_weight;
9588 }
9589 
9590 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9591 static inline int migrate_degrades_locality(struct task_struct *p,
9592 					     struct lb_env *env)
9593 {
9594 	return -1;
9595 }
9596 #endif
9597 
9598 /*
9599  * Check whether the task is ineligible on the destination cpu
9600  *
9601  * When the PLACE_LAG scheduling feature is enabled and
9602  * dst_cfs_rq->nr_running is greater than 1, if the task
9603  * is ineligible, it will also be ineligible when
9604  * it is migrated to the destination cpu.
9605  */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9606 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9607 {
9608 	struct cfs_rq *dst_cfs_rq;
9609 
9610 #ifdef CONFIG_FAIR_GROUP_SCHED
9611 	dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9612 #else
9613 	dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9614 #endif
9615 	if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_running &&
9616 	    !entity_eligible(task_cfs_rq(p), &p->se))
9617 		return 1;
9618 
9619 	return 0;
9620 }
9621 
9622 /*
9623  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9624  */
9625 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9626 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9627 {
9628 	int tsk_cache_hot;
9629 	int can_migrate = 1;
9630 
9631 	lockdep_assert_rq_held(env->src_rq);
9632 	if (p->sched_task_hot)
9633 		p->sched_task_hot = 0;
9634 
9635 	trace_android_rvh_can_migrate_task(p, env->dst_cpu, &can_migrate);
9636 	if (!can_migrate)
9637 		return 0;
9638 
9639 	/*
9640 	 * We do not migrate tasks that are:
9641 	 * 1) throttled_lb_pair, or
9642 	 * 2) cannot be migrated to this CPU due to cpus_ptr, or
9643 	 * 3) running (obviously), or
9644 	 * 4) are cache-hot on their current CPU.
9645 	 * 5) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9646 	 */
9647 	if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
9648 		return 0;
9649 
9650 	/*
9651 	 * We want to prioritize the migration of eligible tasks.
9652 	 * For ineligible tasks we soft-limit them and only allow
9653 	 * them to migrate when nr_balance_failed is non-zero to
9654 	 * avoid load-balancing trying very hard to balance the load.
9655 	 */
9656 	if (!env->sd->nr_balance_failed &&
9657 	    task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9658 		return 0;
9659 
9660 	/* Disregard percpu kthreads; they are where they need to be. */
9661 	if (kthread_is_per_cpu(p))
9662 		return 0;
9663 
9664 	if (task_is_blocked(p))
9665 		return 0;
9666 
9667 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9668 		int cpu;
9669 
9670 		schedstat_inc(p->stats.nr_failed_migrations_affine);
9671 
9672 		env->flags |= LBF_SOME_PINNED;
9673 
9674 		/*
9675 		 * Remember if this task can be migrated to any other CPU in
9676 		 * our sched_group. We may want to revisit it if we couldn't
9677 		 * meet load balance goals by pulling other tasks on src_cpu.
9678 		 *
9679 		 * Avoid computing new_dst_cpu
9680 		 * - for NEWLY_IDLE
9681 		 * - if we have already computed one in current iteration
9682 		 * - if it's an active balance
9683 		 */
9684 		if (env->idle == CPU_NEWLY_IDLE ||
9685 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9686 			return 0;
9687 
9688 		/* Prevent to re-select dst_cpu via env's CPUs: */
9689 		for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
9690 			if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
9691 				env->flags |= LBF_DST_PINNED;
9692 				env->new_dst_cpu = cpu;
9693 				break;
9694 			}
9695 		}
9696 
9697 		return 0;
9698 	}
9699 
9700 	/* Record that we found at least one task that could run on dst_cpu */
9701 	env->flags &= ~LBF_ALL_PINNED;
9702 
9703 	if (task_on_cpu(env->src_rq, p) ||
9704 	    task_current_donor(env->src_rq, p)) {
9705 		schedstat_inc(p->stats.nr_failed_migrations_running);
9706 		return 0;
9707 	}
9708 
9709 	/*
9710 	 * Aggressive migration if:
9711 	 * 1) active balance
9712 	 * 2) destination numa is preferred
9713 	 * 3) task is cache cold, or
9714 	 * 4) too many balance attempts have failed.
9715 	 */
9716 	if (env->flags & LBF_ACTIVE_LB)
9717 		return 1;
9718 
9719 	tsk_cache_hot = migrate_degrades_locality(p, env);
9720 	if (tsk_cache_hot == -1)
9721 		tsk_cache_hot = task_hot(p, env);
9722 
9723 	if (tsk_cache_hot <= 0 ||
9724 	    env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9725 		if (tsk_cache_hot == 1)
9726 			p->sched_task_hot = 1;
9727 		return 1;
9728 	}
9729 
9730 	schedstat_inc(p->stats.nr_failed_migrations_hot);
9731 	return 0;
9732 }
9733 
9734 /*
9735  * detach_task() -- detach the task for the migration specified in env
9736  */
detach_task(struct task_struct * p,struct lb_env * env)9737 static void detach_task(struct task_struct *p, struct lb_env *env)
9738 {
9739 	int detached = 0;
9740 
9741 	lockdep_assert_rq_held(env->src_rq);
9742 
9743 	/*
9744 	 * The vendor hook may drop the lock temporarily, so
9745 	 * pass the rq flags to unpin lock. We expect the
9746 	 * rq lock to be held after return.
9747 	 */
9748 	trace_android_rvh_migrate_queued_task(env->src_rq, env->src_rq_rf, p,
9749 					      env->dst_cpu, &detached);
9750 	if (detached)
9751 		return;
9752 
9753 	WARN_ON(task_current(env->src_rq, p));
9754 	WARN_ON(task_current_donor(env->src_rq, p));
9755 
9756 	if (p->sched_task_hot) {
9757 		p->sched_task_hot = 0;
9758 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9759 		schedstat_inc(p->stats.nr_forced_migrations);
9760 	}
9761 
9762 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9763 	set_task_cpu(p, env->dst_cpu);
9764 }
9765 
9766 /*
9767  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9768  * part of active balancing operations within "domain".
9769  *
9770  * Returns a task if successful and NULL otherwise.
9771  */
detach_one_task(struct lb_env * env)9772 static struct task_struct *detach_one_task(struct lb_env *env)
9773 {
9774 	struct task_struct *p;
9775 
9776 	lockdep_assert_rq_held(env->src_rq);
9777 
9778 	list_for_each_entry_reverse(p,
9779 			&env->src_rq->cfs_tasks, se.group_node) {
9780 		if (!can_migrate_task(p, env))
9781 			continue;
9782 
9783 		detach_task(p, env);
9784 
9785 		/*
9786 		 * Right now, this is only the second place where
9787 		 * lb_gained[env->idle] is updated (other is detach_tasks)
9788 		 * so we can safely collect stats here rather than
9789 		 * inside detach_tasks().
9790 		 */
9791 		schedstat_inc(env->sd->lb_gained[env->idle]);
9792 		return p;
9793 	}
9794 	return NULL;
9795 }
9796 
9797 /*
9798  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9799  * busiest_rq, as part of a balancing operation within domain "sd".
9800  *
9801  * Returns number of detached tasks if successful and 0 otherwise.
9802  */
detach_tasks(struct lb_env * env)9803 static int detach_tasks(struct lb_env *env)
9804 {
9805 	struct list_head *tasks = &env->src_rq->cfs_tasks;
9806 	unsigned long util, load;
9807 	struct task_struct *p;
9808 	int detached = 0;
9809 
9810 	lockdep_assert_rq_held(env->src_rq);
9811 
9812 	/*
9813 	 * Source run queue has been emptied by another CPU, clear
9814 	 * LBF_ALL_PINNED flag as we will not test any task.
9815 	 */
9816 	if (env->src_rq->nr_running <= 1) {
9817 		env->flags &= ~LBF_ALL_PINNED;
9818 		return 0;
9819 	}
9820 
9821 	if (env->imbalance <= 0)
9822 		return 0;
9823 
9824 	while (!list_empty(tasks)) {
9825 		/*
9826 		 * We don't want to steal all, otherwise we may be treated likewise,
9827 		 * which could at worst lead to a livelock crash.
9828 		 */
9829 		if (env->idle && env->src_rq->nr_running <= 1)
9830 			break;
9831 
9832 		env->loop++;
9833 		/* We've more or less seen every task there is, call it quits */
9834 		if (env->loop > env->loop_max)
9835 			break;
9836 
9837 		/* take a breather every nr_migrate tasks */
9838 		if (env->loop > env->loop_break) {
9839 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
9840 			env->flags |= LBF_NEED_BREAK;
9841 			break;
9842 		}
9843 
9844 		p = list_last_entry(tasks, struct task_struct, se.group_node);
9845 
9846 		if (!can_migrate_task(p, env))
9847 			goto next;
9848 
9849 		switch (env->migration_type) {
9850 		case migrate_load:
9851 			/*
9852 			 * Depending of the number of CPUs and tasks and the
9853 			 * cgroup hierarchy, task_h_load() can return a null
9854 			 * value. Make sure that env->imbalance decreases
9855 			 * otherwise detach_tasks() will stop only after
9856 			 * detaching up to loop_max tasks.
9857 			 */
9858 			load = max_t(unsigned long, task_h_load(p), 1);
9859 
9860 			if (sched_feat(LB_MIN) &&
9861 			    load < 16 && !env->sd->nr_balance_failed)
9862 				goto next;
9863 
9864 			/*
9865 			 * Make sure that we don't migrate too much load.
9866 			 * Nevertheless, let relax the constraint if
9867 			 * scheduler fails to find a good waiting task to
9868 			 * migrate.
9869 			 */
9870 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9871 				goto next;
9872 
9873 			env->imbalance -= load;
9874 			break;
9875 
9876 		case migrate_util:
9877 			util = task_util_est(p);
9878 
9879 			if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9880 				goto next;
9881 
9882 			env->imbalance -= util;
9883 			break;
9884 
9885 		case migrate_task:
9886 			env->imbalance--;
9887 			break;
9888 
9889 		case migrate_misfit:
9890 			/* This is not a misfit task */
9891 			if (!is_misfit_task(p, cpu_rq(env->src_cpu), NULL))
9892 				goto next;
9893 
9894 			env->imbalance = 0;
9895 			break;
9896 		}
9897 
9898 		detach_task(p, env);
9899 		list_add(&p->se.group_node, &env->tasks);
9900 
9901 		detached++;
9902 
9903 #ifdef CONFIG_PREEMPTION
9904 		/*
9905 		 * NEWIDLE balancing is a source of latency, so preemptible
9906 		 * kernels will stop after the first task is detached to minimize
9907 		 * the critical section.
9908 		 */
9909 		if (env->idle == CPU_NEWLY_IDLE)
9910 			break;
9911 #endif
9912 
9913 		/*
9914 		 * We only want to steal up to the prescribed amount of
9915 		 * load/util/tasks.
9916 		 */
9917 		if (env->imbalance <= 0)
9918 			break;
9919 
9920 		continue;
9921 next:
9922 		if (p->sched_task_hot)
9923 			schedstat_inc(p->stats.nr_failed_migrations_hot);
9924 
9925 		list_move(&p->se.group_node, tasks);
9926 	}
9927 
9928 	/*
9929 	 * Right now, this is one of only two places we collect this stat
9930 	 * so we can safely collect detach_one_task() stats here rather
9931 	 * than inside detach_one_task().
9932 	 */
9933 	schedstat_add(env->sd->lb_gained[env->idle], detached);
9934 
9935 	return detached;
9936 }
9937 
9938 /*
9939  * attach_task() -- attach the task detached by detach_task() to its new rq.
9940  */
attach_task(struct rq * rq,struct task_struct * p)9941 static void attach_task(struct rq *rq, struct task_struct *p)
9942 {
9943 	lockdep_assert_rq_held(rq);
9944 
9945 	WARN_ON_ONCE(task_rq(p) != rq);
9946 	activate_task(rq, p, ENQUEUE_NOCLOCK);
9947 	wakeup_preempt(rq, p, 0);
9948 }
9949 
9950 /*
9951  * attach_one_task() -- attaches the task returned from detach_one_task() to
9952  * its new rq.
9953  */
attach_one_task(struct rq * rq,struct task_struct * p)9954 static void attach_one_task(struct rq *rq, struct task_struct *p)
9955 {
9956 	struct rq_flags rf;
9957 
9958 	rq_lock(rq, &rf);
9959 	update_rq_clock(rq);
9960 	attach_task(rq, p);
9961 	rq_unlock(rq, &rf);
9962 }
9963 
9964 /*
9965  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9966  * new rq.
9967  */
attach_tasks(struct lb_env * env)9968 static void attach_tasks(struct lb_env *env)
9969 {
9970 	struct list_head *tasks = &env->tasks;
9971 	struct task_struct *p;
9972 	struct rq_flags rf;
9973 
9974 	rq_lock(env->dst_rq, &rf);
9975 	update_rq_clock(env->dst_rq);
9976 
9977 	while (!list_empty(tasks)) {
9978 		p = list_first_entry(tasks, struct task_struct, se.group_node);
9979 		list_del_init(&p->se.group_node);
9980 
9981 		attach_task(env->dst_rq, p);
9982 	}
9983 
9984 	rq_unlock(env->dst_rq, &rf);
9985 }
9986 
9987 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9988 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9989 {
9990 	if (cfs_rq->avg.load_avg)
9991 		return true;
9992 
9993 	if (cfs_rq->avg.util_avg)
9994 		return true;
9995 
9996 	return false;
9997 }
9998 
others_have_blocked(struct rq * rq)9999 static inline bool others_have_blocked(struct rq *rq)
10000 {
10001 	if (cpu_util_rt(rq))
10002 		return true;
10003 
10004 	if (cpu_util_dl(rq))
10005 		return true;
10006 
10007 	if (hw_load_avg(rq))
10008 		return true;
10009 
10010 	if (cpu_util_irq(rq))
10011 		return true;
10012 
10013 	return false;
10014 }
10015 
update_blocked_load_tick(struct rq * rq)10016 static inline void update_blocked_load_tick(struct rq *rq)
10017 {
10018 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
10019 }
10020 
update_blocked_load_status(struct rq * rq,bool has_blocked)10021 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
10022 {
10023 	if (!has_blocked)
10024 		rq->has_blocked_load = 0;
10025 }
10026 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)10027 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)10028 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)10029 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)10030 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
10031 #endif
10032 
__update_blocked_others(struct rq * rq,bool * done)10033 static bool __update_blocked_others(struct rq *rq, bool *done)
10034 {
10035 	bool updated;
10036 
10037 	/*
10038 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
10039 	 * DL and IRQ signals have been updated before updating CFS.
10040 	 */
10041 	updated = update_other_load_avgs(rq);
10042 
10043 	if (others_have_blocked(rq))
10044 		*done = false;
10045 
10046 	return updated;
10047 }
10048 
10049 #ifdef CONFIG_FAIR_GROUP_SCHED
10050 
__update_blocked_fair(struct rq * rq,bool * done)10051 static bool __update_blocked_fair(struct rq *rq, bool *done)
10052 {
10053 	struct cfs_rq *cfs_rq, *pos;
10054 	bool decayed = false;
10055 	int cpu = cpu_of(rq);
10056 
10057 	trace_android_rvh_update_blocked_fair(rq);
10058 
10059 	/*
10060 	 * Iterates the task_group tree in a bottom up fashion, see
10061 	 * list_add_leaf_cfs_rq() for details.
10062 	 */
10063 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
10064 		struct sched_entity *se;
10065 
10066 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
10067 			update_tg_load_avg(cfs_rq);
10068 
10069 			if (cfs_rq->nr_running == 0)
10070 				update_idle_cfs_rq_clock_pelt(cfs_rq);
10071 
10072 			if (cfs_rq == &rq->cfs)
10073 				decayed = true;
10074 		}
10075 
10076 		/* Propagate pending load changes to the parent, if any: */
10077 		se = cfs_rq->tg->se[cpu];
10078 		if (se && !skip_blocked_update(se))
10079 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
10080 
10081 		/*
10082 		 * There can be a lot of idle CPU cgroups.  Don't let fully
10083 		 * decayed cfs_rqs linger on the list.
10084 		 */
10085 		if (cfs_rq_is_decayed(cfs_rq))
10086 			list_del_leaf_cfs_rq(cfs_rq);
10087 
10088 		/* Don't need periodic decay once load/util_avg are null */
10089 		if (cfs_rq_has_blocked(cfs_rq))
10090 			*done = false;
10091 	}
10092 
10093 	return decayed;
10094 }
10095 
10096 /*
10097  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
10098  * This needs to be done in a top-down fashion because the load of a child
10099  * group is a fraction of its parents load.
10100  */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)10101 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
10102 {
10103 	struct rq *rq = rq_of(cfs_rq);
10104 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
10105 	unsigned long now = jiffies;
10106 	unsigned long load;
10107 
10108 	if (cfs_rq->last_h_load_update == now)
10109 		return;
10110 
10111 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
10112 	for_each_sched_entity(se) {
10113 		cfs_rq = cfs_rq_of(se);
10114 		WRITE_ONCE(cfs_rq->h_load_next, se);
10115 		if (cfs_rq->last_h_load_update == now)
10116 			break;
10117 	}
10118 
10119 	if (!se) {
10120 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
10121 		cfs_rq->last_h_load_update = now;
10122 	}
10123 
10124 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
10125 		load = cfs_rq->h_load;
10126 		load = div64_ul(load * se->avg.load_avg,
10127 			cfs_rq_load_avg(cfs_rq) + 1);
10128 		cfs_rq = group_cfs_rq(se);
10129 		cfs_rq->h_load = load;
10130 		cfs_rq->last_h_load_update = now;
10131 	}
10132 }
10133 
task_h_load(struct task_struct * p)10134 static unsigned long task_h_load(struct task_struct *p)
10135 {
10136 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
10137 
10138 	update_cfs_rq_h_load(cfs_rq);
10139 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
10140 			cfs_rq_load_avg(cfs_rq) + 1);
10141 }
10142 #else
__update_blocked_fair(struct rq * rq,bool * done)10143 static bool __update_blocked_fair(struct rq *rq, bool *done)
10144 {
10145 	struct cfs_rq *cfs_rq = &rq->cfs;
10146 	bool decayed;
10147 
10148 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
10149 	if (cfs_rq_has_blocked(cfs_rq))
10150 		*done = false;
10151 
10152 	return decayed;
10153 }
10154 
task_h_load(struct task_struct * p)10155 static unsigned long task_h_load(struct task_struct *p)
10156 {
10157 	return p->se.avg.load_avg;
10158 }
10159 #endif
10160 
sched_balance_update_blocked_averages(int cpu)10161 static void sched_balance_update_blocked_averages(int cpu)
10162 {
10163 	bool decayed = false, done = true;
10164 	struct rq *rq = cpu_rq(cpu);
10165 	struct rq_flags rf;
10166 
10167 	rq_lock_irqsave(rq, &rf);
10168 	update_blocked_load_tick(rq);
10169 	update_rq_clock(rq);
10170 
10171 	decayed |= __update_blocked_others(rq, &done);
10172 	decayed |= __update_blocked_fair(rq, &done);
10173 
10174 	update_blocked_load_status(rq, !done);
10175 	if (decayed)
10176 		cpufreq_update_util(rq, 0);
10177 	rq_unlock_irqrestore(rq, &rf);
10178 }
10179 
10180 /********** Helpers for sched_balance_find_src_group ************************/
10181 
10182 /*
10183  * sg_lb_stats - stats of a sched_group required for load-balancing:
10184  */
10185 struct sg_lb_stats {
10186 	unsigned long avg_load;			/* Avg load            over the CPUs of the group */
10187 	unsigned long group_load;		/* Total load          over the CPUs of the group */
10188 	unsigned long group_capacity;		/* Capacity            over the CPUs of the group */
10189 	unsigned long group_util;		/* Total utilization   over the CPUs of the group */
10190 	unsigned long group_runnable;		/* Total runnable time over the CPUs of the group */
10191 	unsigned int sum_nr_running;		/* Nr of all tasks running in the group */
10192 	unsigned int sum_h_nr_running;		/* Nr of CFS tasks running in the group */
10193 	unsigned int idle_cpus;                 /* Nr of idle CPUs         in the group */
10194 	unsigned int group_weight;
10195 	enum group_type group_type;
10196 	unsigned int group_asym_packing;	/* Tasks should be moved to preferred CPU */
10197 	unsigned int group_smt_balance;		/* Task on busy SMT be moved */
10198 	unsigned long group_misfit_task_load;	/* A CPU has a task too big for its capacity */
10199 	misfit_reason_t group_misfit_reason;
10200 #ifdef CONFIG_NUMA_BALANCING
10201 	unsigned int nr_numa_running;
10202 	unsigned int nr_preferred_running;
10203 #endif
10204 };
10205 
10206 /*
10207  * sd_lb_stats - stats of a sched_domain required for load-balancing:
10208  */
10209 struct sd_lb_stats {
10210 	struct sched_group *busiest;		/* Busiest group in this sd */
10211 	struct sched_group *local;		/* Local group in this sd */
10212 	unsigned long total_load;		/* Total load of all groups in sd */
10213 	unsigned long total_capacity;		/* Total capacity of all groups in sd */
10214 	unsigned long avg_load;			/* Average load across all groups in sd */
10215 	unsigned int prefer_sibling;		/* Tasks should go to sibling first */
10216 
10217 	struct sg_lb_stats busiest_stat;	/* Statistics of the busiest group */
10218 	struct sg_lb_stats local_stat;		/* Statistics of the local group */
10219 };
10220 
init_sd_lb_stats(struct sd_lb_stats * sds)10221 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
10222 {
10223 	/*
10224 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
10225 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10226 	 * We must however set busiest_stat::group_type and
10227 	 * busiest_stat::idle_cpus to the worst busiest group because
10228 	 * update_sd_pick_busiest() reads these before assignment.
10229 	 */
10230 	*sds = (struct sd_lb_stats){
10231 		.busiest = NULL,
10232 		.local = NULL,
10233 		.total_load = 0UL,
10234 		.total_capacity = 0UL,
10235 		.busiest_stat = {
10236 			.idle_cpus = UINT_MAX,
10237 			.group_type = group_has_spare,
10238 		},
10239 	};
10240 }
10241 
scale_rt_capacity(int cpu)10242 static unsigned long scale_rt_capacity(int cpu)
10243 {
10244 	unsigned long max = get_actual_cpu_capacity(cpu);
10245 	struct rq *rq = cpu_rq(cpu);
10246 	unsigned long used, free;
10247 	unsigned long irq;
10248 
10249 	irq = cpu_util_irq(rq);
10250 
10251 	if (unlikely(irq >= max))
10252 		return 1;
10253 
10254 	/*
10255 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10256 	 * (running and not running) with weights 0 and 1024 respectively.
10257 	 */
10258 	used = cpu_util_rt(rq);
10259 	used += cpu_util_dl(rq);
10260 
10261 	if (unlikely(used >= max))
10262 		return 1;
10263 
10264 	free = max - used;
10265 
10266 	return scale_irq_capacity(free, irq, max);
10267 }
10268 
update_cpu_capacity(struct sched_domain * sd,int cpu)10269 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10270 {
10271 	unsigned long capacity = scale_rt_capacity(cpu);
10272 	struct sched_group *sdg = sd->groups;
10273 
10274 	if (!capacity)
10275 		capacity = 1;
10276 
10277 	trace_android_rvh_update_cpu_capacity(cpu, &capacity);
10278 	cpu_rq(cpu)->cpu_capacity = capacity;
10279 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10280 
10281 	sdg->sgc->capacity = capacity;
10282 	sdg->sgc->min_capacity = capacity;
10283 	sdg->sgc->max_capacity = capacity;
10284 }
10285 
update_group_capacity(struct sched_domain * sd,int cpu)10286 void update_group_capacity(struct sched_domain *sd, int cpu)
10287 {
10288 	struct sched_domain *child = sd->child;
10289 	struct sched_group *group, *sdg = sd->groups;
10290 	unsigned long capacity, min_capacity, max_capacity;
10291 	unsigned long interval;
10292 
10293 	interval = msecs_to_jiffies(sd->balance_interval);
10294 	interval = clamp(interval, 1UL, max_load_balance_interval);
10295 	sdg->sgc->next_update = jiffies + interval;
10296 
10297 	if (!child) {
10298 		update_cpu_capacity(sd, cpu);
10299 		return;
10300 	}
10301 
10302 	capacity = 0;
10303 	min_capacity = ULONG_MAX;
10304 	max_capacity = 0;
10305 
10306 	if (child->flags & SD_OVERLAP) {
10307 		/*
10308 		 * SD_OVERLAP domains cannot assume that child groups
10309 		 * span the current group.
10310 		 */
10311 
10312 		for_each_cpu(cpu, sched_group_span(sdg)) {
10313 			unsigned long cpu_cap = capacity_of(cpu);
10314 
10315 			capacity += cpu_cap;
10316 			min_capacity = min(cpu_cap, min_capacity);
10317 			max_capacity = max(cpu_cap, max_capacity);
10318 		}
10319 	} else  {
10320 		/*
10321 		 * !SD_OVERLAP domains can assume that child groups
10322 		 * span the current group.
10323 		 */
10324 
10325 		group = child->groups;
10326 		do {
10327 			struct sched_group_capacity *sgc = group->sgc;
10328 
10329 			capacity += sgc->capacity;
10330 			min_capacity = min(sgc->min_capacity, min_capacity);
10331 			max_capacity = max(sgc->max_capacity, max_capacity);
10332 			group = group->next;
10333 		} while (group != child->groups);
10334 	}
10335 
10336 	sdg->sgc->capacity = capacity;
10337 	sdg->sgc->min_capacity = min_capacity;
10338 	sdg->sgc->max_capacity = max_capacity;
10339 }
10340 
10341 /*
10342  * Check whether the capacity of the rq has been noticeably reduced by side
10343  * activity. The imbalance_pct is used for the threshold.
10344  * Return true is the capacity is reduced
10345  */
10346 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10347 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10348 {
10349 	return ((rq->cpu_capacity * sd->imbalance_pct) <
10350 				(arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10351 }
10352 
10353 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10354 static inline bool check_misfit_status(struct rq *rq)
10355 {
10356 	return rq->misfit_task_load;
10357 }
10358 
10359 /*
10360  * Group imbalance indicates (and tries to solve) the problem where balancing
10361  * groups is inadequate due to ->cpus_ptr constraints.
10362  *
10363  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10364  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10365  * Something like:
10366  *
10367  *	{ 0 1 2 3 } { 4 5 6 7 }
10368  *	        *     * * *
10369  *
10370  * If we were to balance group-wise we'd place two tasks in the first group and
10371  * two tasks in the second group. Clearly this is undesired as it will overload
10372  * cpu 3 and leave one of the CPUs in the second group unused.
10373  *
10374  * The current solution to this issue is detecting the skew in the first group
10375  * by noticing the lower domain failed to reach balance and had difficulty
10376  * moving tasks due to affinity constraints.
10377  *
10378  * When this is so detected; this group becomes a candidate for busiest; see
10379  * update_sd_pick_busiest(). And calculate_imbalance() and
10380  * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10381  * to create an effective group imbalance.
10382  *
10383  * This is a somewhat tricky proposition since the next run might not find the
10384  * group imbalance and decide the groups need to be balanced again. A most
10385  * subtle and fragile situation.
10386  */
10387 
sg_imbalanced(struct sched_group * group)10388 static inline int sg_imbalanced(struct sched_group *group)
10389 {
10390 	return group->sgc->imbalance;
10391 }
10392 
10393 /*
10394  * group_has_capacity returns true if the group has spare capacity that could
10395  * be used by some tasks.
10396  * We consider that a group has spare capacity if the number of task is
10397  * smaller than the number of CPUs or if the utilization is lower than the
10398  * available capacity for CFS tasks.
10399  * For the latter, we use a threshold to stabilize the state, to take into
10400  * account the variance of the tasks' load and to return true if the available
10401  * capacity in meaningful for the load balancer.
10402  * As an example, an available capacity of 1% can appear but it doesn't make
10403  * any benefit for the load balance.
10404  */
10405 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10406 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10407 {
10408 	if (sgs->sum_nr_running < sgs->group_weight)
10409 		return true;
10410 
10411 	if ((sgs->group_capacity * imbalance_pct) <
10412 			(sgs->group_runnable * 100))
10413 		return false;
10414 
10415 	if ((sgs->group_capacity * 100) >
10416 			(sgs->group_util * imbalance_pct))
10417 		return true;
10418 
10419 	return false;
10420 }
10421 
10422 /*
10423  *  group_is_overloaded returns true if the group has more tasks than it can
10424  *  handle.
10425  *  group_is_overloaded is not equals to !group_has_capacity because a group
10426  *  with the exact right number of tasks, has no more spare capacity but is not
10427  *  overloaded so both group_has_capacity and group_is_overloaded return
10428  *  false.
10429  */
10430 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10431 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10432 {
10433 	if (sgs->sum_nr_running <= sgs->group_weight)
10434 		return false;
10435 
10436 	if ((sgs->group_capacity * 100) <
10437 			(sgs->group_util * imbalance_pct))
10438 		return true;
10439 
10440 	if ((sgs->group_capacity * imbalance_pct) <
10441 			(sgs->group_runnable * 100))
10442 		return true;
10443 
10444 	return false;
10445 }
10446 
10447 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10448 group_type group_classify(unsigned int imbalance_pct,
10449 			  struct sched_group *group,
10450 			  struct sg_lb_stats *sgs)
10451 {
10452 	if (group_is_overloaded(imbalance_pct, sgs))
10453 		return group_overloaded;
10454 
10455 	if (sg_imbalanced(group))
10456 		return group_imbalanced;
10457 
10458 	if (sgs->group_asym_packing)
10459 		return group_asym_packing;
10460 
10461 	if (sgs->group_smt_balance)
10462 		return group_smt_balance;
10463 
10464 	if (sgs->group_misfit_task_load)
10465 		return group_misfit_task;
10466 
10467 	if (!group_has_capacity(imbalance_pct, sgs))
10468 		return group_fully_busy;
10469 
10470 	return group_has_spare;
10471 }
10472 
10473 /**
10474  * sched_use_asym_prio - Check whether asym_packing priority must be used
10475  * @sd:		The scheduling domain of the load balancing
10476  * @cpu:	A CPU
10477  *
10478  * Always use CPU priority when balancing load between SMT siblings. When
10479  * balancing load between cores, it is not sufficient that @cpu is idle. Only
10480  * use CPU priority if the whole core is idle.
10481  *
10482  * Returns: True if the priority of @cpu must be followed. False otherwise.
10483  */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10484 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10485 {
10486 	if (!(sd->flags & SD_ASYM_PACKING))
10487 		return false;
10488 
10489 	if (!sched_smt_active())
10490 		return true;
10491 
10492 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10493 }
10494 
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10495 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10496 {
10497 	/*
10498 	 * First check if @dst_cpu can do asym_packing load balance. Only do it
10499 	 * if it has higher priority than @src_cpu.
10500 	 */
10501 	return sched_use_asym_prio(sd, dst_cpu) &&
10502 		sched_asym_prefer(dst_cpu, src_cpu);
10503 }
10504 
10505 /**
10506  * sched_group_asym - Check if the destination CPU can do asym_packing balance
10507  * @env:	The load balancing environment
10508  * @sgs:	Load-balancing statistics of the candidate busiest group
10509  * @group:	The candidate busiest group
10510  *
10511  * @env::dst_cpu can do asym_packing if it has higher priority than the
10512  * preferred CPU of @group.
10513  *
10514  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10515  * otherwise.
10516  */
10517 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10518 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10519 {
10520 	/*
10521 	 * CPU priorities do not make sense for SMT cores with more than one
10522 	 * busy sibling.
10523 	 */
10524 	if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10525 	    (sgs->group_weight - sgs->idle_cpus != 1))
10526 		return false;
10527 
10528 	return sched_asym(env->sd, env->dst_cpu, group->asym_prefer_cpu);
10529 }
10530 
10531 /* One group has more than one SMT CPU while the other group does not */
smt_vs_nonsmt_groups(struct sched_group * sg1,struct sched_group * sg2)10532 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10533 				    struct sched_group *sg2)
10534 {
10535 	if (!sg1 || !sg2)
10536 		return false;
10537 
10538 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10539 		(sg2->flags & SD_SHARE_CPUCAPACITY);
10540 }
10541 
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10542 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10543 			       struct sched_group *group)
10544 {
10545 	if (!env->idle)
10546 		return false;
10547 
10548 	/*
10549 	 * For SMT source group, it is better to move a task
10550 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10551 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10552 	 * will not be on.
10553 	 */
10554 	if (group->flags & SD_SHARE_CPUCAPACITY &&
10555 	    sgs->sum_h_nr_running > 1)
10556 		return true;
10557 
10558 	return false;
10559 }
10560 
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10561 static inline long sibling_imbalance(struct lb_env *env,
10562 				    struct sd_lb_stats *sds,
10563 				    struct sg_lb_stats *busiest,
10564 				    struct sg_lb_stats *local)
10565 {
10566 	int ncores_busiest, ncores_local;
10567 	long imbalance;
10568 
10569 	if (!env->idle || !busiest->sum_nr_running)
10570 		return 0;
10571 
10572 	ncores_busiest = sds->busiest->cores;
10573 	ncores_local = sds->local->cores;
10574 
10575 	if (ncores_busiest == ncores_local) {
10576 		imbalance = busiest->sum_nr_running;
10577 		lsub_positive(&imbalance, local->sum_nr_running);
10578 		return imbalance;
10579 	}
10580 
10581 	/* Balance such that nr_running/ncores ratio are same on both groups */
10582 	imbalance = ncores_local * busiest->sum_nr_running;
10583 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10584 	/* Normalize imbalance and do rounding on normalization */
10585 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10586 	imbalance /= ncores_local + ncores_busiest;
10587 
10588 	/* Take advantage of resource in an empty sched group */
10589 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
10590 	    busiest->sum_nr_running > 1)
10591 		imbalance = 2;
10592 
10593 	return imbalance;
10594 }
10595 
10596 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10597 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10598 {
10599 	/*
10600 	 * When there is more than 1 task, the group_overloaded case already
10601 	 * takes care of cpu with reduced capacity
10602 	 */
10603 	if (rq->cfs.h_nr_running != 1)
10604 		return false;
10605 
10606 	return check_cpu_capacity(rq, sd);
10607 }
10608 
10609 /**
10610  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10611  * @env: The load balancing environment.
10612  * @sds: Load-balancing data with statistics of the local group.
10613  * @group: sched_group whose statistics are to be updated.
10614  * @sgs: variable to hold the statistics for this group.
10615  * @sg_overloaded: sched_group is overloaded
10616  * @sg_overutilized: sched_group is overutilized
10617  */
update_sg_lb_stats(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * group,struct sg_lb_stats * sgs,bool * sg_overloaded,bool * sg_overutilized)10618 static inline void update_sg_lb_stats(struct lb_env *env,
10619 				      struct sd_lb_stats *sds,
10620 				      struct sched_group *group,
10621 				      struct sg_lb_stats *sgs,
10622 				      bool *sg_overloaded,
10623 				      bool *sg_overutilized)
10624 {
10625 	int i, nr_running, local_group;
10626 
10627 	memset(sgs, 0, sizeof(*sgs));
10628 
10629 	local_group = group == sds->local;
10630 
10631 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10632 		struct rq *rq = cpu_rq(i);
10633 		unsigned long load = cpu_load(rq);
10634 
10635 		sgs->group_load += load;
10636 		sgs->group_util += cpu_util_cfs(i);
10637 		sgs->group_runnable += cpu_runnable(rq);
10638 		sgs->sum_h_nr_running += rq->cfs.h_nr_running;
10639 
10640 		nr_running = rq->nr_running;
10641 		sgs->sum_nr_running += nr_running;
10642 
10643 		if (nr_running > 1)
10644 			*sg_overloaded = 1;
10645 
10646 		if (cpu_overutilized(i))
10647 			*sg_overutilized = 1;
10648 
10649 #ifdef CONFIG_NUMA_BALANCING
10650 		sgs->nr_numa_running += rq->nr_numa_running;
10651 		sgs->nr_preferred_running += rq->nr_preferred_running;
10652 #endif
10653 		/*
10654 		 * No need to call idle_cpu() if nr_running is not 0
10655 		 */
10656 		if (!nr_running && idle_cpu(i)) {
10657 			sgs->idle_cpus++;
10658 			/* Idle cpu can't have misfit task */
10659 			continue;
10660 		}
10661 
10662 		if (local_group)
10663 			continue;
10664 
10665 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10666 			/* Check for a misfit task on the cpu */
10667 			if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10668 				sgs->group_misfit_task_load = rq->misfit_task_load;
10669 				*sg_overloaded = 1;
10670 				sgs->group_misfit_reason = rq->misfit_reason;
10671 			}
10672 		} else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10673 			/* Check for a task running on a CPU with reduced capacity */
10674 			if (sgs->group_misfit_task_load < load)
10675 				sgs->group_misfit_task_load = load;
10676 		}
10677 	}
10678 
10679 	sgs->group_capacity = group->sgc->capacity;
10680 
10681 	sgs->group_weight = group->group_weight;
10682 
10683 	/* Check if dst CPU is idle and preferred to this group */
10684 	if (!local_group && env->idle && sgs->sum_h_nr_running &&
10685 	    sched_group_asym(env, sgs, group))
10686 		sgs->group_asym_packing = 1;
10687 
10688 	/* Check for loaded SMT group to be balanced to dst CPU */
10689 	if (!local_group && smt_balance(env, sgs, group))
10690 		sgs->group_smt_balance = 1;
10691 
10692 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10693 
10694 	/* Computing avg_load makes sense only when group is overloaded */
10695 	if (sgs->group_type == group_overloaded)
10696 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10697 				sgs->group_capacity;
10698 }
10699 
10700 /**
10701  * update_sd_pick_busiest - return 1 on busiest group
10702  * @env: The load balancing environment.
10703  * @sds: sched_domain statistics
10704  * @sg: sched_group candidate to be checked for being the busiest
10705  * @sgs: sched_group statistics
10706  *
10707  * Determine if @sg is a busier group than the previously selected
10708  * busiest group.
10709  *
10710  * Return: %true if @sg is a busier group than the previously selected
10711  * busiest group. %false otherwise.
10712  */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10713 static bool update_sd_pick_busiest(struct lb_env *env,
10714 				   struct sd_lb_stats *sds,
10715 				   struct sched_group *sg,
10716 				   struct sg_lb_stats *sgs)
10717 {
10718 	struct sg_lb_stats *busiest = &sds->busiest_stat;
10719 
10720 	/* Make sure that there is at least one task to pull */
10721 	if (!sgs->sum_h_nr_running)
10722 		return false;
10723 
10724 	/*
10725 	 * Don't try to pull misfit tasks we can't help.
10726 	 * We can use max_capacity here as reduction in capacity on some
10727 	 * CPUs in the group should either be possible to resolve
10728 	 * internally or be covered by avg_load imbalance (eventually).
10729 	 */
10730 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10731 	    (sgs->group_type == group_misfit_task) &&
10732 	    (sgs->group_misfit_reason == MISFIT_PERF) &&
10733 	    (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10734 	     sds->local_stat.group_type != group_has_spare))
10735 		return false;
10736 
10737 	if (sgs->group_type > busiest->group_type)
10738 		return true;
10739 
10740 	if (sgs->group_type < busiest->group_type)
10741 		return false;
10742 
10743 	/*
10744 	 * The candidate and the current busiest group are the same type of
10745 	 * group. Let check which one is the busiest according to the type.
10746 	 */
10747 
10748 	switch (sgs->group_type) {
10749 	case group_overloaded:
10750 		/* Select the overloaded group with highest avg_load. */
10751 		return sgs->avg_load > busiest->avg_load;
10752 
10753 	case group_imbalanced:
10754 		/*
10755 		 * Select the 1st imbalanced group as we don't have any way to
10756 		 * choose one more than another.
10757 		 */
10758 		return false;
10759 
10760 	case group_asym_packing:
10761 		/* Prefer to move from lowest priority CPU's work */
10762 		return sched_asym_prefer(sds->busiest->asym_prefer_cpu, sg->asym_prefer_cpu);
10763 
10764 	case group_misfit_task:
10765 		/*
10766 		 * If we have more than one misfit sg go with the biggest
10767 		 * misfit.
10768 		 */
10769 		return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10770 
10771 	case group_smt_balance:
10772 		/*
10773 		 * Check if we have spare CPUs on either SMT group to
10774 		 * choose has spare or fully busy handling.
10775 		 */
10776 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10777 			goto has_spare;
10778 
10779 		fallthrough;
10780 
10781 	case group_fully_busy:
10782 		/*
10783 		 * Select the fully busy group with highest avg_load. In
10784 		 * theory, there is no need to pull task from such kind of
10785 		 * group because tasks have all compute capacity that they need
10786 		 * but we can still improve the overall throughput by reducing
10787 		 * contention when accessing shared HW resources.
10788 		 *
10789 		 * XXX for now avg_load is not computed and always 0 so we
10790 		 * select the 1st one, except if @sg is composed of SMT
10791 		 * siblings.
10792 		 */
10793 
10794 		if (sgs->avg_load < busiest->avg_load)
10795 			return false;
10796 
10797 		if (sgs->avg_load == busiest->avg_load) {
10798 			/*
10799 			 * SMT sched groups need more help than non-SMT groups.
10800 			 * If @sg happens to also be SMT, either choice is good.
10801 			 */
10802 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10803 				return false;
10804 		}
10805 
10806 		break;
10807 
10808 	case group_has_spare:
10809 		/*
10810 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10811 		 * as we do not want to pull task off SMT core with one task
10812 		 * and make the core idle.
10813 		 */
10814 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10815 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10816 				return false;
10817 			else
10818 				return true;
10819 		}
10820 has_spare:
10821 
10822 		/*
10823 		 * Select not overloaded group with lowest number of idle CPUs
10824 		 * and highest number of running tasks. We could also compare
10825 		 * the spare capacity which is more stable but it can end up
10826 		 * that the group has less spare capacity but finally more idle
10827 		 * CPUs which means less opportunity to pull tasks.
10828 		 */
10829 		if (sgs->idle_cpus > busiest->idle_cpus)
10830 			return false;
10831 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10832 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
10833 			return false;
10834 
10835 		break;
10836 	}
10837 
10838 	/*
10839 	 * Candidate sg has no more than one task per CPU and has higher
10840 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10841 	 * throughput. Maximize throughput, power/energy consequences are not
10842 	 * considered.
10843 	 */
10844 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10845 	    (sgs->group_type <= group_fully_busy) &&
10846 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10847 		return false;
10848 
10849 	return true;
10850 }
10851 
10852 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10853 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10854 {
10855 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10856 		return regular;
10857 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10858 		return remote;
10859 	return all;
10860 }
10861 
fbq_classify_rq(struct rq * rq)10862 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10863 {
10864 	if (rq->nr_running > rq->nr_numa_running)
10865 		return regular;
10866 	if (rq->nr_running > rq->nr_preferred_running)
10867 		return remote;
10868 	return all;
10869 }
10870 #else
fbq_classify_group(struct sg_lb_stats * sgs)10871 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10872 {
10873 	return all;
10874 }
10875 
fbq_classify_rq(struct rq * rq)10876 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10877 {
10878 	return regular;
10879 }
10880 #endif /* CONFIG_NUMA_BALANCING */
10881 
10882 
10883 struct sg_lb_stats;
10884 
10885 /*
10886  * task_running_on_cpu - return 1 if @p is running on @cpu.
10887  */
10888 
task_running_on_cpu(int cpu,struct task_struct * p)10889 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10890 {
10891 	/* Task has no contribution or is new */
10892 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10893 		return 0;
10894 
10895 	if (task_on_rq_queued(p))
10896 		return 1;
10897 
10898 	return 0;
10899 }
10900 
10901 /**
10902  * idle_cpu_without - would a given CPU be idle without p ?
10903  * @cpu: the processor on which idleness is tested.
10904  * @p: task which should be ignored.
10905  *
10906  * Return: 1 if the CPU would be idle. 0 otherwise.
10907  */
idle_cpu_without(int cpu,struct task_struct * p)10908 static int idle_cpu_without(int cpu, struct task_struct *p)
10909 {
10910 	struct rq *rq = cpu_rq(cpu);
10911 
10912 	if (rq->curr != rq->idle && rq->curr != p)
10913 		return 0;
10914 
10915 	/*
10916 	 * rq->nr_running can't be used but an updated version without the
10917 	 * impact of p on cpu must be used instead. The updated nr_running
10918 	 * be computed and tested before calling idle_cpu_without().
10919 	 */
10920 
10921 	if (rq->ttwu_pending)
10922 		return 0;
10923 
10924 	return 1;
10925 }
10926 
10927 /*
10928  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10929  * @sd: The sched_domain level to look for idlest group.
10930  * @group: sched_group whose statistics are to be updated.
10931  * @sgs: variable to hold the statistics for this group.
10932  * @p: The task for which we look for the idlest group/CPU.
10933  */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10934 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10935 					  struct sched_group *group,
10936 					  struct sg_lb_stats *sgs,
10937 					  struct task_struct *p)
10938 {
10939 	int i, nr_running;
10940 
10941 	memset(sgs, 0, sizeof(*sgs));
10942 
10943 	/* Assume that task can't fit any CPU of the group */
10944 	if (sd->flags & SD_ASYM_CPUCAPACITY)
10945 		sgs->group_misfit_task_load = 1;
10946 
10947 	for_each_cpu(i, sched_group_span(group)) {
10948 		struct rq *rq = cpu_rq(i);
10949 		misfit_reason_t reason;
10950 		unsigned int local;
10951 
10952 		sgs->group_load += cpu_load_without(rq, p);
10953 		sgs->group_util += cpu_util_without(i, p);
10954 		sgs->group_runnable += cpu_runnable_without(rq, p);
10955 		local = task_running_on_cpu(i, p);
10956 		sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10957 
10958 		nr_running = rq->nr_running - local;
10959 		sgs->sum_nr_running += nr_running;
10960 
10961 		/*
10962 		 * No need to call idle_cpu_without() if nr_running is not 0
10963 		 */
10964 		if (!nr_running && idle_cpu_without(i, p))
10965 			sgs->idle_cpus++;
10966 
10967 		/* Check if task fits in the CPU */
10968 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
10969 		    sgs->group_misfit_task_load) {
10970 			if (!is_misfit_task(p, rq, &reason)) {
10971 				sgs->group_misfit_task_load = 0;
10972 				sgs->group_misfit_reason = -1;
10973 			} else {
10974 				sgs->group_misfit_task_load =
10975 					max_t(unsigned long, task_h_load(p), 1);
10976 				sgs->group_misfit_reason = reason;
10977 			}
10978 		}
10979 
10980 	}
10981 
10982 	sgs->group_capacity = group->sgc->capacity;
10983 
10984 	sgs->group_weight = group->group_weight;
10985 
10986 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10987 
10988 	/*
10989 	 * Computing avg_load makes sense only when group is fully busy or
10990 	 * overloaded
10991 	 */
10992 	if (sgs->group_type == group_fully_busy ||
10993 		sgs->group_type == group_overloaded)
10994 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10995 				sgs->group_capacity;
10996 }
10997 
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10998 static bool update_pick_idlest(struct sched_group *idlest,
10999 			       struct sg_lb_stats *idlest_sgs,
11000 			       struct sched_group *group,
11001 			       struct sg_lb_stats *sgs)
11002 {
11003 	if (sgs->group_type < idlest_sgs->group_type)
11004 		return true;
11005 
11006 	if (sgs->group_type > idlest_sgs->group_type)
11007 		return false;
11008 
11009 	/*
11010 	 * The candidate and the current idlest group are the same type of
11011 	 * group. Let check which one is the idlest according to the type.
11012 	 */
11013 
11014 	switch (sgs->group_type) {
11015 	case group_overloaded:
11016 	case group_fully_busy:
11017 		/* Select the group with lowest avg_load. */
11018 		if (idlest_sgs->avg_load <= sgs->avg_load)
11019 			return false;
11020 		break;
11021 
11022 	case group_imbalanced:
11023 	case group_asym_packing:
11024 	case group_smt_balance:
11025 		/* Those types are not used in the slow wakeup path */
11026 		return false;
11027 
11028 	case group_misfit_task:
11029 		/* Select group with the highest max capacity */
11030 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
11031 			return false;
11032 		break;
11033 
11034 	case group_has_spare:
11035 		/* Select group with most idle CPUs */
11036 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
11037 			return false;
11038 
11039 		/* Select group with lowest group_util */
11040 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
11041 			idlest_sgs->group_util <= sgs->group_util)
11042 			return false;
11043 
11044 		break;
11045 	}
11046 
11047 	return true;
11048 }
11049 
11050 /*
11051  * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
11052  * domain.
11053  *
11054  * Assumes p is allowed on at least one CPU in sd.
11055  */
11056 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)11057 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
11058 {
11059 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
11060 	struct sg_lb_stats local_sgs, tmp_sgs;
11061 	struct sg_lb_stats *sgs;
11062 	unsigned long imbalance;
11063 	struct sg_lb_stats idlest_sgs = {
11064 			.avg_load = UINT_MAX,
11065 			.group_type = group_overloaded,
11066 	};
11067 
11068 	do {
11069 		int local_group;
11070 
11071 		/* Skip over this group if it has no CPUs allowed */
11072 		if (!cpumask_intersects(sched_group_span(group),
11073 					p->cpus_ptr))
11074 			continue;
11075 
11076 		/* Skip over this group if no cookie matched */
11077 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
11078 			continue;
11079 
11080 		local_group = cpumask_test_cpu(this_cpu,
11081 					       sched_group_span(group));
11082 
11083 		if (local_group) {
11084 			sgs = &local_sgs;
11085 			local = group;
11086 		} else {
11087 			sgs = &tmp_sgs;
11088 		}
11089 
11090 		update_sg_wakeup_stats(sd, group, sgs, p);
11091 
11092 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
11093 			idlest = group;
11094 			idlest_sgs = *sgs;
11095 		}
11096 
11097 	} while (group = group->next, group != sd->groups);
11098 
11099 
11100 	/* There is no idlest group to push tasks to */
11101 	if (!idlest)
11102 		return NULL;
11103 
11104 	/* The local group has been skipped because of CPU affinity */
11105 	if (!local)
11106 		return idlest;
11107 
11108 	/*
11109 	 * If the local group is idler than the selected idlest group
11110 	 * don't try and push the task.
11111 	 */
11112 	if (local_sgs.group_type < idlest_sgs.group_type)
11113 		return NULL;
11114 
11115 	/*
11116 	 * If the local group is busier than the selected idlest group
11117 	 * try and push the task.
11118 	 */
11119 	if (local_sgs.group_type > idlest_sgs.group_type)
11120 		return idlest;
11121 
11122 	switch (local_sgs.group_type) {
11123 	case group_overloaded:
11124 	case group_fully_busy:
11125 
11126 		/* Calculate allowed imbalance based on load */
11127 		imbalance = scale_load_down(NICE_0_LOAD) *
11128 				(sd->imbalance_pct-100) / 100;
11129 
11130 		/*
11131 		 * When comparing groups across NUMA domains, it's possible for
11132 		 * the local domain to be very lightly loaded relative to the
11133 		 * remote domains but "imbalance" skews the comparison making
11134 		 * remote CPUs look much more favourable. When considering
11135 		 * cross-domain, add imbalance to the load on the remote node
11136 		 * and consider staying local.
11137 		 */
11138 
11139 		if ((sd->flags & SD_NUMA) &&
11140 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
11141 			return NULL;
11142 
11143 		/*
11144 		 * If the local group is less loaded than the selected
11145 		 * idlest group don't try and push any tasks.
11146 		 */
11147 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
11148 			return NULL;
11149 
11150 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
11151 			return NULL;
11152 		break;
11153 
11154 	case group_imbalanced:
11155 	case group_asym_packing:
11156 	case group_smt_balance:
11157 		/* Those type are not used in the slow wakeup path */
11158 		return NULL;
11159 
11160 	case group_misfit_task:
11161 		/* Select group with the highest max capacity */
11162 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
11163 			return NULL;
11164 		break;
11165 
11166 	case group_has_spare:
11167 #ifdef CONFIG_NUMA
11168 		if (sd->flags & SD_NUMA) {
11169 			int imb_numa_nr = sd->imb_numa_nr;
11170 #ifdef CONFIG_NUMA_BALANCING
11171 			int idlest_cpu;
11172 			/*
11173 			 * If there is spare capacity at NUMA, try to select
11174 			 * the preferred node
11175 			 */
11176 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
11177 				return NULL;
11178 
11179 			idlest_cpu = cpumask_first(sched_group_span(idlest));
11180 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
11181 				return idlest;
11182 #endif /* CONFIG_NUMA_BALANCING */
11183 			/*
11184 			 * Otherwise, keep the task close to the wakeup source
11185 			 * and improve locality if the number of running tasks
11186 			 * would remain below threshold where an imbalance is
11187 			 * allowed while accounting for the possibility the
11188 			 * task is pinned to a subset of CPUs. If there is a
11189 			 * real need of migration, periodic load balance will
11190 			 * take care of it.
11191 			 */
11192 			if (p->nr_cpus_allowed != NR_CPUS) {
11193 				struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
11194 
11195 				cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
11196 				imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
11197 			}
11198 
11199 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
11200 			if (!adjust_numa_imbalance(imbalance,
11201 						   local_sgs.sum_nr_running + 1,
11202 						   imb_numa_nr)) {
11203 				return NULL;
11204 			}
11205 		}
11206 #endif /* CONFIG_NUMA */
11207 
11208 		/*
11209 		 * Select group with highest number of idle CPUs. We could also
11210 		 * compare the utilization which is more stable but it can end
11211 		 * up that the group has less spare capacity but finally more
11212 		 * idle CPUs which means more opportunity to run task.
11213 		 */
11214 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
11215 			return NULL;
11216 		break;
11217 	}
11218 
11219 	return idlest;
11220 }
11221 
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)11222 static void update_idle_cpu_scan(struct lb_env *env,
11223 				 unsigned long sum_util)
11224 {
11225 	struct sched_domain_shared *sd_share;
11226 	int llc_weight, pct;
11227 	u64 x, y, tmp;
11228 	/*
11229 	 * Update the number of CPUs to scan in LLC domain, which could
11230 	 * be used as a hint in select_idle_cpu(). The update of sd_share
11231 	 * could be expensive because it is within a shared cache line.
11232 	 * So the write of this hint only occurs during periodic load
11233 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11234 	 * can fire way more frequently than the former.
11235 	 */
11236 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11237 		return;
11238 
11239 	llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
11240 	if (env->sd->span_weight != llc_weight)
11241 		return;
11242 
11243 	sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
11244 	if (!sd_share)
11245 		return;
11246 
11247 	/*
11248 	 * The number of CPUs to search drops as sum_util increases, when
11249 	 * sum_util hits 85% or above, the scan stops.
11250 	 * The reason to choose 85% as the threshold is because this is the
11251 	 * imbalance_pct(117) when a LLC sched group is overloaded.
11252 	 *
11253 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
11254 	 * and y'= y / SCHED_CAPACITY_SCALE
11255 	 *
11256 	 * x is the ratio of sum_util compared to the CPU capacity:
11257 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11258 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
11259 	 * and the number of CPUs to scan is calculated by:
11260 	 *
11261 	 * nr_scan = llc_weight * y'                                    [2]
11262 	 *
11263 	 * When x hits the threshold of overloaded, AKA, when
11264 	 * x = 100 / pct, y drops to 0. According to [1],
11265 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11266 	 *
11267 	 * Scale x by SCHED_CAPACITY_SCALE:
11268 	 * x' = sum_util / llc_weight;                                  [3]
11269 	 *
11270 	 * and finally [1] becomes:
11271 	 * y = SCHED_CAPACITY_SCALE -
11272 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
11273 	 *
11274 	 */
11275 	/* equation [3] */
11276 	x = sum_util;
11277 	do_div(x, llc_weight);
11278 
11279 	/* equation [4] */
11280 	pct = env->sd->imbalance_pct;
11281 	tmp = x * x * pct * pct;
11282 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11283 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11284 	y = SCHED_CAPACITY_SCALE - tmp;
11285 
11286 	/* equation [2] */
11287 	y *= llc_weight;
11288 	do_div(y, SCHED_CAPACITY_SCALE);
11289 	if ((int)y != sd_share->nr_idle_scan)
11290 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11291 }
11292 
11293 /**
11294  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11295  * @env: The load balancing environment.
11296  * @sds: variable to hold the statistics for this sched_domain.
11297  */
11298 
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11299 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11300 {
11301 	struct sched_group *sg = env->sd->groups;
11302 	struct sg_lb_stats *local = &sds->local_stat;
11303 	struct sg_lb_stats tmp_sgs;
11304 	unsigned long sum_util = 0;
11305 	bool sg_overloaded = 0, sg_overutilized = 0;
11306 
11307 	do {
11308 		struct sg_lb_stats *sgs = &tmp_sgs;
11309 		int local_group;
11310 
11311 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11312 		if (local_group) {
11313 			sds->local = sg;
11314 			sgs = local;
11315 
11316 			if (env->idle != CPU_NEWLY_IDLE ||
11317 			    time_after_eq(jiffies, sg->sgc->next_update))
11318 				update_group_capacity(env->sd, env->dst_cpu);
11319 		}
11320 
11321 		update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11322 
11323 		if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11324 			sds->busiest = sg;
11325 			sds->busiest_stat = *sgs;
11326 		}
11327 
11328 		/* Now, start updating sd_lb_stats */
11329 		sds->total_load += sgs->group_load;
11330 		sds->total_capacity += sgs->group_capacity;
11331 
11332 		sum_util += sgs->group_util;
11333 		sg = sg->next;
11334 	} while (sg != env->sd->groups);
11335 
11336 	/*
11337 	 * Indicate that the child domain of the busiest group prefers tasks
11338 	 * go to a child's sibling domains first. NB the flags of a sched group
11339 	 * are those of the child domain.
11340 	 */
11341 	if (sds->busiest)
11342 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11343 
11344 
11345 	if (env->sd->flags & SD_NUMA)
11346 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11347 
11348 	if (!env->sd->parent) {
11349 		/* update overload indicator if we are at root domain */
11350 		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11351 
11352 		/* Update over-utilization (tipping point, U >= 0) indicator */
11353 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11354 	} else if (sg_overutilized) {
11355 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11356 	}
11357 
11358 	update_idle_cpu_scan(env, sum_util);
11359 }
11360 
11361 /**
11362  * calculate_imbalance - Calculate the amount of imbalance present within the
11363  *			 groups of a given sched_domain during load balance.
11364  * @env: load balance environment
11365  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11366  */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11367 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11368 {
11369 	struct sg_lb_stats *local, *busiest;
11370 
11371 	local = &sds->local_stat;
11372 	busiest = &sds->busiest_stat;
11373 
11374 	if (busiest->group_type == group_misfit_task) {
11375 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11376 			/* Set imbalance to allow misfit tasks to be balanced. */
11377 			env->migration_type = migrate_misfit;
11378 			env->imbalance = 1;
11379 		} else {
11380 			/*
11381 			 * Set load imbalance to allow moving task from cpu
11382 			 * with reduced capacity.
11383 			 */
11384 			env->migration_type = migrate_load;
11385 			env->imbalance = busiest->group_misfit_task_load;
11386 		}
11387 		return;
11388 	}
11389 
11390 	if (busiest->group_type == group_asym_packing) {
11391 		/*
11392 		 * In case of asym capacity, we will try to migrate all load to
11393 		 * the preferred CPU.
11394 		 */
11395 		env->migration_type = migrate_task;
11396 		env->imbalance = busiest->sum_h_nr_running;
11397 		return;
11398 	}
11399 
11400 	if (busiest->group_type == group_smt_balance) {
11401 		/* Reduce number of tasks sharing CPU capacity */
11402 		env->migration_type = migrate_task;
11403 		env->imbalance = 1;
11404 		return;
11405 	}
11406 
11407 	if (busiest->group_type == group_imbalanced) {
11408 		/*
11409 		 * In the group_imb case we cannot rely on group-wide averages
11410 		 * to ensure CPU-load equilibrium, try to move any task to fix
11411 		 * the imbalance. The next load balance will take care of
11412 		 * balancing back the system.
11413 		 */
11414 		env->migration_type = migrate_task;
11415 		env->imbalance = 1;
11416 		return;
11417 	}
11418 
11419 	/*
11420 	 * Try to use spare capacity of local group without overloading it or
11421 	 * emptying busiest.
11422 	 */
11423 	if (local->group_type == group_has_spare) {
11424 		if ((busiest->group_type > group_fully_busy) &&
11425 		    !(env->sd->flags & SD_SHARE_LLC)) {
11426 			/*
11427 			 * If busiest is overloaded, try to fill spare
11428 			 * capacity. This might end up creating spare capacity
11429 			 * in busiest or busiest still being overloaded but
11430 			 * there is no simple way to directly compute the
11431 			 * amount of load to migrate in order to balance the
11432 			 * system.
11433 			 */
11434 			env->migration_type = migrate_util;
11435 			env->imbalance = max(local->group_capacity, local->group_util) -
11436 					 local->group_util;
11437 
11438 			/*
11439 			 * In some cases, the group's utilization is max or even
11440 			 * higher than capacity because of migrations but the
11441 			 * local CPU is (newly) idle. There is at least one
11442 			 * waiting task in this overloaded busiest group. Let's
11443 			 * try to pull it.
11444 			 */
11445 			if (env->idle && env->imbalance == 0) {
11446 				env->migration_type = migrate_task;
11447 				env->imbalance = 1;
11448 			}
11449 
11450 			return;
11451 		}
11452 
11453 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
11454 			/*
11455 			 * When prefer sibling, evenly spread running tasks on
11456 			 * groups.
11457 			 */
11458 			env->migration_type = migrate_task;
11459 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
11460 		} else {
11461 
11462 			/*
11463 			 * If there is no overload, we just want to even the number of
11464 			 * idle CPUs.
11465 			 */
11466 			env->migration_type = migrate_task;
11467 			env->imbalance = max_t(long, 0,
11468 					       (local->idle_cpus - busiest->idle_cpus));
11469 		}
11470 
11471 #ifdef CONFIG_NUMA
11472 		/* Consider allowing a small imbalance between NUMA groups */
11473 		if (env->sd->flags & SD_NUMA) {
11474 			env->imbalance = adjust_numa_imbalance(env->imbalance,
11475 							       local->sum_nr_running + 1,
11476 							       env->sd->imb_numa_nr);
11477 		}
11478 #endif
11479 
11480 		/* Number of tasks to move to restore balance */
11481 		env->imbalance >>= 1;
11482 
11483 		return;
11484 	}
11485 
11486 	/*
11487 	 * Local is fully busy but has to take more load to relieve the
11488 	 * busiest group
11489 	 */
11490 	if (local->group_type < group_overloaded) {
11491 		/*
11492 		 * Local will become overloaded so the avg_load metrics are
11493 		 * finally needed.
11494 		 */
11495 
11496 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11497 				  local->group_capacity;
11498 
11499 		/*
11500 		 * If the local group is more loaded than the selected
11501 		 * busiest group don't try to pull any tasks.
11502 		 */
11503 		if (local->avg_load >= busiest->avg_load) {
11504 			env->imbalance = 0;
11505 			return;
11506 		}
11507 
11508 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11509 				sds->total_capacity;
11510 
11511 		/*
11512 		 * If the local group is more loaded than the average system
11513 		 * load, don't try to pull any tasks.
11514 		 */
11515 		if (local->avg_load >= sds->avg_load) {
11516 			env->imbalance = 0;
11517 			return;
11518 		}
11519 
11520 	}
11521 
11522 	/*
11523 	 * Both group are or will become overloaded and we're trying to get all
11524 	 * the CPUs to the average_load, so we don't want to push ourselves
11525 	 * above the average load, nor do we wish to reduce the max loaded CPU
11526 	 * below the average load. At the same time, we also don't want to
11527 	 * reduce the group load below the group capacity. Thus we look for
11528 	 * the minimum possible imbalance.
11529 	 */
11530 	env->migration_type = migrate_load;
11531 	env->imbalance = min(
11532 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11533 		(sds->avg_load - local->avg_load) * local->group_capacity
11534 	) / SCHED_CAPACITY_SCALE;
11535 }
11536 
11537 /******* sched_balance_find_src_group() helpers end here *********************/
11538 
11539 /*
11540  * Decision matrix according to the local and busiest group type:
11541  *
11542  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11543  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
11544  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
11545  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
11546  * asym_packing     force     force      N/A    N/A  force      force
11547  * imbalanced       force     force      N/A    N/A  force      force
11548  * overloaded       force     force      N/A    N/A  force      avg_load
11549  *
11550  * N/A :      Not Applicable because already filtered while updating
11551  *            statistics.
11552  * balanced : The system is balanced for these 2 groups.
11553  * force :    Calculate the imbalance as load migration is probably needed.
11554  * avg_load : Only if imbalance is significant enough.
11555  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
11556  *            different in groups.
11557  */
11558 
11559 /**
11560  * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11561  * if there is an imbalance.
11562  * @env: The load balancing environment.
11563  *
11564  * Also calculates the amount of runnable load which should be moved
11565  * to restore balance.
11566  *
11567  * Return:	- The busiest group if imbalance exists.
11568  */
sched_balance_find_src_group(struct lb_env * env)11569 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11570 {
11571 	struct sg_lb_stats *local, *busiest;
11572 	struct sd_lb_stats sds;
11573 	int out_balance = 1;
11574 
11575 	init_sd_lb_stats(&sds);
11576 
11577 	/*
11578 	 * Compute the various statistics relevant for load balancing at
11579 	 * this level.
11580 	 */
11581 	update_sd_lb_stats(env, &sds);
11582 
11583 	/* There is no busy sibling group to pull tasks from */
11584 	if (!sds.busiest)
11585 		goto out_balanced;
11586 
11587 	busiest = &sds.busiest_stat;
11588 
11589 	/* Misfit tasks should be dealt with regardless of the avg load */
11590 	if (busiest->group_type == group_misfit_task)
11591 		goto force_balance;
11592 
11593 	trace_android_rvh_sched_balance_find_src_group(sds.busiest, env->dst_rq, &out_balance);
11594 	if (!is_rd_overutilized(env->dst_rq->rd) &&
11595 	    rcu_dereference(env->dst_rq->rd->pd) && out_balance)
11596 		goto out_balanced;
11597 
11598 	/* ASYM feature bypasses nice load balance check */
11599 	if (busiest->group_type == group_asym_packing)
11600 		goto force_balance;
11601 
11602 	/*
11603 	 * If the busiest group is imbalanced the below checks don't
11604 	 * work because they assume all things are equal, which typically
11605 	 * isn't true due to cpus_ptr constraints and the like.
11606 	 */
11607 	if (busiest->group_type == group_imbalanced)
11608 		goto force_balance;
11609 
11610 	local = &sds.local_stat;
11611 	/*
11612 	 * If the local group is busier than the selected busiest group
11613 	 * don't try and pull any tasks.
11614 	 */
11615 	if (local->group_type > busiest->group_type)
11616 		goto out_balanced;
11617 
11618 	/*
11619 	 * When groups are overloaded, use the avg_load to ensure fairness
11620 	 * between tasks.
11621 	 */
11622 	if (local->group_type == group_overloaded) {
11623 		/*
11624 		 * If the local group is more loaded than the selected
11625 		 * busiest group don't try to pull any tasks.
11626 		 */
11627 		if (local->avg_load >= busiest->avg_load)
11628 			goto out_balanced;
11629 
11630 		/* XXX broken for overlapping NUMA groups */
11631 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11632 				sds.total_capacity;
11633 
11634 		/*
11635 		 * Don't pull any tasks if this group is already above the
11636 		 * domain average load.
11637 		 */
11638 		if (local->avg_load >= sds.avg_load)
11639 			goto out_balanced;
11640 
11641 		/*
11642 		 * If the busiest group is more loaded, use imbalance_pct to be
11643 		 * conservative.
11644 		 */
11645 		if (100 * busiest->avg_load <=
11646 				env->sd->imbalance_pct * local->avg_load)
11647 			goto out_balanced;
11648 	}
11649 
11650 	/*
11651 	 * Try to move all excess tasks to a sibling domain of the busiest
11652 	 * group's child domain.
11653 	 */
11654 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
11655 	    sibling_imbalance(env, &sds, busiest, local) > 1)
11656 		goto force_balance;
11657 
11658 	if (busiest->group_type != group_overloaded) {
11659 		if (!env->idle) {
11660 			/*
11661 			 * If the busiest group is not overloaded (and as a
11662 			 * result the local one too) but this CPU is already
11663 			 * busy, let another idle CPU try to pull task.
11664 			 */
11665 			goto out_balanced;
11666 		}
11667 
11668 		if (busiest->group_type == group_smt_balance &&
11669 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11670 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
11671 			goto force_balance;
11672 		}
11673 
11674 		if (busiest->group_weight > 1 &&
11675 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
11676 			/*
11677 			 * If the busiest group is not overloaded
11678 			 * and there is no imbalance between this and busiest
11679 			 * group wrt idle CPUs, it is balanced. The imbalance
11680 			 * becomes significant if the diff is greater than 1
11681 			 * otherwise we might end up to just move the imbalance
11682 			 * on another group. Of course this applies only if
11683 			 * there is more than 1 CPU per group.
11684 			 */
11685 			goto out_balanced;
11686 		}
11687 
11688 		if (busiest->sum_h_nr_running == 1) {
11689 			/*
11690 			 * busiest doesn't have any tasks waiting to run
11691 			 */
11692 			goto out_balanced;
11693 		}
11694 	}
11695 
11696 force_balance:
11697 	/* Looks like there is an imbalance. Compute it */
11698 	calculate_imbalance(env, &sds);
11699 	return env->imbalance ? sds.busiest : NULL;
11700 
11701 out_balanced:
11702 	env->imbalance = 0;
11703 	return NULL;
11704 }
11705 
11706 /*
11707  * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11708  */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11709 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11710 				     struct sched_group *group)
11711 {
11712 	struct rq *busiest = NULL, *rq;
11713 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11714 	unsigned int busiest_nr = 0;
11715 	int i, done = 0;
11716 
11717 	trace_android_rvh_find_busiest_queue(env->dst_cpu, group, env->cpus,
11718 					     &busiest, &done);
11719 	if (done)
11720 		return busiest;
11721 
11722 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11723 		unsigned long capacity, load, util;
11724 		unsigned int nr_running;
11725 		enum fbq_type rt;
11726 
11727 		rq = cpu_rq(i);
11728 		rt = fbq_classify_rq(rq);
11729 
11730 		/*
11731 		 * We classify groups/runqueues into three groups:
11732 		 *  - regular: there are !numa tasks
11733 		 *  - remote:  there are numa tasks that run on the 'wrong' node
11734 		 *  - all:     there is no distinction
11735 		 *
11736 		 * In order to avoid migrating ideally placed numa tasks,
11737 		 * ignore those when there's better options.
11738 		 *
11739 		 * If we ignore the actual busiest queue to migrate another
11740 		 * task, the next balance pass can still reduce the busiest
11741 		 * queue by moving tasks around inside the node.
11742 		 *
11743 		 * If we cannot move enough load due to this classification
11744 		 * the next pass will adjust the group classification and
11745 		 * allow migration of more tasks.
11746 		 *
11747 		 * Both cases only affect the total convergence complexity.
11748 		 */
11749 		if (rt > env->fbq_type)
11750 			continue;
11751 
11752 		nr_running = rq->cfs.h_nr_running;
11753 		if (!nr_running)
11754 			continue;
11755 
11756 		capacity = capacity_of(i);
11757 
11758 		/*
11759 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11760 		 * eventually lead to active_balancing high->low capacity.
11761 		 * Higher per-CPU capacity is considered better than balancing
11762 		 * average load.
11763 		 */
11764 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11765 		    rq->misfit_reason == MISFIT_PERF &&
11766 		    !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11767 		    nr_running == 1)
11768 			continue;
11769 
11770 		/*
11771 		 * Make sure we only pull tasks from a CPU of lower priority
11772 		 * when balancing between SMT siblings.
11773 		 *
11774 		 * If balancing between cores, let lower priority CPUs help
11775 		 * SMT cores with more than one busy sibling.
11776 		 */
11777 		if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11778 			continue;
11779 
11780 		switch (env->migration_type) {
11781 		case migrate_load:
11782 			/*
11783 			 * When comparing with load imbalance, use cpu_load()
11784 			 * which is not scaled with the CPU capacity.
11785 			 */
11786 			load = cpu_load(rq);
11787 
11788 			if (nr_running == 1 && load > env->imbalance &&
11789 			    !check_cpu_capacity(rq, env->sd))
11790 				break;
11791 
11792 			/*
11793 			 * For the load comparisons with the other CPUs,
11794 			 * consider the cpu_load() scaled with the CPU
11795 			 * capacity, so that the load can be moved away
11796 			 * from the CPU that is potentially running at a
11797 			 * lower capacity.
11798 			 *
11799 			 * Thus we're looking for max(load_i / capacity_i),
11800 			 * crosswise multiplication to rid ourselves of the
11801 			 * division works out to:
11802 			 * load_i * capacity_j > load_j * capacity_i;
11803 			 * where j is our previous maximum.
11804 			 */
11805 			if (load * busiest_capacity > busiest_load * capacity) {
11806 				busiest_load = load;
11807 				busiest_capacity = capacity;
11808 				busiest = rq;
11809 			}
11810 			break;
11811 
11812 		case migrate_util:
11813 			util = cpu_util_cfs_boost(i);
11814 
11815 			/*
11816 			 * Don't try to pull utilization from a CPU with one
11817 			 * running task. Whatever its utilization, we will fail
11818 			 * detach the task.
11819 			 */
11820 			if (nr_running <= 1)
11821 				continue;
11822 
11823 			if (busiest_util < util) {
11824 				busiest_util = util;
11825 				busiest = rq;
11826 			}
11827 			break;
11828 
11829 		case migrate_task:
11830 			if (busiest_nr < nr_running) {
11831 				busiest_nr = nr_running;
11832 				busiest = rq;
11833 			}
11834 			break;
11835 
11836 		case migrate_misfit:
11837 			/*
11838 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
11839 			 * simply seek the "biggest" misfit task.
11840 			 */
11841 			if (rq->misfit_task_load > busiest_load) {
11842 				busiest_load = rq->misfit_task_load;
11843 				busiest = rq;
11844 			}
11845 
11846 			break;
11847 
11848 		}
11849 	}
11850 
11851 	return busiest;
11852 }
11853 
11854 /*
11855  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11856  * so long as it is large enough.
11857  */
11858 #define MAX_PINNED_INTERVAL	512
11859 
11860 static inline bool
asym_active_balance(struct lb_env * env)11861 asym_active_balance(struct lb_env *env)
11862 {
11863 	/*
11864 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
11865 	 * priority CPUs in order to pack all tasks in the highest priority
11866 	 * CPUs. When done between cores, do it only if the whole core if the
11867 	 * whole core is idle.
11868 	 *
11869 	 * If @env::src_cpu is an SMT core with busy siblings, let
11870 	 * the lower priority @env::dst_cpu help it. Do not follow
11871 	 * CPU priority.
11872 	 */
11873 	return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11874 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11875 		!sched_use_asym_prio(env->sd, env->src_cpu));
11876 }
11877 
11878 static inline bool
imbalanced_active_balance(struct lb_env * env)11879 imbalanced_active_balance(struct lb_env *env)
11880 {
11881 	struct sched_domain *sd = env->sd;
11882 
11883 	/*
11884 	 * The imbalanced case includes the case of pinned tasks preventing a fair
11885 	 * distribution of the load on the system but also the even distribution of the
11886 	 * threads on a system with spare capacity
11887 	 */
11888 	if ((env->migration_type == migrate_task) &&
11889 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
11890 		return 1;
11891 
11892 	return 0;
11893 }
11894 
need_active_balance(struct lb_env * env)11895 static int need_active_balance(struct lb_env *env)
11896 {
11897 	struct sched_domain *sd = env->sd;
11898 
11899 	if (asym_active_balance(env))
11900 		return 1;
11901 
11902 	if (imbalanced_active_balance(env))
11903 		return 1;
11904 
11905 	/*
11906 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11907 	 * It's worth migrating the task if the src_cpu's capacity is reduced
11908 	 * because of other sched_class or IRQs if more capacity stays
11909 	 * available on dst_cpu.
11910 	 */
11911 	if (env->idle &&
11912 	    (env->src_rq->cfs.h_nr_running == 1)) {
11913 		if ((check_cpu_capacity(env->src_rq, sd)) &&
11914 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11915 			return 1;
11916 	}
11917 
11918 	if (env->migration_type == migrate_misfit)
11919 		return 1;
11920 
11921 	return 0;
11922 }
11923 
11924 static int active_load_balance_cpu_stop(void *data);
11925 
should_we_balance(struct lb_env * env)11926 static int should_we_balance(struct lb_env *env)
11927 {
11928 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11929 	struct sched_group *sg = env->sd->groups;
11930 	int cpu, idle_smt = -1;
11931 
11932 	/*
11933 	 * Ensure the balancing environment is consistent; can happen
11934 	 * when the softirq triggers 'during' hotplug.
11935 	 */
11936 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11937 		return 0;
11938 
11939 	/*
11940 	 * In the newly idle case, we will allow all the CPUs
11941 	 * to do the newly idle load balance.
11942 	 *
11943 	 * However, we bail out if we already have tasks or a wakeup pending,
11944 	 * to optimize wakeup latency.
11945 	 */
11946 	if (env->idle == CPU_NEWLY_IDLE) {
11947 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11948 			return 0;
11949 		return 1;
11950 	}
11951 
11952 	cpumask_copy(swb_cpus, group_balance_mask(sg));
11953 	/* Try to find first idle CPU */
11954 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11955 		if (!idle_cpu(cpu))
11956 			continue;
11957 
11958 		/*
11959 		 * Don't balance to idle SMT in busy core right away when
11960 		 * balancing cores, but remember the first idle SMT CPU for
11961 		 * later consideration.  Find CPU on an idle core first.
11962 		 */
11963 		if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11964 			if (idle_smt == -1)
11965 				idle_smt = cpu;
11966 			/*
11967 			 * If the core is not idle, and first SMT sibling which is
11968 			 * idle has been found, then its not needed to check other
11969 			 * SMT siblings for idleness:
11970 			 */
11971 #ifdef CONFIG_SCHED_SMT
11972 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11973 #endif
11974 			continue;
11975 		}
11976 
11977 		/*
11978 		 * Are we the first idle core in a non-SMT domain or higher,
11979 		 * or the first idle CPU in a SMT domain?
11980 		 */
11981 		return cpu == env->dst_cpu;
11982 	}
11983 
11984 	/* Are we the first idle CPU with busy siblings? */
11985 	if (idle_smt != -1)
11986 		return idle_smt == env->dst_cpu;
11987 
11988 	/* Are we the first CPU of this group ? */
11989 	return group_balance_cpu(sg) == env->dst_cpu;
11990 }
11991 
11992 /*
11993  * Check this_cpu to ensure it is balanced within domain. Attempt to move
11994  * tasks if there is an imbalance.
11995  */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11996 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11997 			struct sched_domain *sd, enum cpu_idle_type idle,
11998 			int *continue_balancing)
11999 {
12000 	int ld_moved, cur_ld_moved, active_balance = 0;
12001 	struct sched_domain *sd_parent = sd->parent;
12002 	struct sched_group *group;
12003 	struct rq *busiest;
12004 	struct rq_flags rf;
12005 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
12006 	struct lb_env env = {
12007 		.sd		= sd,
12008 		.dst_cpu	= this_cpu,
12009 		.dst_rq		= this_rq,
12010 		.dst_grpmask    = group_balance_mask(sd->groups),
12011 		.idle		= idle,
12012 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
12013 		.cpus		= cpus,
12014 		.fbq_type	= all,
12015 		.tasks		= LIST_HEAD_INIT(env.tasks),
12016 	};
12017 
12018 	cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
12019 
12020 	schedstat_inc(sd->lb_count[idle]);
12021 
12022 redo:
12023 	if (!should_we_balance(&env)) {
12024 		*continue_balancing = 0;
12025 		goto out_balanced;
12026 	}
12027 
12028 	group = sched_balance_find_src_group(&env);
12029 	if (!group) {
12030 		schedstat_inc(sd->lb_nobusyg[idle]);
12031 		goto out_balanced;
12032 	}
12033 
12034 	busiest = sched_balance_find_src_rq(&env, group);
12035 	if (!busiest) {
12036 		schedstat_inc(sd->lb_nobusyq[idle]);
12037 		goto out_balanced;
12038 	}
12039 
12040 	WARN_ON_ONCE(busiest == env.dst_rq);
12041 
12042 	schedstat_add(sd->lb_imbalance[idle], env.imbalance);
12043 
12044 	env.src_cpu = busiest->cpu;
12045 	env.src_rq = busiest;
12046 
12047 	ld_moved = 0;
12048 	/* Clear this flag as soon as we find a pullable task */
12049 	env.flags |= LBF_ALL_PINNED;
12050 	if (busiest->nr_running > 1) {
12051 		/*
12052 		 * Attempt to move tasks. If sched_balance_find_src_group has found
12053 		 * an imbalance but busiest->nr_running <= 1, the group is
12054 		 * still unbalanced. ld_moved simply stays zero, so it is
12055 		 * correctly treated as an imbalance.
12056 		 */
12057 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
12058 
12059 more_balance:
12060 		rq_lock_irqsave(busiest, &rf);
12061 		env.src_rq_rf = &rf;
12062 		update_rq_clock(busiest);
12063 
12064 		/*
12065 		 * cur_ld_moved - load moved in current iteration
12066 		 * ld_moved     - cumulative load moved across iterations
12067 		 */
12068 		cur_ld_moved = detach_tasks(&env);
12069 
12070 		/*
12071 		 * We've detached some tasks from busiest_rq. Every
12072 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
12073 		 * unlock busiest->lock, and we are able to be sure
12074 		 * that nobody can manipulate the tasks in parallel.
12075 		 * See task_rq_lock() family for the details.
12076 		 */
12077 
12078 		rq_unlock(busiest, &rf);
12079 
12080 		if (cur_ld_moved) {
12081 			attach_tasks(&env);
12082 			ld_moved += cur_ld_moved;
12083 		}
12084 
12085 		local_irq_restore(rf.flags);
12086 
12087 		if (env.flags & LBF_NEED_BREAK) {
12088 			env.flags &= ~LBF_NEED_BREAK;
12089 			goto more_balance;
12090 		}
12091 
12092 		/*
12093 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
12094 		 * us and move them to an alternate dst_cpu in our sched_group
12095 		 * where they can run. The upper limit on how many times we
12096 		 * iterate on same src_cpu is dependent on number of CPUs in our
12097 		 * sched_group.
12098 		 *
12099 		 * This changes load balance semantics a bit on who can move
12100 		 * load to a given_cpu. In addition to the given_cpu itself
12101 		 * (or a ilb_cpu acting on its behalf where given_cpu is
12102 		 * nohz-idle), we now have balance_cpu in a position to move
12103 		 * load to given_cpu. In rare situations, this may cause
12104 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
12105 		 * _independently_ and at _same_ time to move some load to
12106 		 * given_cpu) causing excess load to be moved to given_cpu.
12107 		 * This however should not happen so much in practice and
12108 		 * moreover subsequent load balance cycles should correct the
12109 		 * excess load moved.
12110 		 */
12111 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
12112 
12113 			/* Prevent to re-select dst_cpu via env's CPUs */
12114 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
12115 
12116 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
12117 			env.dst_cpu	 = env.new_dst_cpu;
12118 			env.flags	&= ~LBF_DST_PINNED;
12119 			env.loop	 = 0;
12120 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
12121 
12122 			/*
12123 			 * Go back to "more_balance" rather than "redo" since we
12124 			 * need to continue with same src_cpu.
12125 			 */
12126 			goto more_balance;
12127 		}
12128 
12129 		/*
12130 		 * We failed to reach balance because of affinity.
12131 		 */
12132 		if (sd_parent) {
12133 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12134 
12135 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
12136 				*group_imbalance = 1;
12137 		}
12138 
12139 		/* All tasks on this runqueue were pinned by CPU affinity */
12140 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
12141 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
12142 			/*
12143 			 * Attempting to continue load balancing at the current
12144 			 * sched_domain level only makes sense if there are
12145 			 * active CPUs remaining as possible busiest CPUs to
12146 			 * pull load from which are not contained within the
12147 			 * destination group that is receiving any migrated
12148 			 * load.
12149 			 */
12150 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
12151 				env.loop = 0;
12152 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
12153 				goto redo;
12154 			}
12155 			goto out_all_pinned;
12156 		}
12157 	}
12158 
12159 	if (!ld_moved) {
12160 		schedstat_inc(sd->lb_failed[idle]);
12161 		/*
12162 		 * Increment the failure counter only on periodic balance.
12163 		 * We do not want newidle balance, which can be very
12164 		 * frequent, pollute the failure counter causing
12165 		 * excessive cache_hot migrations and active balances.
12166 		 *
12167 		 * Similarly for migration_misfit which is not related to
12168 		 * load/util migration, don't pollute nr_balance_failed.
12169 		 */
12170 		if (idle != CPU_NEWLY_IDLE &&
12171 		    env.migration_type != migrate_misfit)
12172 			sd->nr_balance_failed++;
12173 
12174 		if (need_active_balance(&env)) {
12175 			unsigned long flags;
12176 
12177 			raw_spin_rq_lock_irqsave(busiest, flags);
12178 
12179 			/*
12180 			 * Don't kick the active_load_balance_cpu_stop,
12181 			 * if the curr task on busiest CPU can't be
12182 			 * moved to this_cpu:
12183 			 */
12184 			if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
12185 				raw_spin_rq_unlock_irqrestore(busiest, flags);
12186 				goto out_one_pinned;
12187 			}
12188 
12189 			/* Record that we found at least one task that could run on this_cpu */
12190 			env.flags &= ~LBF_ALL_PINNED;
12191 
12192 			/*
12193 			 * ->active_balance synchronizes accesses to
12194 			 * ->active_balance_work.  Once set, it's cleared
12195 			 * only after active load balance is finished.
12196 			 */
12197 			if (!busiest->active_balance) {
12198 				busiest->active_balance = 1;
12199 				busiest->push_cpu = this_cpu;
12200 				active_balance = 1;
12201 			}
12202 
12203 			preempt_disable();
12204 			raw_spin_rq_unlock_irqrestore(busiest, flags);
12205 			if (active_balance) {
12206 				stop_one_cpu_nowait(cpu_of(busiest),
12207 					active_load_balance_cpu_stop, busiest,
12208 					&busiest->active_balance_work);
12209 			}
12210 			preempt_enable();
12211 		}
12212 	} else {
12213 		sd->nr_balance_failed = 0;
12214 	}
12215 
12216 	if (likely(!active_balance) || need_active_balance(&env)) {
12217 		/* We were unbalanced, so reset the balancing interval */
12218 		sd->balance_interval = sd->min_interval;
12219 	}
12220 
12221 	goto out;
12222 
12223 out_balanced:
12224 	/*
12225 	 * We reach balance although we may have faced some affinity
12226 	 * constraints. Clear the imbalance flag only if other tasks got
12227 	 * a chance to move and fix the imbalance.
12228 	 */
12229 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12230 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12231 
12232 		if (*group_imbalance)
12233 			*group_imbalance = 0;
12234 	}
12235 
12236 out_all_pinned:
12237 	/*
12238 	 * We reach balance because all tasks are pinned at this level so
12239 	 * we can't migrate them. Let the imbalance flag set so parent level
12240 	 * can try to migrate them.
12241 	 */
12242 	schedstat_inc(sd->lb_balanced[idle]);
12243 
12244 	sd->nr_balance_failed = 0;
12245 
12246 out_one_pinned:
12247 	ld_moved = 0;
12248 
12249 	/*
12250 	 * sched_balance_newidle() disregards balance intervals, so we could
12251 	 * repeatedly reach this code, which would lead to balance_interval
12252 	 * skyrocketing in a short amount of time. Skip the balance_interval
12253 	 * increase logic to avoid that.
12254 	 *
12255 	 * Similarly misfit migration which is not necessarily an indication of
12256 	 * the system being busy and requires lb to backoff to let it settle
12257 	 * down.
12258 	 */
12259 	if (env.idle == CPU_NEWLY_IDLE ||
12260 	    env.migration_type == migrate_misfit)
12261 		goto out;
12262 
12263 	/* tune up the balancing interval */
12264 	if ((env.flags & LBF_ALL_PINNED &&
12265 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
12266 	    sd->balance_interval < sd->max_interval)
12267 		sd->balance_interval *= 2;
12268 out:
12269 	return ld_moved;
12270 }
12271 
12272 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)12273 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12274 {
12275 	unsigned long interval = sd->balance_interval;
12276 
12277 	if (cpu_busy)
12278 		interval *= sd->busy_factor;
12279 
12280 	/* scale ms to jiffies */
12281 	interval = msecs_to_jiffies(interval);
12282 
12283 	/*
12284 	 * Reduce likelihood of busy balancing at higher domains racing with
12285 	 * balancing at lower domains by preventing their balancing periods
12286 	 * from being multiples of each other.
12287 	 */
12288 	if (cpu_busy)
12289 		interval -= 1;
12290 
12291 	interval = clamp(interval, 1UL, max_load_balance_interval);
12292 
12293 	return interval;
12294 }
12295 
12296 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12297 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12298 {
12299 	unsigned long interval, next;
12300 
12301 	/* used by idle balance, so cpu_busy = 0 */
12302 	interval = get_sd_balance_interval(sd, 0);
12303 	next = sd->last_balance + interval;
12304 
12305 	if (time_after(*next_balance, next))
12306 		*next_balance = next;
12307 }
12308 
12309 /*
12310  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12311  * running tasks off the busiest CPU onto idle CPUs. It requires at
12312  * least 1 task to be running on each physical CPU where possible, and
12313  * avoids physical / logical imbalances.
12314  */
active_load_balance_cpu_stop(void * data)12315 static int active_load_balance_cpu_stop(void *data)
12316 {
12317 	struct rq *busiest_rq = data;
12318 	int busiest_cpu = cpu_of(busiest_rq);
12319 	int target_cpu = busiest_rq->push_cpu;
12320 	struct rq *target_rq = cpu_rq(target_cpu);
12321 	struct sched_domain *sd;
12322 	struct task_struct *p = NULL;
12323 	struct rq_flags rf;
12324 
12325 	rq_lock_irq(busiest_rq, &rf);
12326 	/*
12327 	 * Between queueing the stop-work and running it is a hole in which
12328 	 * CPUs can become inactive. We should not move tasks from or to
12329 	 * inactive CPUs.
12330 	 */
12331 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12332 		goto out_unlock;
12333 
12334 	/* Make sure the requested CPU hasn't gone down in the meantime: */
12335 	if (unlikely(busiest_cpu != smp_processor_id() ||
12336 		     !busiest_rq->active_balance))
12337 		goto out_unlock;
12338 
12339 	/* Is there any task to move? */
12340 	if (busiest_rq->nr_running <= 1)
12341 		goto out_unlock;
12342 
12343 	/*
12344 	 * This condition is "impossible", if it occurs
12345 	 * we need to fix it. Originally reported by
12346 	 * Bjorn Helgaas on a 128-CPU setup.
12347 	 */
12348 	WARN_ON_ONCE(busiest_rq == target_rq);
12349 
12350 	/* Search for an sd spanning us and the target CPU. */
12351 	rcu_read_lock();
12352 	for_each_domain(target_cpu, sd) {
12353 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12354 			break;
12355 	}
12356 
12357 	if (likely(sd)) {
12358 		struct lb_env env = {
12359 			.sd		= sd,
12360 			.dst_cpu	= target_cpu,
12361 			.dst_rq		= target_rq,
12362 			.src_cpu	= busiest_rq->cpu,
12363 			.src_rq		= busiest_rq,
12364 			.idle		= CPU_IDLE,
12365 			.flags		= LBF_ACTIVE_LB,
12366 			.src_rq_rf	= &rf,
12367 		};
12368 
12369 		schedstat_inc(sd->alb_count);
12370 		update_rq_clock(busiest_rq);
12371 
12372 		p = detach_one_task(&env);
12373 		if (p) {
12374 			schedstat_inc(sd->alb_pushed);
12375 			/* Active balancing done, reset the failure counter. */
12376 			sd->nr_balance_failed = 0;
12377 		} else {
12378 			schedstat_inc(sd->alb_failed);
12379 		}
12380 	}
12381 	rcu_read_unlock();
12382 out_unlock:
12383 	busiest_rq->active_balance = 0;
12384 	rq_unlock(busiest_rq, &rf);
12385 
12386 	if (p)
12387 		attach_one_task(target_rq, p);
12388 
12389 	local_irq_enable();
12390 
12391 	return 0;
12392 }
12393 
12394 /*
12395  * This flag serializes load-balancing passes over large domains
12396  * (above the NODE topology level) - only one load-balancing instance
12397  * may run at a time, to reduce overhead on very large systems with
12398  * lots of CPUs and large NUMA distances.
12399  *
12400  * - Note that load-balancing passes triggered while another one
12401  *   is executing are skipped and not re-tried.
12402  *
12403  * - Also note that this does not serialize rebalance_domains()
12404  *   execution, as non-SD_SERIALIZE domains will still be
12405  *   load-balanced in parallel.
12406  */
12407 static atomic_t sched_balance_running = ATOMIC_INIT(0);
12408 
12409 /*
12410  * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12411  * This trades load-balance latency on larger machines for less cross talk.
12412  */
update_max_interval(void)12413 void update_max_interval(void)
12414 {
12415 	max_load_balance_interval = HZ*num_online_cpus()/10;
12416 }
12417 
update_newidle_cost(struct sched_domain * sd,u64 cost)12418 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
12419 {
12420 	if (cost > sd->max_newidle_lb_cost) {
12421 		/*
12422 		 * Track max cost of a domain to make sure to not delay the
12423 		 * next wakeup on the CPU.
12424 		 *
12425 		 * sched_balance_newidle() bumps the cost whenever newidle
12426 		 * balance fails, and we don't want things to grow out of
12427 		 * control.  Use the sysctl_sched_migration_cost as the upper
12428 		 * limit, plus a litle extra to avoid off by ones.
12429 		 */
12430 		sd->max_newidle_lb_cost =
12431 			min(cost, sysctl_sched_migration_cost + 200);
12432 		sd->last_decay_max_lb_cost = jiffies;
12433 	} else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
12434 		/*
12435 		 * Decay the newidle max times by ~1% per second to ensure that
12436 		 * it is not outdated and the current max cost is actually
12437 		 * shorter.
12438 		 */
12439 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12440 		sd->last_decay_max_lb_cost = jiffies;
12441 
12442 		return true;
12443 	}
12444 
12445 	return false;
12446 }
12447 
12448 /*
12449  * It checks each scheduling domain to see if it is due to be balanced,
12450  * and initiates a balancing operation if so.
12451  *
12452  * Balancing parameters are set up in init_sched_domains.
12453  */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12454 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12455 {
12456 	int continue_balancing = 1;
12457 	int cpu = rq->cpu;
12458 	int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12459 	unsigned long interval;
12460 	struct sched_domain *sd;
12461 	/* Earliest time when we have to do rebalance again */
12462 	unsigned long next_balance = jiffies + 60*HZ;
12463 	int update_next_balance = 0;
12464 	int need_serialize, need_decay = 0;
12465 	u64 max_cost = 0;
12466 
12467 	trace_android_rvh_sched_rebalance_domains(rq, &continue_balancing);
12468 	if (!continue_balancing)
12469 		return;
12470 
12471 	rcu_read_lock();
12472 	for_each_domain(cpu, sd) {
12473 		/*
12474 		 * Decay the newidle max times here because this is a regular
12475 		 * visit to all the domains.
12476 		 */
12477 		need_decay = update_newidle_cost(sd, 0);
12478 		max_cost += sd->max_newidle_lb_cost;
12479 
12480 		/*
12481 		 * Stop the load balance at this level. There is another
12482 		 * CPU in our sched group which is doing load balancing more
12483 		 * actively.
12484 		 */
12485 		if (!continue_balancing) {
12486 			if (need_decay)
12487 				continue;
12488 			break;
12489 		}
12490 
12491 		interval = get_sd_balance_interval(sd, busy);
12492 
12493 		need_serialize = sd->flags & SD_SERIALIZE;
12494 		if (need_serialize) {
12495 			if (atomic_cmpxchg_acquire(&sched_balance_running, 0, 1))
12496 				goto out;
12497 		}
12498 
12499 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
12500 			if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12501 				/*
12502 				 * The LBF_DST_PINNED logic could have changed
12503 				 * env->dst_cpu, so we can't know our idle
12504 				 * state even if we migrated tasks. Update it.
12505 				 */
12506 				idle = idle_cpu(cpu);
12507 				busy = !idle && !sched_idle_cpu(cpu);
12508 			}
12509 			sd->last_balance = jiffies;
12510 			interval = get_sd_balance_interval(sd, busy);
12511 		}
12512 		if (need_serialize)
12513 			atomic_set_release(&sched_balance_running, 0);
12514 out:
12515 		if (time_after(next_balance, sd->last_balance + interval)) {
12516 			next_balance = sd->last_balance + interval;
12517 			update_next_balance = 1;
12518 		}
12519 	}
12520 	if (need_decay) {
12521 		/*
12522 		 * Ensure the rq-wide value also decays but keep it at a
12523 		 * reasonable floor to avoid funnies with rq->avg_idle.
12524 		 */
12525 		rq->max_idle_balance_cost =
12526 			max((u64)sysctl_sched_migration_cost, max_cost);
12527 	}
12528 	rcu_read_unlock();
12529 
12530 	/*
12531 	 * next_balance will be updated only when there is a need.
12532 	 * When the cpu is attached to null domain for ex, it will not be
12533 	 * updated.
12534 	 */
12535 	if (likely(update_next_balance))
12536 		rq->next_balance = next_balance;
12537 
12538 }
12539 
on_null_domain(struct rq * rq)12540 static inline int on_null_domain(struct rq *rq)
12541 {
12542 	return unlikely(!rcu_dereference_sched(rq->sd));
12543 }
12544 
12545 #ifdef CONFIG_NO_HZ_COMMON
12546 /*
12547  * NOHZ idle load balancing (ILB) details:
12548  *
12549  * - When one of the busy CPUs notices that there may be an idle rebalancing
12550  *   needed, they will kick the idle load balancer, which then does idle
12551  *   load balancing for all the idle CPUs.
12552  *
12553  * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED is not set
12554  *   anywhere yet.
12555  */
find_new_ilb(void)12556 static inline int find_new_ilb(void)
12557 {
12558 	const struct cpumask *hk_mask;
12559 	int ilb_cpu;
12560 	int new_ilb = nr_cpu_ids;
12561 
12562 	trace_android_rvh_find_new_ilb(nohz.idle_cpus_mask, &new_ilb);
12563 	if (new_ilb != nr_cpu_ids)
12564 		return new_ilb;
12565 
12566 	hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
12567 
12568 	for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12569 
12570 		if (ilb_cpu == smp_processor_id())
12571 			continue;
12572 
12573 		if (idle_cpu(ilb_cpu))
12574 			return ilb_cpu;
12575 	}
12576 
12577 	return -1;
12578 }
12579 
12580 /*
12581  * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12582  * SMP function call (IPI).
12583  *
12584  * We pick the first idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
12585  */
kick_ilb(unsigned int flags)12586 static void kick_ilb(unsigned int flags)
12587 {
12588 	int ilb_cpu;
12589 
12590 	/*
12591 	 * Increase nohz.next_balance only when if full ilb is triggered but
12592 	 * not if we only update stats.
12593 	 */
12594 	if (flags & NOHZ_BALANCE_KICK)
12595 		nohz.next_balance = jiffies+1;
12596 
12597 	ilb_cpu = find_new_ilb();
12598 	if (ilb_cpu < 0)
12599 		return;
12600 
12601 	/*
12602 	 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12603 	 * i.e. all bits in flags are already set in ilb_cpu.
12604 	 */
12605 	if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12606 		return;
12607 
12608 	/*
12609 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12610 	 * the first flag owns it; cleared by nohz_csd_func().
12611 	 */
12612 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12613 	if (flags & NOHZ_KICK_MASK)
12614 		return;
12615 
12616 	/*
12617 	 * This way we generate an IPI on the target CPU which
12618 	 * is idle, and the softirq performing NOHZ idle load balancing
12619 	 * will be run before returning from the IPI.
12620 	 */
12621 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12622 }
12623 
12624 /*
12625  * Current decision point for kicking the idle load balancer in the presence
12626  * of idle CPUs in the system.
12627  */
nohz_balancer_kick(struct rq * rq)12628 static void nohz_balancer_kick(struct rq *rq)
12629 {
12630 	unsigned long now = jiffies;
12631 	struct sched_domain_shared *sds;
12632 	struct sched_domain *sd;
12633 	int nr_busy, i, cpu = rq->cpu;
12634 	unsigned int flags = 0;
12635 	int done = 0;
12636 
12637 	if (unlikely(rq->idle_balance))
12638 		return;
12639 
12640 	/*
12641 	 * We may be recently in ticked or tickless idle mode. At the first
12642 	 * busy tick after returning from idle, we will update the busy stats.
12643 	 */
12644 	nohz_balance_exit_idle(rq);
12645 
12646 	/*
12647 	 * None are in tickless mode and hence no need for NOHZ idle load
12648 	 * balancing:
12649 	 */
12650 	if (likely(!atomic_read(&nohz.nr_cpus)))
12651 		return;
12652 
12653 	if (READ_ONCE(nohz.has_blocked) &&
12654 	    time_after(now, READ_ONCE(nohz.next_blocked)))
12655 		flags = NOHZ_STATS_KICK;
12656 
12657 	if (time_before(now, nohz.next_balance))
12658 		goto out;
12659 
12660 	trace_android_rvh_sched_nohz_balancer_kick(rq, &flags, &done);
12661 	if (done)
12662 		goto out;
12663 
12664 	if (rq->nr_running >= 2) {
12665 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12666 		goto out;
12667 	}
12668 
12669 	rcu_read_lock();
12670 
12671 	sd = rcu_dereference(rq->sd);
12672 	if (sd) {
12673 		/*
12674 		 * If there's a runnable CFS task and the current CPU has reduced
12675 		 * capacity, kick the ILB to see if there's a better CPU to run on:
12676 		 */
12677 		if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
12678 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12679 			goto unlock;
12680 		}
12681 	}
12682 
12683 	sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12684 	if (sd) {
12685 		/*
12686 		 * When ASYM_PACKING; see if there's a more preferred CPU
12687 		 * currently idle; in which case, kick the ILB to move tasks
12688 		 * around.
12689 		 *
12690 		 * When balancing between cores, all the SMT siblings of the
12691 		 * preferred CPU must be idle.
12692 		 */
12693 		for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12694 			if (sched_asym(sd, i, cpu)) {
12695 				flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12696 				goto unlock;
12697 			}
12698 		}
12699 	}
12700 
12701 	sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12702 	if (sd) {
12703 		/*
12704 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12705 		 * to run the misfit task on.
12706 		 */
12707 		if (check_misfit_status(rq)) {
12708 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12709 			goto unlock;
12710 		}
12711 
12712 		/*
12713 		 * For asymmetric systems, we do not want to nicely balance
12714 		 * cache use, instead we want to embrace asymmetry and only
12715 		 * ensure tasks have enough CPU capacity.
12716 		 *
12717 		 * Skip the LLC logic because it's not relevant in that case.
12718 		 */
12719 		goto unlock;
12720 	}
12721 
12722 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12723 	if (sds) {
12724 		/*
12725 		 * If there is an imbalance between LLC domains (IOW we could
12726 		 * increase the overall cache utilization), we need a less-loaded LLC
12727 		 * domain to pull some load from. Likewise, we may need to spread
12728 		 * load within the current LLC domain (e.g. packed SMT cores but
12729 		 * other CPUs are idle). We can't really know from here how busy
12730 		 * the others are - so just get a NOHZ balance going if it looks
12731 		 * like this LLC domain has tasks we could move.
12732 		 */
12733 		nr_busy = atomic_read(&sds->nr_busy_cpus);
12734 		if (nr_busy > 1) {
12735 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12736 			goto unlock;
12737 		}
12738 	}
12739 unlock:
12740 	rcu_read_unlock();
12741 out:
12742 	if (READ_ONCE(nohz.needs_update))
12743 		flags |= NOHZ_NEXT_KICK;
12744 
12745 	if (flags)
12746 		kick_ilb(flags);
12747 }
12748 
set_cpu_sd_state_busy(int cpu)12749 static void set_cpu_sd_state_busy(int cpu)
12750 {
12751 	struct sched_domain *sd;
12752 
12753 	rcu_read_lock();
12754 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12755 
12756 	if (!sd || !sd->nohz_idle)
12757 		goto unlock;
12758 	sd->nohz_idle = 0;
12759 
12760 	atomic_inc(&sd->shared->nr_busy_cpus);
12761 unlock:
12762 	rcu_read_unlock();
12763 }
12764 
nohz_balance_exit_idle(struct rq * rq)12765 void nohz_balance_exit_idle(struct rq *rq)
12766 {
12767 	SCHED_WARN_ON(rq != this_rq());
12768 
12769 	if (likely(!rq->nohz_tick_stopped))
12770 		return;
12771 
12772 	rq->nohz_tick_stopped = 0;
12773 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12774 	atomic_dec(&nohz.nr_cpus);
12775 
12776 	set_cpu_sd_state_busy(rq->cpu);
12777 }
12778 
set_cpu_sd_state_idle(int cpu)12779 static void set_cpu_sd_state_idle(int cpu)
12780 {
12781 	struct sched_domain *sd;
12782 
12783 	rcu_read_lock();
12784 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12785 
12786 	if (!sd || sd->nohz_idle)
12787 		goto unlock;
12788 	sd->nohz_idle = 1;
12789 
12790 	atomic_dec(&sd->shared->nr_busy_cpus);
12791 unlock:
12792 	rcu_read_unlock();
12793 }
12794 
12795 /*
12796  * This routine will record that the CPU is going idle with tick stopped.
12797  * This info will be used in performing idle load balancing in the future.
12798  */
nohz_balance_enter_idle(int cpu)12799 void nohz_balance_enter_idle(int cpu)
12800 {
12801 	struct rq *rq = cpu_rq(cpu);
12802 
12803 	SCHED_WARN_ON(cpu != smp_processor_id());
12804 
12805 	/* If this CPU is going down, then nothing needs to be done: */
12806 	if (!cpu_active(cpu))
12807 		return;
12808 
12809 	/* Spare idle load balancing on CPUs that don't want to be disturbed: */
12810 	if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
12811 		return;
12812 
12813 	/*
12814 	 * Can be set safely without rq->lock held
12815 	 * If a clear happens, it will have evaluated last additions because
12816 	 * rq->lock is held during the check and the clear
12817 	 */
12818 	rq->has_blocked_load = 1;
12819 
12820 	/*
12821 	 * The tick is still stopped but load could have been added in the
12822 	 * meantime. We set the nohz.has_blocked flag to trig a check of the
12823 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12824 	 * of nohz.has_blocked can only happen after checking the new load
12825 	 */
12826 	if (rq->nohz_tick_stopped)
12827 		goto out;
12828 
12829 	/* If we're a completely isolated CPU, we don't play: */
12830 	if (on_null_domain(rq))
12831 		return;
12832 
12833 	rq->nohz_tick_stopped = 1;
12834 
12835 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12836 	atomic_inc(&nohz.nr_cpus);
12837 
12838 	/*
12839 	 * Ensures that if nohz_idle_balance() fails to observe our
12840 	 * @idle_cpus_mask store, it must observe the @has_blocked
12841 	 * and @needs_update stores.
12842 	 */
12843 	smp_mb__after_atomic();
12844 
12845 	set_cpu_sd_state_idle(cpu);
12846 
12847 	WRITE_ONCE(nohz.needs_update, 1);
12848 out:
12849 	/*
12850 	 * Each time a cpu enter idle, we assume that it has blocked load and
12851 	 * enable the periodic update of the load of idle CPUs
12852 	 */
12853 	WRITE_ONCE(nohz.has_blocked, 1);
12854 }
12855 
update_nohz_stats(struct rq * rq)12856 static bool update_nohz_stats(struct rq *rq)
12857 {
12858 	unsigned int cpu = rq->cpu;
12859 
12860 	if (!rq->has_blocked_load)
12861 		return false;
12862 
12863 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12864 		return false;
12865 
12866 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12867 		return true;
12868 
12869 	sched_balance_update_blocked_averages(cpu);
12870 
12871 	return rq->has_blocked_load;
12872 }
12873 
12874 /*
12875  * Internal function that runs load balance for all idle CPUs. The load balance
12876  * can be a simple update of blocked load or a complete load balance with
12877  * tasks movement depending of flags.
12878  */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12879 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12880 {
12881 	/* Earliest time when we have to do rebalance again */
12882 	unsigned long now = jiffies;
12883 	unsigned long next_balance = now + 60*HZ;
12884 	bool has_blocked_load = false;
12885 	int update_next_balance = 0;
12886 	int this_cpu = this_rq->cpu;
12887 	int balance_cpu;
12888 	struct rq *rq;
12889 
12890 	SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12891 
12892 	/*
12893 	 * We assume there will be no idle load after this update and clear
12894 	 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12895 	 * set the has_blocked flag and trigger another update of idle load.
12896 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12897 	 * setting the flag, we are sure to not clear the state and not
12898 	 * check the load of an idle cpu.
12899 	 *
12900 	 * Same applies to idle_cpus_mask vs needs_update.
12901 	 */
12902 	if (flags & NOHZ_STATS_KICK)
12903 		WRITE_ONCE(nohz.has_blocked, 0);
12904 	if (flags & NOHZ_NEXT_KICK)
12905 		WRITE_ONCE(nohz.needs_update, 0);
12906 
12907 	/*
12908 	 * Ensures that if we miss the CPU, we must see the has_blocked
12909 	 * store from nohz_balance_enter_idle().
12910 	 */
12911 	smp_mb();
12912 
12913 	/*
12914 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12915 	 * chance for other idle cpu to pull load.
12916 	 */
12917 	for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
12918 		if (!idle_cpu(balance_cpu))
12919 			continue;
12920 
12921 		/*
12922 		 * If this CPU gets work to do, stop the load balancing
12923 		 * work being done for other CPUs. Next load
12924 		 * balancing owner will pick it up.
12925 		 */
12926 		if (!idle_cpu(this_cpu) && need_resched()) {
12927 			if (flags & NOHZ_STATS_KICK)
12928 				has_blocked_load = true;
12929 			if (flags & NOHZ_NEXT_KICK)
12930 				WRITE_ONCE(nohz.needs_update, 1);
12931 			goto abort;
12932 		}
12933 
12934 		rq = cpu_rq(balance_cpu);
12935 
12936 		if (flags & NOHZ_STATS_KICK)
12937 			has_blocked_load |= update_nohz_stats(rq);
12938 
12939 		/*
12940 		 * If time for next balance is due,
12941 		 * do the balance.
12942 		 */
12943 		if (time_after_eq(jiffies, rq->next_balance)) {
12944 			struct rq_flags rf;
12945 
12946 			rq_lock_irqsave(rq, &rf);
12947 			update_rq_clock(rq);
12948 			rq_unlock_irqrestore(rq, &rf);
12949 
12950 			if (flags & NOHZ_BALANCE_KICK)
12951 				sched_balance_domains(rq, CPU_IDLE);
12952 		}
12953 
12954 		if (time_after(next_balance, rq->next_balance)) {
12955 			next_balance = rq->next_balance;
12956 			update_next_balance = 1;
12957 		}
12958 	}
12959 
12960 	/*
12961 	 * next_balance will be updated only when there is a need.
12962 	 * When the CPU is attached to null domain for ex, it will not be
12963 	 * updated.
12964 	 */
12965 	if (likely(update_next_balance))
12966 		nohz.next_balance = next_balance;
12967 
12968 	if (flags & NOHZ_STATS_KICK)
12969 		WRITE_ONCE(nohz.next_blocked,
12970 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12971 
12972 abort:
12973 	/* There is still blocked load, enable periodic update */
12974 	if (has_blocked_load)
12975 		WRITE_ONCE(nohz.has_blocked, 1);
12976 }
12977 
12978 /*
12979  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12980  * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12981  */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12982 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12983 {
12984 	unsigned int flags = this_rq->nohz_idle_balance;
12985 
12986 	if (!flags)
12987 		return false;
12988 
12989 	this_rq->nohz_idle_balance = 0;
12990 
12991 	if (idle != CPU_IDLE)
12992 		return false;
12993 
12994 	_nohz_idle_balance(this_rq, flags);
12995 
12996 	return true;
12997 }
12998 
12999 /*
13000  * Check if we need to directly run the ILB for updating blocked load before
13001  * entering idle state. Here we run ILB directly without issuing IPIs.
13002  *
13003  * Note that when this function is called, the tick may not yet be stopped on
13004  * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
13005  * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
13006  * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
13007  * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
13008  * called from this function on (this) CPU that's not yet in the mask. That's
13009  * OK because the goal of nohz_run_idle_balance() is to run ILB only for
13010  * updating the blocked load of already idle CPUs without waking up one of
13011  * those idle CPUs and outside the preempt disable / IRQ off phase of the local
13012  * cpu about to enter idle, because it can take a long time.
13013  */
nohz_run_idle_balance(int cpu)13014 void nohz_run_idle_balance(int cpu)
13015 {
13016 	unsigned int flags;
13017 
13018 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
13019 
13020 	/*
13021 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
13022 	 * (i.e. NOHZ_STATS_KICK set) and will do the same.
13023 	 */
13024 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
13025 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
13026 }
13027 
nohz_newidle_balance(struct rq * this_rq)13028 static void nohz_newidle_balance(struct rq *this_rq)
13029 {
13030 	int this_cpu = this_rq->cpu;
13031 
13032 	/*
13033 	 * This CPU doesn't want to be disturbed by scheduler
13034 	 * housekeeping
13035 	 */
13036 	if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
13037 		return;
13038 
13039 	/* Will wake up very soon. No time for doing anything else*/
13040 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
13041 		return;
13042 
13043 	/* Don't need to update blocked load of idle CPUs*/
13044 	if (!READ_ONCE(nohz.has_blocked) ||
13045 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
13046 		return;
13047 
13048 	/*
13049 	 * Set the need to trigger ILB in order to update blocked load
13050 	 * before entering idle state.
13051 	 */
13052 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
13053 }
13054 
13055 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)13056 static inline void nohz_balancer_kick(struct rq *rq) { }
13057 
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)13058 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
13059 {
13060 	return false;
13061 }
13062 
nohz_newidle_balance(struct rq * this_rq)13063 static inline void nohz_newidle_balance(struct rq *this_rq) { }
13064 #endif /* CONFIG_NO_HZ_COMMON */
13065 
13066 /*
13067  * sched_balance_newidle is called by schedule() if this_cpu is about to become
13068  * idle. Attempts to pull tasks from other CPUs.
13069  *
13070  * Returns:
13071  *   < 0 - we released the lock and there are !fair tasks present
13072  *     0 - failed, no new tasks
13073  *   > 0 - success, new (fair) tasks present
13074  */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)13075 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
13076 {
13077 	unsigned long next_balance = jiffies + HZ;
13078 	int this_cpu = this_rq->cpu;
13079 	int continue_balancing = 1;
13080 	u64 t0, t1, curr_cost = 0;
13081 	struct sched_domain *sd;
13082 	int pulled_task = 0;
13083 	int done = 0;
13084 
13085 	trace_android_rvh_sched_newidle_balance(this_rq, rf, &pulled_task, &done);
13086 	if (done)
13087 		return pulled_task;
13088 
13089 	update_misfit_status(NULL, this_rq);
13090 
13091 	/*
13092 	 * There is a task waiting to run. No need to search for one.
13093 	 * Return 0; the task will be enqueued when switching to idle.
13094 	 */
13095 	if (this_rq->ttwu_pending)
13096 		return 0;
13097 
13098 	/*
13099 	 * We must set idle_stamp _before_ calling sched_balance_rq()
13100 	 * for CPU_NEWLY_IDLE, such that we measure the this duration
13101 	 * as idle time.
13102 	 */
13103 	this_rq->idle_stamp = rq_clock(this_rq);
13104 
13105 	/*
13106 	 * Do not pull tasks towards !active CPUs...
13107 	 */
13108 	if (!cpu_active(this_cpu))
13109 		return 0;
13110 
13111 	/*
13112 	 * This is OK, because current is on_cpu, which avoids it being picked
13113 	 * for load-balance and preemption/IRQs are still disabled avoiding
13114 	 * further scheduler activity on it and we're being very careful to
13115 	 * re-start the picking loop.
13116 	 */
13117 	rq_unpin_lock(this_rq, rf);
13118 
13119 	rcu_read_lock();
13120 	sd = rcu_dereference_check_sched_domain(this_rq->sd);
13121 
13122 	if (!get_rd_overloaded(this_rq->rd) ||
13123 	    (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
13124 
13125 		if (sd)
13126 			update_next_balance(sd, &next_balance);
13127 		rcu_read_unlock();
13128 
13129 		goto out;
13130 	}
13131 	rcu_read_unlock();
13132 
13133 	raw_spin_rq_unlock(this_rq);
13134 
13135 	t0 = sched_clock_cpu(this_cpu);
13136 	sched_balance_update_blocked_averages(this_cpu);
13137 
13138 	rcu_read_lock();
13139 	for_each_domain(this_cpu, sd) {
13140 		u64 domain_cost;
13141 
13142 		update_next_balance(sd, &next_balance);
13143 
13144 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
13145 			break;
13146 
13147 		if (sd->flags & SD_BALANCE_NEWIDLE) {
13148 
13149 			pulled_task = sched_balance_rq(this_cpu, this_rq,
13150 						   sd, CPU_NEWLY_IDLE,
13151 						   &continue_balancing);
13152 
13153 			t1 = sched_clock_cpu(this_cpu);
13154 			domain_cost = t1 - t0;
13155 			curr_cost += domain_cost;
13156 			t0 = t1;
13157 
13158 			/*
13159 			 * Failing newidle means it is not effective;
13160 			 * bump the cost so we end up doing less of it.
13161 			 */
13162 			if (!pulled_task)
13163 				domain_cost = (3 * sd->max_newidle_lb_cost) / 2;
13164 
13165 			update_newidle_cost(sd, domain_cost);
13166 		}
13167 
13168 		/*
13169 		 * Stop searching for tasks to pull if there are
13170 		 * now runnable tasks on this rq.
13171 		 */
13172 		if (pulled_task || !continue_balancing)
13173 			break;
13174 	}
13175 	rcu_read_unlock();
13176 
13177 	raw_spin_rq_lock(this_rq);
13178 
13179 	if (curr_cost > this_rq->max_idle_balance_cost)
13180 		this_rq->max_idle_balance_cost = curr_cost;
13181 
13182 	/*
13183 	 * While browsing the domains, we released the rq lock, a task could
13184 	 * have been enqueued in the meantime. Since we're not going idle,
13185 	 * pretend we pulled a task.
13186 	 */
13187 	if (this_rq->cfs.h_nr_running && !pulled_task)
13188 		pulled_task = 1;
13189 
13190 	/* Is there a task of a high priority class? */
13191 	if (this_rq->nr_running != this_rq->cfs.h_nr_running)
13192 		pulled_task = -1;
13193 
13194 out:
13195 	/* Move the next balance forward */
13196 	if (time_after(this_rq->next_balance, next_balance))
13197 		this_rq->next_balance = next_balance;
13198 
13199 	if (pulled_task)
13200 		this_rq->idle_stamp = 0;
13201 	else
13202 		nohz_newidle_balance(this_rq);
13203 
13204 	rq_repin_lock(this_rq, rf);
13205 
13206 	return pulled_task;
13207 }
13208 
13209 /*
13210  * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
13211  *
13212  * - directly from the local scheduler_tick() for periodic load balancing
13213  *
13214  * - indirectly from a remote scheduler_tick() for NOHZ idle balancing
13215  *   through the SMP cross-call nohz_csd_func()
13216  */
sched_balance_softirq(void)13217 static __latent_entropy void sched_balance_softirq(void)
13218 {
13219 	struct rq *this_rq = this_rq();
13220 	enum cpu_idle_type idle = this_rq->idle_balance;
13221 	/*
13222 	 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13223 	 * balancing on behalf of the other idle CPUs whose ticks are
13224 	 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13225 	 * give the idle CPUs a chance to load balance. Else we may
13226 	 * load balance only within the local sched_domain hierarchy
13227 	 * and abort nohz_idle_balance altogether if we pull some load.
13228 	 */
13229 	if (nohz_idle_balance(this_rq, idle))
13230 		return;
13231 
13232 	/* normal load balance */
13233 	sched_balance_update_blocked_averages(this_rq->cpu);
13234 	sched_balance_domains(this_rq, idle);
13235 }
13236 
13237 /*
13238  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13239  */
sched_balance_trigger(struct rq * rq)13240 void sched_balance_trigger(struct rq *rq)
13241 {
13242 	/*
13243 	 * Don't need to rebalance while attached to NULL domain or
13244 	 * runqueue CPU is not active
13245 	 */
13246 	if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13247 		return;
13248 
13249 	if (time_after_eq(jiffies, rq->next_balance))
13250 		raise_softirq(SCHED_SOFTIRQ);
13251 
13252 	nohz_balancer_kick(rq);
13253 }
13254 
rq_online_fair(struct rq * rq)13255 static void rq_online_fair(struct rq *rq)
13256 {
13257 	update_sysctl();
13258 
13259 	update_runtime_enabled(rq);
13260 }
13261 
rq_offline_fair(struct rq * rq)13262 static void rq_offline_fair(struct rq *rq)
13263 {
13264 	update_sysctl();
13265 
13266 	/* Ensure any throttled groups are reachable by pick_next_task */
13267 	unthrottle_offline_cfs_rqs(rq);
13268 
13269 	/* Ensure that we remove rq contribution to group share: */
13270 	clear_tg_offline_cfs_rqs(rq);
13271 }
13272 
13273 #endif /* CONFIG_SMP */
13274 
13275 #ifdef CONFIG_SCHED_CORE
13276 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13277 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13278 {
13279 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13280 	u64 slice = se->slice;
13281 
13282 	return (rtime * min_nr_tasks > slice);
13283 }
13284 
13285 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
task_tick_core(struct rq * rq,struct task_struct * curr)13286 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13287 {
13288 	if (!sched_core_enabled(rq))
13289 		return;
13290 
13291 	/*
13292 	 * If runqueue has only one task which used up its slice and
13293 	 * if the sibling is forced idle, then trigger schedule to
13294 	 * give forced idle task a chance.
13295 	 *
13296 	 * sched_slice() considers only this active rq and it gets the
13297 	 * whole slice. But during force idle, we have siblings acting
13298 	 * like a single runqueue and hence we need to consider runnable
13299 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
13300 	 * go through the forced idle rq, but that would be a perf hit.
13301 	 * We can assume that the forced idle CPU has at least
13302 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13303 	 * if we need to give up the CPU.
13304 	 */
13305 	if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
13306 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13307 		resched_curr(rq);
13308 }
13309 
13310 /*
13311  * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
13312  */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13313 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13314 			 bool forceidle)
13315 {
13316 	for_each_sched_entity(se) {
13317 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13318 
13319 		if (forceidle) {
13320 			if (cfs_rq->forceidle_seq == fi_seq)
13321 				break;
13322 			cfs_rq->forceidle_seq = fi_seq;
13323 		}
13324 
13325 		cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
13326 	}
13327 }
13328 
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13329 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13330 {
13331 	struct sched_entity *se = &p->se;
13332 
13333 	if (p->sched_class != &fair_sched_class)
13334 		return;
13335 
13336 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13337 }
13338 
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13339 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13340 			bool in_fi)
13341 {
13342 	struct rq *rq = task_rq(a);
13343 	const struct sched_entity *sea = &a->se;
13344 	const struct sched_entity *seb = &b->se;
13345 	struct cfs_rq *cfs_rqa;
13346 	struct cfs_rq *cfs_rqb;
13347 	s64 delta;
13348 
13349 	SCHED_WARN_ON(task_rq(b)->core != rq->core);
13350 
13351 #ifdef CONFIG_FAIR_GROUP_SCHED
13352 	/*
13353 	 * Find an se in the hierarchy for tasks a and b, such that the se's
13354 	 * are immediate siblings.
13355 	 */
13356 	while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13357 		int sea_depth = sea->depth;
13358 		int seb_depth = seb->depth;
13359 
13360 		if (sea_depth >= seb_depth)
13361 			sea = parent_entity(sea);
13362 		if (sea_depth <= seb_depth)
13363 			seb = parent_entity(seb);
13364 	}
13365 
13366 	se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13367 	se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13368 
13369 	cfs_rqa = sea->cfs_rq;
13370 	cfs_rqb = seb->cfs_rq;
13371 #else
13372 	cfs_rqa = &task_rq(a)->cfs;
13373 	cfs_rqb = &task_rq(b)->cfs;
13374 #endif
13375 
13376 	/*
13377 	 * Find delta after normalizing se's vruntime with its cfs_rq's
13378 	 * min_vruntime_fi, which would have been updated in prior calls
13379 	 * to se_fi_update().
13380 	 */
13381 	delta = (s64)(sea->vruntime - seb->vruntime) +
13382 		(s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
13383 
13384 	return delta > 0;
13385 }
13386 
task_is_throttled_fair(struct task_struct * p,int cpu)13387 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13388 {
13389 	struct cfs_rq *cfs_rq;
13390 
13391 #ifdef CONFIG_FAIR_GROUP_SCHED
13392 	cfs_rq = task_group(p)->cfs_rq[cpu];
13393 #else
13394 	cfs_rq = &cpu_rq(cpu)->cfs;
13395 #endif
13396 	return throttled_hierarchy(cfs_rq);
13397 }
13398 #else
task_tick_core(struct rq * rq,struct task_struct * curr)13399 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13400 #endif
13401 
13402 /*
13403  * scheduler tick hitting a task of our scheduling class.
13404  *
13405  * NOTE: This function can be called remotely by the tick offload that
13406  * goes along full dynticks. Therefore no local assumption can be made
13407  * and everything must be accessed through the @rq and @curr passed in
13408  * parameters.
13409  */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13410 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13411 {
13412 	struct cfs_rq *cfs_rq;
13413 	struct sched_entity *se = &curr->se;
13414 
13415 	for_each_sched_entity(se) {
13416 		cfs_rq = cfs_rq_of(se);
13417 		entity_tick(cfs_rq, se, queued);
13418 	}
13419 
13420 	if (static_branch_unlikely(&sched_numa_balancing))
13421 		task_tick_numa(rq, curr);
13422 
13423 	update_misfit_status(curr, rq);
13424 	check_update_overutilized_status(task_rq(curr));
13425 
13426 	task_tick_core(rq, curr);
13427 }
13428 
13429 /*
13430  * called on fork with the child task as argument from the parent's context
13431  *  - child not yet on the tasklist
13432  *  - preemption disabled
13433  */
task_fork_fair(struct task_struct * p)13434 static void task_fork_fair(struct task_struct *p)
13435 {
13436 	set_task_max_allowed_capacity(p);
13437 }
13438 
13439 /*
13440  * Priority of the task has changed. Check to see if we preempt
13441  * the current task.
13442  */
13443 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)13444 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
13445 {
13446 	if (!task_on_rq_queued(p))
13447 		return;
13448 
13449 	if (rq->cfs.nr_running == 1)
13450 		return;
13451 
13452 	/*
13453 	 * Reschedule if we are currently running on this runqueue and
13454 	 * our priority decreased, or if we are not currently running on
13455 	 * this runqueue and our priority is higher than the current's
13456 	 */
13457 	if (task_current_donor(rq, p)) {
13458 		if (p->prio > oldprio)
13459 			resched_curr(rq);
13460 	} else
13461 		wakeup_preempt(rq, p, 0);
13462 }
13463 
13464 #ifdef CONFIG_FAIR_GROUP_SCHED
13465 /*
13466  * Propagate the changes of the sched_entity across the tg tree to make it
13467  * visible to the root
13468  */
propagate_entity_cfs_rq(struct sched_entity * se)13469 static void propagate_entity_cfs_rq(struct sched_entity *se)
13470 {
13471 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13472 
13473 	if (cfs_rq_throttled(cfs_rq))
13474 		return;
13475 
13476 	if (!throttled_hierarchy(cfs_rq))
13477 		list_add_leaf_cfs_rq(cfs_rq);
13478 
13479 	/* Start to propagate at parent */
13480 	se = se->parent;
13481 
13482 	for_each_sched_entity(se) {
13483 		cfs_rq = cfs_rq_of(se);
13484 
13485 		update_load_avg(cfs_rq, se, UPDATE_TG);
13486 
13487 		if (cfs_rq_throttled(cfs_rq))
13488 			break;
13489 
13490 		if (!throttled_hierarchy(cfs_rq))
13491 			list_add_leaf_cfs_rq(cfs_rq);
13492 	}
13493 }
13494 #else
propagate_entity_cfs_rq(struct sched_entity * se)13495 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13496 #endif
13497 
detach_entity_cfs_rq(struct sched_entity * se)13498 static void detach_entity_cfs_rq(struct sched_entity *se)
13499 {
13500 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13501 
13502 #ifdef CONFIG_SMP
13503 	/*
13504 	 * In case the task sched_avg hasn't been attached:
13505 	 * - A forked task which hasn't been woken up by wake_up_new_task().
13506 	 * - A task which has been woken up by try_to_wake_up() but is
13507 	 *   waiting for actually being woken up by sched_ttwu_pending().
13508 	 */
13509 	if (!se->avg.last_update_time)
13510 		return;
13511 #endif
13512 
13513 	/* Catch up with the cfs_rq and remove our load when we leave */
13514 	update_load_avg(cfs_rq, se, 0);
13515 	detach_entity_load_avg(cfs_rq, se);
13516 	update_tg_load_avg(cfs_rq);
13517 	propagate_entity_cfs_rq(se);
13518 }
13519 
attach_entity_cfs_rq(struct sched_entity * se)13520 static void attach_entity_cfs_rq(struct sched_entity *se)
13521 {
13522 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13523 
13524 	/* Synchronize entity with its cfs_rq */
13525 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13526 	attach_entity_load_avg(cfs_rq, se);
13527 	update_tg_load_avg(cfs_rq);
13528 	propagate_entity_cfs_rq(se);
13529 }
13530 
detach_task_cfs_rq(struct task_struct * p)13531 static void detach_task_cfs_rq(struct task_struct *p)
13532 {
13533 	struct sched_entity *se = &p->se;
13534 
13535 	detach_entity_cfs_rq(se);
13536 }
13537 
attach_task_cfs_rq(struct task_struct * p)13538 static void attach_task_cfs_rq(struct task_struct *p)
13539 {
13540 	struct sched_entity *se = &p->se;
13541 
13542 	attach_entity_cfs_rq(se);
13543 }
13544 
switched_from_fair(struct rq * rq,struct task_struct * p)13545 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13546 {
13547 	detach_task_cfs_rq(p);
13548 }
13549 
switched_to_fair(struct rq * rq,struct task_struct * p)13550 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13551 {
13552 	SCHED_WARN_ON(p->se.sched_delayed);
13553 
13554 	attach_task_cfs_rq(p);
13555 
13556 	set_task_max_allowed_capacity(p);
13557 
13558 	if (task_on_rq_queued(p)) {
13559 		/*
13560 		 * We were most likely switched from sched_rt, so
13561 		 * kick off the schedule if running, otherwise just see
13562 		 * if we can still preempt the current task.
13563 		 */
13564 		if (task_current_donor(rq, p))
13565 			resched_curr(rq);
13566 		else
13567 			wakeup_preempt(rq, p, 0);
13568 	}
13569 }
13570 
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13571 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13572 {
13573 	struct sched_entity *se = &p->se;
13574 
13575 #ifdef CONFIG_SMP
13576 	if (task_on_rq_queued(p)) {
13577 		/*
13578 		 * Move the next running task to the front of the list, so our
13579 		 * cfs_tasks list becomes MRU one.
13580 		 */
13581 		list_move(&se->group_node, &rq->cfs_tasks);
13582 	}
13583 #endif
13584 	if (!first)
13585 		return;
13586 
13587 	SCHED_WARN_ON(se->sched_delayed);
13588 
13589 	if (hrtick_enabled_fair(rq))
13590 		hrtick_start_fair(rq, p);
13591 
13592 	update_misfit_status(p, rq);
13593 	sched_fair_update_stop_tick(rq, p);
13594 }
13595 
13596 /*
13597  * Account for a task changing its policy or group.
13598  *
13599  * This routine is mostly called to set cfs_rq->curr field when a task
13600  * migrates between groups/classes.
13601  */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13602 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13603 {
13604 	struct sched_entity *se = &p->se;
13605 
13606 	for_each_sched_entity(se) {
13607 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13608 
13609 		set_next_entity(cfs_rq, se);
13610 		/* ensure bandwidth has been allocated on our new cfs_rq */
13611 		account_cfs_rq_runtime(cfs_rq, 0);
13612 	}
13613 
13614 	__set_next_task_fair(rq, p, first);
13615 }
13616 
init_cfs_rq(struct cfs_rq * cfs_rq)13617 void init_cfs_rq(struct cfs_rq *cfs_rq)
13618 {
13619 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13620 	cfs_rq->min_vruntime = (u64)(-(1LL << 20));
13621 #ifdef CONFIG_SMP
13622 	raw_spin_lock_init(&cfs_rq->removed.lock);
13623 #endif
13624 }
13625 
13626 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13627 static void task_change_group_fair(struct task_struct *p)
13628 {
13629 	/*
13630 	 * We couldn't detach or attach a forked task which
13631 	 * hasn't been woken up by wake_up_new_task().
13632 	 */
13633 	if (READ_ONCE(p->__state) == TASK_NEW)
13634 		return;
13635 
13636 	detach_task_cfs_rq(p);
13637 
13638 #ifdef CONFIG_SMP
13639 	/* Tell se's cfs_rq has been changed -- migrated */
13640 	p->se.avg.last_update_time = 0;
13641 #endif
13642 	set_task_rq(p, task_cpu(p));
13643 	attach_task_cfs_rq(p);
13644 }
13645 
free_fair_sched_group(struct task_group * tg)13646 void free_fair_sched_group(struct task_group *tg)
13647 {
13648 	int i;
13649 
13650 	for_each_possible_cpu(i) {
13651 		if (tg->cfs_rq)
13652 			kfree(tg->cfs_rq[i]);
13653 		if (tg->se)
13654 			kfree(tg->se[i]);
13655 	}
13656 
13657 	kfree(tg->cfs_rq);
13658 	kfree(tg->se);
13659 }
13660 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13661 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13662 {
13663 	struct sched_entity *se;
13664 	struct cfs_rq *cfs_rq;
13665 	int i;
13666 
13667 	tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13668 	if (!tg->cfs_rq)
13669 		goto err;
13670 	tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13671 	if (!tg->se)
13672 		goto err;
13673 
13674 	tg->shares = NICE_0_LOAD;
13675 
13676 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13677 
13678 	for_each_possible_cpu(i) {
13679 		cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13680 				      GFP_KERNEL, cpu_to_node(i));
13681 		if (!cfs_rq)
13682 			goto err;
13683 
13684 		se = kzalloc_node(sizeof(struct sched_entity_stats),
13685 				  GFP_KERNEL, cpu_to_node(i));
13686 		if (!se)
13687 			goto err_free_rq;
13688 
13689 		init_cfs_rq(cfs_rq);
13690 		init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13691 		init_entity_runnable_average(se);
13692 	}
13693 
13694 	return 1;
13695 
13696 err_free_rq:
13697 	kfree(cfs_rq);
13698 err:
13699 	return 0;
13700 }
13701 
online_fair_sched_group(struct task_group * tg)13702 void online_fair_sched_group(struct task_group *tg)
13703 {
13704 	struct sched_entity *se;
13705 	struct rq_flags rf;
13706 	struct rq *rq;
13707 	int i;
13708 
13709 	for_each_possible_cpu(i) {
13710 		rq = cpu_rq(i);
13711 		se = tg->se[i];
13712 		rq_lock_irq(rq, &rf);
13713 		update_rq_clock(rq);
13714 		attach_entity_cfs_rq(se);
13715 		sync_throttle(tg, i);
13716 		rq_unlock_irq(rq, &rf);
13717 	}
13718 }
13719 
unregister_fair_sched_group(struct task_group * tg)13720 void unregister_fair_sched_group(struct task_group *tg)
13721 {
13722 	int cpu;
13723 
13724 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13725 
13726 	for_each_possible_cpu(cpu) {
13727 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13728 		struct sched_entity *se = tg->se[cpu];
13729 		struct rq *rq = cpu_rq(cpu);
13730 
13731 		if (se) {
13732 			if (se->sched_delayed) {
13733 				guard(rq_lock_irqsave)(rq);
13734 				if (se->sched_delayed) {
13735 					update_rq_clock(rq);
13736 					dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13737 				}
13738 				list_del_leaf_cfs_rq(cfs_rq);
13739 			}
13740 			remove_entity_load_avg(se);
13741 		}
13742 
13743 		/*
13744 		 * Only empty task groups can be destroyed; so we can speculatively
13745 		 * check on_list without danger of it being re-added.
13746 		 */
13747 		if (cfs_rq->on_list) {
13748 			guard(rq_lock_irqsave)(rq);
13749 			list_del_leaf_cfs_rq(cfs_rq);
13750 		}
13751 	}
13752 }
13753 
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13754 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13755 			struct sched_entity *se, int cpu,
13756 			struct sched_entity *parent)
13757 {
13758 	struct rq *rq = cpu_rq(cpu);
13759 
13760 	cfs_rq->tg = tg;
13761 	cfs_rq->rq = rq;
13762 	init_cfs_rq_runtime(cfs_rq);
13763 
13764 	tg->cfs_rq[cpu] = cfs_rq;
13765 	tg->se[cpu] = se;
13766 
13767 	/* se could be NULL for root_task_group */
13768 	if (!se)
13769 		return;
13770 
13771 	if (!parent) {
13772 		se->cfs_rq = &rq->cfs;
13773 		se->depth = 0;
13774 	} else {
13775 		se->cfs_rq = parent->my_q;
13776 		se->depth = parent->depth + 1;
13777 	}
13778 
13779 	se->my_q = cfs_rq;
13780 	/* guarantee group entities always have weight */
13781 	update_load_set(&se->load, NICE_0_LOAD);
13782 	se->parent = parent;
13783 }
13784 
13785 static DEFINE_MUTEX(shares_mutex);
13786 
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13787 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13788 {
13789 	int i;
13790 
13791 	lockdep_assert_held(&shares_mutex);
13792 
13793 	/*
13794 	 * We can't change the weight of the root cgroup.
13795 	 */
13796 	if (!tg->se[0])
13797 		return -EINVAL;
13798 
13799 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13800 
13801 	if (tg->shares == shares)
13802 		return 0;
13803 
13804 	tg->shares = shares;
13805 	for_each_possible_cpu(i) {
13806 		struct rq *rq = cpu_rq(i);
13807 		struct sched_entity *se = tg->se[i];
13808 		struct rq_flags rf;
13809 
13810 		/* Propagate contribution to hierarchy */
13811 		rq_lock_irqsave(rq, &rf);
13812 		update_rq_clock(rq);
13813 		for_each_sched_entity(se) {
13814 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13815 			update_cfs_group(se);
13816 		}
13817 		rq_unlock_irqrestore(rq, &rf);
13818 	}
13819 
13820 	return 0;
13821 }
13822 
sched_group_set_shares(struct task_group * tg,unsigned long shares)13823 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13824 {
13825 	int ret;
13826 
13827 	mutex_lock(&shares_mutex);
13828 	if (tg_is_idle(tg))
13829 		ret = -EINVAL;
13830 	else
13831 		ret = __sched_group_set_shares(tg, shares);
13832 	mutex_unlock(&shares_mutex);
13833 
13834 	return ret;
13835 }
13836 
sched_group_set_idle(struct task_group * tg,long idle)13837 int sched_group_set_idle(struct task_group *tg, long idle)
13838 {
13839 	int i;
13840 
13841 	if (tg == &root_task_group)
13842 		return -EINVAL;
13843 
13844 	if (idle < 0 || idle > 1)
13845 		return -EINVAL;
13846 
13847 	mutex_lock(&shares_mutex);
13848 
13849 	if (tg->idle == idle) {
13850 		mutex_unlock(&shares_mutex);
13851 		return 0;
13852 	}
13853 
13854 	tg->idle = idle;
13855 
13856 	for_each_possible_cpu(i) {
13857 		struct rq *rq = cpu_rq(i);
13858 		struct sched_entity *se = tg->se[i];
13859 		struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
13860 		bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13861 		long idle_task_delta;
13862 		struct rq_flags rf;
13863 
13864 		rq_lock_irqsave(rq, &rf);
13865 
13866 		grp_cfs_rq->idle = idle;
13867 		if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13868 			goto next_cpu;
13869 
13870 		if (se->on_rq) {
13871 			parent_cfs_rq = cfs_rq_of(se);
13872 			if (cfs_rq_is_idle(grp_cfs_rq))
13873 				parent_cfs_rq->idle_nr_running++;
13874 			else
13875 				parent_cfs_rq->idle_nr_running--;
13876 		}
13877 
13878 		idle_task_delta = grp_cfs_rq->h_nr_running -
13879 				  grp_cfs_rq->idle_h_nr_running;
13880 		if (!cfs_rq_is_idle(grp_cfs_rq))
13881 			idle_task_delta *= -1;
13882 
13883 		for_each_sched_entity(se) {
13884 			struct cfs_rq *cfs_rq = cfs_rq_of(se);
13885 
13886 			if (!se->on_rq)
13887 				break;
13888 
13889 			cfs_rq->idle_h_nr_running += idle_task_delta;
13890 
13891 			/* Already accounted at parent level and above. */
13892 			if (cfs_rq_is_idle(cfs_rq))
13893 				break;
13894 		}
13895 
13896 next_cpu:
13897 		rq_unlock_irqrestore(rq, &rf);
13898 	}
13899 
13900 	/* Idle groups have minimum weight. */
13901 	if (tg_is_idle(tg))
13902 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13903 	else
13904 		__sched_group_set_shares(tg, NICE_0_LOAD);
13905 
13906 	mutex_unlock(&shares_mutex);
13907 	return 0;
13908 }
13909 
13910 #endif /* CONFIG_FAIR_GROUP_SCHED */
13911 
13912 
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13913 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13914 {
13915 	struct sched_entity *se = &task->se;
13916 	unsigned int rr_interval = 0;
13917 
13918 	/*
13919 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13920 	 * idle runqueue:
13921 	 */
13922 	if (rq->cfs.load.weight)
13923 		rr_interval = NS_TO_JIFFIES(se->slice);
13924 
13925 	return rr_interval;
13926 }
13927 
13928 /*
13929  * All the scheduling class methods:
13930  */
13931 DEFINE_SCHED_CLASS(fair) = {
13932 
13933 	.enqueue_task		= enqueue_task_fair,
13934 	.dequeue_task		= dequeue_task_fair,
13935 	.yield_task		= yield_task_fair,
13936 	.yield_to_task		= yield_to_task_fair,
13937 
13938 	.wakeup_preempt		= check_preempt_wakeup_fair,
13939 
13940 	.pick_task		= pick_task_fair,
13941 	.pick_next_task		= __pick_next_task_fair,
13942 	.put_prev_task		= put_prev_task_fair,
13943 	.set_next_task          = set_next_task_fair,
13944 
13945 #ifdef CONFIG_SMP
13946 	.balance		= balance_fair,
13947 	.select_task_rq		= select_task_rq_fair,
13948 	.migrate_task_rq	= migrate_task_rq_fair,
13949 
13950 	.rq_online		= rq_online_fair,
13951 	.rq_offline		= rq_offline_fair,
13952 
13953 	.task_dead		= task_dead_fair,
13954 	.set_cpus_allowed	= set_cpus_allowed_fair,
13955 #endif
13956 
13957 	.task_tick		= task_tick_fair,
13958 	.task_fork		= task_fork_fair,
13959 
13960 	.reweight_task		= reweight_task_fair,
13961 	.prio_changed		= prio_changed_fair,
13962 	.switched_from		= switched_from_fair,
13963 	.switched_to		= switched_to_fair,
13964 
13965 	.get_rr_interval	= get_rr_interval_fair,
13966 
13967 	.update_curr		= update_curr_fair,
13968 
13969 #ifdef CONFIG_FAIR_GROUP_SCHED
13970 	.task_change_group	= task_change_group_fair,
13971 #endif
13972 
13973 #ifdef CONFIG_SCHED_CORE
13974 	.task_is_throttled	= task_is_throttled_fair,
13975 #endif
13976 
13977 #ifdef CONFIG_UCLAMP_TASK
13978 	.uclamp_enabled		= 1,
13979 #endif
13980 };
13981 
13982 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)13983 void print_cfs_stats(struct seq_file *m, int cpu)
13984 {
13985 	struct cfs_rq *cfs_rq, *pos;
13986 
13987 	rcu_read_lock();
13988 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13989 		print_cfs_rq(m, cpu, cfs_rq);
13990 	rcu_read_unlock();
13991 }
13992 
13993 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13994 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13995 {
13996 	int node;
13997 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13998 	struct numa_group *ng;
13999 
14000 	rcu_read_lock();
14001 	ng = rcu_dereference(p->numa_group);
14002 	for_each_online_node(node) {
14003 		if (p->numa_faults) {
14004 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
14005 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
14006 		}
14007 		if (ng) {
14008 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
14009 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
14010 		}
14011 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
14012 	}
14013 	rcu_read_unlock();
14014 }
14015 #endif /* CONFIG_NUMA_BALANCING */
14016 #endif /* CONFIG_SCHED_DEBUG */
14017 
init_sched_fair_class(void)14018 __init void init_sched_fair_class(void)
14019 {
14020 #ifdef CONFIG_SMP
14021 	int i;
14022 
14023 	for_each_possible_cpu(i) {
14024 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
14025 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
14026 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
14027 					GFP_KERNEL, cpu_to_node(i));
14028 
14029 #ifdef CONFIG_CFS_BANDWIDTH
14030 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
14031 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
14032 #endif
14033 	}
14034 
14035 	open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
14036 
14037 #ifdef CONFIG_NO_HZ_COMMON
14038 	nohz.next_balance = jiffies;
14039 	nohz.next_blocked = jiffies;
14040 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
14041 #endif
14042 #endif /* SMP */
14043 
14044 }
14045