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