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