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