• 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  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3411  * propagate its contribution. The key to this propagation is the invariant
3412  * that for each group:
3413  *
3414  *   ge->avg == grq->avg						(1)
3415  *
3416  * _IFF_ we look at the pure running and runnable sums. Because they
3417  * represent the very same entity, just at different points in the hierarchy.
3418  *
3419  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
3420  * and simply copies the running/runnable sum over (but still wrong, because
3421  * the group entity and group rq do not have their PELT windows aligned).
3422  *
3423  * However, update_tg_cfs_load() is more complex. So we have:
3424  *
3425  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
3426  *
3427  * And since, like util, the runnable part should be directly transferable,
3428  * the following would _appear_ to be the straight forward approach:
3429  *
3430  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
3431  *
3432  * And per (1) we have:
3433  *
3434  *   ge->avg.runnable_avg == grq->avg.runnable_avg
3435  *
3436  * Which gives:
3437  *
3438  *                      ge->load.weight * grq->avg.load_avg
3439  *   ge->avg.load_avg = -----------------------------------		(4)
3440  *                               grq->load.weight
3441  *
3442  * Except that is wrong!
3443  *
3444  * Because while for entities historical weight is not important and we
3445  * really only care about our future and therefore can consider a pure
3446  * runnable sum, runqueues can NOT do this.
3447  *
3448  * We specifically want runqueues to have a load_avg that includes
3449  * historical weights. Those represent the blocked load, the load we expect
3450  * to (shortly) return to us. This only works by keeping the weights as
3451  * integral part of the sum. We therefore cannot decompose as per (3).
3452  *
3453  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
3454  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
3455  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
3456  * runnable section of these tasks overlap (or not). If they were to perfectly
3457  * align the rq as a whole would be runnable 2/3 of the time. If however we
3458  * always have at least 1 runnable task, the rq as a whole is always runnable.
3459  *
3460  * So we'll have to approximate.. :/
3461  *
3462  * Given the constraint:
3463  *
3464  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
3465  *
3466  * We can construct a rule that adds runnable to a rq by assuming minimal
3467  * overlap.
3468  *
3469  * On removal, we'll assume each task is equally runnable; which yields:
3470  *
3471  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
3472  *
3473  * XXX: only do this for the part of runnable > running ?
3474  *
3475  */
3476 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)3477 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3478 {
3479 	long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
3480 	u32 divider;
3481 
3482 	/* Nothing to update */
3483 	if (!delta)
3484 		return;
3485 
3486 	/*
3487 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3488 	 * See ___update_load_avg() for details.
3489 	 */
3490 	divider = get_pelt_divider(&cfs_rq->avg);
3491 
3492 	/* Set new sched_entity's utilization */
3493 	se->avg.util_avg = gcfs_rq->avg.util_avg;
3494 	se->avg.util_sum = se->avg.util_avg * divider;
3495 
3496 	/* Update parent cfs_rq utilization */
3497 	add_positive(&cfs_rq->avg.util_avg, delta);
3498 	cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * divider;
3499 }
3500 
3501 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)3502 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3503 {
3504 	long delta = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
3505 	u32 divider;
3506 
3507 	/* Nothing to update */
3508 	if (!delta)
3509 		return;
3510 
3511 	/*
3512 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3513 	 * See ___update_load_avg() for details.
3514 	 */
3515 	divider = get_pelt_divider(&cfs_rq->avg);
3516 
3517 	/* Set new sched_entity's runnable */
3518 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
3519 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
3520 
3521 	/* Update parent cfs_rq runnable */
3522 	add_positive(&cfs_rq->avg.runnable_avg, delta);
3523 	cfs_rq->avg.runnable_sum = cfs_rq->avg.runnable_avg * divider;
3524 }
3525 
3526 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)3527 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3528 {
3529 	long delta, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
3530 	unsigned long load_avg;
3531 	u64 load_sum = 0;
3532 	u32 divider;
3533 
3534 	if (!runnable_sum)
3535 		return;
3536 
3537 	gcfs_rq->prop_runnable_sum = 0;
3538 
3539 	/*
3540 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3541 	 * See ___update_load_avg() for details.
3542 	 */
3543 	divider = get_pelt_divider(&cfs_rq->avg);
3544 
3545 	if (runnable_sum >= 0) {
3546 		/*
3547 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
3548 		 * the CPU is saturated running == runnable.
3549 		 */
3550 		runnable_sum += se->avg.load_sum;
3551 		runnable_sum = min_t(long, runnable_sum, divider);
3552 	} else {
3553 		/*
3554 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
3555 		 * assuming all tasks are equally runnable.
3556 		 */
3557 		if (scale_load_down(gcfs_rq->load.weight)) {
3558 			load_sum = div_s64(gcfs_rq->avg.load_sum,
3559 				scale_load_down(gcfs_rq->load.weight));
3560 		}
3561 
3562 		/* But make sure to not inflate se's runnable */
3563 		runnable_sum = min(se->avg.load_sum, load_sum);
3564 	}
3565 
3566 	/*
3567 	 * runnable_sum can't be lower than running_sum
3568 	 * Rescale running sum to be in the same range as runnable sum
3569 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
3570 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
3571 	 */
3572 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
3573 	runnable_sum = max(runnable_sum, running_sum);
3574 
3575 	load_sum = (s64)se_weight(se) * runnable_sum;
3576 	load_avg = div_s64(load_sum, divider);
3577 
3578 	delta = load_avg - se->avg.load_avg;
3579 
3580 	se->avg.load_sum = runnable_sum;
3581 	se->avg.load_avg = load_avg;
3582 
3583 	add_positive(&cfs_rq->avg.load_avg, delta);
3584 	cfs_rq->avg.load_sum = cfs_rq->avg.load_avg * divider;
3585 }
3586 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)3587 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
3588 {
3589 	cfs_rq->propagate = 1;
3590 	cfs_rq->prop_runnable_sum += runnable_sum;
3591 }
3592 
3593 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)3594 static inline int propagate_entity_load_avg(struct sched_entity *se)
3595 {
3596 	struct cfs_rq *cfs_rq, *gcfs_rq;
3597 
3598 	if (entity_is_task(se))
3599 		return 0;
3600 
3601 	gcfs_rq = group_cfs_rq(se);
3602 	if (!gcfs_rq->propagate)
3603 		return 0;
3604 
3605 	gcfs_rq->propagate = 0;
3606 
3607 	cfs_rq = cfs_rq_of(se);
3608 
3609 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
3610 
3611 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
3612 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
3613 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
3614 
3615 	trace_pelt_cfs_tp(cfs_rq);
3616 	trace_pelt_se_tp(se);
3617 
3618 	return 1;
3619 }
3620 
3621 /*
3622  * Check if we need to update the load and the utilization of a blocked
3623  * group_entity:
3624  */
skip_blocked_update(struct sched_entity * se)3625 static inline bool skip_blocked_update(struct sched_entity *se)
3626 {
3627 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3628 
3629 	/*
3630 	 * If sched_entity still have not zero load or utilization, we have to
3631 	 * decay it:
3632 	 */
3633 	if (se->avg.load_avg || se->avg.util_avg)
3634 		return false;
3635 
3636 	/*
3637 	 * If there is a pending propagation, we have to update the load and
3638 	 * the utilization of the sched_entity:
3639 	 */
3640 	if (gcfs_rq->propagate)
3641 		return false;
3642 
3643 	/*
3644 	 * Otherwise, the load and the utilization of the sched_entity is
3645 	 * already zero and there is no pending propagation, so it will be a
3646 	 * waste of time to try to decay it:
3647 	 */
3648 	return true;
3649 }
3650 
3651 #else /* CONFIG_FAIR_GROUP_SCHED */
3652 
update_tg_load_avg(struct cfs_rq * cfs_rq)3653 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
3654 
propagate_entity_load_avg(struct sched_entity * se)3655 static inline int propagate_entity_load_avg(struct sched_entity *se)
3656 {
3657 	return 0;
3658 }
3659 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)3660 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
3661 
3662 #endif /* CONFIG_FAIR_GROUP_SCHED */
3663 
3664 /**
3665  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3666  * @now: current time, as per cfs_rq_clock_pelt()
3667  * @cfs_rq: cfs_rq to update
3668  *
3669  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3670  * avg. The immediate corollary is that all (fair) tasks must be attached, see
3671  * post_init_entity_util_avg().
3672  *
3673  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3674  *
3675  * Returns true if the load decayed or we removed load.
3676  *
3677  * Since both these conditions indicate a changed cfs_rq->avg.load we should
3678  * call update_tg_load_avg() when this function returns true.
3679  */
3680 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)3681 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
3682 {
3683 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
3684 	struct sched_avg *sa = &cfs_rq->avg;
3685 	int decayed = 0;
3686 
3687 	if (cfs_rq->removed.nr) {
3688 		unsigned long r;
3689 		u32 divider = get_pelt_divider(&cfs_rq->avg);
3690 
3691 		raw_spin_lock(&cfs_rq->removed.lock);
3692 		swap(cfs_rq->removed.util_avg, removed_util);
3693 		swap(cfs_rq->removed.load_avg, removed_load);
3694 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
3695 		cfs_rq->removed.nr = 0;
3696 		raw_spin_unlock(&cfs_rq->removed.lock);
3697 
3698 		r = removed_load;
3699 		sub_positive(&sa->load_avg, r);
3700 		sa->load_sum = sa->load_avg * divider;
3701 
3702 		r = removed_util;
3703 		sub_positive(&sa->util_avg, r);
3704 		sub_positive(&sa->util_sum, r * divider);
3705 		/*
3706 		 * Because of rounding, se->util_sum might ends up being +1 more than
3707 		 * cfs->util_sum. Although this is not a problem by itself, detaching
3708 		 * a lot of tasks with the rounding problem between 2 updates of
3709 		 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
3710 		 * cfs_util_avg is not.
3711 		 * Check that util_sum is still above its lower bound for the new
3712 		 * util_avg. Given that period_contrib might have moved since the last
3713 		 * sync, we are only sure that util_sum must be above or equal to
3714 		 *    util_avg * minimum possible divider
3715 		 */
3716 		sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
3717 
3718 		r = removed_runnable;
3719 		sub_positive(&sa->runnable_avg, r);
3720 		sa->runnable_sum = sa->runnable_avg * divider;
3721 
3722 		/*
3723 		 * removed_runnable is the unweighted version of removed_load so we
3724 		 * can use it to estimate removed_load_sum.
3725 		 */
3726 		add_tg_cfs_propagate(cfs_rq,
3727 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
3728 
3729 		decayed = 1;
3730 	}
3731 
3732 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
3733 
3734 #ifndef CONFIG_64BIT
3735 	smp_wmb();
3736 	cfs_rq->load_last_update_time_copy = sa->last_update_time;
3737 #endif
3738 
3739 	return decayed;
3740 }
3741 
3742 /**
3743  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3744  * @cfs_rq: cfs_rq to attach to
3745  * @se: sched_entity to attach
3746  *
3747  * Must call update_cfs_rq_load_avg() before this, since we rely on
3748  * cfs_rq->avg.last_update_time being current.
3749  */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3750 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3751 {
3752 	/*
3753 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3754 	 * See ___update_load_avg() for details.
3755 	 */
3756 	u32 divider = get_pelt_divider(&cfs_rq->avg);
3757 
3758 	/*
3759 	 * When we attach the @se to the @cfs_rq, we must align the decay
3760 	 * window because without that, really weird and wonderful things can
3761 	 * happen.
3762 	 *
3763 	 * XXX illustrate
3764 	 */
3765 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
3766 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
3767 
3768 	/*
3769 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
3770 	 * period_contrib. This isn't strictly correct, but since we're
3771 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
3772 	 * _sum a little.
3773 	 */
3774 	se->avg.util_sum = se->avg.util_avg * divider;
3775 
3776 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
3777 
3778 	se->avg.load_sum = divider;
3779 	if (se_weight(se)) {
3780 		se->avg.load_sum =
3781 			div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
3782 	}
3783 
3784 	enqueue_load_avg(cfs_rq, se);
3785 	cfs_rq->avg.util_avg += se->avg.util_avg;
3786 	cfs_rq->avg.util_sum += se->avg.util_sum;
3787 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
3788 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
3789 
3790 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
3791 
3792 	cfs_rq_util_change(cfs_rq, 0);
3793 
3794 	trace_pelt_cfs_tp(cfs_rq);
3795 }
3796 
3797 /**
3798  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3799  * @cfs_rq: cfs_rq to detach from
3800  * @se: sched_entity to detach
3801  *
3802  * Must call update_cfs_rq_load_avg() before this, since we rely on
3803  * cfs_rq->avg.last_update_time being current.
3804  */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3805 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3806 {
3807 	/*
3808 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3809 	 * See ___update_load_avg() for details.
3810 	 */
3811 	u32 divider = get_pelt_divider(&cfs_rq->avg);
3812 
3813 	dequeue_load_avg(cfs_rq, se);
3814 	sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3815 	cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * divider;
3816 	sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
3817 	cfs_rq->avg.runnable_sum = cfs_rq->avg.runnable_avg * divider;
3818 
3819 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
3820 
3821 	cfs_rq_util_change(cfs_rq, 0);
3822 
3823 	trace_pelt_cfs_tp(cfs_rq);
3824 }
3825 
3826 /*
3827  * Optional action to be done while updating the load average
3828  */
3829 #define UPDATE_TG	0x1
3830 #define SKIP_AGE_LOAD	0x2
3831 #define DO_ATTACH	0x4
3832 
3833 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)3834 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3835 {
3836 	u64 now = cfs_rq_clock_pelt(cfs_rq);
3837 	int decayed;
3838 
3839 	/*
3840 	 * Track task load average for carrying it to new CPU after migrated, and
3841 	 * track group sched_entity load average for task_h_load calc in migration
3842 	 */
3843 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
3844 		__update_load_avg_se(now, cfs_rq, se);
3845 
3846 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
3847 	decayed |= propagate_entity_load_avg(se);
3848 
3849 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
3850 
3851 		/*
3852 		 * DO_ATTACH means we're here from enqueue_entity().
3853 		 * !last_update_time means we've passed through
3854 		 * migrate_task_rq_fair() indicating we migrated.
3855 		 *
3856 		 * IOW we're enqueueing a task on a new CPU.
3857 		 */
3858 		attach_entity_load_avg(cfs_rq, se);
3859 		update_tg_load_avg(cfs_rq);
3860 
3861 	} else if (decayed) {
3862 		cfs_rq_util_change(cfs_rq, 0);
3863 
3864 		if (flags & UPDATE_TG)
3865 			update_tg_load_avg(cfs_rq);
3866 	}
3867 }
3868 
3869 #ifndef CONFIG_64BIT
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)3870 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3871 {
3872 	u64 last_update_time_copy;
3873 	u64 last_update_time;
3874 
3875 	do {
3876 		last_update_time_copy = cfs_rq->load_last_update_time_copy;
3877 		smp_rmb();
3878 		last_update_time = cfs_rq->avg.last_update_time;
3879 	} while (last_update_time != last_update_time_copy);
3880 
3881 	return last_update_time;
3882 }
3883 #else
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)3884 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3885 {
3886 	return cfs_rq->avg.last_update_time;
3887 }
3888 #endif
3889 
3890 /*
3891  * Synchronize entity load avg of dequeued entity without locking
3892  * the previous rq.
3893  */
sync_entity_load_avg(struct sched_entity * se)3894 static void sync_entity_load_avg(struct sched_entity *se)
3895 {
3896 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
3897 	u64 last_update_time;
3898 
3899 	last_update_time = cfs_rq_last_update_time(cfs_rq);
3900 	__update_load_avg_blocked_se(last_update_time, se);
3901 }
3902 
3903 /*
3904  * Task first catches up with cfs_rq, and then subtract
3905  * itself from the cfs_rq (task must be off the queue now).
3906  */
remove_entity_load_avg(struct sched_entity * se)3907 static void remove_entity_load_avg(struct sched_entity *se)
3908 {
3909 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
3910 	unsigned long flags;
3911 
3912 	/*
3913 	 * tasks cannot exit without having gone through wake_up_new_task() ->
3914 	 * post_init_entity_util_avg() which will have added things to the
3915 	 * cfs_rq, so we can remove unconditionally.
3916 	 */
3917 
3918 	sync_entity_load_avg(se);
3919 
3920 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
3921 	++cfs_rq->removed.nr;
3922 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
3923 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
3924 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
3925 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
3926 }
3927 
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)3928 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
3929 {
3930 	return cfs_rq->avg.runnable_avg;
3931 }
3932 
cfs_rq_load_avg(struct cfs_rq * cfs_rq)3933 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3934 {
3935 	return cfs_rq->avg.load_avg;
3936 }
3937 
3938 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
3939 
task_util(struct task_struct * p)3940 static inline unsigned long task_util(struct task_struct *p)
3941 {
3942 #ifdef CONFIG_SCHED_WALT
3943 	if (likely(!walt_disabled && sysctl_sched_use_walt_task_util))
3944 		return p->ravg.demand_scaled;
3945 #endif
3946 	return READ_ONCE(p->se.avg.util_avg);
3947 }
3948 
_task_util_est(struct task_struct * p)3949 static inline unsigned long _task_util_est(struct task_struct *p)
3950 {
3951 	struct util_est ue = READ_ONCE(p->se.avg.util_est);
3952 
3953 	return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
3954 }
3955 
task_util_est(struct task_struct * p)3956 static inline unsigned long task_util_est(struct task_struct *p)
3957 {
3958 #ifdef CONFIG_SCHED_WALT
3959 	if (likely(!walt_disabled && sysctl_sched_use_walt_task_util))
3960 		return p->ravg.demand_scaled;
3961 #endif
3962 	return max(task_util(p), _task_util_est(p));
3963 }
3964 
3965 #ifdef CONFIG_UCLAMP_TASK
3966 #ifdef CONFIG_SCHED_RT_CAS
uclamp_task_util(struct task_struct * p)3967 unsigned long uclamp_task_util(struct task_struct *p)
3968 #else
3969 static inline unsigned long uclamp_task_util(struct task_struct *p)
3970 #endif
3971 {
3972 	return clamp(task_util_est(p),
3973 		     uclamp_eff_value(p, UCLAMP_MIN),
3974 		     uclamp_eff_value(p, UCLAMP_MAX));
3975 }
3976 #else
3977 #ifdef CONFIG_SCHED_RT_CAS
uclamp_task_util(struct task_struct * p)3978 unsigned long uclamp_task_util(struct task_struct *p)
3979 #else
3980 static inline unsigned long uclamp_task_util(struct task_struct *p)
3981 #endif
3982 {
3983 	return task_util_est(p);
3984 }
3985 #endif
3986 
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)3987 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
3988 				    struct task_struct *p)
3989 {
3990 	unsigned int enqueued;
3991 
3992 	if (!sched_feat(UTIL_EST))
3993 		return;
3994 
3995 	/* Update root cfs_rq's estimated utilization */
3996 	enqueued  = cfs_rq->avg.util_est.enqueued;
3997 	enqueued += _task_util_est(p);
3998 	WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3999 
4000 	trace_sched_util_est_cfs_tp(cfs_rq);
4001 }
4002 
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4003 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4004 				    struct task_struct *p)
4005 {
4006 	unsigned int enqueued;
4007 
4008 	if (!sched_feat(UTIL_EST))
4009 		return;
4010 
4011 	/* Update root cfs_rq's estimated utilization */
4012 	enqueued  = cfs_rq->avg.util_est.enqueued;
4013 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4014 	WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4015 
4016 	trace_sched_util_est_cfs_tp(cfs_rq);
4017 }
4018 
4019 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4020 
4021 /*
4022  * Check if a (signed) value is within a specified (unsigned) margin,
4023  * based on the observation that:
4024  *
4025  *     abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4026  *
4027  * NOTE: this only works when value + maring < INT_MAX.
4028  */
within_margin(int value,int margin)4029 static inline bool within_margin(int value, int margin)
4030 {
4031 	return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4032 }
4033 
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4034 static inline void util_est_update(struct cfs_rq *cfs_rq,
4035 				   struct task_struct *p,
4036 				   bool task_sleep)
4037 {
4038 	long last_ewma_diff, last_enqueued_diff;
4039 	struct util_est ue;
4040 
4041 	if (!sched_feat(UTIL_EST))
4042 		return;
4043 
4044 	/*
4045 	 * Skip update of task's estimated utilization when the task has not
4046 	 * yet completed an activation, e.g. being migrated.
4047 	 */
4048 	if (!task_sleep)
4049 		return;
4050 
4051 	/*
4052 	 * If the PELT values haven't changed since enqueue time,
4053 	 * skip the util_est update.
4054 	 */
4055 	ue = p->se.avg.util_est;
4056 	if (ue.enqueued & UTIL_AVG_UNCHANGED)
4057 		return;
4058 
4059 	last_enqueued_diff = ue.enqueued;
4060 
4061 	/*
4062 	 * Reset EWMA on utilization increases, the moving average is used only
4063 	 * to smooth utilization decreases.
4064 	 */
4065 	ue.enqueued = task_util(p);
4066 	if (sched_feat(UTIL_EST_FASTUP)) {
4067 		if (ue.ewma < ue.enqueued) {
4068 			ue.ewma = ue.enqueued;
4069 			goto done;
4070 		}
4071 	}
4072 
4073 	/*
4074 	 * Skip update of task's estimated utilization when its members are
4075 	 * already ~1% close to its last activation value.
4076 	 */
4077 	last_ewma_diff = ue.enqueued - ue.ewma;
4078 	last_enqueued_diff -= ue.enqueued;
4079 	if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4080 		if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4081 			goto done;
4082 
4083 		return;
4084 	}
4085 
4086 	/*
4087 	 * To avoid overestimation of actual task utilization, skip updates if
4088 	 * we cannot grant there is idle time in this CPU.
4089 	 */
4090 	if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4091 		return;
4092 
4093 	/*
4094 	 * Update Task's estimated utilization
4095 	 *
4096 	 * When *p completes an activation we can consolidate another sample
4097 	 * of the task size. This is done by storing the current PELT value
4098 	 * as ue.enqueued and by using this value to update the Exponential
4099 	 * Weighted Moving Average (EWMA):
4100 	 *
4101 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
4102 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
4103 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
4104 	 *          = w * (      last_ewma_diff            ) +     ewma(t-1)
4105 	 *          = w * (last_ewma_diff  +  ewma(t-1) / w)
4106 	 *
4107 	 * Where 'w' is the weight of new samples, which is configured to be
4108 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4109 	 */
4110 	ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4111 	ue.ewma  += last_ewma_diff;
4112 	ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4113 done:
4114 	ue.enqueued |= UTIL_AVG_UNCHANGED;
4115 	WRITE_ONCE(p->se.avg.util_est, ue);
4116 
4117 	trace_sched_util_est_se_tp(&p->se);
4118 }
4119 
task_fits_capacity(struct task_struct * p,long capacity)4120 static inline int task_fits_capacity(struct task_struct *p, long capacity)
4121 {
4122 	return fits_capacity(uclamp_task_util(p), capacity);
4123 }
4124 
4125 #ifdef CONFIG_SCHED_RTG
task_fits_max(struct task_struct * p,int cpu)4126 bool task_fits_max(struct task_struct *p, int cpu)
4127 {
4128 	unsigned long capacity = capacity_orig_of(cpu);
4129 	unsigned long max_capacity = cpu_rq(cpu)->rd->max_cpu_capacity;
4130 
4131 	if (capacity == max_capacity)
4132 		return true;
4133 
4134 	return task_fits_capacity(p, capacity);
4135 }
4136 #endif
4137 
update_misfit_status(struct task_struct * p,struct rq * rq)4138 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4139 {
4140 	bool task_fits = false;
4141 #ifdef CONFIG_SCHED_RTG
4142 	int cpu = cpu_of(rq);
4143 	struct cpumask *rtg_target = NULL;
4144 #endif
4145 
4146 	if (!static_branch_unlikely(&sched_asym_cpucapacity))
4147 		return;
4148 
4149 	if (!p || p->nr_cpus_allowed == 1) {
4150 		rq->misfit_task_load = 0;
4151 		return;
4152 	}
4153 
4154 #ifdef CONFIG_SCHED_RTG
4155 	rtg_target = find_rtg_target(p);
4156 	if (rtg_target)
4157 		task_fits = capacity_orig_of(cpu) >=
4158 				capacity_orig_of(cpumask_first(rtg_target));
4159 	else
4160 		task_fits = task_fits_capacity(p, capacity_of(cpu_of(rq)));
4161 #else
4162 	task_fits = task_fits_capacity(p, capacity_of(cpu_of(rq)));
4163 #endif
4164 	if (task_fits) {
4165 		rq->misfit_task_load = 0;
4166 		return;
4167 	}
4168 
4169 	/*
4170 	 * Make sure that misfit_task_load will not be null even if
4171 	 * task_h_load() returns 0.
4172 	 */
4173 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4174 }
4175 
4176 #else /* CONFIG_SMP */
4177 
4178 #define UPDATE_TG	0x0
4179 #define SKIP_AGE_LOAD	0x0
4180 #define DO_ATTACH	0x0
4181 
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)4182 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4183 {
4184 	cfs_rq_util_change(cfs_rq, 0);
4185 }
4186 
remove_entity_load_avg(struct sched_entity * se)4187 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4188 
4189 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4190 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4191 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4192 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4193 
newidle_balance(struct rq * rq,struct rq_flags * rf)4194 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4195 {
4196 	return 0;
4197 }
4198 
4199 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4200 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4201 
4202 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4203 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4204 
4205 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4206 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4207 		bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)4208 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4209 
4210 #endif /* CONFIG_SMP */
4211 
check_spread(struct cfs_rq * cfs_rq,struct sched_entity * se)4212 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
4213 {
4214 #ifdef CONFIG_SCHED_DEBUG
4215 	s64 d = se->vruntime - cfs_rq->min_vruntime;
4216 
4217 	if (d < 0)
4218 		d = -d;
4219 
4220 	if (d > 3*sysctl_sched_latency)
4221 		schedstat_inc(cfs_rq->nr_spread_over);
4222 #endif
4223 }
4224 
4225 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int initial)4226 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
4227 {
4228 	u64 vruntime = cfs_rq->min_vruntime;
4229 
4230 	/*
4231 	 * The 'current' period is already promised to the current tasks,
4232 	 * however the extra weight of the new task will slow them down a
4233 	 * little, place the new task so that it fits in the slot that
4234 	 * stays open at the end.
4235 	 */
4236 	if (initial && sched_feat(START_DEBIT))
4237 		vruntime += sched_vslice(cfs_rq, se);
4238 
4239 	/* sleeps up to a single latency don't count. */
4240 	if (!initial) {
4241 		unsigned long thresh = sysctl_sched_latency;
4242 
4243 		/*
4244 		 * Halve their sleep time's effect, to allow
4245 		 * for a gentler effect of sleepers:
4246 		 */
4247 		if (sched_feat(GENTLE_FAIR_SLEEPERS))
4248 			thresh >>= 1;
4249 
4250 		vruntime -= thresh;
4251 	}
4252 
4253 	/* ensure we never gain time by being placed backwards. */
4254 	se->vruntime = max_vruntime(se->vruntime, vruntime);
4255 }
4256 
4257 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
4258 
check_schedstat_required(void)4259 static inline void check_schedstat_required(void)
4260 {
4261 #ifdef CONFIG_SCHEDSTATS
4262 	if (schedstat_enabled())
4263 		return;
4264 
4265 	/* Force schedstat enabled if a dependent tracepoint is active */
4266 	if (trace_sched_stat_wait_enabled()    ||
4267 			trace_sched_stat_sleep_enabled()   ||
4268 			trace_sched_stat_iowait_enabled()  ||
4269 			trace_sched_stat_blocked_enabled() ||
4270 			trace_sched_stat_runtime_enabled())  {
4271 		printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
4272 			     "stat_blocked and stat_runtime require the "
4273 			     "kernel parameter schedstats=enable or "
4274 			     "kernel.sched_schedstats=1\n");
4275 	}
4276 #endif
4277 }
4278 
4279 static inline bool cfs_bandwidth_used(void);
4280 
4281 /*
4282  * MIGRATION
4283  *
4284  *	dequeue
4285  *	  update_curr()
4286  *	    update_min_vruntime()
4287  *	  vruntime -= min_vruntime
4288  *
4289  *	enqueue
4290  *	  update_curr()
4291  *	    update_min_vruntime()
4292  *	  vruntime += min_vruntime
4293  *
4294  * this way the vruntime transition between RQs is done when both
4295  * min_vruntime are up-to-date.
4296  *
4297  * WAKEUP (remote)
4298  *
4299  *	->migrate_task_rq_fair() (p->state == TASK_WAKING)
4300  *	  vruntime -= min_vruntime
4301  *
4302  *	enqueue
4303  *	  update_curr()
4304  *	    update_min_vruntime()
4305  *	  vruntime += min_vruntime
4306  *
4307  * this way we don't have the most up-to-date min_vruntime on the originating
4308  * CPU and an up-to-date min_vruntime on the destination CPU.
4309  */
4310 
4311 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4312 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4313 {
4314 	bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
4315 	bool curr = cfs_rq->curr == se;
4316 
4317 	/*
4318 	 * If we're the current task, we must renormalise before calling
4319 	 * update_curr().
4320 	 */
4321 	if (renorm && curr)
4322 		se->vruntime += cfs_rq->min_vruntime;
4323 
4324 	update_curr(cfs_rq);
4325 
4326 	/*
4327 	 * Otherwise, renormalise after, such that we're placed at the current
4328 	 * moment in time, instead of some random moment in the past. Being
4329 	 * placed in the past could significantly boost this task to the
4330 	 * fairness detriment of existing tasks.
4331 	 */
4332 	if (renorm && !curr)
4333 		se->vruntime += cfs_rq->min_vruntime;
4334 
4335 	/*
4336 	 * When enqueuing a sched_entity, we must:
4337 	 *   - Update loads to have both entity and cfs_rq synced with now.
4338 	 *   - Add its load to cfs_rq->runnable_avg
4339 	 *   - For group_entity, update its weight to reflect the new share of
4340 	 *     its group cfs_rq
4341 	 *   - Add its new weight to cfs_rq->load.weight
4342 	 */
4343 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
4344 	se_update_runnable(se);
4345 	update_cfs_group(se);
4346 	account_entity_enqueue(cfs_rq, se);
4347 
4348 	if (flags & ENQUEUE_WAKEUP)
4349 		place_entity(cfs_rq, se, 0);
4350 
4351 	check_schedstat_required();
4352 	update_stats_enqueue(cfs_rq, se, flags);
4353 	check_spread(cfs_rq, se);
4354 	if (!curr)
4355 		__enqueue_entity(cfs_rq, se);
4356 	se->on_rq = 1;
4357 
4358 	/*
4359 	 * When bandwidth control is enabled, cfs might have been removed
4360 	 * because of a parent been throttled but cfs->nr_running > 1. Try to
4361 	 * add it unconditionnally.
4362 	 */
4363 	if (cfs_rq->nr_running == 1 || cfs_bandwidth_used())
4364 		list_add_leaf_cfs_rq(cfs_rq);
4365 
4366 	if (cfs_rq->nr_running == 1)
4367 		check_enqueue_throttle(cfs_rq);
4368 }
4369 
__clear_buddies_last(struct sched_entity * se)4370 static void __clear_buddies_last(struct sched_entity *se)
4371 {
4372 	for_each_sched_entity(se) {
4373 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
4374 		if (cfs_rq->last != se)
4375 			break;
4376 
4377 		cfs_rq->last = NULL;
4378 	}
4379 }
4380 
__clear_buddies_next(struct sched_entity * se)4381 static void __clear_buddies_next(struct sched_entity *se)
4382 {
4383 	for_each_sched_entity(se) {
4384 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
4385 		if (cfs_rq->next != se)
4386 			break;
4387 
4388 		cfs_rq->next = NULL;
4389 	}
4390 }
4391 
__clear_buddies_skip(struct sched_entity * se)4392 static void __clear_buddies_skip(struct sched_entity *se)
4393 {
4394 	for_each_sched_entity(se) {
4395 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
4396 		if (cfs_rq->skip != se)
4397 			break;
4398 
4399 		cfs_rq->skip = NULL;
4400 	}
4401 }
4402 
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)4403 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
4404 {
4405 	if (cfs_rq->last == se)
4406 		__clear_buddies_last(se);
4407 
4408 	if (cfs_rq->next == se)
4409 		__clear_buddies_next(se);
4410 
4411 	if (cfs_rq->skip == se)
4412 		__clear_buddies_skip(se);
4413 }
4414 
4415 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4416 
4417 static void
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4418 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4419 {
4420 	/*
4421 	 * Update run-time statistics of the 'current'.
4422 	 */
4423 	update_curr(cfs_rq);
4424 
4425 	/*
4426 	 * When dequeuing a sched_entity, we must:
4427 	 *   - Update loads to have both entity and cfs_rq synced with now.
4428 	 *   - Subtract its load from the cfs_rq->runnable_avg.
4429 	 *   - Subtract its previous weight from cfs_rq->load.weight.
4430 	 *   - For group entity, update its weight to reflect the new share
4431 	 *     of its group cfs_rq.
4432 	 */
4433 	update_load_avg(cfs_rq, se, UPDATE_TG);
4434 	se_update_runnable(se);
4435 
4436 	update_stats_dequeue(cfs_rq, se, flags);
4437 
4438 	clear_buddies(cfs_rq, se);
4439 
4440 	if (se != cfs_rq->curr)
4441 		__dequeue_entity(cfs_rq, se);
4442 	se->on_rq = 0;
4443 	account_entity_dequeue(cfs_rq, se);
4444 
4445 	/*
4446 	 * Normalize after update_curr(); which will also have moved
4447 	 * min_vruntime if @se is the one holding it back. But before doing
4448 	 * update_min_vruntime() again, which will discount @se's position and
4449 	 * can move min_vruntime forward still more.
4450 	 */
4451 	if (!(flags & DEQUEUE_SLEEP))
4452 		se->vruntime -= cfs_rq->min_vruntime;
4453 
4454 	/* return excess runtime on last dequeue */
4455 	return_cfs_rq_runtime(cfs_rq);
4456 
4457 	update_cfs_group(se);
4458 
4459 	/*
4460 	 * Now advance min_vruntime if @se was the entity holding it back,
4461 	 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4462 	 * put back on, and if we advance min_vruntime, we'll be placed back
4463 	 * further than we started -- ie. we'll be penalized.
4464 	 */
4465 	if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
4466 		update_min_vruntime(cfs_rq);
4467 }
4468 
4469 /*
4470  * Preempt the current task with a newly woken task if needed:
4471  */
4472 static void
check_preempt_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr)4473 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4474 {
4475 	unsigned long ideal_runtime, delta_exec;
4476 	struct sched_entity *se;
4477 	s64 delta;
4478 
4479 	ideal_runtime = sched_slice(cfs_rq, curr);
4480 	delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
4481 	if (delta_exec > ideal_runtime) {
4482 		resched_curr(rq_of(cfs_rq));
4483 		/*
4484 		 * The current task ran long enough, ensure it doesn't get
4485 		 * re-elected due to buddy favours.
4486 		 */
4487 		clear_buddies(cfs_rq, curr);
4488 		return;
4489 	}
4490 
4491 	/*
4492 	 * Ensure that a task that missed wakeup preemption by a
4493 	 * narrow margin doesn't have to wait for a full slice.
4494 	 * This also mitigates buddy induced latencies under load.
4495 	 */
4496 	if (delta_exec < sysctl_sched_min_granularity)
4497 		return;
4498 
4499 	se = __pick_first_entity(cfs_rq);
4500 	delta = curr->vruntime - se->vruntime;
4501 
4502 	if (delta < 0)
4503 		return;
4504 
4505 	if (delta > ideal_runtime)
4506 		resched_curr(rq_of(cfs_rq));
4507 }
4508 
4509 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)4510 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
4511 {
4512 	/* 'current' is not kept within the tree. */
4513 	if (se->on_rq) {
4514 		/*
4515 		 * Any task has to be enqueued before it get to execute on
4516 		 * a CPU. So account for the time it spent waiting on the
4517 		 * runqueue.
4518 		 */
4519 		update_stats_wait_end(cfs_rq, se);
4520 		__dequeue_entity(cfs_rq, se);
4521 		update_load_avg(cfs_rq, se, UPDATE_TG);
4522 	}
4523 
4524 	update_stats_curr_start(cfs_rq, se);
4525 	cfs_rq->curr = se;
4526 
4527 	/*
4528 	 * Track our maximum slice length, if the CPU's load is at
4529 	 * least twice that of our own weight (i.e. dont track it
4530 	 * when there are only lesser-weight tasks around):
4531 	 */
4532 	if (schedstat_enabled() &&
4533 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
4534 		schedstat_set(se->statistics.slice_max,
4535 			max((u64)schedstat_val(se->statistics.slice_max),
4536 			    se->sum_exec_runtime - se->prev_sum_exec_runtime));
4537 	}
4538 
4539 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
4540 }
4541 
4542 static int
4543 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
4544 
4545 /*
4546  * Pick the next process, keeping these things in mind, in this order:
4547  * 1) keep things fair between processes/task groups
4548  * 2) pick the "next" process, since someone really wants that to run
4549  * 3) pick the "last" process, for cache locality
4550  * 4) do not run the "skip" process, if something else is available
4551  */
4552 static struct sched_entity *
pick_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * curr)4553 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4554 {
4555 	struct sched_entity *left = __pick_first_entity(cfs_rq);
4556 	struct sched_entity *se;
4557 
4558 	/*
4559 	 * If curr is set we have to see if its left of the leftmost entity
4560 	 * still in the tree, provided there was anything in the tree at all.
4561 	 */
4562 	if (!left || (curr && entity_before(curr, left)))
4563 		left = curr;
4564 
4565 	se = left; /* ideally we run the leftmost entity */
4566 
4567 	/*
4568 	 * Avoid running the skip buddy, if running something else can
4569 	 * be done without getting too unfair.
4570 	 */
4571 	if (cfs_rq->skip == se) {
4572 		struct sched_entity *second;
4573 
4574 		if (se == curr) {
4575 			second = __pick_first_entity(cfs_rq);
4576 		} else {
4577 			second = __pick_next_entity(se);
4578 			if (!second || (curr && entity_before(curr, second)))
4579 				second = curr;
4580 		}
4581 
4582 		if (second && wakeup_preempt_entity(second, left) < 1)
4583 			se = second;
4584 	}
4585 
4586 	if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) {
4587 		/*
4588 		 * Someone really wants this to run. If it's not unfair, run it.
4589 		 */
4590 		se = cfs_rq->next;
4591 	} else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) {
4592 		/*
4593 		 * Prefer last buddy, try to return the CPU to a preempted task.
4594 		 */
4595 		se = cfs_rq->last;
4596 	}
4597 
4598 	clear_buddies(cfs_rq, se);
4599 
4600 	return se;
4601 }
4602 
4603 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4604 
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)4605 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
4606 {
4607 	/*
4608 	 * If still on the runqueue then deactivate_task()
4609 	 * was not called and update_curr() has to be done:
4610 	 */
4611 	if (prev->on_rq)
4612 		update_curr(cfs_rq);
4613 
4614 	/* throttle cfs_rqs exceeding runtime */
4615 	check_cfs_rq_runtime(cfs_rq);
4616 
4617 	check_spread(cfs_rq, prev);
4618 
4619 	if (prev->on_rq) {
4620 		update_stats_wait_start(cfs_rq, prev);
4621 		/* Put 'current' back into the tree. */
4622 		__enqueue_entity(cfs_rq, prev);
4623 		/* in !on_rq case, update occurred at dequeue */
4624 		update_load_avg(cfs_rq, prev, 0);
4625 	}
4626 	cfs_rq->curr = NULL;
4627 }
4628 
4629 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)4630 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
4631 {
4632 	/*
4633 	 * Update run-time statistics of the 'current'.
4634 	 */
4635 	update_curr(cfs_rq);
4636 
4637 	/*
4638 	 * Ensure that runnable average is periodically updated.
4639 	 */
4640 	update_load_avg(cfs_rq, curr, UPDATE_TG);
4641 	update_cfs_group(curr);
4642 
4643 #ifdef CONFIG_SCHED_HRTICK
4644 	/*
4645 	 * queued ticks are scheduled to match the slice, so don't bother
4646 	 * validating it and just reschedule.
4647 	 */
4648 	if (queued) {
4649 		resched_curr(rq_of(cfs_rq));
4650 		return;
4651 	}
4652 	/*
4653 	 * don't let the period tick interfere with the hrtick preemption
4654 	 */
4655 	if (!sched_feat(DOUBLE_TICK) &&
4656 			hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
4657 		return;
4658 #endif
4659 
4660 	if (cfs_rq->nr_running > 1)
4661 		check_preempt_tick(cfs_rq, curr);
4662 }
4663 
4664 
4665 /**************************************************
4666  * CFS bandwidth control machinery
4667  */
4668 
4669 #ifdef CONFIG_CFS_BANDWIDTH
4670 
4671 #ifdef CONFIG_JUMP_LABEL
4672 static struct static_key __cfs_bandwidth_used;
4673 
cfs_bandwidth_used(void)4674 static inline bool cfs_bandwidth_used(void)
4675 {
4676 	return static_key_false(&__cfs_bandwidth_used);
4677 }
4678 
cfs_bandwidth_usage_inc(void)4679 void cfs_bandwidth_usage_inc(void)
4680 {
4681 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
4682 }
4683 
cfs_bandwidth_usage_dec(void)4684 void cfs_bandwidth_usage_dec(void)
4685 {
4686 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
4687 }
4688 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)4689 static bool cfs_bandwidth_used(void)
4690 {
4691 	return true;
4692 }
4693 
cfs_bandwidth_usage_inc(void)4694 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)4695 void cfs_bandwidth_usage_dec(void) {}
4696 #endif /* CONFIG_JUMP_LABEL */
4697 
4698 /*
4699  * default period for cfs group bandwidth.
4700  * default: 0.1s, units: nanoseconds
4701  */
default_cfs_period(void)4702 static inline u64 default_cfs_period(void)
4703 {
4704 	return 100000000ULL;
4705 }
4706 
sched_cfs_bandwidth_slice(void)4707 static inline u64 sched_cfs_bandwidth_slice(void)
4708 {
4709 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
4710 }
4711 
4712 /*
4713  * Replenish runtime according to assigned quota. We use sched_clock_cpu
4714  * directly instead of rq->clock to avoid adding additional synchronization
4715  * around rq->lock.
4716  *
4717  * requires cfs_b->lock
4718  */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)4719 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
4720 {
4721 	if (cfs_b->quota != RUNTIME_INF)
4722 		cfs_b->runtime = cfs_b->quota;
4723 }
4724 
tg_cfs_bandwidth(struct task_group * tg)4725 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4726 {
4727 	return &tg->cfs_bandwidth;
4728 }
4729 
4730 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)4731 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
4732 				   struct cfs_rq *cfs_rq, u64 target_runtime)
4733 {
4734 	u64 min_amount, amount = 0;
4735 
4736 	lockdep_assert_held(&cfs_b->lock);
4737 
4738 	/* note: this is a positive sum as runtime_remaining <= 0 */
4739 	min_amount = target_runtime - cfs_rq->runtime_remaining;
4740 
4741 	if (cfs_b->quota == RUNTIME_INF)
4742 		amount = min_amount;
4743 	else {
4744 		start_cfs_bandwidth(cfs_b);
4745 
4746 		if (cfs_b->runtime > 0) {
4747 			amount = min(cfs_b->runtime, min_amount);
4748 			cfs_b->runtime -= amount;
4749 			cfs_b->idle = 0;
4750 		}
4751 	}
4752 
4753 	cfs_rq->runtime_remaining += amount;
4754 
4755 	return cfs_rq->runtime_remaining > 0;
4756 }
4757 
4758 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)4759 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4760 {
4761 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4762 	int ret;
4763 
4764 	raw_spin_lock(&cfs_b->lock);
4765 	ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
4766 	raw_spin_unlock(&cfs_b->lock);
4767 
4768 	return ret;
4769 }
4770 
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)4771 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4772 {
4773 	/* dock delta_exec before expiring quota (as it could span periods) */
4774 	cfs_rq->runtime_remaining -= delta_exec;
4775 
4776 	if (likely(cfs_rq->runtime_remaining > 0))
4777 		return;
4778 
4779 	if (cfs_rq->throttled)
4780 		return;
4781 	/*
4782 	 * if we're unable to extend our runtime we resched so that the active
4783 	 * hierarchy can be throttled
4784 	 */
4785 	if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
4786 		resched_curr(rq_of(cfs_rq));
4787 }
4788 
4789 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)4790 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4791 {
4792 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4793 		return;
4794 
4795 	__account_cfs_rq_runtime(cfs_rq, delta_exec);
4796 }
4797 
cfs_rq_throttled(struct cfs_rq * cfs_rq)4798 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4799 {
4800 	return cfs_bandwidth_used() && cfs_rq->throttled;
4801 }
4802 
4803 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)4804 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4805 {
4806 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
4807 }
4808 
4809 /*
4810  * Ensure that neither of the group entities corresponding to src_cpu or
4811  * dest_cpu are members of a throttled hierarchy when performing group
4812  * load-balance operations.
4813  */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)4814 static inline int throttled_lb_pair(struct task_group *tg,
4815 				    int src_cpu, int dest_cpu)
4816 {
4817 	struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4818 
4819 	src_cfs_rq = tg->cfs_rq[src_cpu];
4820 	dest_cfs_rq = tg->cfs_rq[dest_cpu];
4821 
4822 	return throttled_hierarchy(src_cfs_rq) ||
4823 	       throttled_hierarchy(dest_cfs_rq);
4824 }
4825 
tg_unthrottle_up(struct task_group * tg,void * data)4826 static int tg_unthrottle_up(struct task_group *tg, void *data)
4827 {
4828 	struct rq *rq = data;
4829 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4830 
4831 	cfs_rq->throttle_count--;
4832 	if (!cfs_rq->throttle_count) {
4833 		cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
4834 					     cfs_rq->throttled_clock_task;
4835 
4836 		/* Add cfs_rq with already running entity in the list */
4837 		if (cfs_rq->nr_running >= 1)
4838 			list_add_leaf_cfs_rq(cfs_rq);
4839 	}
4840 
4841 	return 0;
4842 }
4843 
tg_throttle_down(struct task_group * tg,void * data)4844 static int tg_throttle_down(struct task_group *tg, void *data)
4845 {
4846 	struct rq *rq = data;
4847 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4848 
4849 	/* group is entering throttled state, stop time */
4850 	if (!cfs_rq->throttle_count) {
4851 		cfs_rq->throttled_clock_task = rq_clock_task(rq);
4852 		list_del_leaf_cfs_rq(cfs_rq);
4853 	}
4854 	cfs_rq->throttle_count++;
4855 
4856 	return 0;
4857 }
4858 
throttle_cfs_rq(struct cfs_rq * cfs_rq)4859 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
4860 {
4861 	struct rq *rq = rq_of(cfs_rq);
4862 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4863 	struct sched_entity *se;
4864 	long task_delta, idle_task_delta, dequeue = 1;
4865 
4866 	raw_spin_lock(&cfs_b->lock);
4867 	/* This will start the period timer if necessary */
4868 	if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
4869 		/*
4870 		 * We have raced with bandwidth becoming available, and if we
4871 		 * actually throttled the timer might not unthrottle us for an
4872 		 * entire period. We additionally needed to make sure that any
4873 		 * subsequent check_cfs_rq_runtime calls agree not to throttle
4874 		 * us, as we may commit to do cfs put_prev+pick_next, so we ask
4875 		 * for 1ns of runtime rather than just check cfs_b.
4876 		 */
4877 		dequeue = 0;
4878 	} else {
4879 		list_add_tail_rcu(&cfs_rq->throttled_list,
4880 				  &cfs_b->throttled_cfs_rq);
4881 	}
4882 	raw_spin_unlock(&cfs_b->lock);
4883 
4884 	if (!dequeue)
4885 		return false;  /* Throttle no longer required. */
4886 
4887 	se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4888 
4889 	/* freeze hierarchy runnable averages while throttled */
4890 	rcu_read_lock();
4891 	walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4892 	rcu_read_unlock();
4893 
4894 	task_delta = cfs_rq->h_nr_running;
4895 	idle_task_delta = cfs_rq->idle_h_nr_running;
4896 	for_each_sched_entity(se) {
4897 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4898 		/* throttled entity or throttle-on-deactivate */
4899 		if (!se->on_rq)
4900 			break;
4901 
4902 		if (dequeue) {
4903 			dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
4904 		} else {
4905 			update_load_avg(qcfs_rq, se, 0);
4906 			se_update_runnable(se);
4907 		}
4908 
4909 		qcfs_rq->h_nr_running -= task_delta;
4910 		qcfs_rq->idle_h_nr_running -= idle_task_delta;
4911 		walt_dec_throttled_cfs_rq_stats(&qcfs_rq->walt_stats, cfs_rq);
4912 
4913 		if (qcfs_rq->load.weight)
4914 			dequeue = 0;
4915 	}
4916 
4917 	if (!se) {
4918 		sub_nr_running(rq, task_delta);
4919 		walt_dec_throttled_cfs_rq_stats(&rq->walt_stats, cfs_rq);
4920 	}
4921 
4922 	/*
4923 	 * Note: distribution will already see us throttled via the
4924 	 * throttled-list.  rq->lock protects completion.
4925 	 */
4926 	cfs_rq->throttled = 1;
4927 	cfs_rq->throttled_clock = rq_clock(rq);
4928 	return true;
4929 }
4930 
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)4931 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
4932 {
4933 	struct rq *rq = rq_of(cfs_rq);
4934 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4935 	struct sched_entity *se;
4936 	long task_delta, idle_task_delta;
4937 	struct cfs_rq *tcfs_rq __maybe_unused = cfs_rq;
4938 
4939 	se = cfs_rq->tg->se[cpu_of(rq)];
4940 
4941 	cfs_rq->throttled = 0;
4942 
4943 	update_rq_clock(rq);
4944 
4945 	raw_spin_lock(&cfs_b->lock);
4946 	cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4947 	list_del_rcu(&cfs_rq->throttled_list);
4948 	raw_spin_unlock(&cfs_b->lock);
4949 
4950 	/* update hierarchical throttle state */
4951 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4952 
4953 	if (!cfs_rq->load.weight)
4954 		return;
4955 
4956 	task_delta = cfs_rq->h_nr_running;
4957 	idle_task_delta = cfs_rq->idle_h_nr_running;
4958 	for_each_sched_entity(se) {
4959 		if (se->on_rq)
4960 			break;
4961 		cfs_rq = cfs_rq_of(se);
4962 		enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4963 
4964 		cfs_rq->h_nr_running += task_delta;
4965 		cfs_rq->idle_h_nr_running += idle_task_delta;
4966 		walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
4967 
4968 		/* end evaluation on encountering a throttled cfs_rq */
4969 		if (cfs_rq_throttled(cfs_rq))
4970 			goto unthrottle_throttle;
4971 	}
4972 
4973 	for_each_sched_entity(se) {
4974 		cfs_rq = cfs_rq_of(se);
4975 
4976 		update_load_avg(cfs_rq, se, UPDATE_TG);
4977 		se_update_runnable(se);
4978 
4979 		cfs_rq->h_nr_running += task_delta;
4980 		cfs_rq->idle_h_nr_running += idle_task_delta;
4981 		walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
4982 
4983 		/* end evaluation on encountering a throttled cfs_rq */
4984 		if (cfs_rq_throttled(cfs_rq))
4985 			goto unthrottle_throttle;
4986 
4987 		/*
4988 		 * One parent has been throttled and cfs_rq removed from the
4989 		 * list. Add it back to not break the leaf list.
4990 		 */
4991 		if (throttled_hierarchy(cfs_rq))
4992 			list_add_leaf_cfs_rq(cfs_rq);
4993 	}
4994 
4995 	/* At this point se is NULL and we are at root level*/
4996 	add_nr_running(rq, task_delta);
4997 	walt_inc_throttled_cfs_rq_stats(&rq->walt_stats, tcfs_rq);
4998 
4999 unthrottle_throttle:
5000 	/*
5001 	 * The cfs_rq_throttled() breaks in the above iteration can result in
5002 	 * incomplete leaf list maintenance, resulting in triggering the
5003 	 * assertion below.
5004 	 */
5005 	for_each_sched_entity(se) {
5006 		cfs_rq = cfs_rq_of(se);
5007 
5008 		if (list_add_leaf_cfs_rq(cfs_rq))
5009 			break;
5010 	}
5011 
5012 	assert_list_leaf_cfs_rq(rq);
5013 
5014 	/* Determine whether we need to wake up potentially idle CPU: */
5015 	if (rq->curr == rq->idle && rq->cfs.nr_running)
5016 		resched_curr(rq);
5017 }
5018 
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)5019 static void distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5020 {
5021 	struct cfs_rq *cfs_rq;
5022 	u64 runtime, remaining = 1;
5023 
5024 	rcu_read_lock();
5025 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5026 				throttled_list) {
5027 		struct rq *rq = rq_of(cfs_rq);
5028 		struct rq_flags rf;
5029 
5030 		rq_lock_irqsave(rq, &rf);
5031 		if (!cfs_rq_throttled(cfs_rq))
5032 			goto next;
5033 
5034 		/* By the above check, this should never be true */
5035 		SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5036 
5037 		raw_spin_lock(&cfs_b->lock);
5038 		runtime = -cfs_rq->runtime_remaining + 1;
5039 		if (runtime > cfs_b->runtime)
5040 			runtime = cfs_b->runtime;
5041 		cfs_b->runtime -= runtime;
5042 		remaining = cfs_b->runtime;
5043 		raw_spin_unlock(&cfs_b->lock);
5044 
5045 		cfs_rq->runtime_remaining += runtime;
5046 
5047 		/* we check whether we're throttled above */
5048 		if (cfs_rq->runtime_remaining > 0)
5049 			unthrottle_cfs_rq(cfs_rq);
5050 
5051 next:
5052 		rq_unlock_irqrestore(rq, &rf);
5053 
5054 		if (!remaining)
5055 			break;
5056 	}
5057 	rcu_read_unlock();
5058 }
5059 
5060 /*
5061  * Responsible for refilling a task_group's bandwidth and unthrottling its
5062  * cfs_rqs as appropriate. If there has been no activity within the last
5063  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5064  * used to track this state.
5065  */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)5066 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5067 {
5068 	int throttled;
5069 
5070 	/* no need to continue the timer with no bandwidth constraint */
5071 	if (cfs_b->quota == RUNTIME_INF)
5072 		goto out_deactivate;
5073 
5074 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5075 	cfs_b->nr_periods += overrun;
5076 
5077 	/*
5078 	 * idle depends on !throttled (for the case of a large deficit), and if
5079 	 * we're going inactive then everything else can be deferred
5080 	 */
5081 	if (cfs_b->idle && !throttled)
5082 		goto out_deactivate;
5083 
5084 	__refill_cfs_bandwidth_runtime(cfs_b);
5085 
5086 	if (!throttled) {
5087 		/* mark as potentially idle for the upcoming period */
5088 		cfs_b->idle = 1;
5089 		return 0;
5090 	}
5091 
5092 	/* account preceding periods in which throttling occurred */
5093 	cfs_b->nr_throttled += overrun;
5094 
5095 	/*
5096 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
5097 	 */
5098 	while (throttled && cfs_b->runtime > 0) {
5099 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5100 		/* we can't nest cfs_b->lock while distributing bandwidth */
5101 		distribute_cfs_runtime(cfs_b);
5102 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
5103 
5104 		throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5105 	}
5106 
5107 	/*
5108 	 * While we are ensured activity in the period following an
5109 	 * unthrottle, this also covers the case in which the new bandwidth is
5110 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
5111 	 * timer to remain active while there are any throttled entities.)
5112 	 */
5113 	cfs_b->idle = 0;
5114 
5115 	return 0;
5116 
5117 out_deactivate:
5118 	return 1;
5119 }
5120 
5121 /* a cfs_rq won't donate quota below this amount */
5122 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5123 /* minimum remaining period time to redistribute slack quota */
5124 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5125 /* how long we wait to gather additional slack before distributing */
5126 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5127 
5128 /*
5129  * Are we near the end of the current quota period?
5130  *
5131  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5132  * hrtimer base being cleared by hrtimer_start. In the case of
5133  * migrate_hrtimers, base is never cleared, so we are fine.
5134  */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)5135 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5136 {
5137 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
5138 	s64 remaining;
5139 
5140 	/* if the call-back is running a quota refresh is already occurring */
5141 	if (hrtimer_callback_running(refresh_timer))
5142 		return 1;
5143 
5144 	/* is a quota refresh about to occur? */
5145 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5146 	if (remaining < (s64)min_expire)
5147 		return 1;
5148 
5149 	return 0;
5150 }
5151 
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)5152 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5153 {
5154 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5155 
5156 	/* if there's a quota refresh soon don't bother with slack */
5157 	if (runtime_refresh_within(cfs_b, min_left))
5158 		return;
5159 
5160 	/* don't push forwards an existing deferred unthrottle */
5161 	if (cfs_b->slack_started)
5162 		return;
5163 	cfs_b->slack_started = true;
5164 
5165 	hrtimer_start(&cfs_b->slack_timer,
5166 			ns_to_ktime(cfs_bandwidth_slack_period),
5167 			HRTIMER_MODE_REL);
5168 }
5169 
5170 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5171 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5172 {
5173 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5174 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5175 
5176 	if (slack_runtime <= 0)
5177 		return;
5178 
5179 	raw_spin_lock(&cfs_b->lock);
5180 	if (cfs_b->quota != RUNTIME_INF) {
5181 		cfs_b->runtime += slack_runtime;
5182 
5183 		/* we are under rq->lock, defer unthrottling using a timer */
5184 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5185 		    !list_empty(&cfs_b->throttled_cfs_rq))
5186 			start_cfs_slack_bandwidth(cfs_b);
5187 	}
5188 	raw_spin_unlock(&cfs_b->lock);
5189 
5190 	/* even if it's not valid for return we don't want to try again */
5191 	cfs_rq->runtime_remaining -= slack_runtime;
5192 }
5193 
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5194 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5195 {
5196 	if (!cfs_bandwidth_used())
5197 		return;
5198 
5199 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
5200 		return;
5201 
5202 	__return_cfs_rq_runtime(cfs_rq);
5203 }
5204 
5205 /*
5206  * This is done with a timer (instead of inline with bandwidth return) since
5207  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5208  */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)5209 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5210 {
5211 	u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
5212 	unsigned long flags;
5213 
5214 	/* confirm we're still not at a refresh boundary */
5215 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
5216 	cfs_b->slack_started = false;
5217 
5218 	if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
5219 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5220 		return;
5221 	}
5222 
5223 	if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
5224 		runtime = cfs_b->runtime;
5225 
5226 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5227 
5228 	if (!runtime)
5229 		return;
5230 
5231 	distribute_cfs_runtime(cfs_b);
5232 
5233 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
5234 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5235 }
5236 
5237 /*
5238  * When a group wakes up we want to make sure that its quota is not already
5239  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
5240  * runtime as update_curr() throttling can not trigger until it's on-rq.
5241  */
check_enqueue_throttle(struct cfs_rq * cfs_rq)5242 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
5243 {
5244 	if (!cfs_bandwidth_used())
5245 		return;
5246 
5247 	/* an active group must be handled by the update_curr()->put() path */
5248 	if (!cfs_rq->runtime_enabled || cfs_rq->curr)
5249 		return;
5250 
5251 	/* ensure the group is not already throttled */
5252 	if (cfs_rq_throttled(cfs_rq))
5253 		return;
5254 
5255 	/* update runtime allocation */
5256 	account_cfs_rq_runtime(cfs_rq, 0);
5257 	if (cfs_rq->runtime_remaining <= 0)
5258 		throttle_cfs_rq(cfs_rq);
5259 }
5260 
sync_throttle(struct task_group * tg,int cpu)5261 static void sync_throttle(struct task_group *tg, int cpu)
5262 {
5263 	struct cfs_rq *pcfs_rq, *cfs_rq;
5264 
5265 	if (!cfs_bandwidth_used())
5266 		return;
5267 
5268 	if (!tg->parent)
5269 		return;
5270 
5271 	cfs_rq = tg->cfs_rq[cpu];
5272 	pcfs_rq = tg->parent->cfs_rq[cpu];
5273 
5274 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
5275 	cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
5276 }
5277 
5278 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)5279 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5280 {
5281 	if (!cfs_bandwidth_used())
5282 		return false;
5283 
5284 	if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
5285 		return false;
5286 
5287 	/*
5288 	 * it's possible for a throttled entity to be forced into a running
5289 	 * state (e.g. set_curr_task), in this case we're finished.
5290 	 */
5291 	if (cfs_rq_throttled(cfs_rq))
5292 		return true;
5293 
5294 	return throttle_cfs_rq(cfs_rq);
5295 }
5296 
sched_cfs_slack_timer(struct hrtimer * timer)5297 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
5298 {
5299 	struct cfs_bandwidth *cfs_b =
5300 		container_of(timer, struct cfs_bandwidth, slack_timer);
5301 
5302 	do_sched_cfs_slack_timer(cfs_b);
5303 
5304 	return HRTIMER_NORESTART;
5305 }
5306 
5307 extern const u64 max_cfs_quota_period;
5308 
sched_cfs_period_timer(struct hrtimer * timer)5309 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
5310 {
5311 	struct cfs_bandwidth *cfs_b =
5312 		container_of(timer, struct cfs_bandwidth, period_timer);
5313 	unsigned long flags;
5314 	int overrun;
5315 	int idle = 0;
5316 	int count = 0;
5317 
5318 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
5319 	for (;;) {
5320 		overrun = hrtimer_forward_now(timer, cfs_b->period);
5321 		if (!overrun)
5322 			break;
5323 
5324 		idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
5325 
5326 		if (++count > 3) {
5327 			u64 new, old = ktime_to_ns(cfs_b->period);
5328 
5329 			/*
5330 			 * Grow period by a factor of 2 to avoid losing precision.
5331 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
5332 			 * to fail.
5333 			 */
5334 			new = old * 2;
5335 			if (new < max_cfs_quota_period) {
5336 				cfs_b->period = ns_to_ktime(new);
5337 				cfs_b->quota *= 2;
5338 
5339 				pr_warn_ratelimited(
5340 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5341 					smp_processor_id(),
5342 					div_u64(new, NSEC_PER_USEC),
5343 					div_u64(cfs_b->quota, NSEC_PER_USEC));
5344 			} else {
5345 				pr_warn_ratelimited(
5346 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5347 					smp_processor_id(),
5348 					div_u64(old, NSEC_PER_USEC),
5349 					div_u64(cfs_b->quota, NSEC_PER_USEC));
5350 			}
5351 
5352 			/* reset count so we don't come right back in here */
5353 			count = 0;
5354 		}
5355 	}
5356 	if (idle)
5357 		cfs_b->period_active = 0;
5358 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5359 
5360 	return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
5361 }
5362 
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5363 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5364 {
5365 	raw_spin_lock_init(&cfs_b->lock);
5366 	cfs_b->runtime = 0;
5367 	cfs_b->quota = RUNTIME_INF;
5368 	cfs_b->period = ns_to_ktime(default_cfs_period());
5369 
5370 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
5371 	hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
5372 	cfs_b->period_timer.function = sched_cfs_period_timer;
5373 	hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5374 	cfs_b->slack_timer.function = sched_cfs_slack_timer;
5375 	cfs_b->slack_started = false;
5376 }
5377 
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)5378 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5379 {
5380 	cfs_rq->runtime_enabled = 0;
5381 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
5382 	walt_init_cfs_rq_stats(cfs_rq);
5383 }
5384 
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5385 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5386 {
5387 	lockdep_assert_held(&cfs_b->lock);
5388 
5389 	if (cfs_b->period_active)
5390 		return;
5391 
5392 	cfs_b->period_active = 1;
5393 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
5394 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
5395 }
5396 
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5397 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5398 {
5399 	/* init_cfs_bandwidth() was not called */
5400 	if (!cfs_b->throttled_cfs_rq.next)
5401 		return;
5402 
5403 	hrtimer_cancel(&cfs_b->period_timer);
5404 	hrtimer_cancel(&cfs_b->slack_timer);
5405 }
5406 
5407 /*
5408  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
5409  *
5410  * The race is harmless, since modifying bandwidth settings of unhooked group
5411  * bits doesn't do much.
5412  */
5413 
5414 /* cpu online calback */
update_runtime_enabled(struct rq * rq)5415 static void __maybe_unused update_runtime_enabled(struct rq *rq)
5416 {
5417 	struct task_group *tg;
5418 
5419 	lockdep_assert_held(&rq->lock);
5420 
5421 	rcu_read_lock();
5422 	list_for_each_entry_rcu(tg, &task_groups, list) {
5423 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
5424 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5425 
5426 		raw_spin_lock(&cfs_b->lock);
5427 		cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
5428 		raw_spin_unlock(&cfs_b->lock);
5429 	}
5430 	rcu_read_unlock();
5431 }
5432 
5433 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)5434 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
5435 {
5436 	struct task_group *tg;
5437 
5438 	lockdep_assert_held(&rq->lock);
5439 
5440 	rcu_read_lock();
5441 	list_for_each_entry_rcu(tg, &task_groups, list) {
5442 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5443 
5444 		if (!cfs_rq->runtime_enabled)
5445 			continue;
5446 
5447 		/*
5448 		 * clock_task is not advancing so we just need to make sure
5449 		 * there's some valid quota amount
5450 		 */
5451 		cfs_rq->runtime_remaining = 1;
5452 		/*
5453 		 * Offline rq is schedulable till CPU is completely disabled
5454 		 * in take_cpu_down(), so we prevent new cfs throttling here.
5455 		 */
5456 		cfs_rq->runtime_enabled = 0;
5457 
5458 		if (cfs_rq_throttled(cfs_rq))
5459 			unthrottle_cfs_rq(cfs_rq);
5460 	}
5461 	rcu_read_unlock();
5462 }
5463 
5464 #else /* CONFIG_CFS_BANDWIDTH */
5465 
cfs_bandwidth_used(void)5466 static inline bool cfs_bandwidth_used(void)
5467 {
5468 	return false;
5469 }
5470 
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5471 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)5472 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)5473 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)5474 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5475 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5476 
cfs_rq_throttled(struct cfs_rq * cfs_rq)5477 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5478 {
5479 	return 0;
5480 }
5481 
throttled_hierarchy(struct cfs_rq * cfs_rq)5482 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5483 {
5484 	return 0;
5485 }
5486 
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)5487 static inline int throttled_lb_pair(struct task_group *tg,
5488 				    int src_cpu, int dest_cpu)
5489 {
5490 	return 0;
5491 }
5492 
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5493 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5494 
5495 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)5496 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5497 #endif
5498 
tg_cfs_bandwidth(struct task_group * tg)5499 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5500 {
5501 	return NULL;
5502 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5503 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)5504 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)5505 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
5506 
5507 #endif /* CONFIG_CFS_BANDWIDTH */
5508 
5509 /**************************************************
5510  * CFS operations on tasks:
5511  */
5512 
5513 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)5514 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
5515 {
5516 	struct sched_entity *se = &p->se;
5517 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
5518 
5519 	SCHED_WARN_ON(task_rq(p) != rq);
5520 
5521 	if (rq->cfs.h_nr_running > 1) {
5522 		u64 slice = sched_slice(cfs_rq, se);
5523 		u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
5524 		s64 delta = slice - ran;
5525 
5526 		if (delta < 0) {
5527 			if (rq->curr == p)
5528 				resched_curr(rq);
5529 			return;
5530 		}
5531 		hrtick_start(rq, delta);
5532 	}
5533 }
5534 
5535 /*
5536  * called from enqueue/dequeue and updates the hrtick when the
5537  * current task is from our class and nr_running is low enough
5538  * to matter.
5539  */
hrtick_update(struct rq * rq)5540 static void hrtick_update(struct rq *rq)
5541 {
5542 	struct task_struct *curr = rq->curr;
5543 
5544 	if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
5545 		return;
5546 
5547 	if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
5548 		hrtick_start_fair(rq, curr);
5549 }
5550 #else /* !CONFIG_SCHED_HRTICK */
5551 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)5552 hrtick_start_fair(struct rq *rq, struct task_struct *p)
5553 {
5554 }
5555 
hrtick_update(struct rq * rq)5556 static inline void hrtick_update(struct rq *rq)
5557 {
5558 }
5559 #endif
5560 
5561 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)5562 static inline bool cpu_overutilized(int cpu)
5563 {
5564 	return !fits_capacity(cpu_util(cpu), capacity_of(cpu));
5565 }
5566 
update_overutilized_status(struct rq * rq)5567 static inline void update_overutilized_status(struct rq *rq)
5568 {
5569 	if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
5570 		WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
5571 		trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
5572 	}
5573 }
5574 #else
update_overutilized_status(struct rq * rq)5575 static inline void update_overutilized_status(struct rq *rq) { }
5576 #endif
5577 
5578 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)5579 static int sched_idle_rq(struct rq *rq)
5580 {
5581 	return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
5582 			rq->nr_running);
5583 }
5584 
5585 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)5586 static int sched_idle_cpu(int cpu)
5587 {
5588 	return sched_idle_rq(cpu_rq(cpu));
5589 }
5590 #endif
5591 
5592 static void set_next_buddy(struct sched_entity *se);
5593 
5594 #ifdef CONFIG_SCHED_LATENCY_NICE
check_preempt_from_idle(struct cfs_rq * cfs,struct sched_entity * se)5595 static void check_preempt_from_idle(struct cfs_rq *cfs, struct sched_entity *se)
5596 {
5597 	struct sched_entity *next;
5598 
5599 	if (se->latency_weight <= 0)
5600 		return;
5601 
5602 	if (cfs->nr_running <= 1)
5603 		return;
5604 	/*
5605 	 * When waking from idle, we don't need to check to preempt at wakeup
5606 	 * the idle thread and don't set next buddy as a candidate for being
5607 	 * picked in priority.
5608 	 * In case of simultaneous wakeup from idle, the latency sensitive tasks
5609 	 * lost opportunity to preempt non sensitive tasks which woke up
5610 	 * simultaneously.
5611 	 */
5612 
5613 	if (cfs->next)
5614 		next = cfs->next;
5615 	else
5616 		next = __pick_first_entity(cfs);
5617 
5618 	if (next && wakeup_preempt_entity(next, se) == 1)
5619 		set_next_buddy(se);
5620 }
5621 #endif
5622 
5623 /*
5624  * The enqueue_task method is called before nr_running is
5625  * increased. Here we update the fair scheduling stats and
5626  * then put the task into the rbtree:
5627  */
5628 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)5629 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5630 {
5631 	struct cfs_rq *cfs_rq;
5632 	struct sched_entity *se = &p->se;
5633 	int idle_h_nr_running = task_has_idle_policy(p);
5634 	int task_new = !(flags & ENQUEUE_WAKEUP);
5635 
5636 	/*
5637 	 * The code below (indirectly) updates schedutil which looks at
5638 	 * the cfs_rq utilization to select a frequency.
5639 	 * Let's add the task's estimated utilization to the cfs_rq's
5640 	 * estimated utilization, before we update schedutil.
5641 	 */
5642 	util_est_enqueue(&rq->cfs, p);
5643 
5644 	/*
5645 	 * If in_iowait is set, the code below may not trigger any cpufreq
5646 	 * utilization updates, so do it here explicitly with the IOWAIT flag
5647 	 * passed.
5648 	 */
5649 	if (p->in_iowait)
5650 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
5651 
5652 	for_each_sched_entity(se) {
5653 		if (se->on_rq)
5654 			break;
5655 		cfs_rq = cfs_rq_of(se);
5656 		enqueue_entity(cfs_rq, se, flags);
5657 
5658 		cfs_rq->h_nr_running++;
5659 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
5660 		walt_inc_cfs_rq_stats(cfs_rq, p);
5661 
5662 		/* end evaluation on encountering a throttled cfs_rq */
5663 		if (cfs_rq_throttled(cfs_rq))
5664 			goto enqueue_throttle;
5665 
5666 		flags = ENQUEUE_WAKEUP;
5667 	}
5668 
5669 	for_each_sched_entity(se) {
5670 		cfs_rq = cfs_rq_of(se);
5671 
5672 		update_load_avg(cfs_rq, se, UPDATE_TG);
5673 		se_update_runnable(se);
5674 		update_cfs_group(se);
5675 
5676 		cfs_rq->h_nr_running++;
5677 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
5678 		walt_inc_cfs_rq_stats(cfs_rq, p);
5679 
5680 		/* end evaluation on encountering a throttled cfs_rq */
5681 		if (cfs_rq_throttled(cfs_rq))
5682 			goto enqueue_throttle;
5683 
5684                /*
5685                 * One parent has been throttled and cfs_rq removed from the
5686                 * list. Add it back to not break the leaf list.
5687                 */
5688                if (throttled_hierarchy(cfs_rq))
5689                        list_add_leaf_cfs_rq(cfs_rq);
5690 	}
5691 
5692 	/* At this point se is NULL and we are at root level*/
5693 	add_nr_running(rq, 1);
5694 	inc_rq_walt_stats(rq, p);
5695 	/*
5696 	 * Since new tasks are assigned an initial util_avg equal to
5697 	 * half of the spare capacity of their CPU, tiny tasks have the
5698 	 * ability to cross the overutilized threshold, which will
5699 	 * result in the load balancer ruining all the task placement
5700 	 * done by EAS. As a way to mitigate that effect, do not account
5701 	 * for the first enqueue operation of new tasks during the
5702 	 * overutilized flag detection.
5703 	 *
5704 	 * A better way of solving this problem would be to wait for
5705 	 * the PELT signals of tasks to converge before taking them
5706 	 * into account, but that is not straightforward to implement,
5707 	 * and the following generally works well enough in practice.
5708 	 */
5709 	if (!task_new)
5710 		update_overutilized_status(rq);
5711 
5712 #ifdef CONFIG_SCHED_LATENCY_NICE
5713 	if (rq->curr == rq->idle)
5714 		check_preempt_from_idle(cfs_rq_of(&p->se), &p->se);
5715 #endif
5716 
5717 enqueue_throttle:
5718 	if (cfs_bandwidth_used()) {
5719 		/*
5720 		 * When bandwidth control is enabled; the cfs_rq_throttled()
5721 		 * breaks in the above iteration can result in incomplete
5722 		 * leaf list maintenance, resulting in triggering the assertion
5723 		 * below.
5724 		 */
5725 		for_each_sched_entity(se) {
5726 			cfs_rq = cfs_rq_of(se);
5727 
5728 			if (list_add_leaf_cfs_rq(cfs_rq))
5729 				break;
5730 		}
5731 	}
5732 
5733 	assert_list_leaf_cfs_rq(rq);
5734 
5735 	hrtick_update(rq);
5736 }
5737 
5738 /*
5739  * The dequeue_task method is called before nr_running is
5740  * decreased. We remove the task from the rbtree and
5741  * update the fair scheduling stats:
5742  */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)5743 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5744 {
5745 	struct cfs_rq *cfs_rq;
5746 	struct sched_entity *se = &p->se;
5747 	int task_sleep = flags & DEQUEUE_SLEEP;
5748 	int idle_h_nr_running = task_has_idle_policy(p);
5749 	bool was_sched_idle = sched_idle_rq(rq);
5750 
5751 	util_est_dequeue(&rq->cfs, p);
5752 
5753 	for_each_sched_entity(se) {
5754 		cfs_rq = cfs_rq_of(se);
5755 		dequeue_entity(cfs_rq, se, flags);
5756 
5757 		cfs_rq->h_nr_running--;
5758 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5759 		walt_dec_cfs_rq_stats(cfs_rq, p);
5760 
5761 		/* end evaluation on encountering a throttled cfs_rq */
5762 		if (cfs_rq_throttled(cfs_rq))
5763 			goto dequeue_throttle;
5764 
5765 		/* Don't dequeue parent if it has other entities besides us */
5766 		if (cfs_rq->load.weight) {
5767 			/* Avoid re-evaluating load for this entity: */
5768 			se = parent_entity(se);
5769 			/*
5770 			 * Bias pick_next to pick a task from this cfs_rq, as
5771 			 * p is sleeping when it is within its sched_slice.
5772 			 */
5773 			if (task_sleep && se && !throttled_hierarchy(cfs_rq))
5774 				set_next_buddy(se);
5775 			break;
5776 		}
5777 		flags |= DEQUEUE_SLEEP;
5778 	}
5779 
5780 	for_each_sched_entity(se) {
5781 		cfs_rq = cfs_rq_of(se);
5782 
5783 		update_load_avg(cfs_rq, se, UPDATE_TG);
5784 		se_update_runnable(se);
5785 		update_cfs_group(se);
5786 
5787 		cfs_rq->h_nr_running--;
5788 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5789 		walt_dec_cfs_rq_stats(cfs_rq, p);
5790 
5791 		/* end evaluation on encountering a throttled cfs_rq */
5792 		if (cfs_rq_throttled(cfs_rq))
5793 			goto dequeue_throttle;
5794 
5795 	}
5796 
5797 	/* At this point se is NULL and we are at root level*/
5798 	sub_nr_running(rq, 1);
5799 	dec_rq_walt_stats(rq, p);
5800 
5801 	/* balance early to pull high priority tasks */
5802 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
5803 		rq->next_balance = jiffies;
5804 
5805 dequeue_throttle:
5806 	util_est_update(&rq->cfs, p, task_sleep);
5807 	hrtick_update(rq);
5808 }
5809 
5810 #ifdef CONFIG_SMP
5811 
5812 /* Working cpumask for: load_balance, load_balance_newidle. */
5813 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5814 DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
5815 
5816 #ifdef CONFIG_NO_HZ_COMMON
5817 
5818 static struct {
5819 	cpumask_var_t idle_cpus_mask;
5820 	atomic_t nr_cpus;
5821 	int has_blocked;		/* Idle CPUS has blocked load */
5822 	unsigned long next_balance;     /* in jiffy units */
5823 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
5824 } nohz ____cacheline_aligned;
5825 
5826 #endif /* CONFIG_NO_HZ_COMMON */
5827 
cpu_load(struct rq * rq)5828 static unsigned long cpu_load(struct rq *rq)
5829 {
5830 	return cfs_rq_load_avg(&rq->cfs);
5831 }
5832 
5833 /*
5834  * cpu_load_without - compute CPU load without any contributions from *p
5835  * @cpu: the CPU which load is requested
5836  * @p: the task which load should be discounted
5837  *
5838  * The load of a CPU is defined by the load of tasks currently enqueued on that
5839  * CPU as well as tasks which are currently sleeping after an execution on that
5840  * CPU.
5841  *
5842  * This method returns the load of the specified CPU by discounting the load of
5843  * the specified task, whenever the task is currently contributing to the CPU
5844  * load.
5845  */
cpu_load_without(struct rq * rq,struct task_struct * p)5846 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
5847 {
5848 	struct cfs_rq *cfs_rq;
5849 	unsigned int load;
5850 
5851 	/* Task has no contribution or is new */
5852 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5853 		return cpu_load(rq);
5854 
5855 	cfs_rq = &rq->cfs;
5856 	load = READ_ONCE(cfs_rq->avg.load_avg);
5857 
5858 	/* Discount task's util from CPU's util */
5859 	lsub_positive(&load, task_h_load(p));
5860 
5861 	return load;
5862 }
5863 
cpu_runnable(struct rq * rq)5864 static unsigned long cpu_runnable(struct rq *rq)
5865 {
5866 	return cfs_rq_runnable_avg(&rq->cfs);
5867 }
5868 
cpu_runnable_without(struct rq * rq,struct task_struct * p)5869 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
5870 {
5871 	struct cfs_rq *cfs_rq;
5872 	unsigned int runnable;
5873 
5874 	/* Task has no contribution or is new */
5875 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5876 		return cpu_runnable(rq);
5877 
5878 	cfs_rq = &rq->cfs;
5879 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
5880 
5881 	/* Discount task's runnable from CPU's runnable */
5882 	lsub_positive(&runnable, p->se.avg.runnable_avg);
5883 
5884 	return runnable;
5885 }
5886 
record_wakee(struct task_struct * p)5887 static void record_wakee(struct task_struct *p)
5888 {
5889 	/*
5890 	 * Only decay a single time; tasks that have less then 1 wakeup per
5891 	 * jiffy will not have built up many flips.
5892 	 */
5893 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5894 		current->wakee_flips >>= 1;
5895 		current->wakee_flip_decay_ts = jiffies;
5896 	}
5897 
5898 	if (current->last_wakee != p) {
5899 		current->last_wakee = p;
5900 		current->wakee_flips++;
5901 	}
5902 }
5903 
5904 /*
5905  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5906  *
5907  * A waker of many should wake a different task than the one last awakened
5908  * at a frequency roughly N times higher than one of its wakees.
5909  *
5910  * In order to determine whether we should let the load spread vs consolidating
5911  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5912  * partner, and a factor of lls_size higher frequency in the other.
5913  *
5914  * With both conditions met, we can be relatively sure that the relationship is
5915  * non-monogamous, with partner count exceeding socket size.
5916  *
5917  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5918  * whatever is irrelevant, spread criteria is apparent partner count exceeds
5919  * socket size.
5920  */
wake_wide(struct task_struct * p)5921 static int wake_wide(struct task_struct *p)
5922 {
5923 	unsigned int master = current->wakee_flips;
5924 	unsigned int slave = p->wakee_flips;
5925 	int factor = __this_cpu_read(sd_llc_size);
5926 
5927 	if (master < slave)
5928 		swap(master, slave);
5929 	if (slave < factor || master < slave * factor)
5930 		return 0;
5931 	return 1;
5932 }
5933 
5934 /*
5935  * The purpose of wake_affine() is to quickly determine on which CPU we can run
5936  * soonest. For the purpose of speed we only consider the waking and previous
5937  * CPU.
5938  *
5939  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
5940  *			cache-affine and is (or	will be) idle.
5941  *
5942  * wake_affine_weight() - considers the weight to reflect the average
5943  *			  scheduling latency of the CPUs. This seems to work
5944  *			  for the overloaded case.
5945  */
5946 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)5947 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
5948 {
5949 	/*
5950 	 * If this_cpu is idle, it implies the wakeup is from interrupt
5951 	 * context. Only allow the move if cache is shared. Otherwise an
5952 	 * interrupt intensive workload could force all tasks onto one
5953 	 * node depending on the IO topology or IRQ affinity settings.
5954 	 *
5955 	 * If the prev_cpu is idle and cache affine then avoid a migration.
5956 	 * There is no guarantee that the cache hot data from an interrupt
5957 	 * is more important than cache hot data on the prev_cpu and from
5958 	 * a cpufreq perspective, it's better to have higher utilisation
5959 	 * on one CPU.
5960 	 */
5961 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
5962 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
5963 
5964 	if (sync && cpu_rq(this_cpu)->nr_running == 1)
5965 		return this_cpu;
5966 
5967 	return nr_cpumask_bits;
5968 }
5969 
5970 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)5971 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
5972 		   int this_cpu, int prev_cpu, int sync)
5973 {
5974 	s64 this_eff_load, prev_eff_load;
5975 	unsigned long task_load;
5976 
5977 	this_eff_load = cpu_load(cpu_rq(this_cpu));
5978 
5979 	if (sync) {
5980 		unsigned long current_load = task_h_load(current);
5981 
5982 		if (current_load > this_eff_load)
5983 			return this_cpu;
5984 
5985 		this_eff_load -= current_load;
5986 	}
5987 
5988 	task_load = task_h_load(p);
5989 
5990 	this_eff_load += task_load;
5991 	if (sched_feat(WA_BIAS))
5992 		this_eff_load *= 100;
5993 	this_eff_load *= capacity_of(prev_cpu);
5994 
5995 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
5996 	prev_eff_load -= task_load;
5997 	if (sched_feat(WA_BIAS))
5998 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
5999 	prev_eff_load *= capacity_of(this_cpu);
6000 
6001 	/*
6002 	 * If sync, adjust the weight of prev_eff_load such that if
6003 	 * prev_eff == this_eff that select_idle_sibling() will consider
6004 	 * stacking the wakee on top of the waker if no other CPU is
6005 	 * idle.
6006 	 */
6007 	if (sync)
6008 		prev_eff_load += 1;
6009 
6010 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6011 }
6012 
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)6013 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6014 		       int this_cpu, int prev_cpu, int sync)
6015 {
6016 	int target = nr_cpumask_bits;
6017 
6018 	if (sched_feat(WA_IDLE))
6019 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
6020 
6021 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6022 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6023 
6024 	schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
6025 	if (target == nr_cpumask_bits)
6026 		return prev_cpu;
6027 
6028 	schedstat_inc(sd->ttwu_move_affine);
6029 	schedstat_inc(p->se.statistics.nr_wakeups_affine);
6030 	return target;
6031 }
6032 
6033 static struct sched_group *
6034 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6035 
6036 /*
6037  * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6038  */
6039 static int
find_idlest_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)6040 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6041 {
6042 	unsigned long load, min_load = ULONG_MAX;
6043 	unsigned int min_exit_latency = UINT_MAX;
6044 	u64 latest_idle_timestamp = 0;
6045 	int least_loaded_cpu = this_cpu;
6046 	int shallowest_idle_cpu = -1;
6047 	int i;
6048 
6049 	/* Check if we have any choice: */
6050 	if (group->group_weight == 1)
6051 		return cpumask_first(sched_group_span(group));
6052 
6053 	/* Traverse only the allowed CPUs */
6054 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6055 		if (cpu_isolated(i))
6056 			continue;
6057 
6058 		if (sched_idle_cpu(i))
6059 			return i;
6060 
6061 		if (available_idle_cpu(i)) {
6062 			struct rq *rq = cpu_rq(i);
6063 			struct cpuidle_state *idle = idle_get_state(rq);
6064 			if (idle && idle->exit_latency < min_exit_latency) {
6065 				/*
6066 				 * We give priority to a CPU whose idle state
6067 				 * has the smallest exit latency irrespective
6068 				 * of any idle timestamp.
6069 				 */
6070 				min_exit_latency = idle->exit_latency;
6071 				latest_idle_timestamp = rq->idle_stamp;
6072 				shallowest_idle_cpu = i;
6073 			} else if ((!idle || idle->exit_latency == min_exit_latency) &&
6074 				   rq->idle_stamp > latest_idle_timestamp) {
6075 				/*
6076 				 * If equal or no active idle state, then
6077 				 * the most recently idled CPU might have
6078 				 * a warmer cache.
6079 				 */
6080 				latest_idle_timestamp = rq->idle_stamp;
6081 				shallowest_idle_cpu = i;
6082 			}
6083 		} else if (shallowest_idle_cpu == -1) {
6084 			load = cpu_load(cpu_rq(i));
6085 			if (load < min_load) {
6086 				min_load = load;
6087 				least_loaded_cpu = i;
6088 			}
6089 		}
6090 	}
6091 
6092 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6093 }
6094 
find_idlest_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)6095 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6096 				  int cpu, int prev_cpu, int sd_flag)
6097 {
6098 	int new_cpu = cpu;
6099 
6100 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6101 		return prev_cpu;
6102 
6103 	/*
6104 	 * We need task's util for cpu_util_without, sync it up to
6105 	 * prev_cpu's last_update_time.
6106 	 */
6107 	if (!(sd_flag & SD_BALANCE_FORK))
6108 		sync_entity_load_avg(&p->se);
6109 
6110 	while (sd) {
6111 		struct sched_group *group;
6112 		struct sched_domain *tmp;
6113 		int weight;
6114 
6115 		if (!(sd->flags & sd_flag)) {
6116 			sd = sd->child;
6117 			continue;
6118 		}
6119 
6120 		group = find_idlest_group(sd, p, cpu);
6121 		if (!group) {
6122 			sd = sd->child;
6123 			continue;
6124 		}
6125 
6126 		new_cpu = find_idlest_group_cpu(group, p, cpu);
6127 		if (new_cpu == cpu) {
6128 			/* Now try balancing at a lower domain level of 'cpu': */
6129 			sd = sd->child;
6130 			continue;
6131 		}
6132 
6133 		/* Now try balancing at a lower domain level of 'new_cpu': */
6134 		cpu = new_cpu;
6135 		weight = sd->span_weight;
6136 		sd = NULL;
6137 		for_each_domain(cpu, tmp) {
6138 			if (weight <= tmp->span_weight)
6139 				break;
6140 			if (tmp->flags & sd_flag)
6141 				sd = tmp;
6142 		}
6143 	}
6144 
6145 	return new_cpu;
6146 }
6147 
6148 #ifdef CONFIG_SCHED_SMT
6149 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6150 EXPORT_SYMBOL_GPL(sched_smt_present);
6151 
set_idle_cores(int cpu,int val)6152 static inline void set_idle_cores(int cpu, int val)
6153 {
6154 	struct sched_domain_shared *sds;
6155 
6156 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6157 	if (sds)
6158 		WRITE_ONCE(sds->has_idle_cores, val);
6159 }
6160 
test_idle_cores(int cpu,bool def)6161 static inline bool test_idle_cores(int cpu, bool def)
6162 {
6163 	struct sched_domain_shared *sds;
6164 
6165 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6166 	if (sds)
6167 		return READ_ONCE(sds->has_idle_cores);
6168 
6169 	return def;
6170 }
6171 
6172 /*
6173  * Scans the local SMT mask to see if the entire core is idle, and records this
6174  * information in sd_llc_shared->has_idle_cores.
6175  *
6176  * Since SMT siblings share all cache levels, inspecting this limited remote
6177  * state should be fairly cheap.
6178  */
__update_idle_core(struct rq * rq)6179 void __update_idle_core(struct rq *rq)
6180 {
6181 	int core = cpu_of(rq);
6182 	int cpu;
6183 
6184 	rcu_read_lock();
6185 	if (test_idle_cores(core, true))
6186 		goto unlock;
6187 
6188 	for_each_cpu(cpu, cpu_smt_mask(core)) {
6189 		if (cpu == core)
6190 			continue;
6191 
6192 		if (!available_idle_cpu(cpu))
6193 			goto unlock;
6194 	}
6195 
6196 	set_idle_cores(core, 1);
6197 unlock:
6198 	rcu_read_unlock();
6199 }
6200 
6201 /*
6202  * Scan the entire LLC domain for idle cores; this dynamically switches off if
6203  * there are no idle cores left in the system; tracked through
6204  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6205  */
select_idle_core(struct task_struct * p,struct sched_domain * sd,int target)6206 static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6207 {
6208 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6209 	int core, cpu;
6210 
6211 	if (!static_branch_likely(&sched_smt_present))
6212 		return -1;
6213 
6214 	if (!test_idle_cores(target, false))
6215 		return -1;
6216 
6217 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6218 #ifdef CONFIG_CPU_ISOLATION_OPT
6219 	cpumask_andnot(cpus, cpus, cpu_isolated_mask);
6220 #endif
6221 
6222 	for_each_cpu_wrap(core, cpus, target) {
6223 		bool idle = true;
6224 
6225 		for_each_cpu(cpu, cpu_smt_mask(core)) {
6226 			if (!available_idle_cpu(cpu)) {
6227 				idle = false;
6228 				break;
6229 			}
6230 		}
6231 		cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
6232 
6233 		if (idle)
6234 			return core;
6235 	}
6236 
6237 	/*
6238 	 * Failed to find an idle core; stop looking for one.
6239 	 */
6240 	set_idle_cores(target, 0);
6241 
6242 	return -1;
6243 }
6244 
6245 /*
6246  * Scan the local SMT mask for idle CPUs.
6247  */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)6248 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6249 {
6250 	int cpu;
6251 
6252 	if (!static_branch_likely(&sched_smt_present))
6253 		return -1;
6254 
6255 	for_each_cpu(cpu, cpu_smt_mask(target)) {
6256 		if (!cpumask_test_cpu(cpu, p->cpus_ptr) ||
6257 		    !cpumask_test_cpu(cpu, sched_domain_span(sd)))
6258 			continue;
6259 		if (cpu_isolated(cpu))
6260 			continue;
6261 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6262 			return cpu;
6263 	}
6264 
6265 	return -1;
6266 }
6267 
6268 #else /* CONFIG_SCHED_SMT */
6269 
select_idle_core(struct task_struct * p,struct sched_domain * sd,int target)6270 static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6271 {
6272 	return -1;
6273 }
6274 
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)6275 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6276 {
6277 	return -1;
6278 }
6279 
6280 #endif /* CONFIG_SCHED_SMT */
6281 
6282 /*
6283  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6284  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6285  * average idle time for this rq (as found in rq->avg_idle).
6286  */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,int target)6287 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
6288 {
6289 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6290 	struct sched_domain *this_sd;
6291 	u64 avg_cost, avg_idle;
6292 	u64 time;
6293 	int this = smp_processor_id();
6294 	int cpu, nr = INT_MAX;
6295 
6296 	this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
6297 	if (!this_sd)
6298 		return -1;
6299 
6300 	/*
6301 	 * Due to large variance we need a large fuzz factor; hackbench in
6302 	 * particularly is sensitive here.
6303 	 */
6304 	avg_idle = this_rq()->avg_idle / 512;
6305 	avg_cost = this_sd->avg_scan_cost + 1;
6306 
6307 	if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
6308 		return -1;
6309 
6310 	if (sched_feat(SIS_PROP)) {
6311 		u64 span_avg = sd->span_weight * avg_idle;
6312 		if (span_avg > 4*avg_cost)
6313 			nr = div_u64(span_avg, avg_cost);
6314 		else
6315 			nr = 4;
6316 	}
6317 
6318 	time = cpu_clock(this);
6319 
6320 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6321 
6322 	for_each_cpu_wrap(cpu, cpus, target) {
6323 		if (!--nr)
6324 			return -1;
6325 		if (cpu_isolated(cpu))
6326 			continue;
6327 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6328 			break;
6329 	}
6330 
6331 	time = cpu_clock(this) - time;
6332 	update_avg(&this_sd->avg_scan_cost, time);
6333 
6334 	return cpu;
6335 }
6336 
6337 /*
6338  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
6339  * the task fits. If no CPU is big enough, but there are idle ones, try to
6340  * maximize capacity.
6341  */
6342 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)6343 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
6344 {
6345 	unsigned long task_util, best_cap = 0;
6346 	int cpu, best_cpu = -1;
6347 	struct cpumask *cpus;
6348 
6349 	cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6350 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6351 
6352 	task_util = uclamp_task_util(p);
6353 
6354 	for_each_cpu_wrap(cpu, cpus, target) {
6355 		unsigned long cpu_cap = capacity_of(cpu);
6356 
6357 		if (cpu_isolated(cpu))
6358 			continue;
6359 
6360 		if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
6361 			continue;
6362 		if (fits_capacity(task_util, cpu_cap))
6363 			return cpu;
6364 
6365 		if (cpu_cap > best_cap) {
6366 			best_cap = cpu_cap;
6367 			best_cpu = cpu;
6368 		}
6369 	}
6370 
6371 	return best_cpu;
6372 }
6373 
asym_fits_capacity(int task_util,int cpu)6374 static inline bool asym_fits_capacity(int task_util, int cpu)
6375 {
6376 	if (static_branch_unlikely(&sched_asym_cpucapacity))
6377 		return fits_capacity(task_util, capacity_of(cpu));
6378 
6379 	return true;
6380 }
6381 
6382 /*
6383  * Try and locate an idle core/thread in the LLC cache domain.
6384  */
select_idle_sibling(struct task_struct * p,int prev,int target)6385 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6386 {
6387 	struct sched_domain *sd;
6388 	unsigned long task_util;
6389 	int i, recent_used_cpu;
6390 
6391 	/*
6392 	 * On asymmetric system, update task utilization because we will check
6393 	 * that the task fits with cpu's capacity.
6394 	 */
6395 	if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6396 		sync_entity_load_avg(&p->se);
6397 		task_util = uclamp_task_util(p);
6398 	}
6399 
6400 	if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
6401 	    !cpu_isolated(target) && asym_fits_capacity(task_util, target))
6402 		return target;
6403 
6404 	/*
6405 	 * If the previous CPU is cache affine and idle, don't be stupid:
6406 	 */
6407 	if (prev != target && cpus_share_cache(prev, target) &&
6408 	    ((available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
6409 	    !cpu_isolated(target) && asym_fits_capacity(task_util, prev)))
6410 		return prev;
6411 
6412 	/*
6413 	 * Allow a per-cpu kthread to stack with the wakee if the
6414 	 * kworker thread and the tasks previous CPUs are the same.
6415 	 * The assumption is that the wakee queued work for the
6416 	 * per-cpu kthread that is now complete and the wakeup is
6417 	 * essentially a sync wakeup. An obvious example of this
6418 	 * pattern is IO completions.
6419 	 */
6420 	if (is_per_cpu_kthread(current) &&
6421 	    in_task() &&
6422 	    prev == smp_processor_id() &&
6423 	    this_rq()->nr_running <= 1 &&
6424 	    asym_fits_capacity(task_util, prev)) {
6425 		return prev;
6426 	}
6427 
6428 	/* Check a recently used CPU as a potential idle candidate: */
6429 	recent_used_cpu = p->recent_used_cpu;
6430 	if (recent_used_cpu != prev &&
6431 	    recent_used_cpu != target &&
6432 	    cpus_share_cache(recent_used_cpu, target) &&
6433 	    (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
6434 	    cpumask_test_cpu(p->recent_used_cpu, p->cpus_ptr) &&
6435 	    asym_fits_capacity(task_util, recent_used_cpu)) {
6436 		/*
6437 		 * Replace recent_used_cpu with prev as it is a potential
6438 		 * candidate for the next wake:
6439 		 */
6440 		p->recent_used_cpu = prev;
6441 		return recent_used_cpu;
6442 	}
6443 
6444 	/*
6445 	 * For asymmetric CPU capacity systems, our domain of interest is
6446 	 * sd_asym_cpucapacity rather than sd_llc.
6447 	 */
6448 	if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6449 		sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
6450 		/*
6451 		 * On an asymmetric CPU capacity system where an exclusive
6452 		 * cpuset defines a symmetric island (i.e. one unique
6453 		 * capacity_orig value through the cpuset), the key will be set
6454 		 * but the CPUs within that cpuset will not have a domain with
6455 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
6456 		 * capacity path.
6457 		 */
6458 		if (sd) {
6459 			i = select_idle_capacity(p, sd, target);
6460 			return ((unsigned)i < nr_cpumask_bits) ? i : target;
6461 		}
6462 	}
6463 
6464 	sd = rcu_dereference(per_cpu(sd_llc, target));
6465 	if (!sd)
6466 		return target;
6467 
6468 	i = select_idle_core(p, sd, target);
6469 	if ((unsigned)i < nr_cpumask_bits)
6470 		return i;
6471 
6472 	i = select_idle_cpu(p, sd, target);
6473 	if ((unsigned)i < nr_cpumask_bits)
6474 		return i;
6475 
6476 	i = select_idle_smt(p, sd, target);
6477 	if ((unsigned)i < nr_cpumask_bits)
6478 		return i;
6479 
6480 	return target;
6481 }
6482 
6483 /**
6484  * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
6485  * @cpu: the CPU to get the utilization of
6486  *
6487  * The unit of the return value must be the one of capacity so we can compare
6488  * the utilization with the capacity of the CPU that is available for CFS task
6489  * (ie cpu_capacity).
6490  *
6491  * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
6492  * recent utilization of currently non-runnable tasks on a CPU. It represents
6493  * the amount of utilization of a CPU in the range [0..capacity_orig] where
6494  * capacity_orig is the cpu_capacity available at the highest frequency
6495  * (arch_scale_freq_capacity()).
6496  * The utilization of a CPU converges towards a sum equal to or less than the
6497  * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
6498  * the running time on this CPU scaled by capacity_curr.
6499  *
6500  * The estimated utilization of a CPU is defined to be the maximum between its
6501  * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
6502  * currently RUNNABLE on that CPU.
6503  * This allows to properly represent the expected utilization of a CPU which
6504  * has just got a big task running since a long sleep period. At the same time
6505  * however it preserves the benefits of the "blocked utilization" in
6506  * describing the potential for other tasks waking up on the same CPU.
6507  *
6508  * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
6509  * higher than capacity_orig because of unfortunate rounding in
6510  * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
6511  * the average stabilizes with the new running time. We need to check that the
6512  * utilization stays within the range of [0..capacity_orig] and cap it if
6513  * necessary. Without utilization capping, a group could be seen as overloaded
6514  * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
6515  * available capacity. We allow utilization to overshoot capacity_curr (but not
6516  * capacity_orig) as it useful for predicting the capacity required after task
6517  * migrations (scheduler-driven DVFS).
6518  *
6519  * Return: the (estimated) utilization for the specified CPU
6520  */
cpu_util(int cpu)6521 unsigned long cpu_util(int cpu)
6522 {
6523 	struct cfs_rq *cfs_rq;
6524 	unsigned int util;
6525 
6526 #ifdef CONFIG_SCHED_WALT
6527 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
6528 		u64 walt_cpu_util =
6529 			cpu_rq(cpu)->walt_stats.cumulative_runnable_avg_scaled;
6530 
6531 		return min_t(unsigned long, walt_cpu_util,
6532 				capacity_orig_of(cpu));
6533 	}
6534 #endif
6535 
6536 	cfs_rq = &cpu_rq(cpu)->cfs;
6537 	util = READ_ONCE(cfs_rq->avg.util_avg);
6538 
6539 	if (sched_feat(UTIL_EST))
6540 		util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
6541 
6542 	return min_t(unsigned long, util, capacity_orig_of(cpu));
6543 }
6544 
6545 /*
6546  * cpu_util_without: compute cpu utilization without any contributions from *p
6547  * @cpu: the CPU which utilization is requested
6548  * @p: the task which utilization should be discounted
6549  *
6550  * The utilization of a CPU is defined by the utilization of tasks currently
6551  * enqueued on that CPU as well as tasks which are currently sleeping after an
6552  * execution on that CPU.
6553  *
6554  * This method returns the utilization of the specified CPU by discounting the
6555  * utilization of the specified task, whenever the task is currently
6556  * contributing to the CPU utilization.
6557  */
cpu_util_without(int cpu,struct task_struct * p)6558 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
6559 {
6560 	struct cfs_rq *cfs_rq;
6561 	unsigned int util;
6562 
6563 #ifdef CONFIG_SCHED_WALT
6564 	/*
6565 	 * WALT does not decay idle tasks in the same manner
6566 	 * as PELT, so it makes little sense to subtract task
6567 	 * utilization from cpu utilization. Instead just use
6568 	 * cpu_util for this case.
6569 	 */
6570 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util) &&
6571 						p->state == TASK_WAKING)
6572 		return cpu_util(cpu);
6573 #endif
6574 
6575 	/* Task has no contribution or is new */
6576 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6577 		return cpu_util(cpu);
6578 
6579 #ifdef CONFIG_SCHED_WALT
6580 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
6581 		util = max_t(long, cpu_util(cpu) - task_util(p), 0);
6582 		return min_t(unsigned long, util, capacity_orig_of(cpu));
6583 	}
6584 #endif
6585 
6586 	cfs_rq = &cpu_rq(cpu)->cfs;
6587 	util = READ_ONCE(cfs_rq->avg.util_avg);
6588 
6589 	/* Discount task's util from CPU's util */
6590 	lsub_positive(&util, task_util(p));
6591 
6592 	/*
6593 	 * Covered cases:
6594 	 *
6595 	 * a) if *p is the only task sleeping on this CPU, then:
6596 	 *      cpu_util (== task_util) > util_est (== 0)
6597 	 *    and thus we return:
6598 	 *      cpu_util_without = (cpu_util - task_util) = 0
6599 	 *
6600 	 * b) if other tasks are SLEEPING on this CPU, which is now exiting
6601 	 *    IDLE, then:
6602 	 *      cpu_util >= task_util
6603 	 *      cpu_util > util_est (== 0)
6604 	 *    and thus we discount *p's blocked utilization to return:
6605 	 *      cpu_util_without = (cpu_util - task_util) >= 0
6606 	 *
6607 	 * c) if other tasks are RUNNABLE on that CPU and
6608 	 *      util_est > cpu_util
6609 	 *    then we use util_est since it returns a more restrictive
6610 	 *    estimation of the spare capacity on that CPU, by just
6611 	 *    considering the expected utilization of tasks already
6612 	 *    runnable on that CPU.
6613 	 *
6614 	 * Cases a) and b) are covered by the above code, while case c) is
6615 	 * covered by the following code when estimated utilization is
6616 	 * enabled.
6617 	 */
6618 	if (sched_feat(UTIL_EST)) {
6619 		unsigned int estimated =
6620 			READ_ONCE(cfs_rq->avg.util_est.enqueued);
6621 
6622 		/*
6623 		 * Despite the following checks we still have a small window
6624 		 * for a possible race, when an execl's select_task_rq_fair()
6625 		 * races with LB's detach_task():
6626 		 *
6627 		 *   detach_task()
6628 		 *     p->on_rq = TASK_ON_RQ_MIGRATING;
6629 		 *     ---------------------------------- A
6630 		 *     deactivate_task()                   \
6631 		 *       dequeue_task()                     + RaceTime
6632 		 *         util_est_dequeue()              /
6633 		 *     ---------------------------------- B
6634 		 *
6635 		 * The additional check on "current == p" it's required to
6636 		 * properly fix the execl regression and it helps in further
6637 		 * reducing the chances for the above race.
6638 		 */
6639 		if (unlikely(task_on_rq_queued(p) || current == p))
6640 			lsub_positive(&estimated, _task_util_est(p));
6641 
6642 		util = max(util, estimated);
6643 	}
6644 
6645 	/*
6646 	 * Utilization (estimated) can exceed the CPU capacity, thus let's
6647 	 * clamp to the maximum CPU capacity to ensure consistency with
6648 	 * the cpu_util call.
6649 	 */
6650 	return min_t(unsigned long, util, capacity_orig_of(cpu));
6651 }
6652 
6653 #ifdef CONFIG_SCHED_RTG
capacity_spare_without(int cpu,struct task_struct * p)6654 unsigned long capacity_spare_without(int cpu, struct task_struct *p)
6655 {
6656 	return max_t(long, capacity_of(cpu) - cpu_util_without(cpu, p), 0);
6657 }
6658 #endif
6659 /*
6660  * Predicts what cpu_util(@cpu) would return if @p was migrated (and enqueued)
6661  * to @dst_cpu.
6662  */
cpu_util_next(int cpu,struct task_struct * p,int dst_cpu)6663 static unsigned long cpu_util_next(int cpu, struct task_struct *p, int dst_cpu)
6664 {
6665 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
6666 	unsigned long util_est, util = READ_ONCE(cfs_rq->avg.util_avg);
6667 
6668 	/*
6669 	 * If @p migrates from @cpu to another, remove its contribution. Or,
6670 	 * if @p migrates from another CPU to @cpu, add its contribution. In
6671 	 * the other cases, @cpu is not impacted by the migration, so the
6672 	 * util_avg should already be correct.
6673 	 */
6674 	if (task_cpu(p) == cpu && dst_cpu != cpu)
6675 		sub_positive(&util, task_util(p));
6676 	else if (task_cpu(p) != cpu && dst_cpu == cpu)
6677 		util += task_util(p);
6678 
6679 	if (sched_feat(UTIL_EST)) {
6680 		util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
6681 
6682 		/*
6683 		 * During wake-up, the task isn't enqueued yet and doesn't
6684 		 * appear in the cfs_rq->avg.util_est.enqueued of any rq,
6685 		 * so just add it (if needed) to "simulate" what will be
6686 		 * cpu_util() after the task has been enqueued.
6687 		 */
6688 		if (dst_cpu == cpu)
6689 			util_est += _task_util_est(p);
6690 
6691 		util = max(util, util_est);
6692 	}
6693 
6694 	return min(util, capacity_orig_of(cpu));
6695 }
6696 
6697 /*
6698  * Returns the current capacity of cpu after applying both
6699  * cpu and freq scaling.
6700  */
capacity_curr_of(int cpu)6701 unsigned long capacity_curr_of(int cpu)
6702 {
6703 	unsigned long max_cap = cpu_rq(cpu)->cpu_capacity_orig;
6704 	unsigned long scale_freq = arch_scale_freq_capacity(cpu);
6705 
6706 	return cap_scale(max_cap, scale_freq);
6707 }
6708 
6709 /*
6710  * compute_energy(): Estimates the energy that @pd would consume if @p was
6711  * migrated to @dst_cpu. compute_energy() predicts what will be the utilization
6712  * landscape of @pd's CPUs after the task migration, and uses the Energy Model
6713  * to compute what would be the energy if we decided to actually migrate that
6714  * task.
6715  */
6716 static long
compute_energy(struct task_struct * p,int dst_cpu,struct perf_domain * pd)6717 compute_energy(struct task_struct *p, int dst_cpu, struct perf_domain *pd)
6718 {
6719 	struct cpumask *pd_mask = perf_domain_span(pd);
6720 	unsigned long cpu_cap = arch_scale_cpu_capacity(cpumask_first(pd_mask));
6721 	unsigned long max_util = 0, sum_util = 0;
6722 	int cpu;
6723 
6724 	/*
6725 	 * The capacity state of CPUs of the current rd can be driven by CPUs
6726 	 * of another rd if they belong to the same pd. So, account for the
6727 	 * utilization of these CPUs too by masking pd with cpu_online_mask
6728 	 * instead of the rd span.
6729 	 *
6730 	 * If an entire pd is outside of the current rd, it will not appear in
6731 	 * its pd list and will not be accounted by compute_energy().
6732 	 */
6733 	for_each_cpu_and(cpu, pd_mask, cpu_online_mask) {
6734 		unsigned long cpu_util, util_cfs = cpu_util_next(cpu, p, dst_cpu);
6735 		struct task_struct *tsk = cpu == dst_cpu ? p : NULL;
6736 
6737 		/*
6738 		 * Busy time computation: utilization clamping is not
6739 		 * required since the ratio (sum_util / cpu_capacity)
6740 		 * is already enough to scale the EM reported power
6741 		 * consumption at the (eventually clamped) cpu_capacity.
6742 		 */
6743 		sum_util += schedutil_cpu_util(cpu, util_cfs, cpu_cap,
6744 					       ENERGY_UTIL, NULL);
6745 
6746 		/*
6747 		 * Performance domain frequency: utilization clamping
6748 		 * must be considered since it affects the selection
6749 		 * of the performance domain frequency.
6750 		 * NOTE: in case RT tasks are running, by default the
6751 		 * FREQUENCY_UTIL's utilization can be max OPP.
6752 		 */
6753 		cpu_util = schedutil_cpu_util(cpu, util_cfs, cpu_cap,
6754 					      FREQUENCY_UTIL, tsk);
6755 		max_util = max(max_util, cpu_util);
6756 	}
6757 
6758 	return em_cpu_energy(pd->em_pd, max_util, sum_util);
6759 }
6760 
6761 /*
6762  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
6763  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
6764  * spare capacity in each performance domain and uses it as a potential
6765  * candidate to execute the task. Then, it uses the Energy Model to figure
6766  * out which of the CPU candidates is the most energy-efficient.
6767  *
6768  * The rationale for this heuristic is as follows. In a performance domain,
6769  * all the most energy efficient CPU candidates (according to the Energy
6770  * Model) are those for which we'll request a low frequency. When there are
6771  * several CPUs for which the frequency request will be the same, we don't
6772  * have enough data to break the tie between them, because the Energy Model
6773  * only includes active power costs. With this model, if we assume that
6774  * frequency requests follow utilization (e.g. using schedutil), the CPU with
6775  * the maximum spare capacity in a performance domain is guaranteed to be among
6776  * the best candidates of the performance domain.
6777  *
6778  * In practice, it could be preferable from an energy standpoint to pack
6779  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
6780  * but that could also hurt our chances to go cluster idle, and we have no
6781  * ways to tell with the current Energy Model if this is actually a good
6782  * idea or not. So, find_energy_efficient_cpu() basically favors
6783  * cluster-packing, and spreading inside a cluster. That should at least be
6784  * a good thing for latency, and this is consistent with the idea that most
6785  * of the energy savings of EAS come from the asymmetry of the system, and
6786  * not so much from breaking the tie between identical CPUs. That's also the
6787  * reason why EAS is enabled in the topology code only for systems where
6788  * SD_ASYM_CPUCAPACITY is set.
6789  *
6790  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
6791  * they don't have any useful utilization data yet and it's not possible to
6792  * forecast their impact on energy consumption. Consequently, they will be
6793  * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
6794  * to be energy-inefficient in some use-cases. The alternative would be to
6795  * bias new tasks towards specific types of CPUs first, or to try to infer
6796  * their util_avg from the parent task, but those heuristics could hurt
6797  * other use-cases too. So, until someone finds a better way to solve this,
6798  * let's keep things simple by re-using the existing slow path.
6799  */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)6800 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
6801 {
6802 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
6803 	struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6804 	unsigned long cpu_cap, util, base_energy = 0;
6805 	int cpu, best_energy_cpu = prev_cpu;
6806 	struct sched_domain *sd;
6807 	struct perf_domain *pd;
6808 
6809 	rcu_read_lock();
6810 	pd = rcu_dereference(rd->pd);
6811 	if (!pd || READ_ONCE(rd->overutilized))
6812 		goto fail;
6813 
6814 	/*
6815 	 * Energy-aware wake-up happens on the lowest sched_domain starting
6816 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
6817 	 */
6818 	sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
6819 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
6820 		sd = sd->parent;
6821 	if (!sd)
6822 		goto fail;
6823 
6824 	sync_entity_load_avg(&p->se);
6825 	if (!task_util_est(p))
6826 		goto unlock;
6827 
6828 	for (; pd; pd = pd->next) {
6829 		unsigned long cur_delta, spare_cap, max_spare_cap = 0;
6830 		unsigned long base_energy_pd;
6831 		int max_spare_cap_cpu = -1;
6832 
6833 		/* Compute the 'base' energy of the pd, without @p */
6834 		base_energy_pd = compute_energy(p, -1, pd);
6835 		base_energy += base_energy_pd;
6836 
6837 		for_each_cpu_and(cpu, perf_domain_span(pd), sched_domain_span(sd)) {
6838 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
6839 				continue;
6840 
6841 			util = cpu_util_next(cpu, p, cpu);
6842 			cpu_cap = capacity_of(cpu);
6843 			spare_cap = cpu_cap;
6844 			lsub_positive(&spare_cap, util);
6845 
6846 			/*
6847 			 * Skip CPUs that cannot satisfy the capacity request.
6848 			 * IOW, placing the task there would make the CPU
6849 			 * overutilized. Take uclamp into account to see how
6850 			 * much capacity we can get out of the CPU; this is
6851 			 * aligned with schedutil_cpu_util().
6852 			 */
6853 			util = uclamp_rq_util_with(cpu_rq(cpu), util, p);
6854 			if (!fits_capacity(util, cpu_cap))
6855 				continue;
6856 
6857 			/* Always use prev_cpu as a candidate. */
6858 			if (cpu == prev_cpu) {
6859 				prev_delta = compute_energy(p, prev_cpu, pd);
6860 				prev_delta -= base_energy_pd;
6861 				best_delta = min(best_delta, prev_delta);
6862 			}
6863 
6864 			/*
6865 			 * Find the CPU with the maximum spare capacity in
6866 			 * the performance domain
6867 			 */
6868 			if (spare_cap > max_spare_cap) {
6869 				max_spare_cap = spare_cap;
6870 				max_spare_cap_cpu = cpu;
6871 			}
6872 		}
6873 
6874 		/* Evaluate the energy impact of using this CPU. */
6875 		if (max_spare_cap_cpu >= 0 && max_spare_cap_cpu != prev_cpu) {
6876 			cur_delta = compute_energy(p, max_spare_cap_cpu, pd);
6877 			cur_delta -= base_energy_pd;
6878 			if (cur_delta < best_delta) {
6879 				best_delta = cur_delta;
6880 				best_energy_cpu = max_spare_cap_cpu;
6881 			}
6882 		}
6883 	}
6884 unlock:
6885 	rcu_read_unlock();
6886 
6887 	/*
6888 	 * Pick the best CPU if prev_cpu cannot be used, or if it saves at
6889 	 * least 6% of the energy used by prev_cpu.
6890 	 */
6891 	if (prev_delta == ULONG_MAX)
6892 		return best_energy_cpu;
6893 
6894 	if ((prev_delta - best_delta) > ((prev_delta + base_energy) >> 4))
6895 		return best_energy_cpu;
6896 
6897 	return prev_cpu;
6898 
6899 fail:
6900 	rcu_read_unlock();
6901 
6902 	return -1;
6903 }
6904 
6905 /*
6906  * select_task_rq_fair: Select target runqueue for the waking task in domains
6907  * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
6908  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
6909  *
6910  * Balances load by selecting the idlest CPU in the idlest group, or under
6911  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
6912  *
6913  * Returns the target CPU number.
6914  *
6915  * preempt must be disabled.
6916  */
6917 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int sd_flag,int wake_flags)6918 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
6919 {
6920 	struct sched_domain *tmp, *sd = NULL;
6921 	int cpu = smp_processor_id();
6922 	int new_cpu = prev_cpu;
6923 	int want_affine = 0;
6924 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
6925 #ifdef CONFIG_SCHED_RTG
6926 	int target_cpu = -1;
6927 		target_cpu = find_rtg_cpu(p);
6928 		if (target_cpu >= 0)
6929 			return target_cpu;
6930 #endif
6931 
6932 	if (sd_flag & SD_BALANCE_WAKE) {
6933 		record_wakee(p);
6934 
6935 		if (sched_energy_enabled()) {
6936 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
6937 			if (new_cpu >= 0)
6938 				return new_cpu;
6939 			new_cpu = prev_cpu;
6940 		}
6941 
6942 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
6943 	}
6944 
6945 	rcu_read_lock();
6946 	for_each_domain(cpu, tmp) {
6947 		/*
6948 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
6949 		 * cpu is a valid SD_WAKE_AFFINE target.
6950 		 */
6951 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6952 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
6953 			if (cpu != prev_cpu)
6954 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
6955 
6956 			sd = NULL; /* Prefer wake_affine over balance flags */
6957 			break;
6958 		}
6959 
6960 		if (tmp->flags & sd_flag)
6961 			sd = tmp;
6962 		else if (!want_affine)
6963 			break;
6964 	}
6965 
6966 	if (unlikely(sd)) {
6967 		/* Slow path */
6968 		new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
6969 	} else if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
6970 		/* Fast path */
6971 
6972 		new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6973 
6974 		if (want_affine)
6975 			current->recent_used_cpu = cpu;
6976 	}
6977 	rcu_read_unlock();
6978 
6979 	return new_cpu;
6980 }
6981 
6982 static void detach_entity_cfs_rq(struct sched_entity *se);
6983 
6984 /*
6985  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
6986  * cfs_rq_of(p) references at time of call are still valid and identify the
6987  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
6988  */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)6989 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
6990 {
6991 	/*
6992 	 * As blocked tasks retain absolute vruntime the migration needs to
6993 	 * deal with this by subtracting the old and adding the new
6994 	 * min_vruntime -- the latter is done by enqueue_entity() when placing
6995 	 * the task on the new runqueue.
6996 	 */
6997 	if (p->state == TASK_WAKING) {
6998 		struct sched_entity *se = &p->se;
6999 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
7000 		u64 min_vruntime;
7001 
7002 #ifndef CONFIG_64BIT
7003 		u64 min_vruntime_copy;
7004 
7005 		do {
7006 			min_vruntime_copy = cfs_rq->min_vruntime_copy;
7007 			smp_rmb();
7008 			min_vruntime = cfs_rq->min_vruntime;
7009 		} while (min_vruntime != min_vruntime_copy);
7010 #else
7011 		min_vruntime = cfs_rq->min_vruntime;
7012 #endif
7013 
7014 		se->vruntime -= min_vruntime;
7015 	}
7016 
7017 	if (p->on_rq == TASK_ON_RQ_MIGRATING) {
7018 		/*
7019 		 * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
7020 		 * rq->lock and can modify state directly.
7021 		 */
7022 		lockdep_assert_held(&task_rq(p)->lock);
7023 		detach_entity_cfs_rq(&p->se);
7024 
7025 	} else {
7026 		/*
7027 		 * We are supposed to update the task to "current" time, then
7028 		 * its up to date and ready to go to new CPU/cfs_rq. But we
7029 		 * have difficulty in getting what current time is, so simply
7030 		 * throw away the out-of-date time. This will result in the
7031 		 * wakee task is less decayed, but giving the wakee more load
7032 		 * sounds not bad.
7033 		 */
7034 		remove_entity_load_avg(&p->se);
7035 	}
7036 
7037 	/* Tell new CPU we are migrated */
7038 	p->se.avg.last_update_time = 0;
7039 
7040 	/* We have migrated, no longer consider this task hot */
7041 	p->se.exec_start = 0;
7042 
7043 	update_scan_period(p, new_cpu);
7044 }
7045 
task_dead_fair(struct task_struct * p)7046 static void task_dead_fair(struct task_struct *p)
7047 {
7048 	remove_entity_load_avg(&p->se);
7049 }
7050 
7051 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)7052 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7053 {
7054 	if (rq->nr_running)
7055 		return 1;
7056 
7057 	return newidle_balance(rq, rf) != 0;
7058 }
7059 #endif /* CONFIG_SMP */
7060 
7061 #ifdef CONFIG_SCHED_LATENCY_NICE
wakeup_latency_gran(struct sched_entity * curr,struct sched_entity * se)7062 static long wakeup_latency_gran(struct sched_entity *curr, struct sched_entity *se)
7063 {
7064 	int latency_weight = se->latency_weight;
7065 	long thresh = sysctl_sched_latency;
7066 
7067 	/*
7068 	 * A positive latency weigth means that the sched_entity has latency
7069 	 * requirement that needs to be evaluated versus other entity.
7070 	 * Otherwise, use the latency weight to evaluate how much scheduling
7071 	 * delay is acceptable by se.
7072 	 */
7073 	if ((se->latency_weight > 0) || (curr->latency_weight > 0))
7074 		latency_weight -= curr->latency_weight;
7075 
7076 	if (!latency_weight)
7077 		return 0;
7078 
7079 	if (sched_feat(GENTLE_FAIR_SLEEPERS))
7080 		thresh >>= 1;
7081 
7082 	/*
7083 	 * Clamp the delta to stay in the scheduler period range
7084 	 * [-sysctl_sched_latency:sysctl_sched_latency]
7085 	 */
7086 	latency_weight = clamp_t(long, latency_weight,
7087 				-1 * NICE_LATENCY_WEIGHT_MAX,
7088 				NICE_LATENCY_WEIGHT_MAX);
7089 
7090 	return (thresh * latency_weight) >> NICE_LATENCY_SHIFT;
7091 }
7092 #endif
7093 
wakeup_gran(struct sched_entity * se)7094 static unsigned long wakeup_gran(struct sched_entity *se)
7095 {
7096 	unsigned long gran = sysctl_sched_wakeup_granularity;
7097 
7098 	/*
7099 	 * Since its curr running now, convert the gran from real-time
7100 	 * to virtual-time in his units.
7101 	 *
7102 	 * By using 'se' instead of 'curr' we penalize light tasks, so
7103 	 * they get preempted easier. That is, if 'se' < 'curr' then
7104 	 * the resulting gran will be larger, therefore penalizing the
7105 	 * lighter, if otoh 'se' > 'curr' then the resulting gran will
7106 	 * be smaller, again penalizing the lighter task.
7107 	 *
7108 	 * This is especially important for buddies when the leftmost
7109 	 * task is higher priority than the buddy.
7110 	 */
7111 	return calc_delta_fair(gran, se);
7112 }
7113 
7114 /*
7115  * Should 'se' preempt 'curr'.
7116  *
7117  *             |s1
7118  *        |s2
7119  *   |s3
7120  *         g
7121  *      |<--->|c
7122  *
7123  *  w(c, s1) = -1
7124  *  w(c, s2) =  0
7125  *  w(c, s3) =  1
7126  *
7127  */
7128 static int
wakeup_preempt_entity(struct sched_entity * curr,struct sched_entity * se)7129 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
7130 {
7131 	s64 gran, vdiff = curr->vruntime - se->vruntime;
7132 
7133 #ifdef CONFIG_SCHED_LATENCY_NICE
7134 	/* Take into account latency priority */
7135 	vdiff += wakeup_latency_gran(curr, se);
7136 #endif
7137 
7138 	if (vdiff <= 0)
7139 		return -1;
7140 
7141 	gran = wakeup_gran(se);
7142 	if (vdiff > gran)
7143 		return 1;
7144 
7145 	return 0;
7146 }
7147 
set_last_buddy(struct sched_entity * se)7148 static void set_last_buddy(struct sched_entity *se)
7149 {
7150 	if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
7151 		return;
7152 
7153 	for_each_sched_entity(se) {
7154 		if (SCHED_WARN_ON(!se->on_rq))
7155 			return;
7156 		cfs_rq_of(se)->last = se;
7157 	}
7158 }
7159 
set_next_buddy(struct sched_entity * se)7160 static void set_next_buddy(struct sched_entity *se)
7161 {
7162 	if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
7163 		return;
7164 
7165 	for_each_sched_entity(se) {
7166 		if (SCHED_WARN_ON(!se->on_rq))
7167 			return;
7168 		cfs_rq_of(se)->next = se;
7169 	}
7170 }
7171 
set_skip_buddy(struct sched_entity * se)7172 static void set_skip_buddy(struct sched_entity *se)
7173 {
7174 	for_each_sched_entity(se)
7175 		cfs_rq_of(se)->skip = se;
7176 }
7177 
7178 /*
7179  * Preempt the current task with a newly woken task if needed:
7180  */
check_preempt_wakeup(struct rq * rq,struct task_struct * p,int wake_flags)7181 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
7182 {
7183 	struct task_struct *curr = rq->curr;
7184 	struct sched_entity *se = &curr->se, *pse = &p->se;
7185 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7186 	int scale = cfs_rq->nr_running >= sched_nr_latency;
7187 	int next_buddy_marked = 0;
7188 
7189 	if (unlikely(se == pse))
7190 		return;
7191 
7192 	/*
7193 	 * This is possible from callers such as attach_tasks(), in which we
7194 	 * unconditionally check_prempt_curr() after an enqueue (which may have
7195 	 * lead to a throttle).  This both saves work and prevents false
7196 	 * next-buddy nomination below.
7197 	 */
7198 	if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
7199 		return;
7200 
7201 	if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
7202 		set_next_buddy(pse);
7203 		next_buddy_marked = 1;
7204 	}
7205 
7206 	/*
7207 	 * We can come here with TIF_NEED_RESCHED already set from new task
7208 	 * wake up path.
7209 	 *
7210 	 * Note: this also catches the edge-case of curr being in a throttled
7211 	 * group (e.g. via set_curr_task), since update_curr() (in the
7212 	 * enqueue of curr) will have resulted in resched being set.  This
7213 	 * prevents us from potentially nominating it as a false LAST_BUDDY
7214 	 * below.
7215 	 */
7216 	if (test_tsk_need_resched(curr))
7217 		return;
7218 
7219 	/* Idle tasks are by definition preempted by non-idle tasks. */
7220 	if (unlikely(task_has_idle_policy(curr)) &&
7221 	    likely(!task_has_idle_policy(p)))
7222 		goto preempt;
7223 
7224 	/*
7225 	 * Batch and idle tasks do not preempt non-idle tasks (their preemption
7226 	 * is driven by the tick):
7227 	 */
7228 	if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
7229 		return;
7230 
7231 	find_matching_se(&se, &pse);
7232 	update_curr(cfs_rq_of(se));
7233 	BUG_ON(!pse);
7234 	if (wakeup_preempt_entity(se, pse) == 1) {
7235 		/*
7236 		 * Bias pick_next to pick the sched entity that is
7237 		 * triggering this preemption.
7238 		 */
7239 		if (!next_buddy_marked)
7240 			set_next_buddy(pse);
7241 		goto preempt;
7242 	}
7243 
7244 	return;
7245 
7246 preempt:
7247 	resched_curr(rq);
7248 	/*
7249 	 * Only set the backward buddy when the current task is still
7250 	 * on the rq. This can happen when a wakeup gets interleaved
7251 	 * with schedule on the ->pre_schedule() or idle_balance()
7252 	 * point, either of which can * drop the rq lock.
7253 	 *
7254 	 * Also, during early boot the idle thread is in the fair class,
7255 	 * for obvious reasons its a bad idea to schedule back to it.
7256 	 */
7257 	if (unlikely(!se->on_rq || curr == rq->idle))
7258 		return;
7259 
7260 	if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7261 		set_last_buddy(se);
7262 }
7263 
7264 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)7265 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7266 {
7267 	struct cfs_rq *cfs_rq = &rq->cfs;
7268 	struct sched_entity *se;
7269 	struct task_struct *p;
7270 	int new_tasks;
7271 
7272 again:
7273 	if (!sched_fair_runnable(rq))
7274 		goto idle;
7275 
7276 #ifdef CONFIG_FAIR_GROUP_SCHED
7277 	if (!prev || prev->sched_class != &fair_sched_class)
7278 		goto simple;
7279 
7280 	/*
7281 	 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7282 	 * likely that a next task is from the same cgroup as the current.
7283 	 *
7284 	 * Therefore attempt to avoid putting and setting the entire cgroup
7285 	 * hierarchy, only change the part that actually changes.
7286 	 */
7287 
7288 	do {
7289 		struct sched_entity *curr = cfs_rq->curr;
7290 
7291 		/*
7292 		 * Since we got here without doing put_prev_entity() we also
7293 		 * have to consider cfs_rq->curr. If it is still a runnable
7294 		 * entity, update_curr() will update its vruntime, otherwise
7295 		 * forget we've ever seen it.
7296 		 */
7297 		if (curr) {
7298 			if (curr->on_rq)
7299 				update_curr(cfs_rq);
7300 			else
7301 				curr = NULL;
7302 
7303 			/*
7304 			 * This call to check_cfs_rq_runtime() will do the
7305 			 * throttle and dequeue its entity in the parent(s).
7306 			 * Therefore the nr_running test will indeed
7307 			 * be correct.
7308 			 */
7309 			if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
7310 				cfs_rq = &rq->cfs;
7311 
7312 				if (!cfs_rq->nr_running)
7313 					goto idle;
7314 
7315 				goto simple;
7316 			}
7317 		}
7318 
7319 		se = pick_next_entity(cfs_rq, curr);
7320 		cfs_rq = group_cfs_rq(se);
7321 	} while (cfs_rq);
7322 
7323 	p = task_of(se);
7324 
7325 	/*
7326 	 * Since we haven't yet done put_prev_entity and if the selected task
7327 	 * is a different task than we started out with, try and touch the
7328 	 * least amount of cfs_rqs.
7329 	 */
7330 	if (prev != p) {
7331 		struct sched_entity *pse = &prev->se;
7332 
7333 		while (!(cfs_rq = is_same_group(se, pse))) {
7334 			int se_depth = se->depth;
7335 			int pse_depth = pse->depth;
7336 
7337 			if (se_depth <= pse_depth) {
7338 				put_prev_entity(cfs_rq_of(pse), pse);
7339 				pse = parent_entity(pse);
7340 			}
7341 			if (se_depth >= pse_depth) {
7342 				set_next_entity(cfs_rq_of(se), se);
7343 				se = parent_entity(se);
7344 			}
7345 		}
7346 
7347 		put_prev_entity(cfs_rq, pse);
7348 		set_next_entity(cfs_rq, se);
7349 	}
7350 
7351 	goto done;
7352 simple:
7353 #endif
7354 	if (prev)
7355 		put_prev_task(rq, prev);
7356 
7357 	do {
7358 		se = pick_next_entity(cfs_rq, NULL);
7359 		set_next_entity(cfs_rq, se);
7360 		cfs_rq = group_cfs_rq(se);
7361 	} while (cfs_rq);
7362 
7363 	p = task_of(se);
7364 
7365 done: __maybe_unused;
7366 #ifdef CONFIG_SMP
7367 	/*
7368 	 * Move the next running task to the front of
7369 	 * the list, so our cfs_tasks list becomes MRU
7370 	 * one.
7371 	 */
7372 	list_move(&p->se.group_node, &rq->cfs_tasks);
7373 #endif
7374 
7375 	if (hrtick_enabled(rq))
7376 		hrtick_start_fair(rq, p);
7377 
7378 	update_misfit_status(p, rq);
7379 
7380 	return p;
7381 
7382 idle:
7383 	if (!rf)
7384 		return NULL;
7385 
7386 	new_tasks = newidle_balance(rq, rf);
7387 
7388 	/*
7389 	 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
7390 	 * possible for any higher priority task to appear. In that case we
7391 	 * must re-start the pick_next_entity() loop.
7392 	 */
7393 	if (new_tasks < 0)
7394 		return RETRY_TASK;
7395 
7396 	if (new_tasks > 0)
7397 		goto again;
7398 
7399 	/*
7400 	 * rq is about to be idle, check if we need to update the
7401 	 * lost_idle_time of clock_pelt
7402 	 */
7403 	update_idle_rq_clock_pelt(rq);
7404 
7405 	return NULL;
7406 }
7407 
__pick_next_task_fair(struct rq * rq)7408 static struct task_struct *__pick_next_task_fair(struct rq *rq)
7409 {
7410 	return pick_next_task_fair(rq, NULL, NULL);
7411 }
7412 
7413 /*
7414  * Account for a descheduled task:
7415  */
put_prev_task_fair(struct rq * rq,struct task_struct * prev)7416 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
7417 {
7418 	struct sched_entity *se = &prev->se;
7419 	struct cfs_rq *cfs_rq;
7420 
7421 	for_each_sched_entity(se) {
7422 		cfs_rq = cfs_rq_of(se);
7423 		put_prev_entity(cfs_rq, se);
7424 	}
7425 }
7426 
7427 /*
7428  * sched_yield() is very simple
7429  *
7430  * The magic of dealing with the ->skip buddy is in pick_next_entity.
7431  */
yield_task_fair(struct rq * rq)7432 static void yield_task_fair(struct rq *rq)
7433 {
7434 	struct task_struct *curr = rq->curr;
7435 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7436 	struct sched_entity *se = &curr->se;
7437 
7438 	/*
7439 	 * Are we the only task in the tree?
7440 	 */
7441 	if (unlikely(rq->nr_running == 1))
7442 		return;
7443 
7444 	clear_buddies(cfs_rq, se);
7445 
7446 	if (curr->policy != SCHED_BATCH) {
7447 		update_rq_clock(rq);
7448 		/*
7449 		 * Update run-time statistics of the 'current'.
7450 		 */
7451 		update_curr(cfs_rq);
7452 		/*
7453 		 * Tell update_rq_clock() that we've just updated,
7454 		 * so we don't do microscopic update in schedule()
7455 		 * and double the fastpath cost.
7456 		 */
7457 		rq_clock_skip_update(rq);
7458 	}
7459 
7460 	set_skip_buddy(se);
7461 }
7462 
yield_to_task_fair(struct rq * rq,struct task_struct * p)7463 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
7464 {
7465 	struct sched_entity *se = &p->se;
7466 
7467 	/* throttled hierarchies are not runnable */
7468 	if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
7469 		return false;
7470 
7471 	/* Tell the scheduler that we'd really like pse to run next. */
7472 	set_next_buddy(se);
7473 
7474 	yield_task_fair(rq);
7475 
7476 	return true;
7477 }
7478 
7479 #ifdef CONFIG_SMP
7480 /**************************************************
7481  * Fair scheduling class load-balancing methods.
7482  *
7483  * BASICS
7484  *
7485  * The purpose of load-balancing is to achieve the same basic fairness the
7486  * per-CPU scheduler provides, namely provide a proportional amount of compute
7487  * time to each task. This is expressed in the following equation:
7488  *
7489  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
7490  *
7491  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
7492  * W_i,0 is defined as:
7493  *
7494  *   W_i,0 = \Sum_j w_i,j                                             (2)
7495  *
7496  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
7497  * is derived from the nice value as per sched_prio_to_weight[].
7498  *
7499  * The weight average is an exponential decay average of the instantaneous
7500  * weight:
7501  *
7502  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
7503  *
7504  * C_i is the compute capacity of CPU i, typically it is the
7505  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7506  * can also include other factors [XXX].
7507  *
7508  * To achieve this balance we define a measure of imbalance which follows
7509  * directly from (1):
7510  *
7511  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
7512  *
7513  * We them move tasks around to minimize the imbalance. In the continuous
7514  * function space it is obvious this converges, in the discrete case we get
7515  * a few fun cases generally called infeasible weight scenarios.
7516  *
7517  * [XXX expand on:
7518  *     - infeasible weights;
7519  *     - local vs global optima in the discrete case. ]
7520  *
7521  *
7522  * SCHED DOMAINS
7523  *
7524  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
7525  * for all i,j solution, we create a tree of CPUs that follows the hardware
7526  * topology where each level pairs two lower groups (or better). This results
7527  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
7528  * tree to only the first of the previous level and we decrease the frequency
7529  * of load-balance at each level inv. proportional to the number of CPUs in
7530  * the groups.
7531  *
7532  * This yields:
7533  *
7534  *     log_2 n     1     n
7535  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
7536  *     i = 0      2^i   2^i
7537  *                               `- size of each group
7538  *         |         |     `- number of CPUs doing load-balance
7539  *         |         `- freq
7540  *         `- sum over all levels
7541  *
7542  * Coupled with a limit on how many tasks we can migrate every balance pass,
7543  * this makes (5) the runtime complexity of the balancer.
7544  *
7545  * An important property here is that each CPU is still (indirectly) connected
7546  * to every other CPU in at most O(log n) steps:
7547  *
7548  * The adjacency matrix of the resulting graph is given by:
7549  *
7550  *             log_2 n
7551  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
7552  *             k = 0
7553  *
7554  * And you'll find that:
7555  *
7556  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
7557  *
7558  * Showing there's indeed a path between every CPU in at most O(log n) steps.
7559  * The task movement gives a factor of O(m), giving a convergence complexity
7560  * of:
7561  *
7562  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
7563  *
7564  *
7565  * WORK CONSERVING
7566  *
7567  * In order to avoid CPUs going idle while there's still work to do, new idle
7568  * balancing is more aggressive and has the newly idle CPU iterate up the domain
7569  * tree itself instead of relying on other CPUs to bring it work.
7570  *
7571  * This adds some complexity to both (5) and (8) but it reduces the total idle
7572  * time.
7573  *
7574  * [XXX more?]
7575  *
7576  *
7577  * CGROUPS
7578  *
7579  * Cgroups make a horror show out of (2), instead of a simple sum we get:
7580  *
7581  *                                s_k,i
7582  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
7583  *                                 S_k
7584  *
7585  * Where
7586  *
7587  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
7588  *
7589  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
7590  *
7591  * The big problem is S_k, its a global sum needed to compute a local (W_i)
7592  * property.
7593  *
7594  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7595  *      rewrite all of this once again.]
7596  */
7597 
7598 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7599 
7600 enum fbq_type { regular, remote, all };
7601 
7602 /*
7603  * 'group_type' describes the group of CPUs at the moment of load balancing.
7604  *
7605  * The enum is ordered by pulling priority, with the group with lowest priority
7606  * first so the group_type can simply be compared when selecting the busiest
7607  * group. See update_sd_pick_busiest().
7608  */
7609 enum group_type {
7610 	/* The group has spare capacity that can be used to run more tasks.  */
7611 	group_has_spare = 0,
7612 	/*
7613 	 * The group is fully used and the tasks don't compete for more CPU
7614 	 * cycles. Nevertheless, some tasks might wait before running.
7615 	 */
7616 	group_fully_busy,
7617 	/*
7618 	 * SD_ASYM_CPUCAPACITY only: One task doesn't fit with CPU's capacity
7619 	 * and must be migrated to a more powerful CPU.
7620 	 */
7621 	group_misfit_task,
7622 	/*
7623 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
7624 	 * and the task should be migrated to it instead of running on the
7625 	 * current CPU.
7626 	 */
7627 	group_asym_packing,
7628 	/*
7629 	 * The tasks' affinity constraints previously prevented the scheduler
7630 	 * from balancing the load across the system.
7631 	 */
7632 	group_imbalanced,
7633 	/*
7634 	 * The CPU is overloaded and can't provide expected CPU cycles to all
7635 	 * tasks.
7636 	 */
7637 	group_overloaded
7638 };
7639 
7640 enum migration_type {
7641 	migrate_load = 0,
7642 	migrate_util,
7643 	migrate_task,
7644 	migrate_misfit
7645 };
7646 
7647 #define LBF_ALL_PINNED	0x01
7648 #define LBF_NEED_BREAK	0x02
7649 #define LBF_DST_PINNED  0x04
7650 #define LBF_SOME_PINNED	0x08
7651 #define LBF_NOHZ_STATS	0x10
7652 #define LBF_NOHZ_AGAIN	0x20
7653 #define LBF_IGNORE_PREFERRED_CLUSTER_TASKS 0x200
7654 
7655 struct lb_env {
7656 	struct sched_domain	*sd;
7657 
7658 	struct rq		*src_rq;
7659 	int			src_cpu;
7660 
7661 	int			dst_cpu;
7662 	struct rq		*dst_rq;
7663 
7664 	struct cpumask		*dst_grpmask;
7665 	int			new_dst_cpu;
7666 	enum cpu_idle_type	idle;
7667 	long			imbalance;
7668 	/* The set of CPUs under consideration for load-balancing */
7669 	struct cpumask		*cpus;
7670 
7671 	unsigned int		flags;
7672 
7673 	unsigned int		loop;
7674 	unsigned int		loop_break;
7675 	unsigned int		loop_max;
7676 
7677 	enum fbq_type		fbq_type;
7678 	enum migration_type	migration_type;
7679 	struct list_head	tasks;
7680 };
7681 
7682 /*
7683  * Is this task likely cache-hot:
7684  */
task_hot(struct task_struct * p,struct lb_env * env)7685 static int task_hot(struct task_struct *p, struct lb_env *env)
7686 {
7687 	s64 delta;
7688 
7689 	lockdep_assert_held(&env->src_rq->lock);
7690 
7691 	if (p->sched_class != &fair_sched_class)
7692 		return 0;
7693 
7694 	if (unlikely(task_has_idle_policy(p)))
7695 		return 0;
7696 
7697 	/* SMT siblings share cache */
7698 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
7699 		return 0;
7700 
7701 	/*
7702 	 * Buddy candidates are cache hot:
7703 	 */
7704 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
7705 			(&p->se == cfs_rq_of(&p->se)->next ||
7706 			 &p->se == cfs_rq_of(&p->se)->last))
7707 		return 1;
7708 
7709 	if (sysctl_sched_migration_cost == -1)
7710 		return 1;
7711 	if (sysctl_sched_migration_cost == 0)
7712 		return 0;
7713 
7714 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
7715 
7716 	return delta < (s64)sysctl_sched_migration_cost;
7717 }
7718 
7719 #ifdef CONFIG_NUMA_BALANCING
7720 /*
7721  * Returns 1, if task migration degrades locality
7722  * Returns 0, if task migration improves locality i.e migration preferred.
7723  * Returns -1, if task migration is not affected by locality.
7724  */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)7725 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
7726 {
7727 	struct numa_group *numa_group = rcu_dereference(p->numa_group);
7728 	unsigned long src_weight, dst_weight;
7729 	int src_nid, dst_nid, dist;
7730 
7731 	if (!static_branch_likely(&sched_numa_balancing))
7732 		return -1;
7733 
7734 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
7735 		return -1;
7736 
7737 	src_nid = cpu_to_node(env->src_cpu);
7738 	dst_nid = cpu_to_node(env->dst_cpu);
7739 
7740 	if (src_nid == dst_nid)
7741 		return -1;
7742 
7743 	/* Migrating away from the preferred node is always bad. */
7744 	if (src_nid == p->numa_preferred_nid) {
7745 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7746 			return 1;
7747 		else
7748 			return -1;
7749 	}
7750 
7751 	/* Encourage migration to the preferred node. */
7752 	if (dst_nid == p->numa_preferred_nid)
7753 		return 0;
7754 
7755 	/* Leaving a core idle is often worse than degrading locality. */
7756 	if (env->idle == CPU_IDLE)
7757 		return -1;
7758 
7759 	dist = node_distance(src_nid, dst_nid);
7760 	if (numa_group) {
7761 		src_weight = group_weight(p, src_nid, dist);
7762 		dst_weight = group_weight(p, dst_nid, dist);
7763 	} else {
7764 		src_weight = task_weight(p, src_nid, dist);
7765 		dst_weight = task_weight(p, dst_nid, dist);
7766 	}
7767 
7768 	return dst_weight < src_weight;
7769 }
7770 
7771 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)7772 static inline int migrate_degrades_locality(struct task_struct *p,
7773 					     struct lb_env *env)
7774 {
7775 	return -1;
7776 }
7777 #endif
7778 
7779 /*
7780  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7781  */
7782 static
can_migrate_task(struct task_struct * p,struct lb_env * env)7783 int can_migrate_task(struct task_struct *p, struct lb_env *env)
7784 {
7785 	int tsk_cache_hot;
7786 
7787 	lockdep_assert_held(&env->src_rq->lock);
7788 
7789 	/*
7790 	 * We do not migrate tasks that are:
7791 	 * 1) throttled_lb_pair, or
7792 	 * 2) cannot be migrated to this CPU due to cpus_ptr, or
7793 	 * 3) running (obviously), or
7794 	 * 4) are cache-hot on their current CPU.
7795 	 */
7796 	if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7797 		return 0;
7798 
7799 	/* Disregard pcpu kthreads; they are where they need to be. */
7800 	if (kthread_is_per_cpu(p))
7801 		return 0;
7802 
7803 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
7804 		int cpu;
7805 
7806 		schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
7807 
7808 		env->flags |= LBF_SOME_PINNED;
7809 
7810 		/*
7811 		 * Remember if this task can be migrated to any other CPU in
7812 		 * our sched_group. We may want to revisit it if we couldn't
7813 		 * meet load balance goals by pulling other tasks on src_cpu.
7814 		 *
7815 		 * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
7816 		 * already computed one in current iteration.
7817 		 */
7818 		if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
7819 			return 0;
7820 
7821 		/* Prevent to re-select dst_cpu via env's CPUs: */
7822 		for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
7823 			if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
7824 				env->flags |= LBF_DST_PINNED;
7825 				env->new_dst_cpu = cpu;
7826 				break;
7827 			}
7828 		}
7829 
7830 		return 0;
7831 	}
7832 
7833 	/* Record that we found atleast one task that could run on dst_cpu */
7834 	env->flags &= ~LBF_ALL_PINNED;
7835 
7836 
7837 #ifdef CONFIG_SCHED_RTG
7838 	if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS &&
7839 			 !preferred_cluster(cpu_rq(env->dst_cpu)->cluster, p))
7840 		return 0;
7841 #endif
7842 
7843 	if (task_running(env->src_rq, p)) {
7844 		schedstat_inc(p->se.statistics.nr_failed_migrations_running);
7845 		return 0;
7846 	}
7847 
7848 	/*
7849 	 * Aggressive migration if:
7850 	 * 1) destination numa is preferred
7851 	 * 2) task is cache cold, or
7852 	 * 3) too many balance attempts have failed.
7853 	 */
7854 	tsk_cache_hot = migrate_degrades_locality(p, env);
7855 	if (tsk_cache_hot == -1)
7856 		tsk_cache_hot = task_hot(p, env);
7857 
7858 	if (tsk_cache_hot <= 0 ||
7859 	    env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
7860 		if (tsk_cache_hot == 1) {
7861 			schedstat_inc(env->sd->lb_hot_gained[env->idle]);
7862 			schedstat_inc(p->se.statistics.nr_forced_migrations);
7863 		}
7864 		return 1;
7865 	}
7866 
7867 	schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
7868 	return 0;
7869 }
7870 
7871 /*
7872  * detach_task() -- detach the task for the migration specified in env
7873  */
detach_task(struct task_struct * p,struct lb_env * env)7874 static void detach_task(struct task_struct *p, struct lb_env *env)
7875 {
7876 	lockdep_assert_held(&env->src_rq->lock);
7877 
7878 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
7879 #ifdef CONFIG_SCHED_WALT
7880 	double_lock_balance(env->src_rq, env->dst_rq);
7881 	if (!(env->src_rq->clock_update_flags & RQCF_UPDATED))
7882 		update_rq_clock(env->src_rq);
7883 #endif
7884 	set_task_cpu(p, env->dst_cpu);
7885 #ifdef CONFIG_SCHED_WALT
7886 	double_unlock_balance(env->src_rq, env->dst_rq);
7887 #endif
7888 }
7889 
7890 /*
7891  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
7892  * part of active balancing operations within "domain".
7893  *
7894  * Returns a task if successful and NULL otherwise.
7895  */
detach_one_task(struct lb_env * env)7896 static struct task_struct *detach_one_task(struct lb_env *env)
7897 {
7898 	struct task_struct *p;
7899 
7900 	lockdep_assert_held(&env->src_rq->lock);
7901 
7902 	list_for_each_entry_reverse(p,
7903 			&env->src_rq->cfs_tasks, se.group_node) {
7904 		if (!can_migrate_task(p, env))
7905 			continue;
7906 
7907 		detach_task(p, env);
7908 
7909 		/*
7910 		 * Right now, this is only the second place where
7911 		 * lb_gained[env->idle] is updated (other is detach_tasks)
7912 		 * so we can safely collect stats here rather than
7913 		 * inside detach_tasks().
7914 		 */
7915 		schedstat_inc(env->sd->lb_gained[env->idle]);
7916 		return p;
7917 	}
7918 	return NULL;
7919 }
7920 
7921 static const unsigned int sched_nr_migrate_break = 32;
7922 
7923 /*
7924  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
7925  * busiest_rq, as part of a balancing operation within domain "sd".
7926  *
7927  * Returns number of detached tasks if successful and 0 otherwise.
7928  */
detach_tasks(struct lb_env * env)7929 static int detach_tasks(struct lb_env *env)
7930 {
7931 	struct list_head *tasks = &env->src_rq->cfs_tasks;
7932 	unsigned long util, load;
7933 	struct task_struct *p;
7934 	int detached = 0;
7935 #ifdef CONFIG_SCHED_RTG
7936 	int orig_loop = env->loop;
7937 #endif
7938 
7939 	lockdep_assert_held(&env->src_rq->lock);
7940 
7941 	if (env->imbalance <= 0)
7942 		return 0;
7943 
7944 #ifdef CONFIG_SCHED_RTG
7945 	if (!same_cluster(env->dst_cpu, env->src_cpu))
7946 		env->flags |= LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
7947 
7948 redo:
7949 #endif
7950 	while (!list_empty(tasks)) {
7951 		/*
7952 		 * We don't want to steal all, otherwise we may be treated likewise,
7953 		 * which could at worst lead to a livelock crash.
7954 		 */
7955 		if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
7956 			break;
7957 
7958 		p = list_last_entry(tasks, struct task_struct, se.group_node);
7959 
7960 		env->loop++;
7961 		/* We've more or less seen every task there is, call it quits */
7962 		if (env->loop > env->loop_max)
7963 			break;
7964 
7965 		/* take a breather every nr_migrate tasks */
7966 		if (env->loop > env->loop_break) {
7967 			env->loop_break += sched_nr_migrate_break;
7968 			env->flags |= LBF_NEED_BREAK;
7969 			break;
7970 		}
7971 
7972 		if (!can_migrate_task(p, env))
7973 			goto next;
7974 
7975 		switch (env->migration_type) {
7976 		case migrate_load:
7977 			/*
7978 			 * Depending of the number of CPUs and tasks and the
7979 			 * cgroup hierarchy, task_h_load() can return a null
7980 			 * value. Make sure that env->imbalance decreases
7981 			 * otherwise detach_tasks() will stop only after
7982 			 * detaching up to loop_max tasks.
7983 			 */
7984 			load = max_t(unsigned long, task_h_load(p), 1);
7985 
7986 			if (sched_feat(LB_MIN) &&
7987 			    load < 16 && !env->sd->nr_balance_failed)
7988 				goto next;
7989 
7990 			/*
7991 			 * Make sure that we don't migrate too much load.
7992 			 * Nevertheless, let relax the constraint if
7993 			 * scheduler fails to find a good waiting task to
7994 			 * migrate.
7995 			 */
7996 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
7997 				goto next;
7998 
7999 			env->imbalance -= load;
8000 			break;
8001 
8002 		case migrate_util:
8003 			util = task_util_est(p);
8004 
8005 			if (util > env->imbalance)
8006 				goto next;
8007 
8008 			env->imbalance -= util;
8009 			break;
8010 
8011 		case migrate_task:
8012 			env->imbalance--;
8013 			break;
8014 
8015 		case migrate_misfit:
8016 			/* This is not a misfit task */
8017 			if (task_fits_capacity(p, capacity_of(env->src_cpu)))
8018 				goto next;
8019 
8020 			env->imbalance = 0;
8021 			break;
8022 		}
8023 
8024 		detach_task(p, env);
8025 		list_add(&p->se.group_node, &env->tasks);
8026 
8027 		detached++;
8028 
8029 #ifdef CONFIG_PREEMPTION
8030 		/*
8031 		 * NEWIDLE balancing is a source of latency, so preemptible
8032 		 * kernels will stop after the first task is detached to minimize
8033 		 * the critical section.
8034 		 */
8035 		if (env->idle == CPU_NEWLY_IDLE)
8036 			break;
8037 #endif
8038 
8039 		/*
8040 		 * We only want to steal up to the prescribed amount of
8041 		 * load/util/tasks.
8042 		 */
8043 		if (env->imbalance <= 0)
8044 			break;
8045 
8046 		continue;
8047 next:
8048 		list_move(&p->se.group_node, tasks);
8049 	}
8050 
8051 #ifdef CONFIG_SCHED_RTG
8052 	if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS && !detached) {
8053 		tasks = &env->src_rq->cfs_tasks;
8054 		env->flags &= ~LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
8055 		env->loop = orig_loop;
8056 		goto redo;
8057 	}
8058 #endif
8059 
8060 	/*
8061 	 * Right now, this is one of only two places we collect this stat
8062 	 * so we can safely collect detach_one_task() stats here rather
8063 	 * than inside detach_one_task().
8064 	 */
8065 	schedstat_add(env->sd->lb_gained[env->idle], detached);
8066 
8067 	return detached;
8068 }
8069 
8070 /*
8071  * attach_task() -- attach the task detached by detach_task() to its new rq.
8072  */
attach_task(struct rq * rq,struct task_struct * p)8073 static void attach_task(struct rq *rq, struct task_struct *p)
8074 {
8075 	lockdep_assert_held(&rq->lock);
8076 
8077 	BUG_ON(task_rq(p) != rq);
8078 	activate_task(rq, p, ENQUEUE_NOCLOCK);
8079 	check_preempt_curr(rq, p, 0);
8080 }
8081 
8082 /*
8083  * attach_one_task() -- attaches the task returned from detach_one_task() to
8084  * its new rq.
8085  */
attach_one_task(struct rq * rq,struct task_struct * p)8086 static void attach_one_task(struct rq *rq, struct task_struct *p)
8087 {
8088 	struct rq_flags rf;
8089 
8090 	rq_lock(rq, &rf);
8091 	update_rq_clock(rq);
8092 	attach_task(rq, p);
8093 	rq_unlock(rq, &rf);
8094 }
8095 
8096 /*
8097  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8098  * new rq.
8099  */
attach_tasks(struct lb_env * env)8100 static void attach_tasks(struct lb_env *env)
8101 {
8102 	struct list_head *tasks = &env->tasks;
8103 	struct task_struct *p;
8104 	struct rq_flags rf;
8105 
8106 	rq_lock(env->dst_rq, &rf);
8107 	update_rq_clock(env->dst_rq);
8108 
8109 	while (!list_empty(tasks)) {
8110 		p = list_first_entry(tasks, struct task_struct, se.group_node);
8111 		list_del_init(&p->se.group_node);
8112 
8113 		attach_task(env->dst_rq, p);
8114 	}
8115 
8116 	rq_unlock(env->dst_rq, &rf);
8117 }
8118 
8119 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)8120 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
8121 {
8122 	if (cfs_rq->avg.load_avg)
8123 		return true;
8124 
8125 	if (cfs_rq->avg.util_avg)
8126 		return true;
8127 
8128 	return false;
8129 }
8130 
others_have_blocked(struct rq * rq)8131 static inline bool others_have_blocked(struct rq *rq)
8132 {
8133 	if (READ_ONCE(rq->avg_rt.util_avg))
8134 		return true;
8135 
8136 	if (READ_ONCE(rq->avg_dl.util_avg))
8137 		return true;
8138 
8139 	if (thermal_load_avg(rq))
8140 		return true;
8141 
8142 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
8143 	if (READ_ONCE(rq->avg_irq.util_avg))
8144 		return true;
8145 #endif
8146 
8147 	return false;
8148 }
8149 
update_blocked_load_status(struct rq * rq,bool has_blocked)8150 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
8151 {
8152 	rq->last_blocked_load_update_tick = jiffies;
8153 
8154 	if (!has_blocked)
8155 		rq->has_blocked_load = 0;
8156 }
8157 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)8158 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)8159 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_status(struct rq * rq,bool has_blocked)8160 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
8161 #endif
8162 
__update_blocked_others(struct rq * rq,bool * done)8163 static bool __update_blocked_others(struct rq *rq, bool *done)
8164 {
8165 	const struct sched_class *curr_class;
8166 	u64 now = rq_clock_pelt(rq);
8167 	unsigned long thermal_pressure;
8168 	bool decayed;
8169 
8170 	/*
8171 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
8172 	 * DL and IRQ signals have been updated before updating CFS.
8173 	 */
8174 	curr_class = rq->curr->sched_class;
8175 
8176 	thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
8177 
8178 	decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
8179 		  update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
8180 		  update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
8181 		  update_irq_load_avg(rq, 0);
8182 
8183 	if (others_have_blocked(rq))
8184 		*done = false;
8185 
8186 	return decayed;
8187 }
8188 
8189 #ifdef CONFIG_FAIR_GROUP_SCHED
8190 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)8191 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
8192 {
8193 	if (cfs_rq->load.weight)
8194 		return false;
8195 
8196 	if (cfs_rq->avg.load_sum)
8197 		return false;
8198 
8199 	if (cfs_rq->avg.util_sum)
8200 		return false;
8201 
8202 	if (cfs_rq->avg.runnable_sum)
8203 		return false;
8204 
8205 	return true;
8206 }
8207 
__update_blocked_fair(struct rq * rq,bool * done)8208 static bool __update_blocked_fair(struct rq *rq, bool *done)
8209 {
8210 	struct cfs_rq *cfs_rq, *pos;
8211 	bool decayed = false;
8212 	int cpu = cpu_of(rq);
8213 
8214 	/*
8215 	 * Iterates the task_group tree in a bottom up fashion, see
8216 	 * list_add_leaf_cfs_rq() for details.
8217 	 */
8218 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
8219 		struct sched_entity *se;
8220 
8221 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
8222 			update_tg_load_avg(cfs_rq);
8223 
8224 			if (cfs_rq == &rq->cfs)
8225 				decayed = true;
8226 		}
8227 
8228 		/* Propagate pending load changes to the parent, if any: */
8229 		se = cfs_rq->tg->se[cpu];
8230 		if (se && !skip_blocked_update(se))
8231 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
8232 
8233 		/*
8234 		 * There can be a lot of idle CPU cgroups.  Don't let fully
8235 		 * decayed cfs_rqs linger on the list.
8236 		 */
8237 		if (cfs_rq_is_decayed(cfs_rq))
8238 			list_del_leaf_cfs_rq(cfs_rq);
8239 
8240 		/* Don't need periodic decay once load/util_avg are null */
8241 		if (cfs_rq_has_blocked(cfs_rq))
8242 			*done = false;
8243 	}
8244 
8245 	return decayed;
8246 }
8247 
8248 /*
8249  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
8250  * This needs to be done in a top-down fashion because the load of a child
8251  * group is a fraction of its parents load.
8252  */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)8253 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
8254 {
8255 	struct rq *rq = rq_of(cfs_rq);
8256 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
8257 	unsigned long now = jiffies;
8258 	unsigned long load;
8259 
8260 	if (cfs_rq->last_h_load_update == now)
8261 		return;
8262 
8263 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
8264 	for_each_sched_entity(se) {
8265 		cfs_rq = cfs_rq_of(se);
8266 		WRITE_ONCE(cfs_rq->h_load_next, se);
8267 		if (cfs_rq->last_h_load_update == now)
8268 			break;
8269 	}
8270 
8271 	if (!se) {
8272 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
8273 		cfs_rq->last_h_load_update = now;
8274 	}
8275 
8276 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
8277 		load = cfs_rq->h_load;
8278 		load = div64_ul(load * se->avg.load_avg,
8279 			cfs_rq_load_avg(cfs_rq) + 1);
8280 		cfs_rq = group_cfs_rq(se);
8281 		cfs_rq->h_load = load;
8282 		cfs_rq->last_h_load_update = now;
8283 	}
8284 }
8285 
task_h_load(struct task_struct * p)8286 static unsigned long task_h_load(struct task_struct *p)
8287 {
8288 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
8289 
8290 	update_cfs_rq_h_load(cfs_rq);
8291 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
8292 			cfs_rq_load_avg(cfs_rq) + 1);
8293 }
8294 #else
__update_blocked_fair(struct rq * rq,bool * done)8295 static bool __update_blocked_fair(struct rq *rq, bool *done)
8296 {
8297 	struct cfs_rq *cfs_rq = &rq->cfs;
8298 	bool decayed;
8299 
8300 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
8301 	if (cfs_rq_has_blocked(cfs_rq))
8302 		*done = false;
8303 
8304 	return decayed;
8305 }
8306 
task_h_load(struct task_struct * p)8307 static unsigned long task_h_load(struct task_struct *p)
8308 {
8309 	return p->se.avg.load_avg;
8310 }
8311 #endif
8312 
update_blocked_averages(int cpu)8313 static void update_blocked_averages(int cpu)
8314 {
8315 	bool decayed = false, done = true;
8316 	struct rq *rq = cpu_rq(cpu);
8317 	struct rq_flags rf;
8318 
8319 	rq_lock_irqsave(rq, &rf);
8320 	update_rq_clock(rq);
8321 
8322 	decayed |= __update_blocked_others(rq, &done);
8323 	decayed |= __update_blocked_fair(rq, &done);
8324 
8325 	update_blocked_load_status(rq, !done);
8326 	if (decayed)
8327 		cpufreq_update_util(rq, 0);
8328 	rq_unlock_irqrestore(rq, &rf);
8329 }
8330 
8331 /********** Helpers for find_busiest_group ************************/
8332 
8333 /*
8334  * sg_lb_stats - stats of a sched_group required for load_balancing
8335  */
8336 struct sg_lb_stats {
8337 	unsigned long avg_load; /*Avg load across the CPUs of the group */
8338 	unsigned long group_load; /* Total load over the CPUs of the group */
8339 	unsigned long group_capacity;
8340 	unsigned long group_util; /* Total utilization over the CPUs of the group */
8341 	unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
8342 	unsigned int sum_nr_running; /* Nr of tasks running in the group */
8343 	unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
8344 	unsigned int idle_cpus;
8345 	unsigned int group_weight;
8346 	enum group_type group_type;
8347 	unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
8348 	unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
8349 #ifdef CONFIG_NUMA_BALANCING
8350 	unsigned int nr_numa_running;
8351 	unsigned int nr_preferred_running;
8352 #endif
8353 };
8354 
8355 /*
8356  * sd_lb_stats - Structure to store the statistics of a sched_domain
8357  *		 during load balancing.
8358  */
8359 struct sd_lb_stats {
8360 	struct sched_group *busiest;	/* Busiest group in this sd */
8361 	struct sched_group *local;	/* Local group in this sd */
8362 	unsigned long total_load;	/* Total load of all groups in sd */
8363 	unsigned long total_capacity;	/* Total capacity of all groups in sd */
8364 	unsigned long avg_load;	/* Average load across all groups in sd */
8365 	unsigned int prefer_sibling; /* tasks should go to sibling first */
8366 
8367 	struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
8368 	struct sg_lb_stats local_stat;	/* Statistics of the local group */
8369 };
8370 
init_sd_lb_stats(struct sd_lb_stats * sds)8371 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
8372 {
8373 	/*
8374 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
8375 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
8376 	 * We must however set busiest_stat::group_type and
8377 	 * busiest_stat::idle_cpus to the worst busiest group because
8378 	 * update_sd_pick_busiest() reads these before assignment.
8379 	 */
8380 	*sds = (struct sd_lb_stats){
8381 		.busiest = NULL,
8382 		.local = NULL,
8383 		.total_load = 0UL,
8384 		.total_capacity = 0UL,
8385 		.busiest_stat = {
8386 			.idle_cpus = UINT_MAX,
8387 			.group_type = group_has_spare,
8388 		},
8389 	};
8390 }
8391 
scale_rt_capacity(int cpu)8392 static unsigned long scale_rt_capacity(int cpu)
8393 {
8394 	struct rq *rq = cpu_rq(cpu);
8395 	unsigned long max = arch_scale_cpu_capacity(cpu);
8396 	unsigned long used, free;
8397 	unsigned long irq;
8398 
8399 	irq = cpu_util_irq(rq);
8400 
8401 	if (unlikely(irq >= max))
8402 		return 1;
8403 
8404 	/*
8405 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
8406 	 * (running and not running) with weights 0 and 1024 respectively.
8407 	 * avg_thermal.load_avg tracks thermal pressure and the weighted
8408 	 * average uses the actual delta max capacity(load).
8409 	 */
8410 	used = READ_ONCE(rq->avg_rt.util_avg);
8411 	used += READ_ONCE(rq->avg_dl.util_avg);
8412 	used += thermal_load_avg(rq);
8413 
8414 	if (unlikely(used >= max))
8415 		return 1;
8416 
8417 	free = max - used;
8418 
8419 	return scale_irq_capacity(free, irq, max);
8420 }
8421 
update_cpu_capacity(struct sched_domain * sd,int cpu)8422 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
8423 {
8424 	unsigned long capacity = scale_rt_capacity(cpu);
8425 	struct sched_group *sdg = sd->groups;
8426 
8427 	cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
8428 
8429 	if (!capacity)
8430 		capacity = 1;
8431 
8432 	cpu_rq(cpu)->cpu_capacity = capacity;
8433 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
8434 
8435 	sdg->sgc->capacity = capacity;
8436 	sdg->sgc->min_capacity = capacity;
8437 	sdg->sgc->max_capacity = capacity;
8438 }
8439 
update_group_capacity(struct sched_domain * sd,int cpu)8440 void update_group_capacity(struct sched_domain *sd, int cpu)
8441 {
8442 	struct sched_domain *child = sd->child;
8443 	struct sched_group *group, *sdg = sd->groups;
8444 	unsigned long capacity, min_capacity, max_capacity;
8445 	unsigned long interval;
8446 
8447 	interval = msecs_to_jiffies(sd->balance_interval);
8448 	interval = clamp(interval, 1UL, max_load_balance_interval);
8449 	sdg->sgc->next_update = jiffies + interval;
8450 
8451 	if (!child) {
8452 		update_cpu_capacity(sd, cpu);
8453 		return;
8454 	}
8455 
8456 	capacity = 0;
8457 	min_capacity = ULONG_MAX;
8458 	max_capacity = 0;
8459 
8460 	if (child->flags & SD_OVERLAP) {
8461 		/*
8462 		 * SD_OVERLAP domains cannot assume that child groups
8463 		 * span the current group.
8464 		 */
8465 
8466 		for_each_cpu(cpu, sched_group_span(sdg)) {
8467 			unsigned long cpu_cap = capacity_of(cpu);
8468 
8469 			if (cpu_isolated(cpu))
8470 				continue;
8471 
8472 			capacity += cpu_cap;
8473 			min_capacity = min(cpu_cap, min_capacity);
8474 			max_capacity = max(cpu_cap, max_capacity);
8475 		}
8476 	} else  {
8477 		/*
8478 		 * !SD_OVERLAP domains can assume that child groups
8479 		 * span the current group.
8480 		 */
8481 
8482 		group = child->groups;
8483 		do {
8484 			struct sched_group_capacity *sgc = group->sgc;
8485 			__maybe_unused cpumask_t *cpus =
8486 					sched_group_span(group);
8487 
8488 			if (!cpu_isolated(cpumask_first(cpus))) {
8489 				capacity += sgc->capacity;
8490 				min_capacity = min(sgc->min_capacity,
8491 							min_capacity);
8492 				max_capacity = max(sgc->max_capacity,
8493 							max_capacity);
8494 			}
8495 			group = group->next;
8496 		} while (group != child->groups);
8497 	}
8498 
8499 	sdg->sgc->capacity = capacity;
8500 	sdg->sgc->min_capacity = min_capacity;
8501 	sdg->sgc->max_capacity = max_capacity;
8502 }
8503 
8504 /*
8505  * Check whether the capacity of the rq has been noticeably reduced by side
8506  * activity. The imbalance_pct is used for the threshold.
8507  * Return true is the capacity is reduced
8508  */
8509 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)8510 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
8511 {
8512 	return ((rq->cpu_capacity * sd->imbalance_pct) <
8513 				(rq->cpu_capacity_orig * 100));
8514 }
8515 
8516 /*
8517  * Check whether a rq has a misfit task and if it looks like we can actually
8518  * help that task: we can migrate the task to a CPU of higher capacity, or
8519  * the task's current CPU is heavily pressured.
8520  */
check_misfit_status(struct rq * rq,struct sched_domain * sd)8521 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
8522 {
8523 	return rq->misfit_task_load &&
8524 		(rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
8525 		 check_cpu_capacity(rq, sd));
8526 }
8527 
8528 /*
8529  * Group imbalance indicates (and tries to solve) the problem where balancing
8530  * groups is inadequate due to ->cpus_ptr constraints.
8531  *
8532  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
8533  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
8534  * Something like:
8535  *
8536  *	{ 0 1 2 3 } { 4 5 6 7 }
8537  *	        *     * * *
8538  *
8539  * If we were to balance group-wise we'd place two tasks in the first group and
8540  * two tasks in the second group. Clearly this is undesired as it will overload
8541  * cpu 3 and leave one of the CPUs in the second group unused.
8542  *
8543  * The current solution to this issue is detecting the skew in the first group
8544  * by noticing the lower domain failed to reach balance and had difficulty
8545  * moving tasks due to affinity constraints.
8546  *
8547  * When this is so detected; this group becomes a candidate for busiest; see
8548  * update_sd_pick_busiest(). And calculate_imbalance() and
8549  * find_busiest_group() avoid some of the usual balance conditions to allow it
8550  * to create an effective group imbalance.
8551  *
8552  * This is a somewhat tricky proposition since the next run might not find the
8553  * group imbalance and decide the groups need to be balanced again. A most
8554  * subtle and fragile situation.
8555  */
8556 
sg_imbalanced(struct sched_group * group)8557 static inline int sg_imbalanced(struct sched_group *group)
8558 {
8559 	return group->sgc->imbalance;
8560 }
8561 
8562 /*
8563  * group_has_capacity returns true if the group has spare capacity that could
8564  * be used by some tasks.
8565  * We consider that a group has spare capacity if the  * number of task is
8566  * smaller than the number of CPUs or if the utilization is lower than the
8567  * available capacity for CFS tasks.
8568  * For the latter, we use a threshold to stabilize the state, to take into
8569  * account the variance of the tasks' load and to return true if the available
8570  * capacity in meaningful for the load balancer.
8571  * As an example, an available capacity of 1% can appear but it doesn't make
8572  * any benefit for the load balance.
8573  */
8574 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)8575 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8576 {
8577 	if (sgs->sum_nr_running < sgs->group_weight)
8578 		return true;
8579 
8580 	if ((sgs->group_capacity * imbalance_pct) <
8581 			(sgs->group_runnable * 100))
8582 		return false;
8583 
8584 	if ((sgs->group_capacity * 100) >
8585 			(sgs->group_util * imbalance_pct))
8586 		return true;
8587 
8588 	return false;
8589 }
8590 
8591 /*
8592  *  group_is_overloaded returns true if the group has more tasks than it can
8593  *  handle.
8594  *  group_is_overloaded is not equals to !group_has_capacity because a group
8595  *  with the exact right number of tasks, has no more spare capacity but is not
8596  *  overloaded so both group_has_capacity and group_is_overloaded return
8597  *  false.
8598  */
8599 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)8600 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8601 {
8602 	if (sgs->sum_nr_running <= sgs->group_weight)
8603 		return false;
8604 
8605 	if ((sgs->group_capacity * 100) <
8606 			(sgs->group_util * imbalance_pct))
8607 		return true;
8608 
8609 	if ((sgs->group_capacity * imbalance_pct) <
8610 			(sgs->group_runnable * 100))
8611 		return true;
8612 
8613 	return false;
8614 }
8615 
8616 /*
8617  * group_smaller_min_cpu_capacity: Returns true if sched_group sg has smaller
8618  * per-CPU capacity than sched_group ref.
8619  */
8620 static inline bool
group_smaller_min_cpu_capacity(struct sched_group * sg,struct sched_group * ref)8621 group_smaller_min_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8622 {
8623 	return fits_capacity(sg->sgc->min_capacity, ref->sgc->min_capacity);
8624 }
8625 
8626 /*
8627  * group_smaller_max_cpu_capacity: Returns true if sched_group sg has smaller
8628  * per-CPU capacity_orig than sched_group ref.
8629  */
8630 static inline bool
group_smaller_max_cpu_capacity(struct sched_group * sg,struct sched_group * ref)8631 group_smaller_max_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8632 {
8633 	return fits_capacity(sg->sgc->max_capacity, ref->sgc->max_capacity);
8634 }
8635 
8636 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)8637 group_type group_classify(unsigned int imbalance_pct,
8638 			  struct sched_group *group,
8639 			  struct sg_lb_stats *sgs)
8640 {
8641 	if (group_is_overloaded(imbalance_pct, sgs))
8642 		return group_overloaded;
8643 
8644 	if (sg_imbalanced(group))
8645 		return group_imbalanced;
8646 
8647 	if (sgs->group_asym_packing)
8648 		return group_asym_packing;
8649 
8650 	if (sgs->group_misfit_task_load)
8651 		return group_misfit_task;
8652 
8653 	if (!group_has_capacity(imbalance_pct, sgs))
8654 		return group_fully_busy;
8655 
8656 	return group_has_spare;
8657 }
8658 
update_nohz_stats(struct rq * rq,bool force)8659 static bool update_nohz_stats(struct rq *rq, bool force)
8660 {
8661 #ifdef CONFIG_NO_HZ_COMMON
8662 	unsigned int cpu = rq->cpu;
8663 
8664 	if (!rq->has_blocked_load)
8665 		return false;
8666 
8667 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
8668 		return false;
8669 
8670 	if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
8671 		return true;
8672 
8673 	update_blocked_averages(cpu);
8674 
8675 	return rq->has_blocked_load;
8676 #else
8677 	return false;
8678 #endif
8679 }
8680 
8681 /**
8682  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
8683  * @env: The load balancing environment.
8684  * @group: sched_group whose statistics are to be updated.
8685  * @sgs: variable to hold the statistics for this group.
8686  * @sg_status: Holds flag indicating the status of the sched_group
8687  */
update_sg_lb_stats(struct lb_env * env,struct sched_group * group,struct sg_lb_stats * sgs,int * sg_status)8688 static inline void update_sg_lb_stats(struct lb_env *env,
8689 				      struct sched_group *group,
8690 				      struct sg_lb_stats *sgs,
8691 				      int *sg_status)
8692 {
8693 	int i, nr_running, local_group;
8694 
8695 	memset(sgs, 0, sizeof(*sgs));
8696 
8697 	local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(group));
8698 
8699 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
8700 		struct rq *rq = cpu_rq(i);
8701 
8702 		if (cpu_isolated(i))
8703 			continue;
8704 
8705 		if ((env->flags & LBF_NOHZ_STATS) && update_nohz_stats(rq, false))
8706 			env->flags |= LBF_NOHZ_AGAIN;
8707 
8708 		sgs->group_load += cpu_load(rq);
8709 		sgs->group_util += cpu_util(i);
8710 		sgs->group_runnable += cpu_runnable(rq);
8711 		sgs->sum_h_nr_running += rq->cfs.h_nr_running;
8712 
8713 		nr_running = rq->nr_running;
8714 		sgs->sum_nr_running += nr_running;
8715 
8716 		if (nr_running > 1)
8717 			*sg_status |= SG_OVERLOAD;
8718 
8719 		if (cpu_overutilized(i))
8720 			*sg_status |= SG_OVERUTILIZED;
8721 
8722 #ifdef CONFIG_NUMA_BALANCING
8723 		sgs->nr_numa_running += rq->nr_numa_running;
8724 		sgs->nr_preferred_running += rq->nr_preferred_running;
8725 #endif
8726 		/*
8727 		 * No need to call idle_cpu() if nr_running is not 0
8728 		 */
8729 		if (!nr_running && idle_cpu(i)) {
8730 			sgs->idle_cpus++;
8731 			/* Idle cpu can't have misfit task */
8732 			continue;
8733 		}
8734 
8735 		if (local_group)
8736 			continue;
8737 
8738 		/* Check for a misfit task on the cpu */
8739 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
8740 		    sgs->group_misfit_task_load < rq->misfit_task_load) {
8741 			sgs->group_misfit_task_load = rq->misfit_task_load;
8742 			*sg_status |= SG_OVERLOAD;
8743 		}
8744 	}
8745 
8746 	/* Isolated CPU has no weight */
8747 	if (!group->group_weight) {
8748 		sgs->group_capacity = 0;
8749 		sgs->avg_load = 0;
8750 		sgs->group_type = group_has_spare;
8751 		sgs->group_weight = group->group_weight;
8752 		return;
8753 	}
8754 
8755 	/* Check if dst CPU is idle and preferred to this group */
8756 	if (env->sd->flags & SD_ASYM_PACKING &&
8757 	    env->idle != CPU_NOT_IDLE &&
8758 	    sgs->sum_h_nr_running &&
8759 	    sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu)) {
8760 		sgs->group_asym_packing = 1;
8761 	}
8762 
8763 	sgs->group_capacity = group->sgc->capacity;
8764 
8765 	sgs->group_weight = group->group_weight;
8766 
8767 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
8768 
8769 	/* Computing avg_load makes sense only when group is overloaded */
8770 	if (sgs->group_type == group_overloaded)
8771 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8772 				sgs->group_capacity;
8773 }
8774 
8775 /**
8776  * update_sd_pick_busiest - return 1 on busiest group
8777  * @env: The load balancing environment.
8778  * @sds: sched_domain statistics
8779  * @sg: sched_group candidate to be checked for being the busiest
8780  * @sgs: sched_group statistics
8781  *
8782  * Determine if @sg is a busier group than the previously selected
8783  * busiest group.
8784  *
8785  * Return: %true if @sg is a busier group than the previously selected
8786  * busiest group. %false otherwise.
8787  */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)8788 static bool update_sd_pick_busiest(struct lb_env *env,
8789 				   struct sd_lb_stats *sds,
8790 				   struct sched_group *sg,
8791 				   struct sg_lb_stats *sgs)
8792 {
8793 	struct sg_lb_stats *busiest = &sds->busiest_stat;
8794 
8795 	/* Make sure that there is at least one task to pull */
8796 	if (!sgs->sum_h_nr_running)
8797 		return false;
8798 
8799 	/*
8800 	 * Don't try to pull misfit tasks we can't help.
8801 	 * We can use max_capacity here as reduction in capacity on some
8802 	 * CPUs in the group should either be possible to resolve
8803 	 * internally or be covered by avg_load imbalance (eventually).
8804 	 */
8805 	if (sgs->group_type == group_misfit_task &&
8806 	    (!group_smaller_max_cpu_capacity(sg, sds->local) ||
8807 	     sds->local_stat.group_type != group_has_spare))
8808 		return false;
8809 
8810 	if (sgs->group_type > busiest->group_type)
8811 		return true;
8812 
8813 	if (sgs->group_type < busiest->group_type)
8814 		return false;
8815 
8816 	/*
8817 	 * The candidate and the current busiest group are the same type of
8818 	 * group. Let check which one is the busiest according to the type.
8819 	 */
8820 
8821 	switch (sgs->group_type) {
8822 	case group_overloaded:
8823 		/* Select the overloaded group with highest avg_load. */
8824 		if (sgs->avg_load <= busiest->avg_load)
8825 			return false;
8826 		break;
8827 
8828 	case group_imbalanced:
8829 		/*
8830 		 * Select the 1st imbalanced group as we don't have any way to
8831 		 * choose one more than another.
8832 		 */
8833 		return false;
8834 
8835 	case group_asym_packing:
8836 		/* Prefer to move from lowest priority CPU's work */
8837 		if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
8838 			return false;
8839 		break;
8840 
8841 	case group_misfit_task:
8842 		/*
8843 		 * If we have more than one misfit sg go with the biggest
8844 		 * misfit.
8845 		 */
8846 		if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
8847 			return false;
8848 		break;
8849 
8850 	case group_fully_busy:
8851 		/*
8852 		 * Select the fully busy group with highest avg_load. In
8853 		 * theory, there is no need to pull task from such kind of
8854 		 * group because tasks have all compute capacity that they need
8855 		 * but we can still improve the overall throughput by reducing
8856 		 * contention when accessing shared HW resources.
8857 		 *
8858 		 * XXX for now avg_load is not computed and always 0 so we
8859 		 * select the 1st one.
8860 		 */
8861 		if (sgs->avg_load <= busiest->avg_load)
8862 			return false;
8863 		break;
8864 
8865 	case group_has_spare:
8866 		/*
8867 		 * Select not overloaded group with lowest number of idle cpus
8868 		 * and highest number of running tasks. We could also compare
8869 		 * the spare capacity which is more stable but it can end up
8870 		 * that the group has less spare capacity but finally more idle
8871 		 * CPUs which means less opportunity to pull tasks.
8872 		 */
8873 		if (sgs->idle_cpus > busiest->idle_cpus)
8874 			return false;
8875 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
8876 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
8877 			return false;
8878 
8879 		break;
8880 	}
8881 
8882 	/*
8883 	 * Candidate sg has no more than one task per CPU and has higher
8884 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
8885 	 * throughput. Maximize throughput, power/energy consequences are not
8886 	 * considered.
8887 	 */
8888 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
8889 	    (sgs->group_type <= group_fully_busy) &&
8890 	    (group_smaller_min_cpu_capacity(sds->local, sg)))
8891 		return false;
8892 
8893 	return true;
8894 }
8895 
8896 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)8897 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8898 {
8899 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
8900 		return regular;
8901 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
8902 		return remote;
8903 	return all;
8904 }
8905 
fbq_classify_rq(struct rq * rq)8906 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8907 {
8908 	if (rq->nr_running > rq->nr_numa_running)
8909 		return regular;
8910 	if (rq->nr_running > rq->nr_preferred_running)
8911 		return remote;
8912 	return all;
8913 }
8914 #else
fbq_classify_group(struct sg_lb_stats * sgs)8915 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8916 {
8917 	return all;
8918 }
8919 
fbq_classify_rq(struct rq * rq)8920 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8921 {
8922 	return regular;
8923 }
8924 #endif /* CONFIG_NUMA_BALANCING */
8925 
8926 
8927 struct sg_lb_stats;
8928 
8929 /*
8930  * task_running_on_cpu - return 1 if @p is running on @cpu.
8931  */
8932 
task_running_on_cpu(int cpu,struct task_struct * p)8933 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
8934 {
8935 	/* Task has no contribution or is new */
8936 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8937 		return 0;
8938 
8939 	if (task_on_rq_queued(p))
8940 		return 1;
8941 
8942 	return 0;
8943 }
8944 
8945 /**
8946  * idle_cpu_without - would a given CPU be idle without p ?
8947  * @cpu: the processor on which idleness is tested.
8948  * @p: task which should be ignored.
8949  *
8950  * Return: 1 if the CPU would be idle. 0 otherwise.
8951  */
idle_cpu_without(int cpu,struct task_struct * p)8952 static int idle_cpu_without(int cpu, struct task_struct *p)
8953 {
8954 	struct rq *rq = cpu_rq(cpu);
8955 
8956 	if (rq->curr != rq->idle && rq->curr != p)
8957 		return 0;
8958 
8959 	/*
8960 	 * rq->nr_running can't be used but an updated version without the
8961 	 * impact of p on cpu must be used instead. The updated nr_running
8962 	 * be computed and tested before calling idle_cpu_without().
8963 	 */
8964 
8965 #ifdef CONFIG_SMP
8966 	if (rq->ttwu_pending)
8967 		return 0;
8968 #endif
8969 
8970 	return 1;
8971 }
8972 
8973 /*
8974  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
8975  * @sd: The sched_domain level to look for idlest group.
8976  * @group: sched_group whose statistics are to be updated.
8977  * @sgs: variable to hold the statistics for this group.
8978  * @p: The task for which we look for the idlest group/CPU.
8979  */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)8980 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
8981 					  struct sched_group *group,
8982 					  struct sg_lb_stats *sgs,
8983 					  struct task_struct *p)
8984 {
8985 	int i, nr_running;
8986 
8987 	memset(sgs, 0, sizeof(*sgs));
8988 
8989 	for_each_cpu(i, sched_group_span(group)) {
8990 		struct rq *rq = cpu_rq(i);
8991 		unsigned int local;
8992 
8993 		sgs->group_load += cpu_load_without(rq, p);
8994 		sgs->group_util += cpu_util_without(i, p);
8995 		sgs->group_runnable += cpu_runnable_without(rq, p);
8996 		local = task_running_on_cpu(i, p);
8997 		sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
8998 
8999 		nr_running = rq->nr_running - local;
9000 		sgs->sum_nr_running += nr_running;
9001 
9002 		/*
9003 		 * No need to call idle_cpu_without() if nr_running is not 0
9004 		 */
9005 		if (!nr_running && idle_cpu_without(i, p))
9006 			sgs->idle_cpus++;
9007 
9008 	}
9009 
9010 	/* Check if task fits in the group */
9011 	if (sd->flags & SD_ASYM_CPUCAPACITY &&
9012 	    !task_fits_capacity(p, group->sgc->max_capacity)) {
9013 		sgs->group_misfit_task_load = 1;
9014 	}
9015 
9016 	sgs->group_capacity = group->sgc->capacity;
9017 
9018 	sgs->group_weight = group->group_weight;
9019 
9020 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
9021 
9022 	/*
9023 	 * Computing avg_load makes sense only when group is fully busy or
9024 	 * overloaded
9025 	 */
9026 	if (sgs->group_type == group_fully_busy ||
9027 		sgs->group_type == group_overloaded)
9028 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9029 				sgs->group_capacity;
9030 }
9031 
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)9032 static bool update_pick_idlest(struct sched_group *idlest,
9033 			       struct sg_lb_stats *idlest_sgs,
9034 			       struct sched_group *group,
9035 			       struct sg_lb_stats *sgs)
9036 {
9037 	if (sgs->group_type < idlest_sgs->group_type)
9038 		return true;
9039 
9040 	if (sgs->group_type > idlest_sgs->group_type)
9041 		return false;
9042 
9043 	/*
9044 	 * The candidate and the current idlest group are the same type of
9045 	 * group. Let check which one is the idlest according to the type.
9046 	 */
9047 
9048 	switch (sgs->group_type) {
9049 	case group_overloaded:
9050 	case group_fully_busy:
9051 		/* Select the group with lowest avg_load. */
9052 		if (idlest_sgs->avg_load <= sgs->avg_load)
9053 			return false;
9054 		break;
9055 
9056 	case group_imbalanced:
9057 	case group_asym_packing:
9058 		/* Those types are not used in the slow wakeup path */
9059 		return false;
9060 
9061 	case group_misfit_task:
9062 		/* Select group with the highest max capacity */
9063 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
9064 			return false;
9065 		break;
9066 
9067 	case group_has_spare:
9068 		/* Select group with most idle CPUs */
9069 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
9070 			return false;
9071 
9072 		/* Select group with lowest group_util */
9073 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
9074 			idlest_sgs->group_util <= sgs->group_util)
9075 			return false;
9076 
9077 		break;
9078 	}
9079 
9080 	return true;
9081 }
9082 
9083 /*
9084  * find_idlest_group() finds and returns the least busy CPU group within the
9085  * domain.
9086  *
9087  * Assumes p is allowed on at least one CPU in sd.
9088  */
9089 static struct sched_group *
find_idlest_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)9090 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
9091 {
9092 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
9093 	struct sg_lb_stats local_sgs, tmp_sgs;
9094 	struct sg_lb_stats *sgs;
9095 	unsigned long imbalance;
9096 	struct sg_lb_stats idlest_sgs = {
9097 			.avg_load = UINT_MAX,
9098 			.group_type = group_overloaded,
9099 	};
9100 #ifdef CONFIG_CPU_ISOLATION_OPT
9101 	cpumask_t allowed_cpus;
9102 
9103 	cpumask_andnot(&allowed_cpus, p->cpus_ptr, cpu_isolated_mask);
9104 #endif
9105 
9106 	imbalance = scale_load_down(NICE_0_LOAD) *
9107 				(sd->imbalance_pct-100) / 100;
9108 
9109 	do {
9110 		int local_group;
9111 
9112 		/* Skip over this group if it has no CPUs allowed */
9113 #ifdef CONFIG_CPU_ISOLATION_OPT
9114 		if (!cpumask_intersects(sched_group_span(group),
9115 					&allowed_cpus))
9116 #else
9117 		if (!cpumask_intersects(sched_group_span(group),
9118 					p->cpus_ptr))
9119 #endif
9120 			continue;
9121 
9122 		local_group = cpumask_test_cpu(this_cpu,
9123 					       sched_group_span(group));
9124 
9125 		if (local_group) {
9126 			sgs = &local_sgs;
9127 			local = group;
9128 		} else {
9129 			sgs = &tmp_sgs;
9130 		}
9131 
9132 		update_sg_wakeup_stats(sd, group, sgs, p);
9133 
9134 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
9135 			idlest = group;
9136 			idlest_sgs = *sgs;
9137 		}
9138 
9139 	} while (group = group->next, group != sd->groups);
9140 
9141 
9142 	/* There is no idlest group to push tasks to */
9143 	if (!idlest)
9144 		return NULL;
9145 
9146 	/* The local group has been skipped because of CPU affinity */
9147 	if (!local)
9148 		return idlest;
9149 
9150 	/*
9151 	 * If the local group is idler than the selected idlest group
9152 	 * don't try and push the task.
9153 	 */
9154 	if (local_sgs.group_type < idlest_sgs.group_type)
9155 		return NULL;
9156 
9157 	/*
9158 	 * If the local group is busier than the selected idlest group
9159 	 * try and push the task.
9160 	 */
9161 	if (local_sgs.group_type > idlest_sgs.group_type)
9162 		return idlest;
9163 
9164 	switch (local_sgs.group_type) {
9165 	case group_overloaded:
9166 	case group_fully_busy:
9167 		/*
9168 		 * When comparing groups across NUMA domains, it's possible for
9169 		 * the local domain to be very lightly loaded relative to the
9170 		 * remote domains but "imbalance" skews the comparison making
9171 		 * remote CPUs look much more favourable. When considering
9172 		 * cross-domain, add imbalance to the load on the remote node
9173 		 * and consider staying local.
9174 		 */
9175 
9176 		if ((sd->flags & SD_NUMA) &&
9177 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
9178 			return NULL;
9179 
9180 		/*
9181 		 * If the local group is less loaded than the selected
9182 		 * idlest group don't try and push any tasks.
9183 		 */
9184 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
9185 			return NULL;
9186 
9187 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
9188 			return NULL;
9189 		break;
9190 
9191 	case group_imbalanced:
9192 	case group_asym_packing:
9193 		/* Those type are not used in the slow wakeup path */
9194 		return NULL;
9195 
9196 	case group_misfit_task:
9197 		/* Select group with the highest max capacity */
9198 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
9199 			return NULL;
9200 		break;
9201 
9202 	case group_has_spare:
9203 		if (sd->flags & SD_NUMA) {
9204 #ifdef CONFIG_NUMA_BALANCING
9205 			int idlest_cpu;
9206 			/*
9207 			 * If there is spare capacity at NUMA, try to select
9208 			 * the preferred node
9209 			 */
9210 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
9211 				return NULL;
9212 
9213 			idlest_cpu = cpumask_first(sched_group_span(idlest));
9214 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
9215 				return idlest;
9216 #endif
9217 			/*
9218 			 * Otherwise, keep the task on this node to stay close
9219 			 * its wakeup source and improve locality. If there is
9220 			 * a real need of migration, periodic load balance will
9221 			 * take care of it.
9222 			 */
9223 			if (local_sgs.idle_cpus)
9224 				return NULL;
9225 		}
9226 
9227 		/*
9228 		 * Select group with highest number of idle CPUs. We could also
9229 		 * compare the utilization which is more stable but it can end
9230 		 * up that the group has less spare capacity but finally more
9231 		 * idle CPUs which means more opportunity to run task.
9232 		 */
9233 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
9234 			return NULL;
9235 		break;
9236 	}
9237 
9238 	return idlest;
9239 }
9240 
9241 /**
9242  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
9243  * @env: The load balancing environment.
9244  * @sds: variable to hold the statistics for this sched_domain.
9245  */
9246 
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)9247 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
9248 {
9249 	struct sched_domain *child = env->sd->child;
9250 	struct sched_group *sg = env->sd->groups;
9251 	struct sg_lb_stats *local = &sds->local_stat;
9252 	struct sg_lb_stats tmp_sgs;
9253 	int sg_status = 0;
9254 
9255 #ifdef CONFIG_NO_HZ_COMMON
9256 	if (env->idle == CPU_NEWLY_IDLE && READ_ONCE(nohz.has_blocked))
9257 		env->flags |= LBF_NOHZ_STATS;
9258 #endif
9259 
9260 	do {
9261 		struct sg_lb_stats *sgs = &tmp_sgs;
9262 		int local_group;
9263 
9264 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
9265 		if (local_group) {
9266 			sds->local = sg;
9267 			sgs = local;
9268 
9269 			if (env->idle != CPU_NEWLY_IDLE ||
9270 			    time_after_eq(jiffies, sg->sgc->next_update))
9271 				update_group_capacity(env->sd, env->dst_cpu);
9272 		}
9273 
9274 		update_sg_lb_stats(env, sg, sgs, &sg_status);
9275 
9276 		if (local_group)
9277 			goto next_group;
9278 
9279 
9280 		if (update_sd_pick_busiest(env, sds, sg, sgs)) {
9281 			sds->busiest = sg;
9282 			sds->busiest_stat = *sgs;
9283 		}
9284 
9285 next_group:
9286 		/* Now, start updating sd_lb_stats */
9287 		sds->total_load += sgs->group_load;
9288 		sds->total_capacity += sgs->group_capacity;
9289 
9290 		sg = sg->next;
9291 	} while (sg != env->sd->groups);
9292 
9293 	/* Tag domain that child domain prefers tasks go to siblings first */
9294 	sds->prefer_sibling = child && child->flags & SD_PREFER_SIBLING;
9295 
9296 #ifdef CONFIG_NO_HZ_COMMON
9297 	if ((env->flags & LBF_NOHZ_AGAIN) &&
9298 	    cpumask_subset(nohz.idle_cpus_mask, sched_domain_span(env->sd))) {
9299 
9300 		WRITE_ONCE(nohz.next_blocked,
9301 			   jiffies + msecs_to_jiffies(LOAD_AVG_PERIOD));
9302 	}
9303 #endif
9304 
9305 	if (env->sd->flags & SD_NUMA)
9306 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
9307 
9308 	if (!env->sd->parent) {
9309 		struct root_domain *rd = env->dst_rq->rd;
9310 
9311 		/* update overload indicator if we are at root domain */
9312 		WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
9313 
9314 		/* Update over-utilization (tipping point, U >= 0) indicator */
9315 		WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
9316 		trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
9317 	} else if (sg_status & SG_OVERUTILIZED) {
9318 		struct root_domain *rd = env->dst_rq->rd;
9319 
9320 		WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
9321 		trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
9322 	}
9323 }
9324 
adjust_numa_imbalance(int imbalance,int nr_running)9325 static inline long adjust_numa_imbalance(int imbalance, int nr_running)
9326 {
9327 	unsigned int imbalance_min;
9328 
9329 	/*
9330 	 * Allow a small imbalance based on a simple pair of communicating
9331 	 * tasks that remain local when the source domain is almost idle.
9332 	 */
9333 	imbalance_min = 2;
9334 	if (nr_running <= imbalance_min)
9335 		return 0;
9336 
9337 	return imbalance;
9338 }
9339 
9340 /**
9341  * calculate_imbalance - Calculate the amount of imbalance present within the
9342  *			 groups of a given sched_domain during load balance.
9343  * @env: load balance environment
9344  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
9345  */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)9346 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
9347 {
9348 	struct sg_lb_stats *local, *busiest;
9349 
9350 	local = &sds->local_stat;
9351 	busiest = &sds->busiest_stat;
9352 
9353 	if (busiest->group_type == group_misfit_task) {
9354 		/* Set imbalance to allow misfit tasks to be balanced. */
9355 		env->migration_type = migrate_misfit;
9356 		env->imbalance = 1;
9357 		return;
9358 	}
9359 
9360 	if (busiest->group_type == group_asym_packing) {
9361 		/*
9362 		 * In case of asym capacity, we will try to migrate all load to
9363 		 * the preferred CPU.
9364 		 */
9365 		env->migration_type = migrate_task;
9366 		env->imbalance = busiest->sum_h_nr_running;
9367 		return;
9368 	}
9369 
9370 	if (busiest->group_type == group_imbalanced) {
9371 		/*
9372 		 * In the group_imb case we cannot rely on group-wide averages
9373 		 * to ensure CPU-load equilibrium, try to move any task to fix
9374 		 * the imbalance. The next load balance will take care of
9375 		 * balancing back the system.
9376 		 */
9377 		env->migration_type = migrate_task;
9378 		env->imbalance = 1;
9379 		return;
9380 	}
9381 
9382 	/*
9383 	 * Try to use spare capacity of local group without overloading it or
9384 	 * emptying busiest.
9385 	 */
9386 	if (local->group_type == group_has_spare) {
9387 		if ((busiest->group_type > group_fully_busy) &&
9388 		    !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
9389 			/*
9390 			 * If busiest is overloaded, try to fill spare
9391 			 * capacity. This might end up creating spare capacity
9392 			 * in busiest or busiest still being overloaded but
9393 			 * there is no simple way to directly compute the
9394 			 * amount of load to migrate in order to balance the
9395 			 * system.
9396 			 */
9397 			env->migration_type = migrate_util;
9398 			env->imbalance = max(local->group_capacity, local->group_util) -
9399 					 local->group_util;
9400 
9401 			/*
9402 			 * In some cases, the group's utilization is max or even
9403 			 * higher than capacity because of migrations but the
9404 			 * local CPU is (newly) idle. There is at least one
9405 			 * waiting task in this overloaded busiest group. Let's
9406 			 * try to pull it.
9407 			 */
9408 			if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
9409 				env->migration_type = migrate_task;
9410 				env->imbalance = 1;
9411 			}
9412 
9413 			return;
9414 		}
9415 
9416 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
9417 			unsigned int nr_diff = busiest->sum_nr_running;
9418 			/*
9419 			 * When prefer sibling, evenly spread running tasks on
9420 			 * groups.
9421 			 */
9422 			env->migration_type = migrate_task;
9423 			lsub_positive(&nr_diff, local->sum_nr_running);
9424 			env->imbalance = nr_diff >> 1;
9425 		} else {
9426 
9427 			/*
9428 			 * If there is no overload, we just want to even the number of
9429 			 * idle cpus.
9430 			 */
9431 			env->migration_type = migrate_task;
9432 			env->imbalance = max_t(long, 0, (local->idle_cpus -
9433 						 busiest->idle_cpus) >> 1);
9434 		}
9435 
9436 		/* Consider allowing a small imbalance between NUMA groups */
9437 		if (env->sd->flags & SD_NUMA)
9438 			env->imbalance = adjust_numa_imbalance(env->imbalance,
9439 						busiest->sum_nr_running);
9440 
9441 		return;
9442 	}
9443 
9444 	/*
9445 	 * Local is fully busy but has to take more load to relieve the
9446 	 * busiest group
9447 	 */
9448 	if (local->group_type < group_overloaded) {
9449 		/*
9450 		 * Local will become overloaded so the avg_load metrics are
9451 		 * finally needed.
9452 		 */
9453 
9454 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
9455 				  local->group_capacity;
9456 
9457 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
9458 				sds->total_capacity;
9459 		/*
9460 		 * If the local group is more loaded than the selected
9461 		 * busiest group don't try to pull any tasks.
9462 		 */
9463 		if (local->avg_load >= busiest->avg_load) {
9464 			env->imbalance = 0;
9465 			return;
9466 		}
9467 	}
9468 
9469 	/*
9470 	 * Both group are or will become overloaded and we're trying to get all
9471 	 * the CPUs to the average_load, so we don't want to push ourselves
9472 	 * above the average load, nor do we wish to reduce the max loaded CPU
9473 	 * below the average load. At the same time, we also don't want to
9474 	 * reduce the group load below the group capacity. Thus we look for
9475 	 * the minimum possible imbalance.
9476 	 */
9477 	env->migration_type = migrate_load;
9478 	env->imbalance = min(
9479 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
9480 		(sds->avg_load - local->avg_load) * local->group_capacity
9481 	) / SCHED_CAPACITY_SCALE;
9482 }
9483 
9484 /******* find_busiest_group() helpers end here *********************/
9485 
9486 /*
9487  * Decision matrix according to the local and busiest group type:
9488  *
9489  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
9490  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
9491  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
9492  * misfit_task      force     N/A        N/A    N/A  force      force
9493  * asym_packing     force     force      N/A    N/A  force      force
9494  * imbalanced       force     force      N/A    N/A  force      force
9495  * overloaded       force     force      N/A    N/A  force      avg_load
9496  *
9497  * N/A :      Not Applicable because already filtered while updating
9498  *            statistics.
9499  * balanced : The system is balanced for these 2 groups.
9500  * force :    Calculate the imbalance as load migration is probably needed.
9501  * avg_load : Only if imbalance is significant enough.
9502  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
9503  *            different in groups.
9504  */
9505 
9506 /**
9507  * find_busiest_group - Returns the busiest group within the sched_domain
9508  * if there is an imbalance.
9509  *
9510  * Also calculates the amount of runnable load which should be moved
9511  * to restore balance.
9512  *
9513  * @env: The load balancing environment.
9514  *
9515  * Return:	- The busiest group if imbalance exists.
9516  */
find_busiest_group(struct lb_env * env)9517 static struct sched_group *find_busiest_group(struct lb_env *env)
9518 {
9519 	struct sg_lb_stats *local, *busiest;
9520 	struct sd_lb_stats sds;
9521 
9522 	init_sd_lb_stats(&sds);
9523 
9524 	/*
9525 	 * Compute the various statistics relevant for load balancing at
9526 	 * this level.
9527 	 */
9528 	update_sd_lb_stats(env, &sds);
9529 
9530 	if (sched_energy_enabled()) {
9531 		struct root_domain *rd = env->dst_rq->rd;
9532 
9533 		if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
9534 			goto out_balanced;
9535 	}
9536 
9537 	local = &sds.local_stat;
9538 	busiest = &sds.busiest_stat;
9539 
9540 	/* There is no busy sibling group to pull tasks from */
9541 	if (!sds.busiest)
9542 		goto out_balanced;
9543 
9544 	/* Misfit tasks should be dealt with regardless of the avg load */
9545 	if (busiest->group_type == group_misfit_task)
9546 		goto force_balance;
9547 
9548 	/* ASYM feature bypasses nice load balance check */
9549 	if (busiest->group_type == group_asym_packing)
9550 		goto force_balance;
9551 
9552 	/*
9553 	 * If the busiest group is imbalanced the below checks don't
9554 	 * work because they assume all things are equal, which typically
9555 	 * isn't true due to cpus_ptr constraints and the like.
9556 	 */
9557 	if (busiest->group_type == group_imbalanced)
9558 		goto force_balance;
9559 
9560 	/*
9561 	 * If the local group is busier than the selected busiest group
9562 	 * don't try and pull any tasks.
9563 	 */
9564 	if (local->group_type > busiest->group_type)
9565 		goto out_balanced;
9566 
9567 	/*
9568 	 * When groups are overloaded, use the avg_load to ensure fairness
9569 	 * between tasks.
9570 	 */
9571 	if (local->group_type == group_overloaded) {
9572 		/*
9573 		 * If the local group is more loaded than the selected
9574 		 * busiest group don't try to pull any tasks.
9575 		 */
9576 		if (local->avg_load >= busiest->avg_load)
9577 			goto out_balanced;
9578 
9579 		/* XXX broken for overlapping NUMA groups */
9580 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
9581 				sds.total_capacity;
9582 
9583 		/*
9584 		 * Don't pull any tasks if this group is already above the
9585 		 * domain average load.
9586 		 */
9587 		if (local->avg_load >= sds.avg_load)
9588 			goto out_balanced;
9589 
9590 		/*
9591 		 * If the busiest group is more loaded, use imbalance_pct to be
9592 		 * conservative.
9593 		 */
9594 		if (100 * busiest->avg_load <=
9595 				env->sd->imbalance_pct * local->avg_load)
9596 			goto out_balanced;
9597 	}
9598 
9599 	/* Try to move all excess tasks to child's sibling domain */
9600 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
9601 	    busiest->sum_nr_running > local->sum_nr_running + 1)
9602 		goto force_balance;
9603 
9604 	if (busiest->group_type != group_overloaded) {
9605 		if (env->idle == CPU_NOT_IDLE)
9606 			/*
9607 			 * If the busiest group is not overloaded (and as a
9608 			 * result the local one too) but this CPU is already
9609 			 * busy, let another idle CPU try to pull task.
9610 			 */
9611 			goto out_balanced;
9612 
9613 		if (busiest->group_weight > 1 &&
9614 		    local->idle_cpus <= (busiest->idle_cpus + 1))
9615 			/*
9616 			 * If the busiest group is not overloaded
9617 			 * and there is no imbalance between this and busiest
9618 			 * group wrt idle CPUs, it is balanced. The imbalance
9619 			 * becomes significant if the diff is greater than 1
9620 			 * otherwise we might end up to just move the imbalance
9621 			 * on another group. Of course this applies only if
9622 			 * there is more than 1 CPU per group.
9623 			 */
9624 			goto out_balanced;
9625 
9626 		if (busiest->sum_h_nr_running == 1)
9627 			/*
9628 			 * busiest doesn't have any tasks waiting to run
9629 			 */
9630 			goto out_balanced;
9631 	}
9632 
9633 force_balance:
9634 	/* Looks like there is an imbalance. Compute it */
9635 	calculate_imbalance(env, &sds);
9636 	return env->imbalance ? sds.busiest : NULL;
9637 
9638 out_balanced:
9639 	env->imbalance = 0;
9640 	return NULL;
9641 }
9642 
9643 /*
9644  * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
9645  */
find_busiest_queue(struct lb_env * env,struct sched_group * group)9646 static struct rq *find_busiest_queue(struct lb_env *env,
9647 				     struct sched_group *group)
9648 {
9649 	struct rq *busiest = NULL, *rq;
9650 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
9651 	unsigned int busiest_nr = 0;
9652 	int i;
9653 
9654 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9655 		unsigned long capacity, load, util;
9656 		unsigned int nr_running;
9657 		enum fbq_type rt;
9658 
9659 		rq = cpu_rq(i);
9660 		rt = fbq_classify_rq(rq);
9661 
9662 		/*
9663 		 * We classify groups/runqueues into three groups:
9664 		 *  - regular: there are !numa tasks
9665 		 *  - remote:  there are numa tasks that run on the 'wrong' node
9666 		 *  - all:     there is no distinction
9667 		 *
9668 		 * In order to avoid migrating ideally placed numa tasks,
9669 		 * ignore those when there's better options.
9670 		 *
9671 		 * If we ignore the actual busiest queue to migrate another
9672 		 * task, the next balance pass can still reduce the busiest
9673 		 * queue by moving tasks around inside the node.
9674 		 *
9675 		 * If we cannot move enough load due to this classification
9676 		 * the next pass will adjust the group classification and
9677 		 * allow migration of more tasks.
9678 		 *
9679 		 * Both cases only affect the total convergence complexity.
9680 		 */
9681 		if (rt > env->fbq_type)
9682 			continue;
9683 
9684 		if (cpu_isolated(i))
9685 			continue;
9686 
9687 		capacity = capacity_of(i);
9688 		nr_running = rq->cfs.h_nr_running;
9689 
9690 		/*
9691 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
9692 		 * eventually lead to active_balancing high->low capacity.
9693 		 * Higher per-CPU capacity is considered better than balancing
9694 		 * average load.
9695 		 */
9696 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
9697 		    capacity_of(env->dst_cpu) < capacity &&
9698 		    nr_running == 1)
9699 			continue;
9700 
9701 		switch (env->migration_type) {
9702 		case migrate_load:
9703 			/*
9704 			 * When comparing with load imbalance, use cpu_load()
9705 			 * which is not scaled with the CPU capacity.
9706 			 */
9707 			load = cpu_load(rq);
9708 
9709 			if (nr_running == 1 && load > env->imbalance &&
9710 			    !check_cpu_capacity(rq, env->sd))
9711 				break;
9712 
9713 			/*
9714 			 * For the load comparisons with the other CPUs,
9715 			 * consider the cpu_load() scaled with the CPU
9716 			 * capacity, so that the load can be moved away
9717 			 * from the CPU that is potentially running at a
9718 			 * lower capacity.
9719 			 *
9720 			 * Thus we're looking for max(load_i / capacity_i),
9721 			 * crosswise multiplication to rid ourselves of the
9722 			 * division works out to:
9723 			 * load_i * capacity_j > load_j * capacity_i;
9724 			 * where j is our previous maximum.
9725 			 */
9726 			if (load * busiest_capacity > busiest_load * capacity) {
9727 				busiest_load = load;
9728 				busiest_capacity = capacity;
9729 				busiest = rq;
9730 			}
9731 			break;
9732 
9733 		case migrate_util:
9734 			util = cpu_util(cpu_of(rq));
9735 
9736 			/*
9737 			 * Don't try to pull utilization from a CPU with one
9738 			 * running task. Whatever its utilization, we will fail
9739 			 * detach the task.
9740 			 */
9741 			if (nr_running <= 1)
9742 				continue;
9743 
9744 			if (busiest_util < util) {
9745 				busiest_util = util;
9746 				busiest = rq;
9747 			}
9748 			break;
9749 
9750 		case migrate_task:
9751 			if (busiest_nr < nr_running) {
9752 				busiest_nr = nr_running;
9753 				busiest = rq;
9754 			}
9755 			break;
9756 
9757 		case migrate_misfit:
9758 			/*
9759 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
9760 			 * simply seek the "biggest" misfit task.
9761 			 */
9762 			if (rq->misfit_task_load > busiest_load) {
9763 				busiest_load = rq->misfit_task_load;
9764 				busiest = rq;
9765 			}
9766 
9767 			break;
9768 
9769 		}
9770 	}
9771 
9772 	return busiest;
9773 }
9774 
9775 /*
9776  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
9777  * so long as it is large enough.
9778  */
9779 #define MAX_PINNED_INTERVAL	512
9780 
9781 static inline bool
asym_active_balance(struct lb_env * env)9782 asym_active_balance(struct lb_env *env)
9783 {
9784 	/*
9785 	 * ASYM_PACKING needs to force migrate tasks from busy but
9786 	 * lower priority CPUs in order to pack all tasks in the
9787 	 * highest priority CPUs.
9788 	 */
9789 	return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
9790 	       sched_asym_prefer(env->dst_cpu, env->src_cpu);
9791 }
9792 
9793 static inline bool
voluntary_active_balance(struct lb_env * env)9794 voluntary_active_balance(struct lb_env *env)
9795 {
9796 	struct sched_domain *sd = env->sd;
9797 
9798 	if (asym_active_balance(env))
9799 		return 1;
9800 
9801 	/*
9802 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
9803 	 * It's worth migrating the task if the src_cpu's capacity is reduced
9804 	 * because of other sched_class or IRQs if more capacity stays
9805 	 * available on dst_cpu.
9806 	 */
9807 	if ((env->idle != CPU_NOT_IDLE) &&
9808 	    (env->src_rq->cfs.h_nr_running == 1)) {
9809 		if ((check_cpu_capacity(env->src_rq, sd)) &&
9810 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
9811 			return 1;
9812 	}
9813 
9814 	if (env->migration_type == migrate_misfit)
9815 		return 1;
9816 
9817 	return 0;
9818 }
9819 
need_active_balance(struct lb_env * env)9820 static int need_active_balance(struct lb_env *env)
9821 {
9822 	struct sched_domain *sd = env->sd;
9823 
9824 	if (voluntary_active_balance(env))
9825 		return 1;
9826 
9827 	return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
9828 }
9829 
9830 #ifdef CONFIG_CPU_ISOLATION_OPT
group_balance_cpu_not_isolated(struct sched_group * sg)9831 int group_balance_cpu_not_isolated(struct sched_group *sg)
9832 {
9833 	cpumask_t cpus;
9834 
9835 	cpumask_and(&cpus, sched_group_span(sg), group_balance_mask(sg));
9836 	cpumask_andnot(&cpus, &cpus, cpu_isolated_mask);
9837 	return cpumask_first(&cpus);
9838 }
9839 #endif
9840 
9841 static int active_load_balance_cpu_stop(void *data);
9842 
should_we_balance(struct lb_env * env)9843 static int should_we_balance(struct lb_env *env)
9844 {
9845 	struct sched_group *sg = env->sd->groups;
9846 	int cpu;
9847 
9848 	/*
9849 	 * Ensure the balancing environment is consistent; can happen
9850 	 * when the softirq triggers 'during' hotplug.
9851 	 */
9852 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
9853 		return 0;
9854 
9855 	/*
9856 	 * In the newly idle case, we will allow all the CPUs
9857 	 * to do the newly idle load balance.
9858 	 */
9859 	if (env->idle == CPU_NEWLY_IDLE)
9860 		return 1;
9861 
9862 	/* Try to find first idle CPU */
9863 	for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
9864 		if (!idle_cpu(cpu) || cpu_isolated(cpu))
9865 			continue;
9866 
9867 		/* Are we the first idle CPU? */
9868 		return cpu == env->dst_cpu;
9869 	}
9870 
9871 	/* Are we the first CPU of this group ? */
9872 	return group_balance_cpu_not_isolated(sg) == env->dst_cpu;
9873 }
9874 
9875 /*
9876  * Check this_cpu to ensure it is balanced within domain. Attempt to move
9877  * tasks if there is an imbalance.
9878  */
load_balance(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)9879 static int load_balance(int this_cpu, struct rq *this_rq,
9880 			struct sched_domain *sd, enum cpu_idle_type idle,
9881 			int *continue_balancing)
9882 {
9883 	int ld_moved, cur_ld_moved, active_balance = 0;
9884 	struct sched_domain *sd_parent = sd->parent;
9885 	struct sched_group *group;
9886 	struct rq *busiest;
9887 	struct rq_flags rf;
9888 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
9889 
9890 	struct lb_env env = {
9891 		.sd		= sd,
9892 		.dst_cpu	= this_cpu,
9893 		.dst_rq		= this_rq,
9894 		.dst_grpmask    = sched_group_span(sd->groups),
9895 		.idle		= idle,
9896 		.loop_break	= sched_nr_migrate_break,
9897 		.cpus		= cpus,
9898 		.fbq_type	= all,
9899 		.tasks		= LIST_HEAD_INIT(env.tasks),
9900 	};
9901 
9902 	cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
9903 
9904 	schedstat_inc(sd->lb_count[idle]);
9905 
9906 redo:
9907 	if (!should_we_balance(&env)) {
9908 		*continue_balancing = 0;
9909 		goto out_balanced;
9910 	}
9911 
9912 	group = find_busiest_group(&env);
9913 	if (!group) {
9914 		schedstat_inc(sd->lb_nobusyg[idle]);
9915 		goto out_balanced;
9916 	}
9917 
9918 	busiest = find_busiest_queue(&env, group);
9919 	if (!busiest) {
9920 		schedstat_inc(sd->lb_nobusyq[idle]);
9921 		goto out_balanced;
9922 	}
9923 
9924 	BUG_ON(busiest == env.dst_rq);
9925 
9926 	schedstat_add(sd->lb_imbalance[idle], env.imbalance);
9927 
9928 	env.src_cpu = busiest->cpu;
9929 	env.src_rq = busiest;
9930 
9931 	ld_moved = 0;
9932 	if (busiest->nr_running > 1) {
9933 		/*
9934 		 * Attempt to move tasks. If find_busiest_group has found
9935 		 * an imbalance but busiest->nr_running <= 1, the group is
9936 		 * still unbalanced. ld_moved simply stays zero, so it is
9937 		 * correctly treated as an imbalance.
9938 		 */
9939 		env.flags |= LBF_ALL_PINNED;
9940 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
9941 
9942 more_balance:
9943 		rq_lock_irqsave(busiest, &rf);
9944 		update_rq_clock(busiest);
9945 
9946 		/*
9947 		 * cur_ld_moved - load moved in current iteration
9948 		 * ld_moved     - cumulative load moved across iterations
9949 		 */
9950 		cur_ld_moved = detach_tasks(&env);
9951 
9952 		/*
9953 		 * We've detached some tasks from busiest_rq. Every
9954 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9955 		 * unlock busiest->lock, and we are able to be sure
9956 		 * that nobody can manipulate the tasks in parallel.
9957 		 * See task_rq_lock() family for the details.
9958 		 */
9959 
9960 		rq_unlock(busiest, &rf);
9961 
9962 		if (cur_ld_moved) {
9963 			attach_tasks(&env);
9964 			ld_moved += cur_ld_moved;
9965 		}
9966 
9967 		local_irq_restore(rf.flags);
9968 
9969 		if (env.flags & LBF_NEED_BREAK) {
9970 			env.flags &= ~LBF_NEED_BREAK;
9971 			goto more_balance;
9972 		}
9973 
9974 		/*
9975 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
9976 		 * us and move them to an alternate dst_cpu in our sched_group
9977 		 * where they can run. The upper limit on how many times we
9978 		 * iterate on same src_cpu is dependent on number of CPUs in our
9979 		 * sched_group.
9980 		 *
9981 		 * This changes load balance semantics a bit on who can move
9982 		 * load to a given_cpu. In addition to the given_cpu itself
9983 		 * (or a ilb_cpu acting on its behalf where given_cpu is
9984 		 * nohz-idle), we now have balance_cpu in a position to move
9985 		 * load to given_cpu. In rare situations, this may cause
9986 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
9987 		 * _independently_ and at _same_ time to move some load to
9988 		 * given_cpu) causing exceess load to be moved to given_cpu.
9989 		 * This however should not happen so much in practice and
9990 		 * moreover subsequent load balance cycles should correct the
9991 		 * excess load moved.
9992 		 */
9993 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
9994 
9995 			/* Prevent to re-select dst_cpu via env's CPUs */
9996 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
9997 
9998 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
9999 			env.dst_cpu	 = env.new_dst_cpu;
10000 			env.flags	&= ~LBF_DST_PINNED;
10001 			env.loop	 = 0;
10002 			env.loop_break	 = sched_nr_migrate_break;
10003 
10004 			/*
10005 			 * Go back to "more_balance" rather than "redo" since we
10006 			 * need to continue with same src_cpu.
10007 			 */
10008 			goto more_balance;
10009 		}
10010 
10011 		/*
10012 		 * We failed to reach balance because of affinity.
10013 		 */
10014 		if (sd_parent) {
10015 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
10016 
10017 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
10018 				*group_imbalance = 1;
10019 		}
10020 
10021 		/* All tasks on this runqueue were pinned by CPU affinity */
10022 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
10023 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
10024 			/*
10025 			 * Attempting to continue load balancing at the current
10026 			 * sched_domain level only makes sense if there are
10027 			 * active CPUs remaining as possible busiest CPUs to
10028 			 * pull load from which are not contained within the
10029 			 * destination group that is receiving any migrated
10030 			 * load.
10031 			 */
10032 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
10033 				env.loop = 0;
10034 				env.loop_break = sched_nr_migrate_break;
10035 				goto redo;
10036 			}
10037 			goto out_all_pinned;
10038 		}
10039 	}
10040 
10041 	if (!ld_moved) {
10042 		schedstat_inc(sd->lb_failed[idle]);
10043 		/*
10044 		 * Increment the failure counter only on periodic balance.
10045 		 * We do not want newidle balance, which can be very
10046 		 * frequent, pollute the failure counter causing
10047 		 * excessive cache_hot migrations and active balances.
10048 		 */
10049 		if (idle != CPU_NEWLY_IDLE)
10050 			sd->nr_balance_failed++;
10051 
10052 		if (need_active_balance(&env)) {
10053 			unsigned long flags;
10054 
10055 			raw_spin_lock_irqsave(&busiest->lock, flags);
10056 
10057 			/*
10058 			 * Don't kick the active_load_balance_cpu_stop,
10059 			 * if the curr task on busiest CPU can't be
10060 			 * moved to this_cpu:
10061 			 */
10062 			if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
10063 				raw_spin_unlock_irqrestore(&busiest->lock,
10064 							    flags);
10065 				env.flags |= LBF_ALL_PINNED;
10066 				goto out_one_pinned;
10067 			}
10068 
10069 			/*
10070 			 * ->active_balance synchronizes accesses to
10071 			 * ->active_balance_work.  Once set, it's cleared
10072 			 * only after active load balance is finished.
10073 			 */
10074 			if (!busiest->active_balance &&
10075 			    !cpu_isolated(cpu_of(busiest))) {
10076 				busiest->active_balance = 1;
10077 				busiest->push_cpu = this_cpu;
10078 				active_balance = 1;
10079 			}
10080 			raw_spin_unlock_irqrestore(&busiest->lock, flags);
10081 
10082 			if (active_balance) {
10083 				stop_one_cpu_nowait(cpu_of(busiest),
10084 					active_load_balance_cpu_stop, busiest,
10085 					&busiest->active_balance_work);
10086 			}
10087 
10088 			/* We've kicked active balancing, force task migration. */
10089 			sd->nr_balance_failed = sd->cache_nice_tries+1;
10090 		}
10091 	} else
10092 		sd->nr_balance_failed = 0;
10093 
10094 	if (likely(!active_balance) || voluntary_active_balance(&env)) {
10095 		/* We were unbalanced, so reset the balancing interval */
10096 		sd->balance_interval = sd->min_interval;
10097 	} else {
10098 		/*
10099 		 * If we've begun active balancing, start to back off. This
10100 		 * case may not be covered by the all_pinned logic if there
10101 		 * is only 1 task on the busy runqueue (because we don't call
10102 		 * detach_tasks).
10103 		 */
10104 		if (sd->balance_interval < sd->max_interval)
10105 			sd->balance_interval *= 2;
10106 	}
10107 
10108 	goto out;
10109 
10110 out_balanced:
10111 	/*
10112 	 * We reach balance although we may have faced some affinity
10113 	 * constraints. Clear the imbalance flag only if other tasks got
10114 	 * a chance to move and fix the imbalance.
10115 	 */
10116 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
10117 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
10118 
10119 		if (*group_imbalance)
10120 			*group_imbalance = 0;
10121 	}
10122 
10123 out_all_pinned:
10124 	/*
10125 	 * We reach balance because all tasks are pinned at this level so
10126 	 * we can't migrate them. Let the imbalance flag set so parent level
10127 	 * can try to migrate them.
10128 	 */
10129 	schedstat_inc(sd->lb_balanced[idle]);
10130 
10131 	sd->nr_balance_failed = 0;
10132 
10133 out_one_pinned:
10134 	ld_moved = 0;
10135 
10136 	/*
10137 	 * newidle_balance() disregards balance intervals, so we could
10138 	 * repeatedly reach this code, which would lead to balance_interval
10139 	 * skyrocketting in a short amount of time. Skip the balance_interval
10140 	 * increase logic to avoid that.
10141 	 */
10142 	if (env.idle == CPU_NEWLY_IDLE)
10143 		goto out;
10144 
10145 	/* tune up the balancing interval */
10146 	if ((env.flags & LBF_ALL_PINNED &&
10147 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
10148 	    sd->balance_interval < sd->max_interval)
10149 		sd->balance_interval *= 2;
10150 out:
10151 	return ld_moved;
10152 }
10153 
10154 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)10155 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
10156 {
10157 	unsigned long interval = sd->balance_interval;
10158 
10159 	if (cpu_busy)
10160 		interval *= sd->busy_factor;
10161 
10162 	/* scale ms to jiffies */
10163 	interval = msecs_to_jiffies(interval);
10164 
10165 	/*
10166 	 * Reduce likelihood of busy balancing at higher domains racing with
10167 	 * balancing at lower domains by preventing their balancing periods
10168 	 * from being multiples of each other.
10169 	 */
10170 	if (cpu_busy)
10171 		interval -= 1;
10172 
10173 	interval = clamp(interval, 1UL, max_load_balance_interval);
10174 
10175 	return interval;
10176 }
10177 
10178 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)10179 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
10180 {
10181 	unsigned long interval, next;
10182 
10183 	/* used by idle balance, so cpu_busy = 0 */
10184 	interval = get_sd_balance_interval(sd, 0);
10185 	next = sd->last_balance + interval;
10186 
10187 	if (time_after(*next_balance, next))
10188 		*next_balance = next;
10189 }
10190 
10191 /*
10192  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
10193  * running tasks off the busiest CPU onto idle CPUs. It requires at
10194  * least 1 task to be running on each physical CPU where possible, and
10195  * avoids physical / logical imbalances.
10196  */
active_load_balance_cpu_stop(void * data)10197 static int active_load_balance_cpu_stop(void *data)
10198 {
10199 	struct rq *busiest_rq = data;
10200 	int busiest_cpu = cpu_of(busiest_rq);
10201 	int target_cpu = busiest_rq->push_cpu;
10202 	struct rq *target_rq = cpu_rq(target_cpu);
10203 	struct sched_domain *sd = NULL;
10204 	struct task_struct *p = NULL;
10205 	struct rq_flags rf;
10206 #ifdef CONFIG_SCHED_EAS
10207 	struct task_struct *push_task;
10208 	int push_task_detached = 0;
10209 #endif
10210 
10211 	rq_lock_irq(busiest_rq, &rf);
10212 	/*
10213 	 * Between queueing the stop-work and running it is a hole in which
10214 	 * CPUs can become inactive. We should not move tasks from or to
10215 	 * inactive CPUs.
10216 	 */
10217 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
10218 		goto out_unlock;
10219 
10220 	/* Make sure the requested CPU hasn't gone down in the meantime: */
10221 	if (unlikely(busiest_cpu != smp_processor_id() ||
10222 		     !busiest_rq->active_balance))
10223 		goto out_unlock;
10224 
10225 	/* Is there any task to move? */
10226 	if (busiest_rq->nr_running <= 1)
10227 		goto out_unlock;
10228 
10229 	/*
10230 	 * This condition is "impossible", if it occurs
10231 	 * we need to fix it. Originally reported by
10232 	 * Bjorn Helgaas on a 128-CPU setup.
10233 	 */
10234 	BUG_ON(busiest_rq == target_rq);
10235 
10236 #ifdef CONFIG_SCHED_EAS
10237 	push_task = busiest_rq->push_task;
10238 	target_cpu = busiest_rq->push_cpu;
10239 	if (push_task) {
10240 		struct lb_env env = {
10241 			.sd		= sd,
10242 			.dst_cpu	= target_cpu,
10243 			.dst_rq		= target_rq,
10244 			.src_cpu	= busiest_rq->cpu,
10245 			.src_rq		= busiest_rq,
10246 			.idle		= CPU_IDLE,
10247 			.flags		= 0,
10248 			.loop		= 0,
10249 		};
10250 		if (task_on_rq_queued(push_task) &&
10251 		    push_task->state ==  TASK_RUNNING &&
10252 		    task_cpu(push_task) == busiest_cpu &&
10253 		    cpu_online(target_cpu)) {
10254 			update_rq_clock(busiest_rq);
10255 			detach_task(push_task, &env);
10256 			push_task_detached = 1;
10257 		}
10258 		goto out_unlock;
10259 	}
10260 #endif
10261 
10262 	/* Search for an sd spanning us and the target CPU. */
10263 	rcu_read_lock();
10264 	for_each_domain(target_cpu, sd) {
10265 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
10266 			break;
10267 	}
10268 
10269 	if (likely(sd)) {
10270 		struct lb_env env = {
10271 			.sd		= sd,
10272 			.dst_cpu	= target_cpu,
10273 			.dst_rq		= target_rq,
10274 			.src_cpu	= busiest_rq->cpu,
10275 			.src_rq		= busiest_rq,
10276 			.idle		= CPU_IDLE,
10277 			/*
10278 			 * can_migrate_task() doesn't need to compute new_dst_cpu
10279 			 * for active balancing. Since we have CPU_IDLE, but no
10280 			 * @dst_grpmask we need to make that test go away with lying
10281 			 * about DST_PINNED.
10282 			 */
10283 			.flags		= LBF_DST_PINNED,
10284 		};
10285 
10286 		schedstat_inc(sd->alb_count);
10287 		update_rq_clock(busiest_rq);
10288 
10289 		p = detach_one_task(&env);
10290 		if (p) {
10291 			schedstat_inc(sd->alb_pushed);
10292 			/* Active balancing done, reset the failure counter. */
10293 			sd->nr_balance_failed = 0;
10294 		} else {
10295 			schedstat_inc(sd->alb_failed);
10296 		}
10297 	}
10298 	rcu_read_unlock();
10299 out_unlock:
10300 	busiest_rq->active_balance = 0;
10301 
10302 #ifdef CONFIG_SCHED_EAS
10303 	push_task = busiest_rq->push_task;
10304 	if (push_task)
10305 		busiest_rq->push_task = NULL;
10306 #endif
10307 	rq_unlock(busiest_rq, &rf);
10308 
10309 #ifdef CONFIG_SCHED_EAS
10310 	if (push_task) {
10311 		if (push_task_detached)
10312 			attach_one_task(target_rq, push_task);
10313 
10314 		put_task_struct(push_task);
10315 	}
10316 #endif
10317 
10318 	if (p)
10319 		attach_one_task(target_rq, p);
10320 
10321 	local_irq_enable();
10322 
10323 	return 0;
10324 }
10325 
10326 static DEFINE_SPINLOCK(balancing);
10327 
10328 /*
10329  * Scale the max load_balance interval with the number of CPUs in the system.
10330  * This trades load-balance latency on larger machines for less cross talk.
10331  */
update_max_interval(void)10332 void update_max_interval(void)
10333 {
10334 	unsigned int available_cpus;
10335 #ifdef CONFIG_CPU_ISOLATION_OPT
10336 	cpumask_t avail_mask;
10337 
10338 	cpumask_andnot(&avail_mask, cpu_online_mask, cpu_isolated_mask);
10339 	available_cpus = cpumask_weight(&avail_mask);
10340 #else
10341 	available_cpus = num_online_cpus();
10342 #endif
10343 
10344 	max_load_balance_interval = HZ*available_cpus/10;
10345 }
10346 
10347 /*
10348  * It checks each scheduling domain to see if it is due to be balanced,
10349  * and initiates a balancing operation if so.
10350  *
10351  * Balancing parameters are set up in init_sched_domains.
10352  */
rebalance_domains(struct rq * rq,enum cpu_idle_type idle)10353 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
10354 {
10355 	int continue_balancing = 1;
10356 	int cpu = rq->cpu;
10357 	int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
10358 	unsigned long interval;
10359 	struct sched_domain *sd;
10360 	/* Earliest time when we have to do rebalance again */
10361 	unsigned long next_balance = jiffies + 60*HZ;
10362 	int update_next_balance = 0;
10363 	int need_serialize, need_decay = 0;
10364 	u64 max_cost = 0;
10365 
10366 	rcu_read_lock();
10367 	for_each_domain(cpu, sd) {
10368 		/*
10369 		 * Decay the newidle max times here because this is a regular
10370 		 * visit to all the domains. Decay ~1% per second.
10371 		 */
10372 		if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
10373 			sd->max_newidle_lb_cost =
10374 				(sd->max_newidle_lb_cost * 253) / 256;
10375 			sd->next_decay_max_lb_cost = jiffies + HZ;
10376 			need_decay = 1;
10377 		}
10378 		max_cost += sd->max_newidle_lb_cost;
10379 
10380 		/*
10381 		 * Stop the load balance at this level. There is another
10382 		 * CPU in our sched group which is doing load balancing more
10383 		 * actively.
10384 		 */
10385 		if (!continue_balancing) {
10386 			if (need_decay)
10387 				continue;
10388 			break;
10389 		}
10390 
10391 		interval = get_sd_balance_interval(sd, busy);
10392 
10393 		need_serialize = sd->flags & SD_SERIALIZE;
10394 		if (need_serialize) {
10395 			if (!spin_trylock(&balancing))
10396 				goto out;
10397 		}
10398 
10399 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
10400 			if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
10401 				/*
10402 				 * The LBF_DST_PINNED logic could have changed
10403 				 * env->dst_cpu, so we can't know our idle
10404 				 * state even if we migrated tasks. Update it.
10405 				 */
10406 				idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
10407 				busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
10408 			}
10409 			sd->last_balance = jiffies;
10410 			interval = get_sd_balance_interval(sd, busy);
10411 		}
10412 		if (need_serialize)
10413 			spin_unlock(&balancing);
10414 out:
10415 		if (time_after(next_balance, sd->last_balance + interval)) {
10416 			next_balance = sd->last_balance + interval;
10417 			update_next_balance = 1;
10418 		}
10419 	}
10420 	if (need_decay) {
10421 		/*
10422 		 * Ensure the rq-wide value also decays but keep it at a
10423 		 * reasonable floor to avoid funnies with rq->avg_idle.
10424 		 */
10425 		rq->max_idle_balance_cost =
10426 			max((u64)sysctl_sched_migration_cost, max_cost);
10427 	}
10428 	rcu_read_unlock();
10429 
10430 	/*
10431 	 * next_balance will be updated only when there is a need.
10432 	 * When the cpu is attached to null domain for ex, it will not be
10433 	 * updated.
10434 	 */
10435 	if (likely(update_next_balance)) {
10436 		rq->next_balance = next_balance;
10437 
10438 #ifdef CONFIG_NO_HZ_COMMON
10439 		/*
10440 		 * If this CPU has been elected to perform the nohz idle
10441 		 * balance. Other idle CPUs have already rebalanced with
10442 		 * nohz_idle_balance() and nohz.next_balance has been
10443 		 * updated accordingly. This CPU is now running the idle load
10444 		 * balance for itself and we need to update the
10445 		 * nohz.next_balance accordingly.
10446 		 */
10447 		if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
10448 			nohz.next_balance = rq->next_balance;
10449 #endif
10450 	}
10451 }
10452 
on_null_domain(struct rq * rq)10453 static inline int on_null_domain(struct rq *rq)
10454 {
10455 	return unlikely(!rcu_dereference_sched(rq->sd));
10456 }
10457 
10458 #ifdef CONFIG_NO_HZ_COMMON
10459 /*
10460  * idle load balancing details
10461  * - When one of the busy CPUs notice that there may be an idle rebalancing
10462  *   needed, they will kick the idle load balancer, which then does idle
10463  *   load balancing for all the idle CPUs.
10464  * - HK_FLAG_MISC CPUs are used for this task, because HK_FLAG_SCHED not set
10465  *   anywhere yet.
10466  */
10467 
find_new_ilb(void)10468 static inline int find_new_ilb(void)
10469 {
10470 	int ilb;
10471 
10472 	for_each_cpu_and(ilb, nohz.idle_cpus_mask,
10473 			      housekeeping_cpumask(HK_FLAG_MISC)) {
10474 		if (cpu_isolated(ilb))
10475 			continue;
10476 
10477 		if (idle_cpu(ilb))
10478 			return ilb;
10479 	}
10480 
10481 	return nr_cpu_ids;
10482 }
10483 
10484 /*
10485  * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
10486  * idle CPU in the HK_FLAG_MISC housekeeping set (if there is one).
10487  */
kick_ilb(unsigned int flags)10488 static void kick_ilb(unsigned int flags)
10489 {
10490 	int ilb_cpu;
10491 
10492 	/*
10493 	 * Increase nohz.next_balance only when if full ilb is triggered but
10494 	 * not if we only update stats.
10495 	 */
10496 	if (flags & NOHZ_BALANCE_KICK)
10497 		nohz.next_balance = jiffies+1;
10498 
10499 	ilb_cpu = find_new_ilb();
10500 
10501 	if (ilb_cpu >= nr_cpu_ids)
10502 		return;
10503 
10504 	/*
10505 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
10506 	 * the first flag owns it; cleared by nohz_csd_func().
10507 	 */
10508 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
10509 	if (flags & NOHZ_KICK_MASK)
10510 		return;
10511 
10512 	/*
10513 	 * This way we generate an IPI on the target CPU which
10514 	 * is idle. And the softirq performing nohz idle load balance
10515 	 * will be run before returning from the IPI.
10516 	 */
10517 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
10518 }
10519 
10520 /*
10521  * Current decision point for kicking the idle load balancer in the presence
10522  * of idle CPUs in the system.
10523  */
nohz_balancer_kick(struct rq * rq)10524 static void nohz_balancer_kick(struct rq *rq)
10525 {
10526 	unsigned long now = jiffies;
10527 	struct sched_domain_shared *sds;
10528 	struct sched_domain *sd;
10529 	int nr_busy, i, cpu = rq->cpu;
10530 	unsigned int flags = 0;
10531 	cpumask_t cpumask;
10532 
10533 	if (unlikely(rq->idle_balance))
10534 		return;
10535 
10536 	/*
10537 	 * We may be recently in ticked or tickless idle mode. At the first
10538 	 * busy tick after returning from idle, we will update the busy stats.
10539 	 */
10540 	nohz_balance_exit_idle(rq);
10541 
10542 	/*
10543 	 * None are in tickless mode and hence no need for NOHZ idle load
10544 	 * balancing.
10545 	 */
10546 #ifdef CONFIG_CPU_ISOLATION_OPT
10547 	cpumask_andnot(&cpumask, nohz.idle_cpus_mask, cpu_isolated_mask);
10548 	if (cpumask_empty(&cpumask))
10549 		return;
10550 #else
10551 	cpumask_copy(&cpumask, nohz.idle_cpus_mask);
10552 	if (likely(!atomic_read(&nohz.nr_cpus)))
10553 		return;
10554 #endif
10555 
10556 	if (READ_ONCE(nohz.has_blocked) &&
10557 	    time_after(now, READ_ONCE(nohz.next_blocked)))
10558 		flags = NOHZ_STATS_KICK;
10559 
10560 	if (time_before(now, nohz.next_balance))
10561 		goto out;
10562 
10563 	if (rq->nr_running >= 2) {
10564 		flags = NOHZ_KICK_MASK;
10565 		goto out;
10566 	}
10567 
10568 	rcu_read_lock();
10569 
10570 	sd = rcu_dereference(rq->sd);
10571 	if (sd) {
10572 		/*
10573 		 * If there's a CFS task and the current CPU has reduced
10574 		 * capacity; kick the ILB to see if there's a better CPU to run
10575 		 * on.
10576 		 */
10577 		if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
10578 			flags = NOHZ_KICK_MASK;
10579 			goto unlock;
10580 		}
10581 	}
10582 
10583 	sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
10584 	if (sd) {
10585 		/*
10586 		 * When ASYM_PACKING; see if there's a more preferred CPU
10587 		 * currently idle; in which case, kick the ILB to move tasks
10588 		 * around.
10589 		 */
10590 		for_each_cpu_and(i, sched_domain_span(sd), &cpumask) {
10591 			if (sched_asym_prefer(i, cpu)) {
10592 				flags = NOHZ_KICK_MASK;
10593 				goto unlock;
10594 			}
10595 		}
10596 	}
10597 
10598 	sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
10599 	if (sd) {
10600 		/*
10601 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
10602 		 * to run the misfit task on.
10603 		 */
10604 		if (check_misfit_status(rq, sd)) {
10605 			flags = NOHZ_KICK_MASK;
10606 			goto unlock;
10607 		}
10608 
10609 		/*
10610 		 * For asymmetric systems, we do not want to nicely balance
10611 		 * cache use, instead we want to embrace asymmetry and only
10612 		 * ensure tasks have enough CPU capacity.
10613 		 *
10614 		 * Skip the LLC logic because it's not relevant in that case.
10615 		 */
10616 		goto unlock;
10617 	}
10618 
10619 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
10620 	if (sds) {
10621 		/*
10622 		 * If there is an imbalance between LLC domains (IOW we could
10623 		 * increase the overall cache use), we need some less-loaded LLC
10624 		 * domain to pull some load. Likewise, we may need to spread
10625 		 * load within the current LLC domain (e.g. packed SMT cores but
10626 		 * other CPUs are idle). We can't really know from here how busy
10627 		 * the others are - so just get a nohz balance going if it looks
10628 		 * like this LLC domain has tasks we could move.
10629 		 */
10630 		nr_busy = atomic_read(&sds->nr_busy_cpus);
10631 		if (nr_busy > 1) {
10632 			flags = NOHZ_KICK_MASK;
10633 			goto unlock;
10634 		}
10635 	}
10636 unlock:
10637 	rcu_read_unlock();
10638 out:
10639 	if (flags)
10640 		kick_ilb(flags);
10641 }
10642 
set_cpu_sd_state_busy(int cpu)10643 static void set_cpu_sd_state_busy(int cpu)
10644 {
10645 	struct sched_domain *sd;
10646 
10647 	rcu_read_lock();
10648 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
10649 
10650 	if (!sd || !sd->nohz_idle)
10651 		goto unlock;
10652 	sd->nohz_idle = 0;
10653 
10654 	atomic_inc(&sd->shared->nr_busy_cpus);
10655 unlock:
10656 	rcu_read_unlock();
10657 }
10658 
nohz_balance_exit_idle(struct rq * rq)10659 void nohz_balance_exit_idle(struct rq *rq)
10660 {
10661 	SCHED_WARN_ON(rq != this_rq());
10662 
10663 	if (likely(!rq->nohz_tick_stopped))
10664 		return;
10665 
10666 	rq->nohz_tick_stopped = 0;
10667 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
10668 	atomic_dec(&nohz.nr_cpus);
10669 
10670 	set_cpu_sd_state_busy(rq->cpu);
10671 }
10672 
set_cpu_sd_state_idle(int cpu)10673 static void set_cpu_sd_state_idle(int cpu)
10674 {
10675 	struct sched_domain *sd;
10676 
10677 	rcu_read_lock();
10678 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
10679 
10680 	if (!sd || sd->nohz_idle)
10681 		goto unlock;
10682 	sd->nohz_idle = 1;
10683 
10684 	atomic_dec(&sd->shared->nr_busy_cpus);
10685 unlock:
10686 	rcu_read_unlock();
10687 }
10688 
10689 /*
10690  * This routine will record that the CPU is going idle with tick stopped.
10691  * This info will be used in performing idle load balancing in the future.
10692  */
nohz_balance_enter_idle(int cpu)10693 void nohz_balance_enter_idle(int cpu)
10694 {
10695 	struct rq *rq = cpu_rq(cpu);
10696 
10697 	SCHED_WARN_ON(cpu != smp_processor_id());
10698 
10699 	/* If this CPU is going down, then nothing needs to be done: */
10700 	if (!cpu_active(cpu))
10701 		return;
10702 
10703 	/* Spare idle load balancing on CPUs that don't want to be disturbed: */
10704 	if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
10705 		return;
10706 
10707 	/*
10708 	 * Can be set safely without rq->lock held
10709 	 * If a clear happens, it will have evaluated last additions because
10710 	 * rq->lock is held during the check and the clear
10711 	 */
10712 	rq->has_blocked_load = 1;
10713 
10714 	/*
10715 	 * The tick is still stopped but load could have been added in the
10716 	 * meantime. We set the nohz.has_blocked flag to trig a check of the
10717 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
10718 	 * of nohz.has_blocked can only happen after checking the new load
10719 	 */
10720 	if (rq->nohz_tick_stopped)
10721 		goto out;
10722 
10723 	/* If we're a completely isolated CPU, we don't play: */
10724 	if (on_null_domain(rq))
10725 		return;
10726 
10727 	rq->nohz_tick_stopped = 1;
10728 
10729 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
10730 	atomic_inc(&nohz.nr_cpus);
10731 
10732 	/*
10733 	 * Ensures that if nohz_idle_balance() fails to observe our
10734 	 * @idle_cpus_mask store, it must observe the @has_blocked
10735 	 * store.
10736 	 */
10737 	smp_mb__after_atomic();
10738 
10739 	set_cpu_sd_state_idle(cpu);
10740 
10741 out:
10742 	/*
10743 	 * Each time a cpu enter idle, we assume that it has blocked load and
10744 	 * enable the periodic update of the load of idle cpus
10745 	 */
10746 	WRITE_ONCE(nohz.has_blocked, 1);
10747 }
10748 
10749 /*
10750  * Internal function that runs load balance for all idle cpus. The load balance
10751  * can be a simple update of blocked load or a complete load balance with
10752  * tasks movement depending of flags.
10753  * The function returns false if the loop has stopped before running
10754  * through all idle CPUs.
10755  */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags,enum cpu_idle_type idle)10756 static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
10757 			       enum cpu_idle_type idle)
10758 {
10759 	/* Earliest time when we have to do rebalance again */
10760 	unsigned long now = jiffies;
10761 	unsigned long next_balance = now + 60*HZ;
10762 	bool has_blocked_load = false;
10763 	int update_next_balance = 0;
10764 	int this_cpu = this_rq->cpu;
10765 	int balance_cpu;
10766 	int ret = false;
10767 	struct rq *rq;
10768 	cpumask_t cpus;
10769 
10770 	SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
10771 
10772 	/*
10773 	 * We assume there will be no idle load after this update and clear
10774 	 * the has_blocked flag. If a cpu enters idle in the mean time, it will
10775 	 * set the has_blocked flag and trig another update of idle load.
10776 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
10777 	 * setting the flag, we are sure to not clear the state and not
10778 	 * check the load of an idle cpu.
10779 	 */
10780 	WRITE_ONCE(nohz.has_blocked, 0);
10781 
10782 	/*
10783 	 * Ensures that if we miss the CPU, we must see the has_blocked
10784 	 * store from nohz_balance_enter_idle().
10785 	 */
10786 	smp_mb();
10787 
10788 #ifdef CONFIG_CPU_ISOLATION_OPT
10789 	cpumask_andnot(&cpus, nohz.idle_cpus_mask, cpu_isolated_mask);
10790 #else
10791 	cpumask_copy(&cpus, nohz.idle_cpus_mask);
10792 #endif
10793 
10794 	for_each_cpu(balance_cpu, &cpus) {
10795 		if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
10796 			continue;
10797 
10798 		/*
10799 		 * If this CPU gets work to do, stop the load balancing
10800 		 * work being done for other CPUs. Next load
10801 		 * balancing owner will pick it up.
10802 		 */
10803 		if (need_resched()) {
10804 			has_blocked_load = true;
10805 			goto abort;
10806 		}
10807 
10808 		rq = cpu_rq(balance_cpu);
10809 
10810 		has_blocked_load |= update_nohz_stats(rq, true);
10811 
10812 		/*
10813 		 * If time for next balance is due,
10814 		 * do the balance.
10815 		 */
10816 		if (time_after_eq(jiffies, rq->next_balance)) {
10817 			struct rq_flags rf;
10818 
10819 			rq_lock_irqsave(rq, &rf);
10820 			update_rq_clock(rq);
10821 			rq_unlock_irqrestore(rq, &rf);
10822 
10823 			if (flags & NOHZ_BALANCE_KICK)
10824 				rebalance_domains(rq, CPU_IDLE);
10825 		}
10826 
10827 		if (time_after(next_balance, rq->next_balance)) {
10828 			next_balance = rq->next_balance;
10829 			update_next_balance = 1;
10830 		}
10831 	}
10832 
10833 	/*
10834 	 * next_balance will be updated only when there is a need.
10835 	 * When the CPU is attached to null domain for ex, it will not be
10836 	 * updated.
10837 	 */
10838 	if (likely(update_next_balance))
10839 		nohz.next_balance = next_balance;
10840 
10841 	/* Newly idle CPU doesn't need an update */
10842 	if (idle != CPU_NEWLY_IDLE) {
10843 		update_blocked_averages(this_cpu);
10844 		has_blocked_load |= this_rq->has_blocked_load;
10845 	}
10846 
10847 	if (flags & NOHZ_BALANCE_KICK)
10848 		rebalance_domains(this_rq, CPU_IDLE);
10849 
10850 	WRITE_ONCE(nohz.next_blocked,
10851 		now + msecs_to_jiffies(LOAD_AVG_PERIOD));
10852 
10853 	/* The full idle balance loop has been done */
10854 	ret = true;
10855 
10856 abort:
10857 	/* There is still blocked load, enable periodic update */
10858 	if (has_blocked_load)
10859 		WRITE_ONCE(nohz.has_blocked, 1);
10860 
10861 	return ret;
10862 }
10863 
10864 /*
10865  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
10866  * rebalancing for all the cpus for whom scheduler ticks are stopped.
10867  */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)10868 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10869 {
10870 	unsigned int flags = this_rq->nohz_idle_balance;
10871 
10872 	if (!flags)
10873 		return false;
10874 
10875 	this_rq->nohz_idle_balance = 0;
10876 
10877 	if (idle != CPU_IDLE)
10878 		return false;
10879 
10880 	_nohz_idle_balance(this_rq, flags, idle);
10881 
10882 	return true;
10883 }
10884 
nohz_newidle_balance(struct rq * this_rq)10885 static void nohz_newidle_balance(struct rq *this_rq)
10886 {
10887 	int this_cpu = this_rq->cpu;
10888 
10889 	/*
10890 	 * This CPU doesn't want to be disturbed by scheduler
10891 	 * housekeeping
10892 	 */
10893 	if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
10894 		return;
10895 
10896 	/* Will wake up very soon. No time for doing anything else*/
10897 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
10898 		return;
10899 
10900 	/* Don't need to update blocked load of idle CPUs*/
10901 	if (!READ_ONCE(nohz.has_blocked) ||
10902 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
10903 		return;
10904 
10905 	raw_spin_unlock(&this_rq->lock);
10906 	/*
10907 	 * This CPU is going to be idle and blocked load of idle CPUs
10908 	 * need to be updated. Run the ilb locally as it is a good
10909 	 * candidate for ilb instead of waking up another idle CPU.
10910 	 * Kick an normal ilb if we failed to do the update.
10911 	 */
10912 	if (!_nohz_idle_balance(this_rq, NOHZ_STATS_KICK, CPU_NEWLY_IDLE))
10913 		kick_ilb(NOHZ_STATS_KICK);
10914 	raw_spin_lock(&this_rq->lock);
10915 }
10916 
10917 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)10918 static inline void nohz_balancer_kick(struct rq *rq) { }
10919 
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)10920 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10921 {
10922 	return false;
10923 }
10924 
nohz_newidle_balance(struct rq * this_rq)10925 static inline void nohz_newidle_balance(struct rq *this_rq) { }
10926 #endif /* CONFIG_NO_HZ_COMMON */
10927 
10928 /*
10929  * idle_balance is called by schedule() if this_cpu is about to become
10930  * idle. Attempts to pull tasks from other CPUs.
10931  *
10932  * Returns:
10933  *   < 0 - we released the lock and there are !fair tasks present
10934  *     0 - failed, no new tasks
10935  *   > 0 - success, new (fair) tasks present
10936  */
newidle_balance(struct rq * this_rq,struct rq_flags * rf)10937 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
10938 {
10939 	unsigned long next_balance = jiffies + HZ;
10940 	int this_cpu = this_rq->cpu;
10941 	struct sched_domain *sd;
10942 	int pulled_task = 0;
10943 	u64 curr_cost = 0;
10944 
10945 	if (cpu_isolated(this_cpu))
10946 		return 0;
10947 
10948 	update_misfit_status(NULL, this_rq);
10949 	/*
10950 	 * We must set idle_stamp _before_ calling idle_balance(), such that we
10951 	 * measure the duration of idle_balance() as idle time.
10952 	 */
10953 	this_rq->idle_stamp = rq_clock(this_rq);
10954 
10955 	/*
10956 	 * Do not pull tasks towards !active CPUs...
10957 	 */
10958 	if (!cpu_active(this_cpu))
10959 		return 0;
10960 
10961 	/*
10962 	 * This is OK, because current is on_cpu, which avoids it being picked
10963 	 * for load-balance and preemption/IRQs are still disabled avoiding
10964 	 * further scheduler activity on it and we're being very careful to
10965 	 * re-start the picking loop.
10966 	 */
10967 	rq_unpin_lock(this_rq, rf);
10968 
10969 	if (this_rq->avg_idle < sysctl_sched_migration_cost ||
10970 	    !READ_ONCE(this_rq->rd->overload)) {
10971 
10972 		rcu_read_lock();
10973 		sd = rcu_dereference_check_sched_domain(this_rq->sd);
10974 		if (sd)
10975 			update_next_balance(sd, &next_balance);
10976 		rcu_read_unlock();
10977 
10978 		nohz_newidle_balance(this_rq);
10979 
10980 		goto out;
10981 	}
10982 
10983 	raw_spin_unlock(&this_rq->lock);
10984 
10985 	update_blocked_averages(this_cpu);
10986 	rcu_read_lock();
10987 	for_each_domain(this_cpu, sd) {
10988 		int continue_balancing = 1;
10989 		u64 t0, domain_cost;
10990 
10991 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
10992 			update_next_balance(sd, &next_balance);
10993 			break;
10994 		}
10995 
10996 		if (sd->flags & SD_BALANCE_NEWIDLE) {
10997 			t0 = sched_clock_cpu(this_cpu);
10998 
10999 			pulled_task = load_balance(this_cpu, this_rq,
11000 						   sd, CPU_NEWLY_IDLE,
11001 						   &continue_balancing);
11002 
11003 			domain_cost = sched_clock_cpu(this_cpu) - t0;
11004 			if (domain_cost > sd->max_newidle_lb_cost)
11005 				sd->max_newidle_lb_cost = domain_cost;
11006 
11007 			curr_cost += domain_cost;
11008 		}
11009 
11010 		update_next_balance(sd, &next_balance);
11011 
11012 		/*
11013 		 * Stop searching for tasks to pull if there are
11014 		 * now runnable tasks on this rq.
11015 		 */
11016 		if (pulled_task || this_rq->nr_running > 0)
11017 			break;
11018 	}
11019 	rcu_read_unlock();
11020 
11021 	raw_spin_lock(&this_rq->lock);
11022 
11023 	if (curr_cost > this_rq->max_idle_balance_cost)
11024 		this_rq->max_idle_balance_cost = curr_cost;
11025 
11026 out:
11027 	/*
11028 	 * While browsing the domains, we released the rq lock, a task could
11029 	 * have been enqueued in the meantime. Since we're not going idle,
11030 	 * pretend we pulled a task.
11031 	 */
11032 	if (this_rq->cfs.h_nr_running && !pulled_task)
11033 		pulled_task = 1;
11034 
11035 	/* Move the next balance forward */
11036 	if (time_after(this_rq->next_balance, next_balance))
11037 		this_rq->next_balance = next_balance;
11038 
11039 	/* Is there a task of a high priority class? */
11040 	if (this_rq->nr_running != this_rq->cfs.h_nr_running)
11041 		pulled_task = -1;
11042 
11043 	if (pulled_task)
11044 		this_rq->idle_stamp = 0;
11045 
11046 	rq_repin_lock(this_rq, rf);
11047 
11048 	return pulled_task;
11049 }
11050 
11051 /*
11052  * run_rebalance_domains is triggered when needed from the scheduler tick.
11053  * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
11054  */
run_rebalance_domains(struct softirq_action * h)11055 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
11056 {
11057 	struct rq *this_rq = this_rq();
11058 	enum cpu_idle_type idle = this_rq->idle_balance ?
11059 						CPU_IDLE : CPU_NOT_IDLE;
11060 
11061 	/*
11062 	 * Since core isolation doesn't update nohz.idle_cpus_mask, there
11063 	 * is a possibility this nohz kicked cpu could be isolated. Hence
11064 	 * return if the cpu is isolated.
11065 	 */
11066 	if (cpu_isolated(this_rq->cpu))
11067 		return;
11068 
11069 	/*
11070 	 * If this CPU has a pending nohz_balance_kick, then do the
11071 	 * balancing on behalf of the other idle CPUs whose ticks are
11072 	 * stopped. Do nohz_idle_balance *before* rebalance_domains to
11073 	 * give the idle CPUs a chance to load balance. Else we may
11074 	 * load balance only within the local sched_domain hierarchy
11075 	 * and abort nohz_idle_balance altogether if we pull some load.
11076 	 */
11077 	if (nohz_idle_balance(this_rq, idle))
11078 		return;
11079 
11080 	/* normal load balance */
11081 	update_blocked_averages(this_rq->cpu);
11082 	rebalance_domains(this_rq, idle);
11083 }
11084 
11085 /*
11086  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
11087  */
trigger_load_balance(struct rq * rq)11088 void trigger_load_balance(struct rq *rq)
11089 {
11090 	/* Don't need to rebalance while attached to NULL domain or
11091 	 * cpu is isolated.
11092 	 */
11093 	if (unlikely(on_null_domain(rq)) || cpu_isolated(cpu_of(rq)))
11094 		return;
11095 
11096 	if (time_after_eq(jiffies, rq->next_balance))
11097 		raise_softirq(SCHED_SOFTIRQ);
11098 
11099 	nohz_balancer_kick(rq);
11100 }
11101 
rq_online_fair(struct rq * rq)11102 static void rq_online_fair(struct rq *rq)
11103 {
11104 	update_sysctl();
11105 
11106 	update_runtime_enabled(rq);
11107 }
11108 
rq_offline_fair(struct rq * rq)11109 static void rq_offline_fair(struct rq *rq)
11110 {
11111 	update_sysctl();
11112 
11113 	/* Ensure any throttled groups are reachable by pick_next_task */
11114 	unthrottle_offline_cfs_rqs(rq);
11115 }
11116 
11117 #ifdef CONFIG_SCHED_EAS
11118 static inline int
kick_active_balance(struct rq * rq,struct task_struct * p,int new_cpu)11119 kick_active_balance(struct rq *rq, struct task_struct *p, int new_cpu)
11120 {
11121 	unsigned long flags;
11122 	int rc = 0;
11123 
11124 	if (cpu_of(rq) == new_cpu)
11125 		return rc;
11126 
11127 	/* Invoke active balance to force migrate currently running task */
11128 	raw_spin_lock_irqsave(&rq->lock, flags);
11129 	if (!rq->active_balance) {
11130 		rq->active_balance = 1;
11131 		rq->push_cpu = new_cpu;
11132 		get_task_struct(p);
11133 		rq->push_task = p;
11134 		rc = 1;
11135 	}
11136 	raw_spin_unlock_irqrestore(&rq->lock, flags);
11137 	return rc;
11138 }
11139 
11140 DEFINE_RAW_SPINLOCK(migration_lock);
check_for_migration_fair(struct rq * rq,struct task_struct * p)11141 static void check_for_migration_fair(struct rq *rq, struct task_struct *p)
11142 {
11143 	int active_balance;
11144 	int new_cpu = -1;
11145 	int prev_cpu = task_cpu(p);
11146 	int ret;
11147 
11148 #ifdef CONFIG_SCHED_RTG
11149 	bool need_down_migrate = false;
11150 	struct cpumask *rtg_target = find_rtg_target(p);
11151 
11152 	if (rtg_target &&
11153 	    (capacity_orig_of(prev_cpu) >
11154 	     capacity_orig_of(cpumask_first(rtg_target))))
11155 		need_down_migrate = true;
11156 #endif
11157 
11158 	if (rq->misfit_task_load) {
11159 		if (rq->curr->state != TASK_RUNNING ||
11160 		    rq->curr->nr_cpus_allowed == 1)
11161 			return;
11162 
11163 		raw_spin_lock(&migration_lock);
11164 #ifdef CONFIG_SCHED_RTG
11165 		if (rtg_target) {
11166 			new_cpu = find_rtg_cpu(p);
11167 
11168 			if (new_cpu != -1 && need_down_migrate &&
11169 			    cpumask_test_cpu(new_cpu, rtg_target) &&
11170 			    idle_cpu(new_cpu))
11171 				goto do_active_balance;
11172 
11173 			if (new_cpu != -1 &&
11174 			    capacity_orig_of(new_cpu) > capacity_orig_of(prev_cpu))
11175 				goto do_active_balance;
11176 
11177 			goto out_unlock;
11178 		}
11179 #endif
11180 		rcu_read_lock();
11181 		new_cpu = find_energy_efficient_cpu(p, prev_cpu);
11182 		rcu_read_unlock();
11183 
11184 		if (new_cpu == -1 ||
11185 		    capacity_orig_of(new_cpu) <= capacity_orig_of(prev_cpu))
11186 			goto out_unlock;
11187 #ifdef CONFIG_SCHED_RTG
11188 do_active_balance:
11189 #endif
11190 		active_balance = kick_active_balance(rq, p, new_cpu);
11191 		if (active_balance) {
11192 			mark_reserved(new_cpu);
11193 			raw_spin_unlock(&migration_lock);
11194 			ret = stop_one_cpu_nowait(prev_cpu,
11195 				active_load_balance_cpu_stop, rq,
11196 				&rq->active_balance_work);
11197 			if (!ret)
11198 				clear_reserved(new_cpu);
11199 			else
11200 				wake_up_if_idle(new_cpu);
11201 			return;
11202 		}
11203 out_unlock:
11204 		raw_spin_unlock(&migration_lock);
11205 	}
11206 }
11207 #endif /* CONFIG_SCHED_EAS */
11208 #endif /* CONFIG_SMP */
11209 
11210 /*
11211  * scheduler tick hitting a task of our scheduling class.
11212  *
11213  * NOTE: This function can be called remotely by the tick offload that
11214  * goes along full dynticks. Therefore no local assumption can be made
11215  * and everything must be accessed through the @rq and @curr passed in
11216  * parameters.
11217  */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)11218 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
11219 {
11220 	struct cfs_rq *cfs_rq;
11221 	struct sched_entity *se = &curr->se;
11222 
11223 	for_each_sched_entity(se) {
11224 		cfs_rq = cfs_rq_of(se);
11225 		entity_tick(cfs_rq, se, queued);
11226 	}
11227 
11228 	if (static_branch_unlikely(&sched_numa_balancing))
11229 		task_tick_numa(rq, curr);
11230 
11231 	update_misfit_status(curr, rq);
11232 	update_overutilized_status(task_rq(curr));
11233 }
11234 
11235 /*
11236  * called on fork with the child task as argument from the parent's context
11237  *  - child not yet on the tasklist
11238  *  - preemption disabled
11239  */
task_fork_fair(struct task_struct * p)11240 static void task_fork_fair(struct task_struct *p)
11241 {
11242 	struct cfs_rq *cfs_rq;
11243 	struct sched_entity *se = &p->se, *curr;
11244 	struct rq *rq = this_rq();
11245 	struct rq_flags rf;
11246 
11247 	rq_lock(rq, &rf);
11248 	update_rq_clock(rq);
11249 
11250 	cfs_rq = task_cfs_rq(current);
11251 	curr = cfs_rq->curr;
11252 	if (curr) {
11253 		update_curr(cfs_rq);
11254 		se->vruntime = curr->vruntime;
11255 	}
11256 	place_entity(cfs_rq, se, 1);
11257 
11258 	if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
11259 		/*
11260 		 * Upon rescheduling, sched_class::put_prev_task() will place
11261 		 * 'current' within the tree based on its new key value.
11262 		 */
11263 		swap(curr->vruntime, se->vruntime);
11264 		resched_curr(rq);
11265 	}
11266 
11267 	se->vruntime -= cfs_rq->min_vruntime;
11268 	rq_unlock(rq, &rf);
11269 }
11270 
11271 /*
11272  * Priority of the task has changed. Check to see if we preempt
11273  * the current task.
11274  */
11275 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)11276 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
11277 {
11278 	if (!task_on_rq_queued(p))
11279 		return;
11280 
11281 	if (rq->cfs.nr_running == 1)
11282 		return;
11283 
11284 	/*
11285 	 * Reschedule if we are currently running on this runqueue and
11286 	 * our priority decreased, or if we are not currently running on
11287 	 * this runqueue and our priority is higher than the current's
11288 	 */
11289 	if (rq->curr == p) {
11290 		if (p->prio > oldprio)
11291 			resched_curr(rq);
11292 	} else
11293 		check_preempt_curr(rq, p, 0);
11294 }
11295 
vruntime_normalized(struct task_struct * p)11296 static inline bool vruntime_normalized(struct task_struct *p)
11297 {
11298 	struct sched_entity *se = &p->se;
11299 
11300 	/*
11301 	 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
11302 	 * the dequeue_entity(.flags=0) will already have normalized the
11303 	 * vruntime.
11304 	 */
11305 	if (p->on_rq)
11306 		return true;
11307 
11308 	/*
11309 	 * When !on_rq, vruntime of the task has usually NOT been normalized.
11310 	 * But there are some cases where it has already been normalized:
11311 	 *
11312 	 * - A forked child which is waiting for being woken up by
11313 	 *   wake_up_new_task().
11314 	 * - A task which has been woken up by try_to_wake_up() and
11315 	 *   waiting for actually being woken up by sched_ttwu_pending().
11316 	 */
11317 	if (!se->sum_exec_runtime ||
11318 	    (p->state == TASK_WAKING && p->sched_remote_wakeup))
11319 		return true;
11320 
11321 	return false;
11322 }
11323 
11324 #ifdef CONFIG_FAIR_GROUP_SCHED
11325 /*
11326  * Propagate the changes of the sched_entity across the tg tree to make it
11327  * visible to the root
11328  */
propagate_entity_cfs_rq(struct sched_entity * se)11329 static void propagate_entity_cfs_rq(struct sched_entity *se)
11330 {
11331 	struct cfs_rq *cfs_rq;
11332 
11333 	list_add_leaf_cfs_rq(cfs_rq_of(se));
11334 
11335 	/* Start to propagate at parent */
11336 	se = se->parent;
11337 
11338 	for_each_sched_entity(se) {
11339 		cfs_rq = cfs_rq_of(se);
11340 
11341 		if (!cfs_rq_throttled(cfs_rq)){
11342 			update_load_avg(cfs_rq, se, UPDATE_TG);
11343 			list_add_leaf_cfs_rq(cfs_rq);
11344 			continue;
11345 		}
11346 
11347 		if (list_add_leaf_cfs_rq(cfs_rq))
11348 			break;
11349 	}
11350 }
11351 #else
propagate_entity_cfs_rq(struct sched_entity * se)11352 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
11353 #endif
11354 
detach_entity_cfs_rq(struct sched_entity * se)11355 static void detach_entity_cfs_rq(struct sched_entity *se)
11356 {
11357 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
11358 
11359 	/* Catch up with the cfs_rq and remove our load when we leave */
11360 	update_load_avg(cfs_rq, se, 0);
11361 	detach_entity_load_avg(cfs_rq, se);
11362 	update_tg_load_avg(cfs_rq);
11363 	propagate_entity_cfs_rq(se);
11364 }
11365 
attach_entity_cfs_rq(struct sched_entity * se)11366 static void attach_entity_cfs_rq(struct sched_entity *se)
11367 {
11368 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
11369 
11370 #ifdef CONFIG_FAIR_GROUP_SCHED
11371 	/*
11372 	 * Since the real-depth could have been changed (only FAIR
11373 	 * class maintain depth value), reset depth properly.
11374 	 */
11375 	se->depth = se->parent ? se->parent->depth + 1 : 0;
11376 #endif
11377 
11378 	/* Synchronize entity with its cfs_rq */
11379 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
11380 	attach_entity_load_avg(cfs_rq, se);
11381 	update_tg_load_avg(cfs_rq);
11382 	propagate_entity_cfs_rq(se);
11383 }
11384 
detach_task_cfs_rq(struct task_struct * p)11385 static void detach_task_cfs_rq(struct task_struct *p)
11386 {
11387 	struct sched_entity *se = &p->se;
11388 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
11389 
11390 	if (!vruntime_normalized(p)) {
11391 		/*
11392 		 * Fix up our vruntime so that the current sleep doesn't
11393 		 * cause 'unlimited' sleep bonus.
11394 		 */
11395 		place_entity(cfs_rq, se, 0);
11396 		se->vruntime -= cfs_rq->min_vruntime;
11397 	}
11398 
11399 	detach_entity_cfs_rq(se);
11400 }
11401 
attach_task_cfs_rq(struct task_struct * p)11402 static void attach_task_cfs_rq(struct task_struct *p)
11403 {
11404 	struct sched_entity *se = &p->se;
11405 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
11406 
11407 	attach_entity_cfs_rq(se);
11408 
11409 	if (!vruntime_normalized(p))
11410 		se->vruntime += cfs_rq->min_vruntime;
11411 }
11412 
switched_from_fair(struct rq * rq,struct task_struct * p)11413 static void switched_from_fair(struct rq *rq, struct task_struct *p)
11414 {
11415 	detach_task_cfs_rq(p);
11416 }
11417 
switched_to_fair(struct rq * rq,struct task_struct * p)11418 static void switched_to_fair(struct rq *rq, struct task_struct *p)
11419 {
11420 	attach_task_cfs_rq(p);
11421 
11422 	if (task_on_rq_queued(p)) {
11423 		/*
11424 		 * We were most likely switched from sched_rt, so
11425 		 * kick off the schedule if running, otherwise just see
11426 		 * if we can still preempt the current task.
11427 		 */
11428 		if (rq->curr == p)
11429 			resched_curr(rq);
11430 		else
11431 			check_preempt_curr(rq, p, 0);
11432 	}
11433 }
11434 
11435 /* Account for a task changing its policy or group.
11436  *
11437  * This routine is mostly called to set cfs_rq->curr field when a task
11438  * migrates between groups/classes.
11439  */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)11440 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
11441 {
11442 	struct sched_entity *se = &p->se;
11443 
11444 #ifdef CONFIG_SMP
11445 	if (task_on_rq_queued(p)) {
11446 		/*
11447 		 * Move the next running task to the front of the list, so our
11448 		 * cfs_tasks list becomes MRU one.
11449 		 */
11450 		list_move(&se->group_node, &rq->cfs_tasks);
11451 	}
11452 #endif
11453 
11454 	for_each_sched_entity(se) {
11455 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
11456 
11457 		set_next_entity(cfs_rq, se);
11458 		/* ensure bandwidth has been allocated on our new cfs_rq */
11459 		account_cfs_rq_runtime(cfs_rq, 0);
11460 	}
11461 }
11462 
init_cfs_rq(struct cfs_rq * cfs_rq)11463 void init_cfs_rq(struct cfs_rq *cfs_rq)
11464 {
11465 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
11466 	cfs_rq->min_vruntime = (u64)(-(1LL << 20));
11467 #ifndef CONFIG_64BIT
11468 	cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
11469 #endif
11470 #ifdef CONFIG_SMP
11471 	raw_spin_lock_init(&cfs_rq->removed.lock);
11472 #endif
11473 }
11474 
11475 #ifdef CONFIG_FAIR_GROUP_SCHED
task_set_group_fair(struct task_struct * p)11476 static void task_set_group_fair(struct task_struct *p)
11477 {
11478 	struct sched_entity *se = &p->se;
11479 
11480 	set_task_rq(p, task_cpu(p));
11481 	se->depth = se->parent ? se->parent->depth + 1 : 0;
11482 }
11483 
task_move_group_fair(struct task_struct * p)11484 static void task_move_group_fair(struct task_struct *p)
11485 {
11486 	detach_task_cfs_rq(p);
11487 	set_task_rq(p, task_cpu(p));
11488 
11489 #ifdef CONFIG_SMP
11490 	/* Tell se's cfs_rq has been changed -- migrated */
11491 	p->se.avg.last_update_time = 0;
11492 #endif
11493 	attach_task_cfs_rq(p);
11494 }
11495 
task_change_group_fair(struct task_struct * p,int type)11496 static void task_change_group_fair(struct task_struct *p, int type)
11497 {
11498 	switch (type) {
11499 	case TASK_SET_GROUP:
11500 		task_set_group_fair(p);
11501 		break;
11502 
11503 	case TASK_MOVE_GROUP:
11504 		task_move_group_fair(p);
11505 		break;
11506 	}
11507 }
11508 
free_fair_sched_group(struct task_group * tg)11509 void free_fair_sched_group(struct task_group *tg)
11510 {
11511 	int i;
11512 
11513 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
11514 
11515 	for_each_possible_cpu(i) {
11516 		if (tg->cfs_rq)
11517 			kfree(tg->cfs_rq[i]);
11518 		if (tg->se)
11519 			kfree(tg->se[i]);
11520 	}
11521 
11522 	kfree(tg->cfs_rq);
11523 	kfree(tg->se);
11524 }
11525 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)11526 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11527 {
11528 	struct sched_entity *se;
11529 	struct cfs_rq *cfs_rq;
11530 	int i;
11531 
11532 	tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
11533 	if (!tg->cfs_rq)
11534 		goto err;
11535 	tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
11536 	if (!tg->se)
11537 		goto err;
11538 
11539 	tg->shares = NICE_0_LOAD;
11540 
11541 	init_cfs_bandwidth(tg_cfs_bandwidth(tg));
11542 
11543 	for_each_possible_cpu(i) {
11544 		cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
11545 				      GFP_KERNEL, cpu_to_node(i));
11546 		if (!cfs_rq)
11547 			goto err;
11548 
11549 		se = kzalloc_node(sizeof(struct sched_entity),
11550 				  GFP_KERNEL, cpu_to_node(i));
11551 		if (!se)
11552 			goto err_free_rq;
11553 
11554 		init_cfs_rq(cfs_rq);
11555 		init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
11556 		init_entity_runnable_average(se);
11557 	}
11558 
11559 	return 1;
11560 
11561 err_free_rq:
11562 	kfree(cfs_rq);
11563 err:
11564 	return 0;
11565 }
11566 
online_fair_sched_group(struct task_group * tg)11567 void online_fair_sched_group(struct task_group *tg)
11568 {
11569 	struct sched_entity *se;
11570 	struct rq_flags rf;
11571 	struct rq *rq;
11572 	int i;
11573 
11574 	for_each_possible_cpu(i) {
11575 		rq = cpu_rq(i);
11576 		se = tg->se[i];
11577 		rq_lock_irq(rq, &rf);
11578 		update_rq_clock(rq);
11579 		attach_entity_cfs_rq(se);
11580 		sync_throttle(tg, i);
11581 		rq_unlock_irq(rq, &rf);
11582 	}
11583 }
11584 
unregister_fair_sched_group(struct task_group * tg)11585 void unregister_fair_sched_group(struct task_group *tg)
11586 {
11587 	unsigned long flags;
11588 	struct rq *rq;
11589 	int cpu;
11590 
11591 	for_each_possible_cpu(cpu) {
11592 		if (tg->se[cpu])
11593 			remove_entity_load_avg(tg->se[cpu]);
11594 
11595 		/*
11596 		 * Only empty task groups can be destroyed; so we can speculatively
11597 		 * check on_list without danger of it being re-added.
11598 		 */
11599 		if (!tg->cfs_rq[cpu]->on_list)
11600 			continue;
11601 
11602 		rq = cpu_rq(cpu);
11603 
11604 		raw_spin_lock_irqsave(&rq->lock, flags);
11605 		list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
11606 		raw_spin_unlock_irqrestore(&rq->lock, flags);
11607 	}
11608 }
11609 
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)11610 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
11611 			struct sched_entity *se, int cpu,
11612 			struct sched_entity *parent)
11613 {
11614 	struct rq *rq = cpu_rq(cpu);
11615 
11616 	cfs_rq->tg = tg;
11617 	cfs_rq->rq = rq;
11618 	init_cfs_rq_runtime(cfs_rq);
11619 
11620 	tg->cfs_rq[cpu] = cfs_rq;
11621 	tg->se[cpu] = se;
11622 
11623 	/* se could be NULL for root_task_group */
11624 	if (!se)
11625 		return;
11626 
11627 	if (!parent) {
11628 		se->cfs_rq = &rq->cfs;
11629 		se->depth = 0;
11630 	} else {
11631 		se->cfs_rq = parent->my_q;
11632 		se->depth = parent->depth + 1;
11633 	}
11634 
11635 	se->my_q = cfs_rq;
11636 	/* guarantee group entities always have weight */
11637 	update_load_set(&se->load, NICE_0_LOAD);
11638 	se->parent = parent;
11639 }
11640 
11641 static DEFINE_MUTEX(shares_mutex);
11642 
sched_group_set_shares(struct task_group * tg,unsigned long shares)11643 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
11644 {
11645 	int i;
11646 
11647 	/*
11648 	 * We can't change the weight of the root cgroup.
11649 	 */
11650 	if (!tg->se[0])
11651 		return -EINVAL;
11652 
11653 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
11654 
11655 	mutex_lock(&shares_mutex);
11656 	if (tg->shares == shares)
11657 		goto done;
11658 
11659 	tg->shares = shares;
11660 	for_each_possible_cpu(i) {
11661 		struct rq *rq = cpu_rq(i);
11662 		struct sched_entity *se = tg->se[i];
11663 		struct rq_flags rf;
11664 
11665 		/* Propagate contribution to hierarchy */
11666 		rq_lock_irqsave(rq, &rf);
11667 		update_rq_clock(rq);
11668 		for_each_sched_entity(se) {
11669 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11670 			update_cfs_group(se);
11671 		}
11672 		rq_unlock_irqrestore(rq, &rf);
11673 	}
11674 
11675 done:
11676 	mutex_unlock(&shares_mutex);
11677 	return 0;
11678 }
11679 #else /* CONFIG_FAIR_GROUP_SCHED */
11680 
free_fair_sched_group(struct task_group * tg)11681 void free_fair_sched_group(struct task_group *tg) { }
11682 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)11683 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11684 {
11685 	return 1;
11686 }
11687 
online_fair_sched_group(struct task_group * tg)11688 void online_fair_sched_group(struct task_group *tg) { }
11689 
unregister_fair_sched_group(struct task_group * tg)11690 void unregister_fair_sched_group(struct task_group *tg) { }
11691 
11692 #endif /* CONFIG_FAIR_GROUP_SCHED */
11693 
11694 
get_rr_interval_fair(struct rq * rq,struct task_struct * task)11695 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
11696 {
11697 	struct sched_entity *se = &task->se;
11698 	unsigned int rr_interval = 0;
11699 
11700 	/*
11701 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11702 	 * idle runqueue:
11703 	 */
11704 	if (rq->cfs.load.weight)
11705 		rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
11706 
11707 	return rr_interval;
11708 }
11709 
11710 /*
11711  * All the scheduling class methods:
11712  */
11713 const struct sched_class fair_sched_class
11714 	__section("__fair_sched_class") = {
11715 	.enqueue_task		= enqueue_task_fair,
11716 	.dequeue_task		= dequeue_task_fair,
11717 	.yield_task		= yield_task_fair,
11718 	.yield_to_task		= yield_to_task_fair,
11719 
11720 	.check_preempt_curr	= check_preempt_wakeup,
11721 
11722 	.pick_next_task		= __pick_next_task_fair,
11723 	.put_prev_task		= put_prev_task_fair,
11724 	.set_next_task          = set_next_task_fair,
11725 
11726 #ifdef CONFIG_SMP
11727 	.balance		= balance_fair,
11728 	.select_task_rq		= select_task_rq_fair,
11729 	.migrate_task_rq	= migrate_task_rq_fair,
11730 
11731 	.rq_online		= rq_online_fair,
11732 	.rq_offline		= rq_offline_fair,
11733 
11734 	.task_dead		= task_dead_fair,
11735 	.set_cpus_allowed	= set_cpus_allowed_common,
11736 #endif
11737 
11738 	.task_tick		= task_tick_fair,
11739 	.task_fork		= task_fork_fair,
11740 
11741 	.prio_changed		= prio_changed_fair,
11742 	.switched_from		= switched_from_fair,
11743 	.switched_to		= switched_to_fair,
11744 
11745 	.get_rr_interval	= get_rr_interval_fair,
11746 
11747 	.update_curr		= update_curr_fair,
11748 
11749 #ifdef CONFIG_FAIR_GROUP_SCHED
11750 	.task_change_group	= task_change_group_fair,
11751 #endif
11752 
11753 #ifdef CONFIG_UCLAMP_TASK
11754 	.uclamp_enabled		= 1,
11755 #endif
11756 #ifdef CONFIG_SCHED_WALT
11757 	.fixup_walt_sched_stats	= walt_fixup_sched_stats_fair,
11758 #endif
11759 #ifdef CONFIG_SCHED_EAS
11760 	.check_for_migration	= check_for_migration_fair,
11761 #endif
11762 };
11763 
11764 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)11765 void print_cfs_stats(struct seq_file *m, int cpu)
11766 {
11767 	struct cfs_rq *cfs_rq, *pos;
11768 
11769 	rcu_read_lock();
11770 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
11771 		print_cfs_rq(m, cpu, cfs_rq);
11772 	rcu_read_unlock();
11773 }
11774 
11775 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)11776 void show_numa_stats(struct task_struct *p, struct seq_file *m)
11777 {
11778 	int node;
11779 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
11780 	struct numa_group *ng;
11781 
11782 	rcu_read_lock();
11783 	ng = rcu_dereference(p->numa_group);
11784 	for_each_online_node(node) {
11785 		if (p->numa_faults) {
11786 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
11787 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
11788 		}
11789 		if (ng) {
11790 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
11791 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
11792 		}
11793 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
11794 	}
11795 	rcu_read_unlock();
11796 }
11797 #endif /* CONFIG_NUMA_BALANCING */
11798 #endif /* CONFIG_SCHED_DEBUG */
11799 
init_sched_fair_class(void)11800 __init void init_sched_fair_class(void)
11801 {
11802 #ifdef CONFIG_SMP
11803 	open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
11804 
11805 #ifdef CONFIG_NO_HZ_COMMON
11806 	nohz.next_balance = jiffies;
11807 	nohz.next_blocked = jiffies;
11808 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
11809 #endif
11810 #endif /* SMP */
11811 
11812 }
11813 
11814 /* WALT sched implementation begins here */
11815 #ifdef CONFIG_SCHED_WALT
11816 
11817 #ifdef CONFIG_CFS_BANDWIDTH
11818 
walt_init_cfs_rq_stats(struct cfs_rq * cfs_rq)11819 static void walt_init_cfs_rq_stats(struct cfs_rq *cfs_rq)
11820 {
11821 	cfs_rq->walt_stats.cumulative_runnable_avg_scaled = 0;
11822 }
11823 
walt_inc_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)11824 static void walt_inc_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
11825 {
11826 	fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
11827 				      p->ravg.demand_scaled);
11828 }
11829 
walt_dec_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)11830 static void walt_dec_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
11831 {
11832 	fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
11833 				      -(s64)p->ravg.demand_scaled);
11834 }
11835 
walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)11836 static void walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
11837 					    struct cfs_rq *tcfs_rq)
11838 {
11839 	struct rq *rq = rq_of(tcfs_rq);
11840 
11841 	fixup_cumulative_runnable_avg(stats,
11842 			tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11843 
11844 	if (stats == &rq->walt_stats)
11845 		walt_fixup_cum_window_demand(rq,
11846 			tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11847 
11848 }
11849 
walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)11850 static void walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
11851 					    struct cfs_rq *tcfs_rq)
11852 {
11853 	struct rq *rq = rq_of(tcfs_rq);
11854 
11855 	fixup_cumulative_runnable_avg(stats,
11856 			-tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11857 
11858 	/*
11859 	 * We remove the throttled cfs_rq's tasks's contribution from the
11860 	 * cumulative window demand so that the same can be added
11861 	 * unconditionally when the cfs_rq is unthrottled.
11862 	 */
11863 	if (stats == &rq->walt_stats)
11864 		walt_fixup_cum_window_demand(rq,
11865 			-tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11866 }
11867 
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)11868 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
11869 					u16 updated_demand_scaled)
11870 {
11871 	struct cfs_rq *cfs_rq;
11872 	struct sched_entity *se = &p->se;
11873 	s64 task_load_delta = (s64)updated_demand_scaled -
11874 			      p->ravg.demand_scaled;
11875 
11876 	for_each_sched_entity(se) {
11877 		cfs_rq = cfs_rq_of(se);
11878 
11879 		fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
11880 					      task_load_delta);
11881 		if (cfs_rq_throttled(cfs_rq))
11882 			break;
11883 	}
11884 
11885 	/* Fix up rq->walt_stats only if we didn't find any throttled cfs_rq */
11886 	if (!se) {
11887 		fixup_cumulative_runnable_avg(&rq->walt_stats,
11888 					      task_load_delta);
11889 		walt_fixup_cum_window_demand(rq, task_load_delta);
11890 	}
11891 }
11892 
11893 #else /* CONFIG_CFS_BANDWIDTH */
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)11894 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
11895 					u16 updated_demand_scaled)
11896 {
11897 	fixup_walt_sched_stats_common(rq, p, updated_demand_scaled);
11898 }
11899 #endif /* CONFIG_CFS_BANDWIDTH */
11900 #endif /* CONFIG_SCHED_WALT */
11901 
11902 /*
11903  * Helper functions to facilitate extracting info from tracepoints.
11904  */
11905 
sched_trace_cfs_rq_avg(struct cfs_rq * cfs_rq)11906 const struct sched_avg *sched_trace_cfs_rq_avg(struct cfs_rq *cfs_rq)
11907 {
11908 #ifdef CONFIG_SMP
11909 	return cfs_rq ? &cfs_rq->avg : NULL;
11910 #else
11911 	return NULL;
11912 #endif
11913 }
11914 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_avg);
11915 
sched_trace_cfs_rq_path(struct cfs_rq * cfs_rq,char * str,int len)11916 char *sched_trace_cfs_rq_path(struct cfs_rq *cfs_rq, char *str, int len)
11917 {
11918 	if (!cfs_rq) {
11919 		if (str)
11920 			strlcpy(str, "(null)", len);
11921 		else
11922 			return NULL;
11923 	}
11924 
11925 	cfs_rq_tg_path(cfs_rq, str, len);
11926 	return str;
11927 }
11928 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_path);
11929 
sched_trace_cfs_rq_cpu(struct cfs_rq * cfs_rq)11930 int sched_trace_cfs_rq_cpu(struct cfs_rq *cfs_rq)
11931 {
11932 	return cfs_rq ? cpu_of(rq_of(cfs_rq)) : -1;
11933 }
11934 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_cpu);
11935 
sched_trace_rq_avg_rt(struct rq * rq)11936 const struct sched_avg *sched_trace_rq_avg_rt(struct rq *rq)
11937 {
11938 #ifdef CONFIG_SMP
11939 	return rq ? &rq->avg_rt : NULL;
11940 #else
11941 	return NULL;
11942 #endif
11943 }
11944 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_rt);
11945 
sched_trace_rq_avg_dl(struct rq * rq)11946 const struct sched_avg *sched_trace_rq_avg_dl(struct rq *rq)
11947 {
11948 #ifdef CONFIG_SMP
11949 	return rq ? &rq->avg_dl : NULL;
11950 #else
11951 	return NULL;
11952 #endif
11953 }
11954 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_dl);
11955 
sched_trace_rq_avg_irq(struct rq * rq)11956 const struct sched_avg *sched_trace_rq_avg_irq(struct rq *rq)
11957 {
11958 #if defined(CONFIG_SMP) && defined(CONFIG_HAVE_SCHED_AVG_IRQ)
11959 	return rq ? &rq->avg_irq : NULL;
11960 #else
11961 	return NULL;
11962 #endif
11963 }
11964 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_irq);
11965 
sched_trace_rq_cpu(struct rq * rq)11966 int sched_trace_rq_cpu(struct rq *rq)
11967 {
11968 	return rq ? cpu_of(rq) : -1;
11969 }
11970 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu);
11971 
sched_trace_rq_cpu_capacity(struct rq * rq)11972 int sched_trace_rq_cpu_capacity(struct rq *rq)
11973 {
11974 	return rq ?
11975 #ifdef CONFIG_SMP
11976 		rq->cpu_capacity
11977 #else
11978 		SCHED_CAPACITY_SCALE
11979 #endif
11980 		: -1;
11981 }
11982 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu_capacity);
11983 
sched_trace_rd_span(struct root_domain * rd)11984 const struct cpumask *sched_trace_rd_span(struct root_domain *rd)
11985 {
11986 #ifdef CONFIG_SMP
11987 	return rd ? rd->span : NULL;
11988 #else
11989 	return NULL;
11990 #endif
11991 }
11992 EXPORT_SYMBOL_GPL(sched_trace_rd_span);
11993 
sched_trace_rq_nr_running(struct rq * rq)11994 int sched_trace_rq_nr_running(struct rq *rq)
11995 {
11996         return rq ? rq->nr_running : -1;
11997 }
11998 EXPORT_SYMBOL_GPL(sched_trace_rq_nr_running);
11999