xref: /linux/kernel/sched/fair.c (revision af5a3fae860df6d065d796810a3e3a03fbb6f895)
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, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
19  *
20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22  */
23 #include <linux/energy_model.h>
24 #include <linux/mmap_lock.h>
25 #include <linux/hugetlb_inline.h>
26 #include <linux/jiffies.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/spinlock_api.h>
30 #include <linux/cpumask_api.h>
31 #include <linux/lockdep_api.h>
32 #include <linux/softirq.h>
33 #include <linux/refcount_api.h>
34 #include <linux/topology.h>
35 #include <linux/sched/clock.h>
36 #include <linux/sched/cond_resched.h>
37 #include <linux/sched/cputime.h>
38 #include <linux/sched/isolation.h>
39 #include <linux/sched/nohz.h>
40 #include <linux/sched/prio.h>
41 
42 #include <linux/cpuidle.h>
43 #include <linux/interrupt.h>
44 #include <linux/memory-tiers.h>
45 #include <linux/mempolicy.h>
46 #include <linux/mutex_api.h>
47 #include <linux/profile.h>
48 #include <linux/psi.h>
49 #include <linux/ratelimit.h>
50 #include <linux/task_work.h>
51 #include <linux/rbtree_augmented.h>
52 
53 #include <asm/switch_to.h>
54 
55 #include <uapi/linux/sched/types.h>
56 
57 #include "sched.h"
58 #include "stats.h"
59 #include "autogroup.h"
60 
61 /*
62  * The initial- and re-scaling of tunables is configurable
63  *
64  * Options are:
65  *
66  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
67  *   SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
68  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
69  *
70  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
71  */
72 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
73 
74 /*
75  * Minimal preemption granularity for CPU-bound tasks:
76  *
77  * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
78  */
79 unsigned int sysctl_sched_base_slice			= 700000ULL;
80 static unsigned int normalized_sysctl_sched_base_slice	= 700000ULL;
81 
82 __read_mostly unsigned int sysctl_sched_migration_cost	= 500000UL;
83 
setup_sched_thermal_decay_shift(char * str)84 static int __init setup_sched_thermal_decay_shift(char *str)
85 {
86 	pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
87 	return 1;
88 }
89 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
90 
91 /*
92  * For asym packing, by default the lower numbered CPU has higher priority.
93  */
arch_asym_cpu_priority(int cpu)94 int __weak arch_asym_cpu_priority(int cpu)
95 {
96 	return -cpu;
97 }
98 
99 /*
100  * The margin used when comparing utilization with CPU capacity.
101  *
102  * (default: ~20%)
103  */
104 #define fits_capacity(cap, max)	((cap) * 1280 < (max) * 1024)
105 
106 /*
107  * The margin used when comparing CPU capacities.
108  * is 'cap1' noticeably greater than 'cap2'
109  *
110  * (default: ~5%)
111  */
112 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
113 
114 #ifdef CONFIG_CFS_BANDWIDTH
115 /*
116  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
117  * each time a cfs_rq requests quota.
118  *
119  * Note: in the case that the slice exceeds the runtime remaining (either due
120  * to consumption or the quota being specified to be smaller than the slice)
121  * we will always only issue the remaining available time.
122  *
123  * (default: 5 msec, units: microseconds)
124  */
125 static unsigned int sysctl_sched_cfs_bandwidth_slice		= 5000UL;
126 #endif
127 
128 #ifdef CONFIG_NUMA_BALANCING
129 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
130 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
131 #endif
132 
133 #ifdef CONFIG_SYSCTL
134 static const struct ctl_table sched_fair_sysctls[] = {
135 #ifdef CONFIG_CFS_BANDWIDTH
136 	{
137 		.procname       = "sched_cfs_bandwidth_slice_us",
138 		.data           = &sysctl_sched_cfs_bandwidth_slice,
139 		.maxlen         = sizeof(unsigned int),
140 		.mode           = 0644,
141 		.proc_handler   = proc_dointvec_minmax,
142 		.extra1         = SYSCTL_ONE,
143 	},
144 #endif
145 #ifdef CONFIG_NUMA_BALANCING
146 	{
147 		.procname	= "numa_balancing_promote_rate_limit_MBps",
148 		.data		= &sysctl_numa_balancing_promote_rate_limit,
149 		.maxlen		= sizeof(unsigned int),
150 		.mode		= 0644,
151 		.proc_handler	= proc_dointvec_minmax,
152 		.extra1		= SYSCTL_ZERO,
153 	},
154 #endif /* CONFIG_NUMA_BALANCING */
155 };
156 
sched_fair_sysctl_init(void)157 static int __init sched_fair_sysctl_init(void)
158 {
159 	register_sysctl_init("kernel", sched_fair_sysctls);
160 	return 0;
161 }
162 late_initcall(sched_fair_sysctl_init);
163 #endif /* CONFIG_SYSCTL */
164 
update_load_add(struct load_weight * lw,unsigned long inc)165 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
166 {
167 	lw->weight += inc;
168 	lw->inv_weight = 0;
169 }
170 
update_load_sub(struct load_weight * lw,unsigned long dec)171 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
172 {
173 	lw->weight -= dec;
174 	lw->inv_weight = 0;
175 }
176 
update_load_set(struct load_weight * lw,unsigned long w)177 static inline void update_load_set(struct load_weight *lw, unsigned long w)
178 {
179 	lw->weight = w;
180 	lw->inv_weight = 0;
181 }
182 
183 /*
184  * Increase the granularity value when there are more CPUs,
185  * because with more CPUs the 'effective latency' as visible
186  * to users decreases. But the relationship is not linear,
187  * so pick a second-best guess by going with the log2 of the
188  * number of CPUs.
189  *
190  * This idea comes from the SD scheduler of Con Kolivas:
191  */
get_update_sysctl_factor(void)192 static unsigned int get_update_sysctl_factor(void)
193 {
194 	unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
195 	unsigned int factor;
196 
197 	switch (sysctl_sched_tunable_scaling) {
198 	case SCHED_TUNABLESCALING_NONE:
199 		factor = 1;
200 		break;
201 	case SCHED_TUNABLESCALING_LINEAR:
202 		factor = cpus;
203 		break;
204 	case SCHED_TUNABLESCALING_LOG:
205 	default:
206 		factor = 1 + ilog2(cpus);
207 		break;
208 	}
209 
210 	return factor;
211 }
212 
update_sysctl(void)213 static void update_sysctl(void)
214 {
215 	unsigned int factor = get_update_sysctl_factor();
216 
217 #define SET_SYSCTL(name) \
218 	(sysctl_##name = (factor) * normalized_sysctl_##name)
219 	SET_SYSCTL(sched_base_slice);
220 #undef SET_SYSCTL
221 }
222 
sched_init_granularity(void)223 void __init sched_init_granularity(void)
224 {
225 	update_sysctl();
226 }
227 
228 #define WMULT_CONST	(~0U)
229 #define WMULT_SHIFT	32
230 
__update_inv_weight(struct load_weight * lw)231 static void __update_inv_weight(struct load_weight *lw)
232 {
233 	unsigned long w;
234 
235 	if (likely(lw->inv_weight))
236 		return;
237 
238 	w = scale_load_down(lw->weight);
239 
240 	if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
241 		lw->inv_weight = 1;
242 	else if (unlikely(!w))
243 		lw->inv_weight = WMULT_CONST;
244 	else
245 		lw->inv_weight = WMULT_CONST / w;
246 }
247 
248 /*
249  * delta_exec * weight / lw.weight
250  *   OR
251  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
252  *
253  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
254  * we're guaranteed shift stays positive because inv_weight is guaranteed to
255  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
256  *
257  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
258  * weight/lw.weight <= 1, and therefore our shift will also be positive.
259  */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)260 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
261 {
262 	u64 fact = scale_load_down(weight);
263 	u32 fact_hi = (u32)(fact >> 32);
264 	int shift = WMULT_SHIFT;
265 	int fs;
266 
267 	__update_inv_weight(lw);
268 
269 	if (unlikely(fact_hi)) {
270 		fs = fls(fact_hi);
271 		shift -= fs;
272 		fact >>= fs;
273 	}
274 
275 	fact = mul_u32_u32(fact, lw->inv_weight);
276 
277 	fact_hi = (u32)(fact >> 32);
278 	if (fact_hi) {
279 		fs = fls(fact_hi);
280 		shift -= fs;
281 		fact >>= fs;
282 	}
283 
284 	return mul_u64_u32_shr(delta_exec, fact, shift);
285 }
286 
287 /*
288  * delta /= w
289  */
calc_delta_fair(u64 delta,struct sched_entity * se)290 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
291 {
292 	if (unlikely(se->load.weight != NICE_0_LOAD))
293 		delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
294 
295 	return delta;
296 }
297 
298 const struct sched_class fair_sched_class;
299 
300 /**************************************************************
301  * CFS operations on generic schedulable entities:
302  */
303 
304 #ifdef CONFIG_FAIR_GROUP_SCHED
305 
306 /* Walk up scheduling entities hierarchy */
307 #define for_each_sched_entity(se) \
308 		for (; se; se = se->parent)
309 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)310 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
311 {
312 	struct rq *rq = rq_of(cfs_rq);
313 	int cpu = cpu_of(rq);
314 
315 	if (cfs_rq->on_list)
316 		return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
317 
318 	cfs_rq->on_list = 1;
319 
320 	/*
321 	 * Ensure we either appear before our parent (if already
322 	 * enqueued) or force our parent to appear after us when it is
323 	 * enqueued. The fact that we always enqueue bottom-up
324 	 * reduces this to two cases and a special case for the root
325 	 * cfs_rq. Furthermore, it also means that we will always reset
326 	 * tmp_alone_branch either when the branch is connected
327 	 * to a tree or when we reach the top of the tree
328 	 */
329 	if (cfs_rq->tg->parent &&
330 	    cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
331 		/*
332 		 * If parent is already on the list, we add the child
333 		 * just before. Thanks to circular linked property of
334 		 * the list, this means to put the child at the tail
335 		 * of the list that starts by parent.
336 		 */
337 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
338 			&(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
339 		/*
340 		 * The branch is now connected to its tree so we can
341 		 * reset tmp_alone_branch to the beginning of the
342 		 * list.
343 		 */
344 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
345 		return true;
346 	}
347 
348 	if (!cfs_rq->tg->parent) {
349 		/*
350 		 * cfs rq without parent should be put
351 		 * at the tail of the list.
352 		 */
353 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
354 			&rq->leaf_cfs_rq_list);
355 		/*
356 		 * We have reach the top of a tree so we can reset
357 		 * tmp_alone_branch to the beginning of the list.
358 		 */
359 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
360 		return true;
361 	}
362 
363 	/*
364 	 * The parent has not already been added so we want to
365 	 * make sure that it will be put after us.
366 	 * tmp_alone_branch points to the begin of the branch
367 	 * where we will add parent.
368 	 */
369 	list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
370 	/*
371 	 * update tmp_alone_branch to points to the new begin
372 	 * of the branch
373 	 */
374 	rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
375 	return false;
376 }
377 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)378 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
379 {
380 	if (cfs_rq->on_list) {
381 		struct rq *rq = rq_of(cfs_rq);
382 
383 		/*
384 		 * With cfs_rq being unthrottled/throttled during an enqueue,
385 		 * it can happen the tmp_alone_branch points to the leaf that
386 		 * we finally want to delete. In this case, tmp_alone_branch moves
387 		 * to the prev element but it will point to rq->leaf_cfs_rq_list
388 		 * at the end of the enqueue.
389 		 */
390 		if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
391 			rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
392 
393 		list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
394 		cfs_rq->on_list = 0;
395 	}
396 }
397 
assert_list_leaf_cfs_rq(struct rq * rq)398 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
399 {
400 	WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
401 }
402 
403 /* Iterate through all leaf cfs_rq's on a runqueue */
404 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)			\
405 	list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,	\
406 				 leaf_cfs_rq_list)
407 
408 /* Do the two (enqueued) entities belong to the same group ? */
409 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)410 is_same_group(struct sched_entity *se, struct sched_entity *pse)
411 {
412 	if (se->cfs_rq == pse->cfs_rq)
413 		return se->cfs_rq;
414 
415 	return NULL;
416 }
417 
parent_entity(const struct sched_entity * se)418 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
419 {
420 	return se->parent;
421 }
422 
423 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)424 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
425 {
426 	int se_depth, pse_depth;
427 
428 	/*
429 	 * preemption test can be made between sibling entities who are in the
430 	 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
431 	 * both tasks until we find their ancestors who are siblings of common
432 	 * parent.
433 	 */
434 
435 	/* First walk up until both entities are at same depth */
436 	se_depth = (*se)->depth;
437 	pse_depth = (*pse)->depth;
438 
439 	while (se_depth > pse_depth) {
440 		se_depth--;
441 		*se = parent_entity(*se);
442 	}
443 
444 	while (pse_depth > se_depth) {
445 		pse_depth--;
446 		*pse = parent_entity(*pse);
447 	}
448 
449 	while (!is_same_group(*se, *pse)) {
450 		*se = parent_entity(*se);
451 		*pse = parent_entity(*pse);
452 	}
453 }
454 
tg_is_idle(struct task_group * tg)455 static int tg_is_idle(struct task_group *tg)
456 {
457 	return tg->idle > 0;
458 }
459 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)460 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
461 {
462 	return cfs_rq->idle > 0;
463 }
464 
se_is_idle(struct sched_entity * se)465 static int se_is_idle(struct sched_entity *se)
466 {
467 	if (entity_is_task(se))
468 		return task_has_idle_policy(task_of(se));
469 	return cfs_rq_is_idle(group_cfs_rq(se));
470 }
471 
472 #else /* !CONFIG_FAIR_GROUP_SCHED: */
473 
474 #define for_each_sched_entity(se) \
475 		for (; se; se = NULL)
476 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)477 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
478 {
479 	return true;
480 }
481 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)482 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
483 {
484 }
485 
assert_list_leaf_cfs_rq(struct rq * rq)486 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
487 {
488 }
489 
490 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
491 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
492 
parent_entity(struct sched_entity * se)493 static inline struct sched_entity *parent_entity(struct sched_entity *se)
494 {
495 	return NULL;
496 }
497 
498 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)499 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
500 {
501 }
502 
tg_is_idle(struct task_group * tg)503 static inline int tg_is_idle(struct task_group *tg)
504 {
505 	return 0;
506 }
507 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)508 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
509 {
510 	return 0;
511 }
512 
se_is_idle(struct sched_entity * se)513 static int se_is_idle(struct sched_entity *se)
514 {
515 	return task_has_idle_policy(task_of(se));
516 }
517 
518 #endif /* !CONFIG_FAIR_GROUP_SCHED */
519 
520 static __always_inline
521 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
522 
523 /**************************************************************
524  * Scheduling class tree data structure manipulation methods:
525  */
526 
max_vruntime(u64 max_vruntime,u64 vruntime)527 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
528 {
529 	s64 delta = (s64)(vruntime - max_vruntime);
530 	if (delta > 0)
531 		max_vruntime = vruntime;
532 
533 	return max_vruntime;
534 }
535 
min_vruntime(u64 min_vruntime,u64 vruntime)536 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
537 {
538 	s64 delta = (s64)(vruntime - min_vruntime);
539 	if (delta < 0)
540 		min_vruntime = vruntime;
541 
542 	return min_vruntime;
543 }
544 
entity_before(const struct sched_entity * a,const struct sched_entity * b)545 static inline bool entity_before(const struct sched_entity *a,
546 				 const struct sched_entity *b)
547 {
548 	/*
549 	 * Tiebreak on vruntime seems unnecessary since it can
550 	 * hardly happen.
551 	 */
552 	return (s64)(a->deadline - b->deadline) < 0;
553 }
554 
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)555 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
556 {
557 	return (s64)(se->vruntime - cfs_rq->zero_vruntime);
558 }
559 
560 #define __node_2_se(node) \
561 	rb_entry((node), struct sched_entity, run_node)
562 
563 /*
564  * Compute virtual time from the per-task service numbers:
565  *
566  * Fair schedulers conserve lag:
567  *
568  *   \Sum lag_i = 0
569  *
570  * Where lag_i is given by:
571  *
572  *   lag_i = S - s_i = w_i * (V - v_i)
573  *
574  * Where S is the ideal service time and V is it's virtual time counterpart.
575  * Therefore:
576  *
577  *   \Sum lag_i = 0
578  *   \Sum w_i * (V - v_i) = 0
579  *   \Sum w_i * V - w_i * v_i = 0
580  *
581  * From which we can solve an expression for V in v_i (which we have in
582  * se->vruntime):
583  *
584  *       \Sum v_i * w_i   \Sum v_i * w_i
585  *   V = -------------- = --------------
586  *          \Sum w_i            W
587  *
588  * Specifically, this is the weighted average of all entity virtual runtimes.
589  *
590  * [[ NOTE: this is only equal to the ideal scheduler under the condition
591  *          that join/leave operations happen at lag_i = 0, otherwise the
592  *          virtual time has non-contiguous motion equivalent to:
593  *
594  *	      V +-= lag_i / W
595  *
596  *	    Also see the comment in place_entity() that deals with this. ]]
597  *
598  * However, since v_i is u64, and the multiplication could easily overflow
599  * transform it into a relative form that uses smaller quantities:
600  *
601  * Substitute: v_i == (v_i - v0) + v0
602  *
603  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
604  * V = ---------------------------- = --------------------- + v0
605  *                  W                            W
606  *
607  * Which we track using:
608  *
609  *                    v0 := cfs_rq->zero_vruntime
610  * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
611  *              \Sum w_i := cfs_rq->avg_load
612  *
613  * Since zero_vruntime closely tracks the per-task service, these
614  * deltas: (v_i - v), will be in the order of the maximal (virtual) lag
615  * induced in the system due to quantisation.
616  *
617  * Also, we use scale_load_down() to reduce the size.
618  *
619  * As measured, the max (key * weight) value was ~44 bits for a kernel build.
620  */
621 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)622 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
623 {
624 	unsigned long weight = scale_load_down(se->load.weight);
625 	s64 key = entity_key(cfs_rq, se);
626 
627 	cfs_rq->avg_vruntime += key * weight;
628 	cfs_rq->avg_load += weight;
629 }
630 
631 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)632 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
633 {
634 	unsigned long weight = scale_load_down(se->load.weight);
635 	s64 key = entity_key(cfs_rq, se);
636 
637 	cfs_rq->avg_vruntime -= key * weight;
638 	cfs_rq->avg_load -= weight;
639 }
640 
641 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)642 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
643 {
644 	/*
645 	 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
646 	 */
647 	cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
648 }
649 
650 /*
651  * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
652  * For this to be so, the result of this function must have a left bias.
653  */
avg_vruntime(struct cfs_rq * cfs_rq)654 u64 avg_vruntime(struct cfs_rq *cfs_rq)
655 {
656 	struct sched_entity *curr = cfs_rq->curr;
657 	s64 avg = cfs_rq->avg_vruntime;
658 	long load = cfs_rq->avg_load;
659 
660 	if (curr && curr->on_rq) {
661 		unsigned long weight = scale_load_down(curr->load.weight);
662 
663 		avg += entity_key(cfs_rq, curr) * weight;
664 		load += weight;
665 	}
666 
667 	if (load) {
668 		/* sign flips effective floor / ceiling */
669 		if (avg < 0)
670 			avg -= (load - 1);
671 		avg = div_s64(avg, load);
672 	}
673 
674 	return cfs_rq->zero_vruntime + avg;
675 }
676 
677 /*
678  * lag_i = S - s_i = w_i * (V - v_i)
679  *
680  * However, since V is approximated by the weighted average of all entities it
681  * is possible -- by addition/removal/reweight to the tree -- to move V around
682  * and end up with a larger lag than we started with.
683  *
684  * Limit this to either double the slice length with a minimum of TICK_NSEC
685  * since that is the timing granularity.
686  *
687  * EEVDF gives the following limit for a steady state system:
688  *
689  *   -r_max < lag < max(r_max, q)
690  *
691  * XXX could add max_slice to the augmented data to track this.
692  */
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)693 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
694 {
695 	s64 vlag, limit;
696 
697 	WARN_ON_ONCE(!se->on_rq);
698 
699 	vlag = avg_vruntime(cfs_rq) - se->vruntime;
700 	limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
701 
702 	se->vlag = clamp(vlag, -limit, limit);
703 }
704 
705 /*
706  * Entity is eligible once it received less service than it ought to have,
707  * eg. lag >= 0.
708  *
709  * lag_i = S - s_i = w_i*(V - v_i)
710  *
711  * lag_i >= 0 -> V >= v_i
712  *
713  *     \Sum (v_i - v)*w_i
714  * V = ------------------ + v
715  *          \Sum w_i
716  *
717  * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
718  *
719  * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
720  *       to the loss in precision caused by the division.
721  */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)722 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
723 {
724 	struct sched_entity *curr = cfs_rq->curr;
725 	s64 avg = cfs_rq->avg_vruntime;
726 	long load = cfs_rq->avg_load;
727 
728 	if (curr && curr->on_rq) {
729 		unsigned long weight = scale_load_down(curr->load.weight);
730 
731 		avg += entity_key(cfs_rq, curr) * weight;
732 		load += weight;
733 	}
734 
735 	return avg >= (s64)(vruntime - cfs_rq->zero_vruntime) * load;
736 }
737 
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)738 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
739 {
740 	return vruntime_eligible(cfs_rq, se->vruntime);
741 }
742 
update_zero_vruntime(struct cfs_rq * cfs_rq)743 static void update_zero_vruntime(struct cfs_rq *cfs_rq)
744 {
745 	u64 vruntime = avg_vruntime(cfs_rq);
746 	s64 delta = (s64)(vruntime - cfs_rq->zero_vruntime);
747 
748 	avg_vruntime_update(cfs_rq, delta);
749 
750 	cfs_rq->zero_vruntime = vruntime;
751 }
752 
cfs_rq_min_slice(struct cfs_rq * cfs_rq)753 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
754 {
755 	struct sched_entity *root = __pick_root_entity(cfs_rq);
756 	struct sched_entity *curr = cfs_rq->curr;
757 	u64 min_slice = ~0ULL;
758 
759 	if (curr && curr->on_rq)
760 		min_slice = curr->slice;
761 
762 	if (root)
763 		min_slice = min(min_slice, root->min_slice);
764 
765 	return min_slice;
766 }
767 
__entity_less(struct rb_node * a,const struct rb_node * b)768 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
769 {
770 	return entity_before(__node_2_se(a), __node_2_se(b));
771 }
772 
773 #define vruntime_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
774 
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)775 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
776 {
777 	if (node) {
778 		struct sched_entity *rse = __node_2_se(node);
779 		if (vruntime_gt(min_vruntime, se, rse))
780 			se->min_vruntime = rse->min_vruntime;
781 	}
782 }
783 
__min_slice_update(struct sched_entity * se,struct rb_node * node)784 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
785 {
786 	if (node) {
787 		struct sched_entity *rse = __node_2_se(node);
788 		if (rse->min_slice < se->min_slice)
789 			se->min_slice = rse->min_slice;
790 	}
791 }
792 
793 /*
794  * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
795  */
min_vruntime_update(struct sched_entity * se,bool exit)796 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
797 {
798 	u64 old_min_vruntime = se->min_vruntime;
799 	u64 old_min_slice = se->min_slice;
800 	struct rb_node *node = &se->run_node;
801 
802 	se->min_vruntime = se->vruntime;
803 	__min_vruntime_update(se, node->rb_right);
804 	__min_vruntime_update(se, node->rb_left);
805 
806 	se->min_slice = se->slice;
807 	__min_slice_update(se, node->rb_right);
808 	__min_slice_update(se, node->rb_left);
809 
810 	return se->min_vruntime == old_min_vruntime &&
811 	       se->min_slice == old_min_slice;
812 }
813 
814 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
815 		     run_node, min_vruntime, min_vruntime_update);
816 
817 /*
818  * Enqueue an entity into the rb-tree:
819  */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)820 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
821 {
822 	avg_vruntime_add(cfs_rq, se);
823 	update_zero_vruntime(cfs_rq);
824 	se->min_vruntime = se->vruntime;
825 	se->min_slice = se->slice;
826 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
827 				__entity_less, &min_vruntime_cb);
828 }
829 
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)830 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
831 {
832 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
833 				  &min_vruntime_cb);
834 	avg_vruntime_sub(cfs_rq, se);
835 	update_zero_vruntime(cfs_rq);
836 }
837 
__pick_root_entity(struct cfs_rq * cfs_rq)838 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
839 {
840 	struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
841 
842 	if (!root)
843 		return NULL;
844 
845 	return __node_2_se(root);
846 }
847 
__pick_first_entity(struct cfs_rq * cfs_rq)848 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
849 {
850 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
851 
852 	if (!left)
853 		return NULL;
854 
855 	return __node_2_se(left);
856 }
857 
858 /*
859  * Set the vruntime up to which an entity can run before looking
860  * for another entity to pick.
861  * In case of run to parity, we use the shortest slice of the enqueued
862  * entities to set the protected period.
863  * When run to parity is disabled, we give a minimum quantum to the running
864  * entity to ensure progress.
865  */
set_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)866 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
867 {
868 	u64 slice = normalized_sysctl_sched_base_slice;
869 	u64 vprot = se->deadline;
870 
871 	if (sched_feat(RUN_TO_PARITY))
872 		slice = cfs_rq_min_slice(cfs_rq);
873 
874 	slice = min(slice, se->slice);
875 	if (slice != se->slice)
876 		vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
877 
878 	se->vprot = vprot;
879 }
880 
update_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)881 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
882 {
883 	u64 slice = cfs_rq_min_slice(cfs_rq);
884 
885 	se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se));
886 }
887 
protect_slice(struct sched_entity * se)888 static inline bool protect_slice(struct sched_entity *se)
889 {
890 	return ((s64)(se->vprot - se->vruntime) > 0);
891 }
892 
cancel_protect_slice(struct sched_entity * se)893 static inline void cancel_protect_slice(struct sched_entity *se)
894 {
895 	if (protect_slice(se))
896 		se->vprot = se->vruntime;
897 }
898 
899 /*
900  * Earliest Eligible Virtual Deadline First
901  *
902  * In order to provide latency guarantees for different request sizes
903  * EEVDF selects the best runnable task from two criteria:
904  *
905  *  1) the task must be eligible (must be owed service)
906  *
907  *  2) from those tasks that meet 1), we select the one
908  *     with the earliest virtual deadline.
909  *
910  * We can do this in O(log n) time due to an augmented RB-tree. The
911  * tree keeps the entries sorted on deadline, but also functions as a
912  * heap based on the vruntime by keeping:
913  *
914  *  se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
915  *
916  * Which allows tree pruning through eligibility.
917  */
__pick_eevdf(struct cfs_rq * cfs_rq,bool protect)918 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
919 {
920 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
921 	struct sched_entity *se = __pick_first_entity(cfs_rq);
922 	struct sched_entity *curr = cfs_rq->curr;
923 	struct sched_entity *best = NULL;
924 
925 	/*
926 	 * We can safely skip eligibility check if there is only one entity
927 	 * in this cfs_rq, saving some cycles.
928 	 */
929 	if (cfs_rq->nr_queued == 1)
930 		return curr && curr->on_rq ? curr : se;
931 
932 	/*
933 	 * Picking the ->next buddy will affect latency but not fairness.
934 	 */
935 	if (sched_feat(PICK_BUDDY) &&
936 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
937 		/* ->next will never be delayed */
938 		WARN_ON_ONCE(cfs_rq->next->sched_delayed);
939 		return cfs_rq->next;
940 	}
941 
942 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
943 		curr = NULL;
944 
945 	if (curr && protect && protect_slice(curr))
946 		return curr;
947 
948 	/* Pick the leftmost entity if it's eligible */
949 	if (se && entity_eligible(cfs_rq, se)) {
950 		best = se;
951 		goto found;
952 	}
953 
954 	/* Heap search for the EEVD entity */
955 	while (node) {
956 		struct rb_node *left = node->rb_left;
957 
958 		/*
959 		 * Eligible entities in left subtree are always better
960 		 * choices, since they have earlier deadlines.
961 		 */
962 		if (left && vruntime_eligible(cfs_rq,
963 					__node_2_se(left)->min_vruntime)) {
964 			node = left;
965 			continue;
966 		}
967 
968 		se = __node_2_se(node);
969 
970 		/*
971 		 * The left subtree either is empty or has no eligible
972 		 * entity, so check the current node since it is the one
973 		 * with earliest deadline that might be eligible.
974 		 */
975 		if (entity_eligible(cfs_rq, se)) {
976 			best = se;
977 			break;
978 		}
979 
980 		node = node->rb_right;
981 	}
982 found:
983 	if (!best || (curr && entity_before(curr, best)))
984 		best = curr;
985 
986 	return best;
987 }
988 
pick_eevdf(struct cfs_rq * cfs_rq)989 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
990 {
991 	return __pick_eevdf(cfs_rq, true);
992 }
993 
__pick_last_entity(struct cfs_rq * cfs_rq)994 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
995 {
996 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
997 
998 	if (!last)
999 		return NULL;
1000 
1001 	return __node_2_se(last);
1002 }
1003 
1004 /**************************************************************
1005  * Scheduling class statistics methods:
1006  */
sched_update_scaling(void)1007 int sched_update_scaling(void)
1008 {
1009 	unsigned int factor = get_update_sysctl_factor();
1010 
1011 #define WRT_SYSCTL(name) \
1012 	(normalized_sysctl_##name = sysctl_##name / (factor))
1013 	WRT_SYSCTL(sched_base_slice);
1014 #undef WRT_SYSCTL
1015 
1016 	return 0;
1017 }
1018 
1019 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1020 
1021 /*
1022  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1023  * this is probably good enough.
1024  */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1025 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1026 {
1027 	if ((s64)(se->vruntime - se->deadline) < 0)
1028 		return false;
1029 
1030 	/*
1031 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1032 	 * nice) while the request time r_i is determined by
1033 	 * sysctl_sched_base_slice.
1034 	 */
1035 	if (!se->custom_slice)
1036 		se->slice = sysctl_sched_base_slice;
1037 
1038 	/*
1039 	 * EEVDF: vd_i = ve_i + r_i / w_i
1040 	 */
1041 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1042 
1043 	/*
1044 	 * The task has consumed its request, reschedule.
1045 	 */
1046 	return true;
1047 }
1048 
1049 #include "pelt.h"
1050 
1051 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1052 static unsigned long task_h_load(struct task_struct *p);
1053 static unsigned long capacity_of(int cpu);
1054 
1055 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1056 void init_entity_runnable_average(struct sched_entity *se)
1057 {
1058 	struct sched_avg *sa = &se->avg;
1059 
1060 	memset(sa, 0, sizeof(*sa));
1061 
1062 	/*
1063 	 * Tasks are initialized with full load to be seen as heavy tasks until
1064 	 * they get a chance to stabilize to their real load level.
1065 	 * Group entities are initialized with zero load to reflect the fact that
1066 	 * nothing has been attached to the task group yet.
1067 	 */
1068 	if (entity_is_task(se))
1069 		sa->load_avg = scale_load_down(se->load.weight);
1070 
1071 	/* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1072 }
1073 
1074 /*
1075  * With new tasks being created, their initial util_avgs are extrapolated
1076  * based on the cfs_rq's current util_avg:
1077  *
1078  *   util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1079  *		* se_weight(se)
1080  *
1081  * However, in many cases, the above util_avg does not give a desired
1082  * value. Moreover, the sum of the util_avgs may be divergent, such
1083  * as when the series is a harmonic series.
1084  *
1085  * To solve this problem, we also cap the util_avg of successive tasks to
1086  * only 1/2 of the left utilization budget:
1087  *
1088  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1089  *
1090  * where n denotes the nth task and cpu_scale the CPU capacity.
1091  *
1092  * For example, for a CPU with 1024 of capacity, a simplest series from
1093  * the beginning would be like:
1094  *
1095  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1096  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1097  *
1098  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1099  * if util_avg > util_avg_cap.
1100  */
post_init_entity_util_avg(struct task_struct * p)1101 void post_init_entity_util_avg(struct task_struct *p)
1102 {
1103 	struct sched_entity *se = &p->se;
1104 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1105 	struct sched_avg *sa = &se->avg;
1106 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1107 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1108 
1109 	if (p->sched_class != &fair_sched_class) {
1110 		/*
1111 		 * For !fair tasks do:
1112 		 *
1113 		update_cfs_rq_load_avg(now, cfs_rq);
1114 		attach_entity_load_avg(cfs_rq, se);
1115 		switched_from_fair(rq, p);
1116 		 *
1117 		 * such that the next switched_to_fair() has the
1118 		 * expected state.
1119 		 */
1120 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1121 		return;
1122 	}
1123 
1124 	if (cap > 0) {
1125 		if (cfs_rq->avg.util_avg != 0) {
1126 			sa->util_avg  = cfs_rq->avg.util_avg * se_weight(se);
1127 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1128 
1129 			if (sa->util_avg > cap)
1130 				sa->util_avg = cap;
1131 		} else {
1132 			sa->util_avg = cap;
1133 		}
1134 	}
1135 
1136 	sa->runnable_avg = sa->util_avg;
1137 }
1138 
update_se(struct rq * rq,struct sched_entity * se)1139 static s64 update_se(struct rq *rq, struct sched_entity *se)
1140 {
1141 	u64 now = rq_clock_task(rq);
1142 	s64 delta_exec;
1143 
1144 	delta_exec = now - se->exec_start;
1145 	if (unlikely(delta_exec <= 0))
1146 		return delta_exec;
1147 
1148 	se->exec_start = now;
1149 	if (entity_is_task(se)) {
1150 		struct task_struct *donor = task_of(se);
1151 		struct task_struct *running = rq->curr;
1152 		/*
1153 		 * If se is a task, we account the time against the running
1154 		 * task, as w/ proxy-exec they may not be the same.
1155 		 */
1156 		running->se.exec_start = now;
1157 		running->se.sum_exec_runtime += delta_exec;
1158 
1159 		trace_sched_stat_runtime(running, delta_exec);
1160 		account_group_exec_runtime(running, delta_exec);
1161 
1162 		/* cgroup time is always accounted against the donor */
1163 		cgroup_account_cputime(donor, delta_exec);
1164 	} else {
1165 		/* If not task, account the time against donor se  */
1166 		se->sum_exec_runtime += delta_exec;
1167 	}
1168 
1169 	if (schedstat_enabled()) {
1170 		struct sched_statistics *stats;
1171 
1172 		stats = __schedstats_from_se(se);
1173 		__schedstat_set(stats->exec_max,
1174 				max(delta_exec, stats->exec_max));
1175 	}
1176 
1177 	return delta_exec;
1178 }
1179 
1180 static void set_next_buddy(struct sched_entity *se);
1181 
1182 /*
1183  * Used by other classes to account runtime.
1184  */
update_curr_common(struct rq * rq)1185 s64 update_curr_common(struct rq *rq)
1186 {
1187 	return update_se(rq, &rq->donor->se);
1188 }
1189 
1190 /*
1191  * Update the current task's runtime statistics.
1192  */
update_curr(struct cfs_rq * cfs_rq)1193 static void update_curr(struct cfs_rq *cfs_rq)
1194 {
1195 	/*
1196 	 * Note: cfs_rq->curr corresponds to the task picked to
1197 	 * run (ie: rq->donor.se) which due to proxy-exec may
1198 	 * not necessarily be the actual task running
1199 	 * (rq->curr.se). This is easy to confuse!
1200 	 */
1201 	struct sched_entity *curr = cfs_rq->curr;
1202 	struct rq *rq = rq_of(cfs_rq);
1203 	s64 delta_exec;
1204 	bool resched;
1205 
1206 	if (unlikely(!curr))
1207 		return;
1208 
1209 	delta_exec = update_se(rq, curr);
1210 	if (unlikely(delta_exec <= 0))
1211 		return;
1212 
1213 	curr->vruntime += calc_delta_fair(delta_exec, curr);
1214 	resched = update_deadline(cfs_rq, curr);
1215 
1216 	if (entity_is_task(curr)) {
1217 		/*
1218 		 * If the fair_server is active, we need to account for the
1219 		 * fair_server time whether or not the task is running on
1220 		 * behalf of fair_server or not:
1221 		 *  - If the task is running on behalf of fair_server, we need
1222 		 *    to limit its time based on the assigned runtime.
1223 		 *  - Fair task that runs outside of fair_server should account
1224 		 *    against fair_server such that it can account for this time
1225 		 *    and possibly avoid running this period.
1226 		 */
1227 		dl_server_update(&rq->fair_server, delta_exec);
1228 	}
1229 
1230 	account_cfs_rq_runtime(cfs_rq, delta_exec);
1231 
1232 	if (cfs_rq->nr_queued == 1)
1233 		return;
1234 
1235 	if (resched || !protect_slice(curr)) {
1236 		resched_curr_lazy(rq);
1237 		clear_buddies(cfs_rq, curr);
1238 	}
1239 }
1240 
update_curr_fair(struct rq * rq)1241 static void update_curr_fair(struct rq *rq)
1242 {
1243 	update_curr(cfs_rq_of(&rq->donor->se));
1244 }
1245 
1246 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1247 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1248 {
1249 	struct sched_statistics *stats;
1250 	struct task_struct *p = NULL;
1251 
1252 	if (!schedstat_enabled())
1253 		return;
1254 
1255 	stats = __schedstats_from_se(se);
1256 
1257 	if (entity_is_task(se))
1258 		p = task_of(se);
1259 
1260 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
1261 }
1262 
1263 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1264 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1265 {
1266 	struct sched_statistics *stats;
1267 	struct task_struct *p = NULL;
1268 
1269 	if (!schedstat_enabled())
1270 		return;
1271 
1272 	stats = __schedstats_from_se(se);
1273 
1274 	/*
1275 	 * When the sched_schedstat changes from 0 to 1, some sched se
1276 	 * maybe already in the runqueue, the se->statistics.wait_start
1277 	 * will be 0.So it will let the delta wrong. We need to avoid this
1278 	 * scenario.
1279 	 */
1280 	if (unlikely(!schedstat_val(stats->wait_start)))
1281 		return;
1282 
1283 	if (entity_is_task(se))
1284 		p = task_of(se);
1285 
1286 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
1287 }
1288 
1289 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1290 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1291 {
1292 	struct sched_statistics *stats;
1293 	struct task_struct *tsk = NULL;
1294 
1295 	if (!schedstat_enabled())
1296 		return;
1297 
1298 	stats = __schedstats_from_se(se);
1299 
1300 	if (entity_is_task(se))
1301 		tsk = task_of(se);
1302 
1303 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1304 }
1305 
1306 /*
1307  * Task is being enqueued - update stats:
1308  */
1309 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1310 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1311 {
1312 	if (!schedstat_enabled())
1313 		return;
1314 
1315 	/*
1316 	 * Are we enqueueing a waiting task? (for current tasks
1317 	 * a dequeue/enqueue event is a NOP)
1318 	 */
1319 	if (se != cfs_rq->curr)
1320 		update_stats_wait_start_fair(cfs_rq, se);
1321 
1322 	if (flags & ENQUEUE_WAKEUP)
1323 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
1324 }
1325 
1326 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1327 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1328 {
1329 
1330 	if (!schedstat_enabled())
1331 		return;
1332 
1333 	/*
1334 	 * Mark the end of the wait period if dequeueing a
1335 	 * waiting task:
1336 	 */
1337 	if (se != cfs_rq->curr)
1338 		update_stats_wait_end_fair(cfs_rq, se);
1339 
1340 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1341 		struct task_struct *tsk = task_of(se);
1342 		unsigned int state;
1343 
1344 		/* XXX racy against TTWU */
1345 		state = READ_ONCE(tsk->__state);
1346 		if (state & TASK_INTERRUPTIBLE)
1347 			__schedstat_set(tsk->stats.sleep_start,
1348 				      rq_clock(rq_of(cfs_rq)));
1349 		if (state & TASK_UNINTERRUPTIBLE)
1350 			__schedstat_set(tsk->stats.block_start,
1351 				      rq_clock(rq_of(cfs_rq)));
1352 	}
1353 }
1354 
1355 /*
1356  * We are picking a new current task - update its stats:
1357  */
1358 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1359 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1360 {
1361 	/*
1362 	 * We are starting a new run period:
1363 	 */
1364 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
1365 }
1366 
1367 /**************************************************
1368  * Scheduling class queueing methods:
1369  */
1370 
is_core_idle(int cpu)1371 static inline bool is_core_idle(int cpu)
1372 {
1373 #ifdef CONFIG_SCHED_SMT
1374 	int sibling;
1375 
1376 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1377 		if (cpu == sibling)
1378 			continue;
1379 
1380 		if (!idle_cpu(sibling))
1381 			return false;
1382 	}
1383 #endif
1384 
1385 	return true;
1386 }
1387 
1388 #ifdef CONFIG_NUMA
1389 #define NUMA_IMBALANCE_MIN 2
1390 
1391 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1392 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1393 {
1394 	/*
1395 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1396 	 * threshold. Above this threshold, individual tasks may be contending
1397 	 * for both memory bandwidth and any shared HT resources.  This is an
1398 	 * approximation as the number of running tasks may not be related to
1399 	 * the number of busy CPUs due to sched_setaffinity.
1400 	 */
1401 	if (dst_running > imb_numa_nr)
1402 		return imbalance;
1403 
1404 	/*
1405 	 * Allow a small imbalance based on a simple pair of communicating
1406 	 * tasks that remain local when the destination is lightly loaded.
1407 	 */
1408 	if (imbalance <= NUMA_IMBALANCE_MIN)
1409 		return 0;
1410 
1411 	return imbalance;
1412 }
1413 #endif /* CONFIG_NUMA */
1414 
1415 #ifdef CONFIG_NUMA_BALANCING
1416 /*
1417  * Approximate time to scan a full NUMA task in ms. The task scan period is
1418  * calculated based on the tasks virtual memory size and
1419  * numa_balancing_scan_size.
1420  */
1421 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1422 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1423 
1424 /* Portion of address space to scan in MB */
1425 unsigned int sysctl_numa_balancing_scan_size = 256;
1426 
1427 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1428 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1429 
1430 /* The page with hint page fault latency < threshold in ms is considered hot */
1431 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1432 
1433 struct numa_group {
1434 	refcount_t refcount;
1435 
1436 	spinlock_t lock; /* nr_tasks, tasks */
1437 	int nr_tasks;
1438 	pid_t gid;
1439 	int active_nodes;
1440 
1441 	struct rcu_head rcu;
1442 	unsigned long total_faults;
1443 	unsigned long max_faults_cpu;
1444 	/*
1445 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
1446 	 *
1447 	 * Faults_cpu is used to decide whether memory should move
1448 	 * towards the CPU. As a consequence, these stats are weighted
1449 	 * more by CPU use than by memory faults.
1450 	 */
1451 	unsigned long faults[];
1452 };
1453 
1454 /*
1455  * For functions that can be called in multiple contexts that permit reading
1456  * ->numa_group (see struct task_struct for locking rules).
1457  */
deref_task_numa_group(struct task_struct * p)1458 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1459 {
1460 	return rcu_dereference_check(p->numa_group, p == current ||
1461 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1462 }
1463 
deref_curr_numa_group(struct task_struct * p)1464 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1465 {
1466 	return rcu_dereference_protected(p->numa_group, p == current);
1467 }
1468 
1469 static inline unsigned long group_faults_priv(struct numa_group *ng);
1470 static inline unsigned long group_faults_shared(struct numa_group *ng);
1471 
task_nr_scan_windows(struct task_struct * p)1472 static unsigned int task_nr_scan_windows(struct task_struct *p)
1473 {
1474 	unsigned long rss = 0;
1475 	unsigned long nr_scan_pages;
1476 
1477 	/*
1478 	 * Calculations based on RSS as non-present and empty pages are skipped
1479 	 * by the PTE scanner and NUMA hinting faults should be trapped based
1480 	 * on resident pages
1481 	 */
1482 	nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
1483 	rss = get_mm_rss(p->mm);
1484 	if (!rss)
1485 		rss = nr_scan_pages;
1486 
1487 	rss = round_up(rss, nr_scan_pages);
1488 	return rss / nr_scan_pages;
1489 }
1490 
1491 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1492 #define MAX_SCAN_WINDOW 2560
1493 
task_scan_min(struct task_struct * p)1494 static unsigned int task_scan_min(struct task_struct *p)
1495 {
1496 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1497 	unsigned int scan, floor;
1498 	unsigned int windows = 1;
1499 
1500 	if (scan_size < MAX_SCAN_WINDOW)
1501 		windows = MAX_SCAN_WINDOW / scan_size;
1502 	floor = 1000 / windows;
1503 
1504 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1505 	return max_t(unsigned int, floor, scan);
1506 }
1507 
task_scan_start(struct task_struct * p)1508 static unsigned int task_scan_start(struct task_struct *p)
1509 {
1510 	unsigned long smin = task_scan_min(p);
1511 	unsigned long period = smin;
1512 	struct numa_group *ng;
1513 
1514 	/* Scale the maximum scan period with the amount of shared memory. */
1515 	rcu_read_lock();
1516 	ng = rcu_dereference(p->numa_group);
1517 	if (ng) {
1518 		unsigned long shared = group_faults_shared(ng);
1519 		unsigned long private = group_faults_priv(ng);
1520 
1521 		period *= refcount_read(&ng->refcount);
1522 		period *= shared + 1;
1523 		period /= private + shared + 1;
1524 	}
1525 	rcu_read_unlock();
1526 
1527 	return max(smin, period);
1528 }
1529 
task_scan_max(struct task_struct * p)1530 static unsigned int task_scan_max(struct task_struct *p)
1531 {
1532 	unsigned long smin = task_scan_min(p);
1533 	unsigned long smax;
1534 	struct numa_group *ng;
1535 
1536 	/* Watch for min being lower than max due to floor calculations */
1537 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1538 
1539 	/* Scale the maximum scan period with the amount of shared memory. */
1540 	ng = deref_curr_numa_group(p);
1541 	if (ng) {
1542 		unsigned long shared = group_faults_shared(ng);
1543 		unsigned long private = group_faults_priv(ng);
1544 		unsigned long period = smax;
1545 
1546 		period *= refcount_read(&ng->refcount);
1547 		period *= shared + 1;
1548 		period /= private + shared + 1;
1549 
1550 		smax = max(smax, period);
1551 	}
1552 
1553 	return max(smin, smax);
1554 }
1555 
account_numa_enqueue(struct rq * rq,struct task_struct * p)1556 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1557 {
1558 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1559 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1560 }
1561 
account_numa_dequeue(struct rq * rq,struct task_struct * p)1562 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1563 {
1564 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1565 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1566 }
1567 
1568 /* Shared or private faults. */
1569 #define NR_NUMA_HINT_FAULT_TYPES 2
1570 
1571 /* Memory and CPU locality */
1572 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1573 
1574 /* Averaged statistics, and temporary buffers. */
1575 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1576 
task_numa_group_id(struct task_struct * p)1577 pid_t task_numa_group_id(struct task_struct *p)
1578 {
1579 	struct numa_group *ng;
1580 	pid_t gid = 0;
1581 
1582 	rcu_read_lock();
1583 	ng = rcu_dereference(p->numa_group);
1584 	if (ng)
1585 		gid = ng->gid;
1586 	rcu_read_unlock();
1587 
1588 	return gid;
1589 }
1590 
1591 /*
1592  * The averaged statistics, shared & private, memory & CPU,
1593  * occupy the first half of the array. The second half of the
1594  * array is for current counters, which are averaged into the
1595  * first set by task_numa_placement.
1596  */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1597 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1598 {
1599 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1600 }
1601 
task_faults(struct task_struct * p,int nid)1602 static inline unsigned long task_faults(struct task_struct *p, int nid)
1603 {
1604 	if (!p->numa_faults)
1605 		return 0;
1606 
1607 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1608 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1609 }
1610 
group_faults(struct task_struct * p,int nid)1611 static inline unsigned long group_faults(struct task_struct *p, int nid)
1612 {
1613 	struct numa_group *ng = deref_task_numa_group(p);
1614 
1615 	if (!ng)
1616 		return 0;
1617 
1618 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1619 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1620 }
1621 
group_faults_cpu(struct numa_group * group,int nid)1622 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1623 {
1624 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1625 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1626 }
1627 
group_faults_priv(struct numa_group * ng)1628 static inline unsigned long group_faults_priv(struct numa_group *ng)
1629 {
1630 	unsigned long faults = 0;
1631 	int node;
1632 
1633 	for_each_online_node(node) {
1634 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1635 	}
1636 
1637 	return faults;
1638 }
1639 
group_faults_shared(struct numa_group * ng)1640 static inline unsigned long group_faults_shared(struct numa_group *ng)
1641 {
1642 	unsigned long faults = 0;
1643 	int node;
1644 
1645 	for_each_online_node(node) {
1646 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1647 	}
1648 
1649 	return faults;
1650 }
1651 
1652 /*
1653  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1654  * considered part of a numa group's pseudo-interleaving set. Migrations
1655  * between these nodes are slowed down, to allow things to settle down.
1656  */
1657 #define ACTIVE_NODE_FRACTION 3
1658 
numa_is_active_node(int nid,struct numa_group * ng)1659 static bool numa_is_active_node(int nid, struct numa_group *ng)
1660 {
1661 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1662 }
1663 
1664 /* Handle placement on systems where not all nodes are directly connected. */
score_nearby_nodes(struct task_struct * p,int nid,int lim_dist,bool task)1665 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1666 					int lim_dist, bool task)
1667 {
1668 	unsigned long score = 0;
1669 	int node, max_dist;
1670 
1671 	/*
1672 	 * All nodes are directly connected, and the same distance
1673 	 * from each other. No need for fancy placement algorithms.
1674 	 */
1675 	if (sched_numa_topology_type == NUMA_DIRECT)
1676 		return 0;
1677 
1678 	/* sched_max_numa_distance may be changed in parallel. */
1679 	max_dist = READ_ONCE(sched_max_numa_distance);
1680 	/*
1681 	 * This code is called for each node, introducing N^2 complexity,
1682 	 * which should be OK given the number of nodes rarely exceeds 8.
1683 	 */
1684 	for_each_online_node(node) {
1685 		unsigned long faults;
1686 		int dist = node_distance(nid, node);
1687 
1688 		/*
1689 		 * The furthest away nodes in the system are not interesting
1690 		 * for placement; nid was already counted.
1691 		 */
1692 		if (dist >= max_dist || node == nid)
1693 			continue;
1694 
1695 		/*
1696 		 * On systems with a backplane NUMA topology, compare groups
1697 		 * of nodes, and move tasks towards the group with the most
1698 		 * memory accesses. When comparing two nodes at distance
1699 		 * "hoplimit", only nodes closer by than "hoplimit" are part
1700 		 * of each group. Skip other nodes.
1701 		 */
1702 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1703 			continue;
1704 
1705 		/* Add up the faults from nearby nodes. */
1706 		if (task)
1707 			faults = task_faults(p, node);
1708 		else
1709 			faults = group_faults(p, node);
1710 
1711 		/*
1712 		 * On systems with a glueless mesh NUMA topology, there are
1713 		 * no fixed "groups of nodes". Instead, nodes that are not
1714 		 * directly connected bounce traffic through intermediate
1715 		 * nodes; a numa_group can occupy any set of nodes.
1716 		 * The further away a node is, the less the faults count.
1717 		 * This seems to result in good task placement.
1718 		 */
1719 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1720 			faults *= (max_dist - dist);
1721 			faults /= (max_dist - LOCAL_DISTANCE);
1722 		}
1723 
1724 		score += faults;
1725 	}
1726 
1727 	return score;
1728 }
1729 
1730 /*
1731  * These return the fraction of accesses done by a particular task, or
1732  * task group, on a particular numa node.  The group weight is given a
1733  * larger multiplier, in order to group tasks together that are almost
1734  * evenly spread out between numa nodes.
1735  */
task_weight(struct task_struct * p,int nid,int dist)1736 static inline unsigned long task_weight(struct task_struct *p, int nid,
1737 					int dist)
1738 {
1739 	unsigned long faults, total_faults;
1740 
1741 	if (!p->numa_faults)
1742 		return 0;
1743 
1744 	total_faults = p->total_numa_faults;
1745 
1746 	if (!total_faults)
1747 		return 0;
1748 
1749 	faults = task_faults(p, nid);
1750 	faults += score_nearby_nodes(p, nid, dist, true);
1751 
1752 	return 1000 * faults / total_faults;
1753 }
1754 
group_weight(struct task_struct * p,int nid,int dist)1755 static inline unsigned long group_weight(struct task_struct *p, int nid,
1756 					 int dist)
1757 {
1758 	struct numa_group *ng = deref_task_numa_group(p);
1759 	unsigned long faults, total_faults;
1760 
1761 	if (!ng)
1762 		return 0;
1763 
1764 	total_faults = ng->total_faults;
1765 
1766 	if (!total_faults)
1767 		return 0;
1768 
1769 	faults = group_faults(p, nid);
1770 	faults += score_nearby_nodes(p, nid, dist, false);
1771 
1772 	return 1000 * faults / total_faults;
1773 }
1774 
1775 /*
1776  * If memory tiering mode is enabled, cpupid of slow memory page is
1777  * used to record scan time instead of CPU and PID.  When tiering mode
1778  * is disabled at run time, the scan time (in cpupid) will be
1779  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
1780  * access out of array bound.
1781  */
cpupid_valid(int cpupid)1782 static inline bool cpupid_valid(int cpupid)
1783 {
1784 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1785 }
1786 
1787 /*
1788  * For memory tiering mode, if there are enough free pages (more than
1789  * enough watermark defined here) in fast memory node, to take full
1790  * advantage of fast memory capacity, all recently accessed slow
1791  * memory pages will be migrated to fast memory node without
1792  * considering hot threshold.
1793  */
pgdat_free_space_enough(struct pglist_data * pgdat)1794 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1795 {
1796 	int z;
1797 	unsigned long enough_wmark;
1798 
1799 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1800 			   pgdat->node_present_pages >> 4);
1801 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1802 		struct zone *zone = pgdat->node_zones + z;
1803 
1804 		if (!populated_zone(zone))
1805 			continue;
1806 
1807 		if (zone_watermark_ok(zone, 0,
1808 				      promo_wmark_pages(zone) + enough_wmark,
1809 				      ZONE_MOVABLE, 0))
1810 			return true;
1811 	}
1812 	return false;
1813 }
1814 
1815 /*
1816  * For memory tiering mode, when page tables are scanned, the scan
1817  * time will be recorded in struct page in addition to make page
1818  * PROT_NONE for slow memory page.  So when the page is accessed, in
1819  * hint page fault handler, the hint page fault latency is calculated
1820  * via,
1821  *
1822  *	hint page fault latency = hint page fault time - scan time
1823  *
1824  * The smaller the hint page fault latency, the higher the possibility
1825  * for the page to be hot.
1826  */
numa_hint_fault_latency(struct folio * folio)1827 static int numa_hint_fault_latency(struct folio *folio)
1828 {
1829 	int last_time, time;
1830 
1831 	time = jiffies_to_msecs(jiffies);
1832 	last_time = folio_xchg_access_time(folio, time);
1833 
1834 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1835 }
1836 
1837 /*
1838  * For memory tiering mode, too high promotion/demotion throughput may
1839  * hurt application latency.  So we provide a mechanism to rate limit
1840  * the number of pages that are tried to be promoted.
1841  */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1842 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1843 				      unsigned long rate_limit, int nr)
1844 {
1845 	unsigned long nr_cand;
1846 	unsigned int now, start;
1847 
1848 	now = jiffies_to_msecs(jiffies);
1849 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1850 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1851 	start = pgdat->nbp_rl_start;
1852 	if (now - start > MSEC_PER_SEC &&
1853 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1854 		pgdat->nbp_rl_nr_cand = nr_cand;
1855 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1856 		return true;
1857 	return false;
1858 }
1859 
1860 #define NUMA_MIGRATION_ADJUST_STEPS	16
1861 
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1862 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1863 					    unsigned long rate_limit,
1864 					    unsigned int ref_th)
1865 {
1866 	unsigned int now, start, th_period, unit_th, th;
1867 	unsigned long nr_cand, ref_cand, diff_cand;
1868 
1869 	now = jiffies_to_msecs(jiffies);
1870 	th_period = sysctl_numa_balancing_scan_period_max;
1871 	start = pgdat->nbp_th_start;
1872 	if (now - start > th_period &&
1873 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1874 		ref_cand = rate_limit *
1875 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1876 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1877 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1878 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1879 		th = pgdat->nbp_threshold ? : ref_th;
1880 		if (diff_cand > ref_cand * 11 / 10)
1881 			th = max(th - unit_th, unit_th);
1882 		else if (diff_cand < ref_cand * 9 / 10)
1883 			th = min(th + unit_th, ref_th * 2);
1884 		pgdat->nbp_th_nr_cand = nr_cand;
1885 		pgdat->nbp_threshold = th;
1886 	}
1887 }
1888 
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)1889 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1890 				int src_nid, int dst_cpu)
1891 {
1892 	struct numa_group *ng = deref_curr_numa_group(p);
1893 	int dst_nid = cpu_to_node(dst_cpu);
1894 	int last_cpupid, this_cpupid;
1895 
1896 	/*
1897 	 * Cannot migrate to memoryless nodes.
1898 	 */
1899 	if (!node_state(dst_nid, N_MEMORY))
1900 		return false;
1901 
1902 	/*
1903 	 * The pages in slow memory node should be migrated according
1904 	 * to hot/cold instead of private/shared.
1905 	 */
1906 	if (folio_use_access_time(folio)) {
1907 		struct pglist_data *pgdat;
1908 		unsigned long rate_limit;
1909 		unsigned int latency, th, def_th;
1910 		long nr = folio_nr_pages(folio);
1911 
1912 		pgdat = NODE_DATA(dst_nid);
1913 		if (pgdat_free_space_enough(pgdat)) {
1914 			/* workload changed, reset hot threshold */
1915 			pgdat->nbp_threshold = 0;
1916 			mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
1917 			return true;
1918 		}
1919 
1920 		def_th = sysctl_numa_balancing_hot_threshold;
1921 		rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
1922 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1923 
1924 		th = pgdat->nbp_threshold ? : def_th;
1925 		latency = numa_hint_fault_latency(folio);
1926 		if (latency >= th)
1927 			return false;
1928 
1929 		return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
1930 	}
1931 
1932 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1933 	last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
1934 
1935 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1936 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1937 		return false;
1938 
1939 	/*
1940 	 * Allow first faults or private faults to migrate immediately early in
1941 	 * the lifetime of a task. The magic number 4 is based on waiting for
1942 	 * two full passes of the "multi-stage node selection" test that is
1943 	 * executed below.
1944 	 */
1945 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1946 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1947 		return true;
1948 
1949 	/*
1950 	 * Multi-stage node selection is used in conjunction with a periodic
1951 	 * migration fault to build a temporal task<->page relation. By using
1952 	 * a two-stage filter we remove short/unlikely relations.
1953 	 *
1954 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1955 	 * a task's usage of a particular page (n_p) per total usage of this
1956 	 * page (n_t) (in a given time-span) to a probability.
1957 	 *
1958 	 * Our periodic faults will sample this probability and getting the
1959 	 * same result twice in a row, given these samples are fully
1960 	 * independent, is then given by P(n)^2, provided our sample period
1961 	 * is sufficiently short compared to the usage pattern.
1962 	 *
1963 	 * This quadric squishes small probabilities, making it less likely we
1964 	 * act on an unlikely task<->page relation.
1965 	 */
1966 	if (!cpupid_pid_unset(last_cpupid) &&
1967 				cpupid_to_nid(last_cpupid) != dst_nid)
1968 		return false;
1969 
1970 	/* Always allow migrate on private faults */
1971 	if (cpupid_match_pid(p, last_cpupid))
1972 		return true;
1973 
1974 	/* A shared fault, but p->numa_group has not been set up yet. */
1975 	if (!ng)
1976 		return true;
1977 
1978 	/*
1979 	 * Destination node is much more heavily used than the source
1980 	 * node? Allow migration.
1981 	 */
1982 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1983 					ACTIVE_NODE_FRACTION)
1984 		return true;
1985 
1986 	/*
1987 	 * Distribute memory according to CPU & memory use on each node,
1988 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1989 	 *
1990 	 * faults_cpu(dst)   3   faults_cpu(src)
1991 	 * --------------- * - > ---------------
1992 	 * faults_mem(dst)   4   faults_mem(src)
1993 	 */
1994 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1995 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1996 }
1997 
1998 /*
1999  * 'numa_type' describes the node at the moment of load balancing.
2000  */
2001 enum numa_type {
2002 	/* The node has spare capacity that can be used to run more tasks.  */
2003 	node_has_spare = 0,
2004 	/*
2005 	 * The node is fully used and the tasks don't compete for more CPU
2006 	 * cycles. Nevertheless, some tasks might wait before running.
2007 	 */
2008 	node_fully_busy,
2009 	/*
2010 	 * The node is overloaded and can't provide expected CPU cycles to all
2011 	 * tasks.
2012 	 */
2013 	node_overloaded
2014 };
2015 
2016 /* Cached statistics for all CPUs within a node */
2017 struct numa_stats {
2018 	unsigned long load;
2019 	unsigned long runnable;
2020 	unsigned long util;
2021 	/* Total compute capacity of CPUs on a node */
2022 	unsigned long compute_capacity;
2023 	unsigned int nr_running;
2024 	unsigned int weight;
2025 	enum numa_type node_type;
2026 	int idle_cpu;
2027 };
2028 
2029 struct task_numa_env {
2030 	struct task_struct *p;
2031 
2032 	int src_cpu, src_nid;
2033 	int dst_cpu, dst_nid;
2034 	int imb_numa_nr;
2035 
2036 	struct numa_stats src_stats, dst_stats;
2037 
2038 	int imbalance_pct;
2039 	int dist;
2040 
2041 	struct task_struct *best_task;
2042 	long best_imp;
2043 	int best_cpu;
2044 };
2045 
2046 static unsigned long cpu_load(struct rq *rq);
2047 static unsigned long cpu_runnable(struct rq *rq);
2048 
2049 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2050 numa_type numa_classify(unsigned int imbalance_pct,
2051 			 struct numa_stats *ns)
2052 {
2053 	if ((ns->nr_running > ns->weight) &&
2054 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2055 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2056 		return node_overloaded;
2057 
2058 	if ((ns->nr_running < ns->weight) ||
2059 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2060 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2061 		return node_has_spare;
2062 
2063 	return node_fully_busy;
2064 }
2065 
2066 #ifdef CONFIG_SCHED_SMT
2067 /* Forward declarations of select_idle_sibling helpers */
2068 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2069 static inline int numa_idle_core(int idle_core, int cpu)
2070 {
2071 	if (!static_branch_likely(&sched_smt_present) ||
2072 	    idle_core >= 0 || !test_idle_cores(cpu))
2073 		return idle_core;
2074 
2075 	/*
2076 	 * Prefer cores instead of packing HT siblings
2077 	 * and triggering future load balancing.
2078 	 */
2079 	if (is_core_idle(cpu))
2080 		idle_core = cpu;
2081 
2082 	return idle_core;
2083 }
2084 #else /* !CONFIG_SCHED_SMT: */
numa_idle_core(int idle_core,int cpu)2085 static inline int numa_idle_core(int idle_core, int cpu)
2086 {
2087 	return idle_core;
2088 }
2089 #endif /* !CONFIG_SCHED_SMT */
2090 
2091 /*
2092  * Gather all necessary information to make NUMA balancing placement
2093  * decisions that are compatible with standard load balancer. This
2094  * borrows code and logic from update_sg_lb_stats but sharing a
2095  * common implementation is impractical.
2096  */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2097 static void update_numa_stats(struct task_numa_env *env,
2098 			      struct numa_stats *ns, int nid,
2099 			      bool find_idle)
2100 {
2101 	int cpu, idle_core = -1;
2102 
2103 	memset(ns, 0, sizeof(*ns));
2104 	ns->idle_cpu = -1;
2105 
2106 	rcu_read_lock();
2107 	for_each_cpu(cpu, cpumask_of_node(nid)) {
2108 		struct rq *rq = cpu_rq(cpu);
2109 
2110 		ns->load += cpu_load(rq);
2111 		ns->runnable += cpu_runnable(rq);
2112 		ns->util += cpu_util_cfs(cpu);
2113 		ns->nr_running += rq->cfs.h_nr_runnable;
2114 		ns->compute_capacity += capacity_of(cpu);
2115 
2116 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2117 			if (READ_ONCE(rq->numa_migrate_on) ||
2118 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2119 				continue;
2120 
2121 			if (ns->idle_cpu == -1)
2122 				ns->idle_cpu = cpu;
2123 
2124 			idle_core = numa_idle_core(idle_core, cpu);
2125 		}
2126 	}
2127 	rcu_read_unlock();
2128 
2129 	ns->weight = cpumask_weight(cpumask_of_node(nid));
2130 
2131 	ns->node_type = numa_classify(env->imbalance_pct, ns);
2132 
2133 	if (idle_core >= 0)
2134 		ns->idle_cpu = idle_core;
2135 }
2136 
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2137 static void task_numa_assign(struct task_numa_env *env,
2138 			     struct task_struct *p, long imp)
2139 {
2140 	struct rq *rq = cpu_rq(env->dst_cpu);
2141 
2142 	/* Check if run-queue part of active NUMA balance. */
2143 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2144 		int cpu;
2145 		int start = env->dst_cpu;
2146 
2147 		/* Find alternative idle CPU. */
2148 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2149 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2150 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2151 				continue;
2152 			}
2153 
2154 			env->dst_cpu = cpu;
2155 			rq = cpu_rq(env->dst_cpu);
2156 			if (!xchg(&rq->numa_migrate_on, 1))
2157 				goto assign;
2158 		}
2159 
2160 		/* Failed to find an alternative idle CPU */
2161 		return;
2162 	}
2163 
2164 assign:
2165 	/*
2166 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
2167 	 * found a better CPU to move/swap.
2168 	 */
2169 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2170 		rq = cpu_rq(env->best_cpu);
2171 		WRITE_ONCE(rq->numa_migrate_on, 0);
2172 	}
2173 
2174 	if (env->best_task)
2175 		put_task_struct(env->best_task);
2176 	if (p)
2177 		get_task_struct(p);
2178 
2179 	env->best_task = p;
2180 	env->best_imp = imp;
2181 	env->best_cpu = env->dst_cpu;
2182 }
2183 
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2184 static bool load_too_imbalanced(long src_load, long dst_load,
2185 				struct task_numa_env *env)
2186 {
2187 	long imb, old_imb;
2188 	long orig_src_load, orig_dst_load;
2189 	long src_capacity, dst_capacity;
2190 
2191 	/*
2192 	 * The load is corrected for the CPU capacity available on each node.
2193 	 *
2194 	 * src_load        dst_load
2195 	 * ------------ vs ---------
2196 	 * src_capacity    dst_capacity
2197 	 */
2198 	src_capacity = env->src_stats.compute_capacity;
2199 	dst_capacity = env->dst_stats.compute_capacity;
2200 
2201 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2202 
2203 	orig_src_load = env->src_stats.load;
2204 	orig_dst_load = env->dst_stats.load;
2205 
2206 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2207 
2208 	/* Would this change make things worse? */
2209 	return (imb > old_imb);
2210 }
2211 
2212 /*
2213  * Maximum NUMA importance can be 1998 (2*999);
2214  * SMALLIMP @ 30 would be close to 1998/64.
2215  * Used to deter task migration.
2216  */
2217 #define SMALLIMP	30
2218 
2219 /*
2220  * This checks if the overall compute and NUMA accesses of the system would
2221  * be improved if the source tasks was migrated to the target dst_cpu taking
2222  * into account that it might be best if task running on the dst_cpu should
2223  * be exchanged with the source task
2224  */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2225 static bool task_numa_compare(struct task_numa_env *env,
2226 			      long taskimp, long groupimp, bool maymove)
2227 {
2228 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2229 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
2230 	long imp = p_ng ? groupimp : taskimp;
2231 	struct task_struct *cur;
2232 	long src_load, dst_load;
2233 	int dist = env->dist;
2234 	long moveimp = imp;
2235 	long load;
2236 	bool stopsearch = false;
2237 
2238 	if (READ_ONCE(dst_rq->numa_migrate_on))
2239 		return false;
2240 
2241 	rcu_read_lock();
2242 	cur = rcu_dereference(dst_rq->curr);
2243 	if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
2244 		    !cur->mm))
2245 		cur = NULL;
2246 
2247 	/*
2248 	 * Because we have preemption enabled we can get migrated around and
2249 	 * end try selecting ourselves (current == env->p) as a swap candidate.
2250 	 */
2251 	if (cur == env->p) {
2252 		stopsearch = true;
2253 		goto unlock;
2254 	}
2255 
2256 	if (!cur) {
2257 		if (maymove && moveimp >= env->best_imp)
2258 			goto assign;
2259 		else
2260 			goto unlock;
2261 	}
2262 
2263 	/* Skip this swap candidate if cannot move to the source cpu. */
2264 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2265 		goto unlock;
2266 
2267 	/*
2268 	 * Skip this swap candidate if it is not moving to its preferred
2269 	 * node and the best task is.
2270 	 */
2271 	if (env->best_task &&
2272 	    env->best_task->numa_preferred_nid == env->src_nid &&
2273 	    cur->numa_preferred_nid != env->src_nid) {
2274 		goto unlock;
2275 	}
2276 
2277 	/*
2278 	 * "imp" is the fault differential for the source task between the
2279 	 * source and destination node. Calculate the total differential for
2280 	 * the source task and potential destination task. The more negative
2281 	 * the value is, the more remote accesses that would be expected to
2282 	 * be incurred if the tasks were swapped.
2283 	 *
2284 	 * If dst and source tasks are in the same NUMA group, or not
2285 	 * in any group then look only at task weights.
2286 	 */
2287 	cur_ng = rcu_dereference(cur->numa_group);
2288 	if (cur_ng == p_ng) {
2289 		/*
2290 		 * Do not swap within a group or between tasks that have
2291 		 * no group if there is spare capacity. Swapping does
2292 		 * not address the load imbalance and helps one task at
2293 		 * the cost of punishing another.
2294 		 */
2295 		if (env->dst_stats.node_type == node_has_spare)
2296 			goto unlock;
2297 
2298 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
2299 		      task_weight(cur, env->dst_nid, dist);
2300 		/*
2301 		 * Add some hysteresis to prevent swapping the
2302 		 * tasks within a group over tiny differences.
2303 		 */
2304 		if (cur_ng)
2305 			imp -= imp / 16;
2306 	} else {
2307 		/*
2308 		 * Compare the group weights. If a task is all by itself
2309 		 * (not part of a group), use the task weight instead.
2310 		 */
2311 		if (cur_ng && p_ng)
2312 			imp += group_weight(cur, env->src_nid, dist) -
2313 			       group_weight(cur, env->dst_nid, dist);
2314 		else
2315 			imp += task_weight(cur, env->src_nid, dist) -
2316 			       task_weight(cur, env->dst_nid, dist);
2317 	}
2318 
2319 	/* Discourage picking a task already on its preferred node */
2320 	if (cur->numa_preferred_nid == env->dst_nid)
2321 		imp -= imp / 16;
2322 
2323 	/*
2324 	 * Encourage picking a task that moves to its preferred node.
2325 	 * This potentially makes imp larger than it's maximum of
2326 	 * 1998 (see SMALLIMP and task_weight for why) but in this
2327 	 * case, it does not matter.
2328 	 */
2329 	if (cur->numa_preferred_nid == env->src_nid)
2330 		imp += imp / 8;
2331 
2332 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
2333 		imp = moveimp;
2334 		cur = NULL;
2335 		goto assign;
2336 	}
2337 
2338 	/*
2339 	 * Prefer swapping with a task moving to its preferred node over a
2340 	 * task that is not.
2341 	 */
2342 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2343 	    env->best_task->numa_preferred_nid != env->src_nid) {
2344 		goto assign;
2345 	}
2346 
2347 	/*
2348 	 * If the NUMA importance is less than SMALLIMP,
2349 	 * task migration might only result in ping pong
2350 	 * of tasks and also hurt performance due to cache
2351 	 * misses.
2352 	 */
2353 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2354 		goto unlock;
2355 
2356 	/*
2357 	 * In the overloaded case, try and keep the load balanced.
2358 	 */
2359 	load = task_h_load(env->p) - task_h_load(cur);
2360 	if (!load)
2361 		goto assign;
2362 
2363 	dst_load = env->dst_stats.load + load;
2364 	src_load = env->src_stats.load - load;
2365 
2366 	if (load_too_imbalanced(src_load, dst_load, env))
2367 		goto unlock;
2368 
2369 assign:
2370 	/* Evaluate an idle CPU for a task numa move. */
2371 	if (!cur) {
2372 		int cpu = env->dst_stats.idle_cpu;
2373 
2374 		/* Nothing cached so current CPU went idle since the search. */
2375 		if (cpu < 0)
2376 			cpu = env->dst_cpu;
2377 
2378 		/*
2379 		 * If the CPU is no longer truly idle and the previous best CPU
2380 		 * is, keep using it.
2381 		 */
2382 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2383 		    idle_cpu(env->best_cpu)) {
2384 			cpu = env->best_cpu;
2385 		}
2386 
2387 		env->dst_cpu = cpu;
2388 	}
2389 
2390 	task_numa_assign(env, cur, imp);
2391 
2392 	/*
2393 	 * If a move to idle is allowed because there is capacity or load
2394 	 * balance improves then stop the search. While a better swap
2395 	 * candidate may exist, a search is not free.
2396 	 */
2397 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2398 		stopsearch = true;
2399 
2400 	/*
2401 	 * If a swap candidate must be identified and the current best task
2402 	 * moves its preferred node then stop the search.
2403 	 */
2404 	if (!maymove && env->best_task &&
2405 	    env->best_task->numa_preferred_nid == env->src_nid) {
2406 		stopsearch = true;
2407 	}
2408 unlock:
2409 	rcu_read_unlock();
2410 
2411 	return stopsearch;
2412 }
2413 
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2414 static void task_numa_find_cpu(struct task_numa_env *env,
2415 				long taskimp, long groupimp)
2416 {
2417 	bool maymove = false;
2418 	int cpu;
2419 
2420 	/*
2421 	 * If dst node has spare capacity, then check if there is an
2422 	 * imbalance that would be overruled by the load balancer.
2423 	 */
2424 	if (env->dst_stats.node_type == node_has_spare) {
2425 		unsigned int imbalance;
2426 		int src_running, dst_running;
2427 
2428 		/*
2429 		 * Would movement cause an imbalance? Note that if src has
2430 		 * more running tasks that the imbalance is ignored as the
2431 		 * move improves the imbalance from the perspective of the
2432 		 * CPU load balancer.
2433 		 * */
2434 		src_running = env->src_stats.nr_running - 1;
2435 		dst_running = env->dst_stats.nr_running + 1;
2436 		imbalance = max(0, dst_running - src_running);
2437 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
2438 						  env->imb_numa_nr);
2439 
2440 		/* Use idle CPU if there is no imbalance */
2441 		if (!imbalance) {
2442 			maymove = true;
2443 			if (env->dst_stats.idle_cpu >= 0) {
2444 				env->dst_cpu = env->dst_stats.idle_cpu;
2445 				task_numa_assign(env, NULL, 0);
2446 				return;
2447 			}
2448 		}
2449 	} else {
2450 		long src_load, dst_load, load;
2451 		/*
2452 		 * If the improvement from just moving env->p direction is better
2453 		 * than swapping tasks around, check if a move is possible.
2454 		 */
2455 		load = task_h_load(env->p);
2456 		dst_load = env->dst_stats.load + load;
2457 		src_load = env->src_stats.load - load;
2458 		maymove = !load_too_imbalanced(src_load, dst_load, env);
2459 	}
2460 
2461 	for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2462 		/* Skip this CPU if the source task cannot migrate */
2463 		if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2464 			continue;
2465 
2466 		env->dst_cpu = cpu;
2467 		if (task_numa_compare(env, taskimp, groupimp, maymove))
2468 			break;
2469 	}
2470 }
2471 
task_numa_migrate(struct task_struct * p)2472 static int task_numa_migrate(struct task_struct *p)
2473 {
2474 	struct task_numa_env env = {
2475 		.p = p,
2476 
2477 		.src_cpu = task_cpu(p),
2478 		.src_nid = task_node(p),
2479 
2480 		.imbalance_pct = 112,
2481 
2482 		.best_task = NULL,
2483 		.best_imp = 0,
2484 		.best_cpu = -1,
2485 	};
2486 	unsigned long taskweight, groupweight;
2487 	struct sched_domain *sd;
2488 	long taskimp, groupimp;
2489 	struct numa_group *ng;
2490 	struct rq *best_rq;
2491 	int nid, ret, dist;
2492 
2493 	/*
2494 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
2495 	 * imbalance and would be the first to start moving tasks about.
2496 	 *
2497 	 * And we want to avoid any moving of tasks about, as that would create
2498 	 * random movement of tasks -- counter the numa conditions we're trying
2499 	 * to satisfy here.
2500 	 */
2501 	rcu_read_lock();
2502 	sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2503 	if (sd) {
2504 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2505 		env.imb_numa_nr = sd->imb_numa_nr;
2506 	}
2507 	rcu_read_unlock();
2508 
2509 	/*
2510 	 * Cpusets can break the scheduler domain tree into smaller
2511 	 * balance domains, some of which do not cross NUMA boundaries.
2512 	 * Tasks that are "trapped" in such domains cannot be migrated
2513 	 * elsewhere, so there is no point in (re)trying.
2514 	 */
2515 	if (unlikely(!sd)) {
2516 		sched_setnuma(p, task_node(p));
2517 		return -EINVAL;
2518 	}
2519 
2520 	env.dst_nid = p->numa_preferred_nid;
2521 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2522 	taskweight = task_weight(p, env.src_nid, dist);
2523 	groupweight = group_weight(p, env.src_nid, dist);
2524 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2525 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2526 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2527 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2528 
2529 	/* Try to find a spot on the preferred nid. */
2530 	task_numa_find_cpu(&env, taskimp, groupimp);
2531 
2532 	/*
2533 	 * Look at other nodes in these cases:
2534 	 * - there is no space available on the preferred_nid
2535 	 * - the task is part of a numa_group that is interleaved across
2536 	 *   multiple NUMA nodes; in order to better consolidate the group,
2537 	 *   we need to check other locations.
2538 	 */
2539 	ng = deref_curr_numa_group(p);
2540 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2541 		for_each_node_state(nid, N_CPU) {
2542 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
2543 				continue;
2544 
2545 			dist = node_distance(env.src_nid, env.dst_nid);
2546 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
2547 						dist != env.dist) {
2548 				taskweight = task_weight(p, env.src_nid, dist);
2549 				groupweight = group_weight(p, env.src_nid, dist);
2550 			}
2551 
2552 			/* Only consider nodes where both task and groups benefit */
2553 			taskimp = task_weight(p, nid, dist) - taskweight;
2554 			groupimp = group_weight(p, nid, dist) - groupweight;
2555 			if (taskimp < 0 && groupimp < 0)
2556 				continue;
2557 
2558 			env.dist = dist;
2559 			env.dst_nid = nid;
2560 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2561 			task_numa_find_cpu(&env, taskimp, groupimp);
2562 		}
2563 	}
2564 
2565 	/*
2566 	 * If the task is part of a workload that spans multiple NUMA nodes,
2567 	 * and is migrating into one of the workload's active nodes, remember
2568 	 * this node as the task's preferred numa node, so the workload can
2569 	 * settle down.
2570 	 * A task that migrated to a second choice node will be better off
2571 	 * trying for a better one later. Do not set the preferred node here.
2572 	 */
2573 	if (ng) {
2574 		if (env.best_cpu == -1)
2575 			nid = env.src_nid;
2576 		else
2577 			nid = cpu_to_node(env.best_cpu);
2578 
2579 		if (nid != p->numa_preferred_nid)
2580 			sched_setnuma(p, nid);
2581 	}
2582 
2583 	/* No better CPU than the current one was found. */
2584 	if (env.best_cpu == -1) {
2585 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2586 		return -EAGAIN;
2587 	}
2588 
2589 	best_rq = cpu_rq(env.best_cpu);
2590 	if (env.best_task == NULL) {
2591 		ret = migrate_task_to(p, env.best_cpu);
2592 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
2593 		if (ret != 0)
2594 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2595 		return ret;
2596 	}
2597 
2598 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2599 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
2600 
2601 	if (ret != 0)
2602 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2603 	put_task_struct(env.best_task);
2604 	return ret;
2605 }
2606 
2607 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2608 static void numa_migrate_preferred(struct task_struct *p)
2609 {
2610 	unsigned long interval = HZ;
2611 
2612 	/* This task has no NUMA fault statistics yet */
2613 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2614 		return;
2615 
2616 	/* Periodically retry migrating the task to the preferred node */
2617 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2618 	p->numa_migrate_retry = jiffies + interval;
2619 
2620 	/* Success if task is already running on preferred CPU */
2621 	if (task_node(p) == p->numa_preferred_nid)
2622 		return;
2623 
2624 	/* Otherwise, try migrate to a CPU on the preferred node */
2625 	task_numa_migrate(p);
2626 }
2627 
2628 /*
2629  * Find out how many nodes the workload is actively running on. Do this by
2630  * tracking the nodes from which NUMA hinting faults are triggered. This can
2631  * be different from the set of nodes where the workload's memory is currently
2632  * located.
2633  */
numa_group_count_active_nodes(struct numa_group * numa_group)2634 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2635 {
2636 	unsigned long faults, max_faults = 0;
2637 	int nid, active_nodes = 0;
2638 
2639 	for_each_node_state(nid, N_CPU) {
2640 		faults = group_faults_cpu(numa_group, nid);
2641 		if (faults > max_faults)
2642 			max_faults = faults;
2643 	}
2644 
2645 	for_each_node_state(nid, N_CPU) {
2646 		faults = group_faults_cpu(numa_group, nid);
2647 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
2648 			active_nodes++;
2649 	}
2650 
2651 	numa_group->max_faults_cpu = max_faults;
2652 	numa_group->active_nodes = active_nodes;
2653 }
2654 
2655 /*
2656  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2657  * increments. The more local the fault statistics are, the higher the scan
2658  * period will be for the next scan window. If local/(local+remote) ratio is
2659  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2660  * the scan period will decrease. Aim for 70% local accesses.
2661  */
2662 #define NUMA_PERIOD_SLOTS 10
2663 #define NUMA_PERIOD_THRESHOLD 7
2664 
2665 /*
2666  * Increase the scan period (slow down scanning) if the majority of
2667  * our memory is already on our local node, or if the majority of
2668  * the page accesses are shared with other processes.
2669  * Otherwise, decrease the scan period.
2670  */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2671 static void update_task_scan_period(struct task_struct *p,
2672 			unsigned long shared, unsigned long private)
2673 {
2674 	unsigned int period_slot;
2675 	int lr_ratio, ps_ratio;
2676 	int diff;
2677 
2678 	unsigned long remote = p->numa_faults_locality[0];
2679 	unsigned long local = p->numa_faults_locality[1];
2680 
2681 	/*
2682 	 * If there were no record hinting faults then either the task is
2683 	 * completely idle or all activity is in areas that are not of interest
2684 	 * to automatic numa balancing. Related to that, if there were failed
2685 	 * migration then it implies we are migrating too quickly or the local
2686 	 * node is overloaded. In either case, scan slower
2687 	 */
2688 	if (local + shared == 0 || p->numa_faults_locality[2]) {
2689 		p->numa_scan_period = min(p->numa_scan_period_max,
2690 			p->numa_scan_period << 1);
2691 
2692 		p->mm->numa_next_scan = jiffies +
2693 			msecs_to_jiffies(p->numa_scan_period);
2694 
2695 		return;
2696 	}
2697 
2698 	/*
2699 	 * Prepare to scale scan period relative to the current period.
2700 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
2701 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2702 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2703 	 */
2704 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2705 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2706 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2707 
2708 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2709 		/*
2710 		 * Most memory accesses are local. There is no need to
2711 		 * do fast NUMA scanning, since memory is already local.
2712 		 */
2713 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2714 		if (!slot)
2715 			slot = 1;
2716 		diff = slot * period_slot;
2717 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2718 		/*
2719 		 * Most memory accesses are shared with other tasks.
2720 		 * There is no point in continuing fast NUMA scanning,
2721 		 * since other tasks may just move the memory elsewhere.
2722 		 */
2723 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2724 		if (!slot)
2725 			slot = 1;
2726 		diff = slot * period_slot;
2727 	} else {
2728 		/*
2729 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2730 		 * yet they are not on the local NUMA node. Speed up
2731 		 * NUMA scanning to get the memory moved over.
2732 		 */
2733 		int ratio = max(lr_ratio, ps_ratio);
2734 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2735 	}
2736 
2737 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
2738 			task_scan_min(p), task_scan_max(p));
2739 	memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2740 }
2741 
2742 /*
2743  * Get the fraction of time the task has been running since the last
2744  * NUMA placement cycle. The scheduler keeps similar statistics, but
2745  * decays those on a 32ms period, which is orders of magnitude off
2746  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2747  * stats only if the task is so new there are no NUMA statistics yet.
2748  */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2749 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2750 {
2751 	u64 runtime, delta, now;
2752 	/* Use the start of this time slice to avoid calculations. */
2753 	now = p->se.exec_start;
2754 	runtime = p->se.sum_exec_runtime;
2755 
2756 	if (p->last_task_numa_placement) {
2757 		delta = runtime - p->last_sum_exec_runtime;
2758 		*period = now - p->last_task_numa_placement;
2759 
2760 		/* Avoid time going backwards, prevent potential divide error: */
2761 		if (unlikely((s64)*period < 0))
2762 			*period = 0;
2763 	} else {
2764 		delta = p->se.avg.load_sum;
2765 		*period = LOAD_AVG_MAX;
2766 	}
2767 
2768 	p->last_sum_exec_runtime = runtime;
2769 	p->last_task_numa_placement = now;
2770 
2771 	return delta;
2772 }
2773 
2774 /*
2775  * Determine the preferred nid for a task in a numa_group. This needs to
2776  * be done in a way that produces consistent results with group_weight,
2777  * otherwise workloads might not converge.
2778  */
preferred_group_nid(struct task_struct * p,int nid)2779 static int preferred_group_nid(struct task_struct *p, int nid)
2780 {
2781 	nodemask_t nodes;
2782 	int dist;
2783 
2784 	/* Direct connections between all NUMA nodes. */
2785 	if (sched_numa_topology_type == NUMA_DIRECT)
2786 		return nid;
2787 
2788 	/*
2789 	 * On a system with glueless mesh NUMA topology, group_weight
2790 	 * scores nodes according to the number of NUMA hinting faults on
2791 	 * both the node itself, and on nearby nodes.
2792 	 */
2793 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2794 		unsigned long score, max_score = 0;
2795 		int node, max_node = nid;
2796 
2797 		dist = sched_max_numa_distance;
2798 
2799 		for_each_node_state(node, N_CPU) {
2800 			score = group_weight(p, node, dist);
2801 			if (score > max_score) {
2802 				max_score = score;
2803 				max_node = node;
2804 			}
2805 		}
2806 		return max_node;
2807 	}
2808 
2809 	/*
2810 	 * Finding the preferred nid in a system with NUMA backplane
2811 	 * interconnect topology is more involved. The goal is to locate
2812 	 * tasks from numa_groups near each other in the system, and
2813 	 * untangle workloads from different sides of the system. This requires
2814 	 * searching down the hierarchy of node groups, recursively searching
2815 	 * inside the highest scoring group of nodes. The nodemask tricks
2816 	 * keep the complexity of the search down.
2817 	 */
2818 	nodes = node_states[N_CPU];
2819 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2820 		unsigned long max_faults = 0;
2821 		nodemask_t max_group = NODE_MASK_NONE;
2822 		int a, b;
2823 
2824 		/* Are there nodes at this distance from each other? */
2825 		if (!find_numa_distance(dist))
2826 			continue;
2827 
2828 		for_each_node_mask(a, nodes) {
2829 			unsigned long faults = 0;
2830 			nodemask_t this_group;
2831 			nodes_clear(this_group);
2832 
2833 			/* Sum group's NUMA faults; includes a==b case. */
2834 			for_each_node_mask(b, nodes) {
2835 				if (node_distance(a, b) < dist) {
2836 					faults += group_faults(p, b);
2837 					node_set(b, this_group);
2838 					node_clear(b, nodes);
2839 				}
2840 			}
2841 
2842 			/* Remember the top group. */
2843 			if (faults > max_faults) {
2844 				max_faults = faults;
2845 				max_group = this_group;
2846 				/*
2847 				 * subtle: at the smallest distance there is
2848 				 * just one node left in each "group", the
2849 				 * winner is the preferred nid.
2850 				 */
2851 				nid = a;
2852 			}
2853 		}
2854 		/* Next round, evaluate the nodes within max_group. */
2855 		if (!max_faults)
2856 			break;
2857 		nodes = max_group;
2858 	}
2859 	return nid;
2860 }
2861 
task_numa_placement(struct task_struct * p)2862 static void task_numa_placement(struct task_struct *p)
2863 {
2864 	int seq, nid, max_nid = NUMA_NO_NODE;
2865 	unsigned long max_faults = 0;
2866 	unsigned long fault_types[2] = { 0, 0 };
2867 	unsigned long total_faults;
2868 	u64 runtime, period;
2869 	spinlock_t *group_lock = NULL;
2870 	struct numa_group *ng;
2871 
2872 	/*
2873 	 * The p->mm->numa_scan_seq field gets updated without
2874 	 * exclusive access. Use READ_ONCE() here to ensure
2875 	 * that the field is read in a single access:
2876 	 */
2877 	seq = READ_ONCE(p->mm->numa_scan_seq);
2878 	if (p->numa_scan_seq == seq)
2879 		return;
2880 	p->numa_scan_seq = seq;
2881 	p->numa_scan_period_max = task_scan_max(p);
2882 
2883 	total_faults = p->numa_faults_locality[0] +
2884 		       p->numa_faults_locality[1];
2885 	runtime = numa_get_avg_runtime(p, &period);
2886 
2887 	/* If the task is part of a group prevent parallel updates to group stats */
2888 	ng = deref_curr_numa_group(p);
2889 	if (ng) {
2890 		group_lock = &ng->lock;
2891 		spin_lock_irq(group_lock);
2892 	}
2893 
2894 	/* Find the node with the highest number of faults */
2895 	for_each_online_node(nid) {
2896 		/* Keep track of the offsets in numa_faults array */
2897 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2898 		unsigned long faults = 0, group_faults = 0;
2899 		int priv;
2900 
2901 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2902 			long diff, f_diff, f_weight;
2903 
2904 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2905 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2906 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2907 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2908 
2909 			/* Decay existing window, copy faults since last scan */
2910 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2911 			fault_types[priv] += p->numa_faults[membuf_idx];
2912 			p->numa_faults[membuf_idx] = 0;
2913 
2914 			/*
2915 			 * Normalize the faults_from, so all tasks in a group
2916 			 * count according to CPU use, instead of by the raw
2917 			 * number of faults. Tasks with little runtime have
2918 			 * little over-all impact on throughput, and thus their
2919 			 * faults are less important.
2920 			 */
2921 			f_weight = div64_u64(runtime << 16, period + 1);
2922 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2923 				   (total_faults + 1);
2924 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2925 			p->numa_faults[cpubuf_idx] = 0;
2926 
2927 			p->numa_faults[mem_idx] += diff;
2928 			p->numa_faults[cpu_idx] += f_diff;
2929 			faults += p->numa_faults[mem_idx];
2930 			p->total_numa_faults += diff;
2931 			if (ng) {
2932 				/*
2933 				 * safe because we can only change our own group
2934 				 *
2935 				 * mem_idx represents the offset for a given
2936 				 * nid and priv in a specific region because it
2937 				 * is at the beginning of the numa_faults array.
2938 				 */
2939 				ng->faults[mem_idx] += diff;
2940 				ng->faults[cpu_idx] += f_diff;
2941 				ng->total_faults += diff;
2942 				group_faults += ng->faults[mem_idx];
2943 			}
2944 		}
2945 
2946 		if (!ng) {
2947 			if (faults > max_faults) {
2948 				max_faults = faults;
2949 				max_nid = nid;
2950 			}
2951 		} else if (group_faults > max_faults) {
2952 			max_faults = group_faults;
2953 			max_nid = nid;
2954 		}
2955 	}
2956 
2957 	/* Cannot migrate task to CPU-less node */
2958 	max_nid = numa_nearest_node(max_nid, N_CPU);
2959 
2960 	if (ng) {
2961 		numa_group_count_active_nodes(ng);
2962 		spin_unlock_irq(group_lock);
2963 		max_nid = preferred_group_nid(p, max_nid);
2964 	}
2965 
2966 	if (max_faults) {
2967 		/* Set the new preferred node */
2968 		if (max_nid != p->numa_preferred_nid)
2969 			sched_setnuma(p, max_nid);
2970 	}
2971 
2972 	update_task_scan_period(p, fault_types[0], fault_types[1]);
2973 }
2974 
get_numa_group(struct numa_group * grp)2975 static inline int get_numa_group(struct numa_group *grp)
2976 {
2977 	return refcount_inc_not_zero(&grp->refcount);
2978 }
2979 
put_numa_group(struct numa_group * grp)2980 static inline void put_numa_group(struct numa_group *grp)
2981 {
2982 	if (refcount_dec_and_test(&grp->refcount))
2983 		kfree_rcu(grp, rcu);
2984 }
2985 
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)2986 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2987 			int *priv)
2988 {
2989 	struct numa_group *grp, *my_grp;
2990 	struct task_struct *tsk;
2991 	bool join = false;
2992 	int cpu = cpupid_to_cpu(cpupid);
2993 	int i;
2994 
2995 	if (unlikely(!deref_curr_numa_group(p))) {
2996 		unsigned int size = sizeof(struct numa_group) +
2997 				    NR_NUMA_HINT_FAULT_STATS *
2998 				    nr_node_ids * sizeof(unsigned long);
2999 
3000 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3001 		if (!grp)
3002 			return;
3003 
3004 		refcount_set(&grp->refcount, 1);
3005 		grp->active_nodes = 1;
3006 		grp->max_faults_cpu = 0;
3007 		spin_lock_init(&grp->lock);
3008 		grp->gid = p->pid;
3009 
3010 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3011 			grp->faults[i] = p->numa_faults[i];
3012 
3013 		grp->total_faults = p->total_numa_faults;
3014 
3015 		grp->nr_tasks++;
3016 		rcu_assign_pointer(p->numa_group, grp);
3017 	}
3018 
3019 	rcu_read_lock();
3020 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
3021 
3022 	if (!cpupid_match_pid(tsk, cpupid))
3023 		goto no_join;
3024 
3025 	grp = rcu_dereference(tsk->numa_group);
3026 	if (!grp)
3027 		goto no_join;
3028 
3029 	my_grp = deref_curr_numa_group(p);
3030 	if (grp == my_grp)
3031 		goto no_join;
3032 
3033 	/*
3034 	 * Only join the other group if its bigger; if we're the bigger group,
3035 	 * the other task will join us.
3036 	 */
3037 	if (my_grp->nr_tasks > grp->nr_tasks)
3038 		goto no_join;
3039 
3040 	/*
3041 	 * Tie-break on the grp address.
3042 	 */
3043 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3044 		goto no_join;
3045 
3046 	/* Always join threads in the same process. */
3047 	if (tsk->mm == current->mm)
3048 		join = true;
3049 
3050 	/* Simple filter to avoid false positives due to PID collisions */
3051 	if (flags & TNF_SHARED)
3052 		join = true;
3053 
3054 	/* Update priv based on whether false sharing was detected */
3055 	*priv = !join;
3056 
3057 	if (join && !get_numa_group(grp))
3058 		goto no_join;
3059 
3060 	rcu_read_unlock();
3061 
3062 	if (!join)
3063 		return;
3064 
3065 	WARN_ON_ONCE(irqs_disabled());
3066 	double_lock_irq(&my_grp->lock, &grp->lock);
3067 
3068 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3069 		my_grp->faults[i] -= p->numa_faults[i];
3070 		grp->faults[i] += p->numa_faults[i];
3071 	}
3072 	my_grp->total_faults -= p->total_numa_faults;
3073 	grp->total_faults += p->total_numa_faults;
3074 
3075 	my_grp->nr_tasks--;
3076 	grp->nr_tasks++;
3077 
3078 	spin_unlock(&my_grp->lock);
3079 	spin_unlock_irq(&grp->lock);
3080 
3081 	rcu_assign_pointer(p->numa_group, grp);
3082 
3083 	put_numa_group(my_grp);
3084 	return;
3085 
3086 no_join:
3087 	rcu_read_unlock();
3088 	return;
3089 }
3090 
3091 /*
3092  * Get rid of NUMA statistics associated with a task (either current or dead).
3093  * If @final is set, the task is dead and has reached refcount zero, so we can
3094  * safely free all relevant data structures. Otherwise, there might be
3095  * concurrent reads from places like load balancing and procfs, and we should
3096  * reset the data back to default state without freeing ->numa_faults.
3097  */
task_numa_free(struct task_struct * p,bool final)3098 void task_numa_free(struct task_struct *p, bool final)
3099 {
3100 	/* safe: p either is current or is being freed by current */
3101 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3102 	unsigned long *numa_faults = p->numa_faults;
3103 	unsigned long flags;
3104 	int i;
3105 
3106 	if (!numa_faults)
3107 		return;
3108 
3109 	if (grp) {
3110 		spin_lock_irqsave(&grp->lock, flags);
3111 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3112 			grp->faults[i] -= p->numa_faults[i];
3113 		grp->total_faults -= p->total_numa_faults;
3114 
3115 		grp->nr_tasks--;
3116 		spin_unlock_irqrestore(&grp->lock, flags);
3117 		RCU_INIT_POINTER(p->numa_group, NULL);
3118 		put_numa_group(grp);
3119 	}
3120 
3121 	if (final) {
3122 		p->numa_faults = NULL;
3123 		kfree(numa_faults);
3124 	} else {
3125 		p->total_numa_faults = 0;
3126 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3127 			numa_faults[i] = 0;
3128 	}
3129 }
3130 
3131 /*
3132  * Got a PROT_NONE fault for a page on @node.
3133  */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3134 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3135 {
3136 	struct task_struct *p = current;
3137 	bool migrated = flags & TNF_MIGRATED;
3138 	int cpu_node = task_node(current);
3139 	int local = !!(flags & TNF_FAULT_LOCAL);
3140 	struct numa_group *ng;
3141 	int priv;
3142 
3143 	if (!static_branch_likely(&sched_numa_balancing))
3144 		return;
3145 
3146 	/* for example, ksmd faulting in a user's mm */
3147 	if (!p->mm)
3148 		return;
3149 
3150 	/*
3151 	 * NUMA faults statistics are unnecessary for the slow memory
3152 	 * node for memory tiering mode.
3153 	 */
3154 	if (!node_is_toptier(mem_node) &&
3155 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3156 	     !cpupid_valid(last_cpupid)))
3157 		return;
3158 
3159 	/* Allocate buffer to track faults on a per-node basis */
3160 	if (unlikely(!p->numa_faults)) {
3161 		int size = sizeof(*p->numa_faults) *
3162 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3163 
3164 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3165 		if (!p->numa_faults)
3166 			return;
3167 
3168 		p->total_numa_faults = 0;
3169 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3170 	}
3171 
3172 	/*
3173 	 * First accesses are treated as private, otherwise consider accesses
3174 	 * to be private if the accessing pid has not changed
3175 	 */
3176 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3177 		priv = 1;
3178 	} else {
3179 		priv = cpupid_match_pid(p, last_cpupid);
3180 		if (!priv && !(flags & TNF_NO_GROUP))
3181 			task_numa_group(p, last_cpupid, flags, &priv);
3182 	}
3183 
3184 	/*
3185 	 * If a workload spans multiple NUMA nodes, a shared fault that
3186 	 * occurs wholly within the set of nodes that the workload is
3187 	 * actively using should be counted as local. This allows the
3188 	 * scan rate to slow down when a workload has settled down.
3189 	 */
3190 	ng = deref_curr_numa_group(p);
3191 	if (!priv && !local && ng && ng->active_nodes > 1 &&
3192 				numa_is_active_node(cpu_node, ng) &&
3193 				numa_is_active_node(mem_node, ng))
3194 		local = 1;
3195 
3196 	/*
3197 	 * Retry to migrate task to preferred node periodically, in case it
3198 	 * previously failed, or the scheduler moved us.
3199 	 */
3200 	if (time_after(jiffies, p->numa_migrate_retry)) {
3201 		task_numa_placement(p);
3202 		numa_migrate_preferred(p);
3203 	}
3204 
3205 	if (migrated)
3206 		p->numa_pages_migrated += pages;
3207 	if (flags & TNF_MIGRATE_FAIL)
3208 		p->numa_faults_locality[2] += pages;
3209 
3210 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3211 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3212 	p->numa_faults_locality[local] += pages;
3213 }
3214 
reset_ptenuma_scan(struct task_struct * p)3215 static void reset_ptenuma_scan(struct task_struct *p)
3216 {
3217 	/*
3218 	 * We only did a read acquisition of the mmap sem, so
3219 	 * p->mm->numa_scan_seq is written to without exclusive access
3220 	 * and the update is not guaranteed to be atomic. That's not
3221 	 * much of an issue though, since this is just used for
3222 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3223 	 * expensive, to avoid any form of compiler optimizations:
3224 	 */
3225 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3226 	p->mm->numa_scan_offset = 0;
3227 }
3228 
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3229 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3230 {
3231 	unsigned long pids;
3232 	/*
3233 	 * Allow unconditional access first two times, so that all the (pages)
3234 	 * of VMAs get prot_none fault introduced irrespective of accesses.
3235 	 * This is also done to avoid any side effect of task scanning
3236 	 * amplifying the unfairness of disjoint set of VMAs' access.
3237 	 */
3238 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3239 		return true;
3240 
3241 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3242 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3243 		return true;
3244 
3245 	/*
3246 	 * Complete a scan that has already started regardless of PID access, or
3247 	 * some VMAs may never be scanned in multi-threaded applications:
3248 	 */
3249 	if (mm->numa_scan_offset > vma->vm_start) {
3250 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3251 		return true;
3252 	}
3253 
3254 	/*
3255 	 * This vma has not been accessed for a while, and if the number
3256 	 * the threads in the same process is low, which means no other
3257 	 * threads can help scan this vma, force a vma scan.
3258 	 */
3259 	if (READ_ONCE(mm->numa_scan_seq) >
3260 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3261 		return true;
3262 
3263 	return false;
3264 }
3265 
3266 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3267 
3268 /*
3269  * The expensive part of numa migration is done from task_work context.
3270  * Triggered from task_tick_numa().
3271  */
task_numa_work(struct callback_head * work)3272 static void task_numa_work(struct callback_head *work)
3273 {
3274 	unsigned long migrate, next_scan, now = jiffies;
3275 	struct task_struct *p = current;
3276 	struct mm_struct *mm = p->mm;
3277 	u64 runtime = p->se.sum_exec_runtime;
3278 	struct vm_area_struct *vma;
3279 	unsigned long start, end;
3280 	unsigned long nr_pte_updates = 0;
3281 	long pages, virtpages;
3282 	struct vma_iterator vmi;
3283 	bool vma_pids_skipped;
3284 	bool vma_pids_forced = false;
3285 
3286 	WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
3287 
3288 	work->next = work;
3289 	/*
3290 	 * Who cares about NUMA placement when they're dying.
3291 	 *
3292 	 * NOTE: make sure not to dereference p->mm before this check,
3293 	 * exit_task_work() happens _after_ exit_mm() so we could be called
3294 	 * without p->mm even though we still had it when we enqueued this
3295 	 * work.
3296 	 */
3297 	if (p->flags & PF_EXITING)
3298 		return;
3299 
3300 	/*
3301 	 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
3302 	 * no page can be migrated.
3303 	 */
3304 	if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
3305 		trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
3306 		return;
3307 	}
3308 
3309 	if (!mm->numa_next_scan) {
3310 		mm->numa_next_scan = now +
3311 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3312 	}
3313 
3314 	/*
3315 	 * Enforce maximal scan/migration frequency..
3316 	 */
3317 	migrate = mm->numa_next_scan;
3318 	if (time_before(now, migrate))
3319 		return;
3320 
3321 	if (p->numa_scan_period == 0) {
3322 		p->numa_scan_period_max = task_scan_max(p);
3323 		p->numa_scan_period = task_scan_start(p);
3324 	}
3325 
3326 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3327 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3328 		return;
3329 
3330 	/*
3331 	 * Delay this task enough that another task of this mm will likely win
3332 	 * the next time around.
3333 	 */
3334 	p->node_stamp += 2 * TICK_NSEC;
3335 
3336 	pages = sysctl_numa_balancing_scan_size;
3337 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3338 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
3339 	if (!pages)
3340 		return;
3341 
3342 
3343 	if (!mmap_read_trylock(mm))
3344 		return;
3345 
3346 	/*
3347 	 * VMAs are skipped if the current PID has not trapped a fault within
3348 	 * the VMA recently. Allow scanning to be forced if there is no
3349 	 * suitable VMA remaining.
3350 	 */
3351 	vma_pids_skipped = false;
3352 
3353 retry_pids:
3354 	start = mm->numa_scan_offset;
3355 	vma_iter_init(&vmi, mm, start);
3356 	vma = vma_next(&vmi);
3357 	if (!vma) {
3358 		reset_ptenuma_scan(p);
3359 		start = 0;
3360 		vma_iter_set(&vmi, start);
3361 		vma = vma_next(&vmi);
3362 	}
3363 
3364 	for (; vma; vma = vma_next(&vmi)) {
3365 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3366 			is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3367 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3368 			continue;
3369 		}
3370 
3371 		/*
3372 		 * Shared library pages mapped by multiple processes are not
3373 		 * migrated as it is expected they are cache replicated. Avoid
3374 		 * hinting faults in read-only file-backed mappings or the vDSO
3375 		 * as migrating the pages will be of marginal benefit.
3376 		 */
3377 		if (!vma->vm_mm ||
3378 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3379 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3380 			continue;
3381 		}
3382 
3383 		/*
3384 		 * Skip inaccessible VMAs to avoid any confusion between
3385 		 * PROT_NONE and NUMA hinting PTEs
3386 		 */
3387 		if (!vma_is_accessible(vma)) {
3388 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3389 			continue;
3390 		}
3391 
3392 		/* Initialise new per-VMA NUMAB state. */
3393 		if (!vma->numab_state) {
3394 			struct vma_numab_state *ptr;
3395 
3396 			ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3397 			if (!ptr)
3398 				continue;
3399 
3400 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3401 				kfree(ptr);
3402 				continue;
3403 			}
3404 
3405 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3406 
3407 			vma->numab_state->next_scan = now +
3408 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3409 
3410 			/* Reset happens after 4 times scan delay of scan start */
3411 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
3412 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3413 
3414 			/*
3415 			 * Ensure prev_scan_seq does not match numa_scan_seq,
3416 			 * to prevent VMAs being skipped prematurely on the
3417 			 * first scan:
3418 			 */
3419 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3420 		}
3421 
3422 		/*
3423 		 * Scanning the VMAs of short lived tasks add more overhead. So
3424 		 * delay the scan for new VMAs.
3425 		 */
3426 		if (mm->numa_scan_seq && time_before(jiffies,
3427 						vma->numab_state->next_scan)) {
3428 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3429 			continue;
3430 		}
3431 
3432 		/* RESET access PIDs regularly for old VMAs. */
3433 		if (mm->numa_scan_seq &&
3434 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
3435 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3436 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3437 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3438 			vma->numab_state->pids_active[1] = 0;
3439 		}
3440 
3441 		/* Do not rescan VMAs twice within the same sequence. */
3442 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3443 			mm->numa_scan_offset = vma->vm_end;
3444 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3445 			continue;
3446 		}
3447 
3448 		/*
3449 		 * Do not scan the VMA if task has not accessed it, unless no other
3450 		 * VMA candidate exists.
3451 		 */
3452 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3453 			vma_pids_skipped = true;
3454 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3455 			continue;
3456 		}
3457 
3458 		do {
3459 			start = max(start, vma->vm_start);
3460 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3461 			end = min(end, vma->vm_end);
3462 			nr_pte_updates = change_prot_numa(vma, start, end);
3463 
3464 			/*
3465 			 * Try to scan sysctl_numa_balancing_size worth of
3466 			 * hpages that have at least one present PTE that
3467 			 * is not already PTE-numa. If the VMA contains
3468 			 * areas that are unused or already full of prot_numa
3469 			 * PTEs, scan up to virtpages, to skip through those
3470 			 * areas faster.
3471 			 */
3472 			if (nr_pte_updates)
3473 				pages -= (end - start) >> PAGE_SHIFT;
3474 			virtpages -= (end - start) >> PAGE_SHIFT;
3475 
3476 			start = end;
3477 			if (pages <= 0 || virtpages <= 0)
3478 				goto out;
3479 
3480 			cond_resched();
3481 		} while (end != vma->vm_end);
3482 
3483 		/* VMA scan is complete, do not scan until next sequence. */
3484 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3485 
3486 		/*
3487 		 * Only force scan within one VMA at a time, to limit the
3488 		 * cost of scanning a potentially uninteresting VMA.
3489 		 */
3490 		if (vma_pids_forced)
3491 			break;
3492 	}
3493 
3494 	/*
3495 	 * If no VMAs are remaining and VMAs were skipped due to the PID
3496 	 * not accessing the VMA previously, then force a scan to ensure
3497 	 * forward progress:
3498 	 */
3499 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
3500 		vma_pids_forced = true;
3501 		goto retry_pids;
3502 	}
3503 
3504 out:
3505 	/*
3506 	 * It is possible to reach the end of the VMA list but the last few
3507 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3508 	 * would find the !migratable VMA on the next scan but not reset the
3509 	 * scanner to the start so check it now.
3510 	 */
3511 	if (vma)
3512 		mm->numa_scan_offset = start;
3513 	else
3514 		reset_ptenuma_scan(p);
3515 	mmap_read_unlock(mm);
3516 
3517 	/*
3518 	 * Make sure tasks use at least 32x as much time to run other code
3519 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3520 	 * Usually update_task_scan_period slows down scanning enough; on an
3521 	 * overloaded system we need to limit overhead on a per task basis.
3522 	 */
3523 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
3524 		u64 diff = p->se.sum_exec_runtime - runtime;
3525 		p->node_stamp += 32 * diff;
3526 	}
3527 }
3528 
init_numa_balancing(u64 clone_flags,struct task_struct * p)3529 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
3530 {
3531 	int mm_users = 0;
3532 	struct mm_struct *mm = p->mm;
3533 
3534 	if (mm) {
3535 		mm_users = atomic_read(&mm->mm_users);
3536 		if (mm_users == 1) {
3537 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3538 			mm->numa_scan_seq = 0;
3539 		}
3540 	}
3541 	p->node_stamp			= 0;
3542 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
3543 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
3544 	p->numa_migrate_retry		= 0;
3545 	/* Protect against double add, see task_tick_numa and task_numa_work */
3546 	p->numa_work.next		= &p->numa_work;
3547 	p->numa_faults			= NULL;
3548 	p->numa_pages_migrated		= 0;
3549 	p->total_numa_faults		= 0;
3550 	RCU_INIT_POINTER(p->numa_group, NULL);
3551 	p->last_task_numa_placement	= 0;
3552 	p->last_sum_exec_runtime	= 0;
3553 
3554 	init_task_work(&p->numa_work, task_numa_work);
3555 
3556 	/* New address space, reset the preferred nid */
3557 	if (!(clone_flags & CLONE_VM)) {
3558 		p->numa_preferred_nid = NUMA_NO_NODE;
3559 		return;
3560 	}
3561 
3562 	/*
3563 	 * New thread, keep existing numa_preferred_nid which should be copied
3564 	 * already by arch_dup_task_struct but stagger when scans start.
3565 	 */
3566 	if (mm) {
3567 		unsigned int delay;
3568 
3569 		delay = min_t(unsigned int, task_scan_max(current),
3570 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3571 		delay += 2 * TICK_NSEC;
3572 		p->node_stamp = delay;
3573 	}
3574 }
3575 
3576 /*
3577  * Drive the periodic memory faults..
3578  */
task_tick_numa(struct rq * rq,struct task_struct * curr)3579 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3580 {
3581 	struct callback_head *work = &curr->numa_work;
3582 	u64 period, now;
3583 
3584 	/*
3585 	 * We don't care about NUMA placement if we don't have memory.
3586 	 */
3587 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3588 		return;
3589 
3590 	/*
3591 	 * Using runtime rather than walltime has the dual advantage that
3592 	 * we (mostly) drive the selection from busy threads and that the
3593 	 * task needs to have done some actual work before we bother with
3594 	 * NUMA placement.
3595 	 */
3596 	now = curr->se.sum_exec_runtime;
3597 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3598 
3599 	if (now > curr->node_stamp + period) {
3600 		if (!curr->node_stamp)
3601 			curr->numa_scan_period = task_scan_start(curr);
3602 		curr->node_stamp += period;
3603 
3604 		if (!time_before(jiffies, curr->mm->numa_next_scan))
3605 			task_work_add(curr, work, TWA_RESUME);
3606 	}
3607 }
3608 
update_scan_period(struct task_struct * p,int new_cpu)3609 static void update_scan_period(struct task_struct *p, int new_cpu)
3610 {
3611 	int src_nid = cpu_to_node(task_cpu(p));
3612 	int dst_nid = cpu_to_node(new_cpu);
3613 
3614 	if (!static_branch_likely(&sched_numa_balancing))
3615 		return;
3616 
3617 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3618 		return;
3619 
3620 	if (src_nid == dst_nid)
3621 		return;
3622 
3623 	/*
3624 	 * Allow resets if faults have been trapped before one scan
3625 	 * has completed. This is most likely due to a new task that
3626 	 * is pulled cross-node due to wakeups or load balancing.
3627 	 */
3628 	if (p->numa_scan_seq) {
3629 		/*
3630 		 * Avoid scan adjustments if moving to the preferred
3631 		 * node or if the task was not previously running on
3632 		 * the preferred node.
3633 		 */
3634 		if (dst_nid == p->numa_preferred_nid ||
3635 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
3636 			src_nid != p->numa_preferred_nid))
3637 			return;
3638 	}
3639 
3640 	p->numa_scan_period = task_scan_start(p);
3641 }
3642 
3643 #else /* !CONFIG_NUMA_BALANCING: */
3644 
task_tick_numa(struct rq * rq,struct task_struct * curr)3645 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3646 {
3647 }
3648 
account_numa_enqueue(struct rq * rq,struct task_struct * p)3649 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3650 {
3651 }
3652 
account_numa_dequeue(struct rq * rq,struct task_struct * p)3653 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3654 {
3655 }
3656 
update_scan_period(struct task_struct * p,int new_cpu)3657 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3658 {
3659 }
3660 
3661 #endif /* !CONFIG_NUMA_BALANCING */
3662 
3663 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3664 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3665 {
3666 	update_load_add(&cfs_rq->load, se->load.weight);
3667 	if (entity_is_task(se)) {
3668 		struct rq *rq = rq_of(cfs_rq);
3669 
3670 		account_numa_enqueue(rq, task_of(se));
3671 		list_add(&se->group_node, &rq->cfs_tasks);
3672 	}
3673 	cfs_rq->nr_queued++;
3674 }
3675 
3676 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3677 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3678 {
3679 	update_load_sub(&cfs_rq->load, se->load.weight);
3680 	if (entity_is_task(se)) {
3681 		account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3682 		list_del_init(&se->group_node);
3683 	}
3684 	cfs_rq->nr_queued--;
3685 }
3686 
3687 /*
3688  * Signed add and clamp on underflow.
3689  *
3690  * Explicitly do a load-store to ensure the intermediate value never hits
3691  * memory. This allows lockless observations without ever seeing the negative
3692  * values.
3693  */
3694 #define add_positive(_ptr, _val) do {                           \
3695 	typeof(_ptr) ptr = (_ptr);                              \
3696 	typeof(_val) val = (_val);                              \
3697 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3698 								\
3699 	res = var + val;                                        \
3700 								\
3701 	if (val < 0 && res > var)                               \
3702 		res = 0;                                        \
3703 								\
3704 	WRITE_ONCE(*ptr, res);                                  \
3705 } while (0)
3706 
3707 /*
3708  * Unsigned subtract and clamp on underflow.
3709  *
3710  * Explicitly do a load-store to ensure the intermediate value never hits
3711  * memory. This allows lockless observations without ever seeing the negative
3712  * values.
3713  */
3714 #define sub_positive(_ptr, _val) do {				\
3715 	typeof(_ptr) ptr = (_ptr);				\
3716 	typeof(*ptr) val = (_val);				\
3717 	typeof(*ptr) res, var = READ_ONCE(*ptr);		\
3718 	res = var - val;					\
3719 	if (res > var)						\
3720 		res = 0;					\
3721 	WRITE_ONCE(*ptr, res);					\
3722 } while (0)
3723 
3724 /*
3725  * Remove and clamp on negative, from a local variable.
3726  *
3727  * A variant of sub_positive(), which does not use explicit load-store
3728  * and is thus optimized for local variable updates.
3729  */
3730 #define lsub_positive(_ptr, _val) do {				\
3731 	typeof(_ptr) ptr = (_ptr);				\
3732 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
3733 } while (0)
3734 
3735 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3736 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3737 {
3738 	cfs_rq->avg.load_avg += se->avg.load_avg;
3739 	cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3740 }
3741 
3742 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3743 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3744 {
3745 	sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3746 	sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3747 	/* See update_cfs_rq_load_avg() */
3748 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3749 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3750 }
3751 
3752 static void place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags);
3753 
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3754 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3755 			    unsigned long weight)
3756 {
3757 	bool curr = cfs_rq->curr == se;
3758 
3759 	if (se->on_rq) {
3760 		/* commit outstanding execution time */
3761 		update_curr(cfs_rq);
3762 		update_entity_lag(cfs_rq, se);
3763 		se->deadline -= se->vruntime;
3764 		se->rel_deadline = 1;
3765 		cfs_rq->nr_queued--;
3766 		if (!curr)
3767 			__dequeue_entity(cfs_rq, se);
3768 		update_load_sub(&cfs_rq->load, se->load.weight);
3769 	}
3770 	dequeue_load_avg(cfs_rq, se);
3771 
3772 	/*
3773 	 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3774 	 * we need to scale se->vlag when w_i changes.
3775 	 */
3776 	se->vlag = div_s64(se->vlag * se->load.weight, weight);
3777 	if (se->rel_deadline)
3778 		se->deadline = div_s64(se->deadline * se->load.weight, weight);
3779 
3780 	update_load_set(&se->load, weight);
3781 
3782 	do {
3783 		u32 divider = get_pelt_divider(&se->avg);
3784 
3785 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3786 	} while (0);
3787 
3788 	enqueue_load_avg(cfs_rq, se);
3789 	if (se->on_rq) {
3790 		place_entity(cfs_rq, se, 0);
3791 		update_load_add(&cfs_rq->load, se->load.weight);
3792 		if (!curr)
3793 			__enqueue_entity(cfs_rq, se);
3794 		cfs_rq->nr_queued++;
3795 	}
3796 }
3797 
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)3798 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
3799 			       const struct load_weight *lw)
3800 {
3801 	struct sched_entity *se = &p->se;
3802 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
3803 	struct load_weight *load = &se->load;
3804 
3805 	reweight_entity(cfs_rq, se, lw->weight);
3806 	load->inv_weight = lw->inv_weight;
3807 }
3808 
3809 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3810 
3811 #ifdef CONFIG_FAIR_GROUP_SCHED
3812 /*
3813  * All this does is approximate the hierarchical proportion which includes that
3814  * global sum we all love to hate.
3815  *
3816  * That is, the weight of a group entity, is the proportional share of the
3817  * group weight based on the group runqueue weights. That is:
3818  *
3819  *                     tg->weight * grq->load.weight
3820  *   ge->load.weight = -----------------------------               (1)
3821  *                       \Sum grq->load.weight
3822  *
3823  * Now, because computing that sum is prohibitively expensive to compute (been
3824  * there, done that) we approximate it with this average stuff. The average
3825  * moves slower and therefore the approximation is cheaper and more stable.
3826  *
3827  * So instead of the above, we substitute:
3828  *
3829  *   grq->load.weight -> grq->avg.load_avg                         (2)
3830  *
3831  * which yields the following:
3832  *
3833  *                     tg->weight * grq->avg.load_avg
3834  *   ge->load.weight = ------------------------------              (3)
3835  *                             tg->load_avg
3836  *
3837  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3838  *
3839  * That is shares_avg, and it is right (given the approximation (2)).
3840  *
3841  * The problem with it is that because the average is slow -- it was designed
3842  * to be exactly that of course -- this leads to transients in boundary
3843  * conditions. In specific, the case where the group was idle and we start the
3844  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3845  * yielding bad latency etc..
3846  *
3847  * Now, in that special case (1) reduces to:
3848  *
3849  *                     tg->weight * grq->load.weight
3850  *   ge->load.weight = ----------------------------- = tg->weight   (4)
3851  *                         grp->load.weight
3852  *
3853  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3854  *
3855  * So what we do is modify our approximation (3) to approach (4) in the (near)
3856  * UP case, like:
3857  *
3858  *   ge->load.weight =
3859  *
3860  *              tg->weight * grq->load.weight
3861  *     ---------------------------------------------------         (5)
3862  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
3863  *
3864  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3865  * we need to use grq->avg.load_avg as its lower bound, which then gives:
3866  *
3867  *
3868  *                     tg->weight * grq->load.weight
3869  *   ge->load.weight = -----------------------------		   (6)
3870  *                             tg_load_avg'
3871  *
3872  * Where:
3873  *
3874  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3875  *                  max(grq->load.weight, grq->avg.load_avg)
3876  *
3877  * And that is shares_weight and is icky. In the (near) UP case it approaches
3878  * (4) while in the normal case it approaches (3). It consistently
3879  * overestimates the ge->load.weight and therefore:
3880  *
3881  *   \Sum ge->load.weight >= tg->weight
3882  *
3883  * hence icky!
3884  */
calc_group_shares(struct cfs_rq * cfs_rq)3885 static long calc_group_shares(struct cfs_rq *cfs_rq)
3886 {
3887 	long tg_weight, tg_shares, load, shares;
3888 	struct task_group *tg = cfs_rq->tg;
3889 
3890 	tg_shares = READ_ONCE(tg->shares);
3891 
3892 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3893 
3894 	tg_weight = atomic_long_read(&tg->load_avg);
3895 
3896 	/* Ensure tg_weight >= load */
3897 	tg_weight -= cfs_rq->tg_load_avg_contrib;
3898 	tg_weight += load;
3899 
3900 	shares = (tg_shares * load);
3901 	if (tg_weight)
3902 		shares /= tg_weight;
3903 
3904 	/*
3905 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3906 	 * of a group with small tg->shares value. It is a floor value which is
3907 	 * assigned as a minimum load.weight to the sched_entity representing
3908 	 * the group on a CPU.
3909 	 *
3910 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3911 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3912 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3913 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3914 	 * instead of 0.
3915 	 */
3916 	return clamp_t(long, shares, MIN_SHARES, tg_shares);
3917 }
3918 
3919 /*
3920  * Recomputes the group entity based on the current state of its group
3921  * runqueue.
3922  */
update_cfs_group(struct sched_entity * se)3923 static void update_cfs_group(struct sched_entity *se)
3924 {
3925 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3926 	long shares;
3927 
3928 	/*
3929 	 * When a group becomes empty, preserve its weight. This matters for
3930 	 * DELAY_DEQUEUE.
3931 	 */
3932 	if (!gcfs_rq || !gcfs_rq->load.weight)
3933 		return;
3934 
3935 	shares = calc_group_shares(gcfs_rq);
3936 	if (unlikely(se->load.weight != shares))
3937 		reweight_entity(cfs_rq_of(se), se, shares);
3938 }
3939 
3940 #else /* !CONFIG_FAIR_GROUP_SCHED: */
update_cfs_group(struct sched_entity * se)3941 static inline void update_cfs_group(struct sched_entity *se)
3942 {
3943 }
3944 #endif /* !CONFIG_FAIR_GROUP_SCHED */
3945 
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)3946 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3947 {
3948 	struct rq *rq = rq_of(cfs_rq);
3949 
3950 	if (&rq->cfs == cfs_rq) {
3951 		/*
3952 		 * There are a few boundary cases this might miss but it should
3953 		 * get called often enough that that should (hopefully) not be
3954 		 * a real problem.
3955 		 *
3956 		 * It will not get called when we go idle, because the idle
3957 		 * thread is a different class (!fair), nor will the utilization
3958 		 * number include things like RT tasks.
3959 		 *
3960 		 * As is, the util number is not freq-invariant (we'd have to
3961 		 * implement arch_scale_freq_capacity() for that).
3962 		 *
3963 		 * See cpu_util_cfs().
3964 		 */
3965 		cpufreq_update_util(rq, flags);
3966 	}
3967 }
3968 
load_avg_is_decayed(struct sched_avg * sa)3969 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3970 {
3971 	if (sa->load_sum)
3972 		return false;
3973 
3974 	if (sa->util_sum)
3975 		return false;
3976 
3977 	if (sa->runnable_sum)
3978 		return false;
3979 
3980 	/*
3981 	 * _avg must be null when _sum are null because _avg = _sum / divider
3982 	 * Make sure that rounding and/or propagation of PELT values never
3983 	 * break this.
3984 	 */
3985 	WARN_ON_ONCE(sa->load_avg ||
3986 		      sa->util_avg ||
3987 		      sa->runnable_avg);
3988 
3989 	return true;
3990 }
3991 
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)3992 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3993 {
3994 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3995 				 cfs_rq->last_update_time_copy);
3996 }
3997 #ifdef CONFIG_FAIR_GROUP_SCHED
3998 /*
3999  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4000  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4001  * bottom-up, we only have to test whether the cfs_rq before us on the list
4002  * is our child.
4003  * If cfs_rq is not on the list, test whether a child needs its to be added to
4004  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
4005  */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4006 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4007 {
4008 	struct cfs_rq *prev_cfs_rq;
4009 	struct list_head *prev;
4010 	struct rq *rq = rq_of(cfs_rq);
4011 
4012 	if (cfs_rq->on_list) {
4013 		prev = cfs_rq->leaf_cfs_rq_list.prev;
4014 	} else {
4015 		prev = rq->tmp_alone_branch;
4016 	}
4017 
4018 	if (prev == &rq->leaf_cfs_rq_list)
4019 		return false;
4020 
4021 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4022 
4023 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4024 }
4025 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4026 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4027 {
4028 	if (cfs_rq->load.weight)
4029 		return false;
4030 
4031 	if (!load_avg_is_decayed(&cfs_rq->avg))
4032 		return false;
4033 
4034 	if (child_cfs_rq_on_list(cfs_rq))
4035 		return false;
4036 
4037 	if (cfs_rq->tg_load_avg_contrib)
4038 		return false;
4039 
4040 	return true;
4041 }
4042 
4043 /**
4044  * update_tg_load_avg - update the tg's load avg
4045  * @cfs_rq: the cfs_rq whose avg changed
4046  *
4047  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4048  * However, because tg->load_avg is a global value there are performance
4049  * considerations.
4050  *
4051  * In order to avoid having to look at the other cfs_rq's, we use a
4052  * differential update where we store the last value we propagated. This in
4053  * turn allows skipping updates if the differential is 'small'.
4054  *
4055  * Updating tg's load_avg is necessary before update_cfs_share().
4056  */
update_tg_load_avg(struct cfs_rq * cfs_rq)4057 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4058 {
4059 	long delta;
4060 	u64 now;
4061 
4062 	/*
4063 	 * No need to update load_avg for root_task_group as it is not used.
4064 	 */
4065 	if (cfs_rq->tg == &root_task_group)
4066 		return;
4067 
4068 	/* rq has been offline and doesn't contribute to the share anymore: */
4069 	if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4070 		return;
4071 
4072 	/*
4073 	 * For migration heavy workloads, access to tg->load_avg can be
4074 	 * unbound. Limit the update rate to at most once per ms.
4075 	 */
4076 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4077 	if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4078 		return;
4079 
4080 	delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4081 	if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4082 		atomic_long_add(delta, &cfs_rq->tg->load_avg);
4083 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4084 		cfs_rq->last_update_tg_load_avg = now;
4085 	}
4086 }
4087 
clear_tg_load_avg(struct cfs_rq * cfs_rq)4088 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4089 {
4090 	long delta;
4091 	u64 now;
4092 
4093 	/*
4094 	 * No need to update load_avg for root_task_group, as it is not used.
4095 	 */
4096 	if (cfs_rq->tg == &root_task_group)
4097 		return;
4098 
4099 	now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4100 	delta = 0 - cfs_rq->tg_load_avg_contrib;
4101 	atomic_long_add(delta, &cfs_rq->tg->load_avg);
4102 	cfs_rq->tg_load_avg_contrib = 0;
4103 	cfs_rq->last_update_tg_load_avg = now;
4104 }
4105 
4106 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4107 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4108 {
4109 	struct task_group *tg;
4110 
4111 	lockdep_assert_rq_held(rq);
4112 
4113 	/*
4114 	 * The rq clock has already been updated in
4115 	 * set_rq_offline(), so we should skip updating
4116 	 * the rq clock again in unthrottle_cfs_rq().
4117 	 */
4118 	rq_clock_start_loop_update(rq);
4119 
4120 	rcu_read_lock();
4121 	list_for_each_entry_rcu(tg, &task_groups, list) {
4122 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4123 
4124 		clear_tg_load_avg(cfs_rq);
4125 	}
4126 	rcu_read_unlock();
4127 
4128 	rq_clock_stop_loop_update(rq);
4129 }
4130 
4131 /*
4132  * Called within set_task_rq() right before setting a task's CPU. The
4133  * caller only guarantees p->pi_lock is held; no other assumptions,
4134  * including the state of rq->lock, should be made.
4135  */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4136 void set_task_rq_fair(struct sched_entity *se,
4137 		      struct cfs_rq *prev, struct cfs_rq *next)
4138 {
4139 	u64 p_last_update_time;
4140 	u64 n_last_update_time;
4141 
4142 	if (!sched_feat(ATTACH_AGE_LOAD))
4143 		return;
4144 
4145 	/*
4146 	 * We are supposed to update the task to "current" time, then its up to
4147 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4148 	 * getting what current time is, so simply throw away the out-of-date
4149 	 * time. This will result in the wakee task is less decayed, but giving
4150 	 * the wakee more load sounds not bad.
4151 	 */
4152 	if (!(se->avg.last_update_time && prev))
4153 		return;
4154 
4155 	p_last_update_time = cfs_rq_last_update_time(prev);
4156 	n_last_update_time = cfs_rq_last_update_time(next);
4157 
4158 	__update_load_avg_blocked_se(p_last_update_time, se);
4159 	se->avg.last_update_time = n_last_update_time;
4160 }
4161 
4162 /*
4163  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4164  * propagate its contribution. The key to this propagation is the invariant
4165  * that for each group:
4166  *
4167  *   ge->avg == grq->avg						(1)
4168  *
4169  * _IFF_ we look at the pure running and runnable sums. Because they
4170  * represent the very same entity, just at different points in the hierarchy.
4171  *
4172  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4173  * and simply copies the running/runnable sum over (but still wrong, because
4174  * the group entity and group rq do not have their PELT windows aligned).
4175  *
4176  * However, update_tg_cfs_load() is more complex. So we have:
4177  *
4178  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
4179  *
4180  * And since, like util, the runnable part should be directly transferable,
4181  * the following would _appear_ to be the straight forward approach:
4182  *
4183  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
4184  *
4185  * And per (1) we have:
4186  *
4187  *   ge->avg.runnable_avg == grq->avg.runnable_avg
4188  *
4189  * Which gives:
4190  *
4191  *                      ge->load.weight * grq->avg.load_avg
4192  *   ge->avg.load_avg = -----------------------------------		(4)
4193  *                               grq->load.weight
4194  *
4195  * Except that is wrong!
4196  *
4197  * Because while for entities historical weight is not important and we
4198  * really only care about our future and therefore can consider a pure
4199  * runnable sum, runqueues can NOT do this.
4200  *
4201  * We specifically want runqueues to have a load_avg that includes
4202  * historical weights. Those represent the blocked load, the load we expect
4203  * to (shortly) return to us. This only works by keeping the weights as
4204  * integral part of the sum. We therefore cannot decompose as per (3).
4205  *
4206  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4207  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4208  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4209  * runnable section of these tasks overlap (or not). If they were to perfectly
4210  * align the rq as a whole would be runnable 2/3 of the time. If however we
4211  * always have at least 1 runnable task, the rq as a whole is always runnable.
4212  *
4213  * So we'll have to approximate.. :/
4214  *
4215  * Given the constraint:
4216  *
4217  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4218  *
4219  * We can construct a rule that adds runnable to a rq by assuming minimal
4220  * overlap.
4221  *
4222  * On removal, we'll assume each task is equally runnable; which yields:
4223  *
4224  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4225  *
4226  * XXX: only do this for the part of runnable > running ?
4227  *
4228  */
4229 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4230 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4231 {
4232 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4233 	u32 new_sum, divider;
4234 
4235 	/* Nothing to update */
4236 	if (!delta_avg)
4237 		return;
4238 
4239 	/*
4240 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4241 	 * See ___update_load_avg() for details.
4242 	 */
4243 	divider = get_pelt_divider(&cfs_rq->avg);
4244 
4245 
4246 	/* Set new sched_entity's utilization */
4247 	se->avg.util_avg = gcfs_rq->avg.util_avg;
4248 	new_sum = se->avg.util_avg * divider;
4249 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
4250 	se->avg.util_sum = new_sum;
4251 
4252 	/* Update parent cfs_rq utilization */
4253 	add_positive(&cfs_rq->avg.util_avg, delta_avg);
4254 	add_positive(&cfs_rq->avg.util_sum, delta_sum);
4255 
4256 	/* See update_cfs_rq_load_avg() */
4257 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4258 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4259 }
4260 
4261 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4262 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4263 {
4264 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4265 	u32 new_sum, divider;
4266 
4267 	/* Nothing to update */
4268 	if (!delta_avg)
4269 		return;
4270 
4271 	/*
4272 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4273 	 * See ___update_load_avg() for details.
4274 	 */
4275 	divider = get_pelt_divider(&cfs_rq->avg);
4276 
4277 	/* Set new sched_entity's runnable */
4278 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4279 	new_sum = se->avg.runnable_avg * divider;
4280 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4281 	se->avg.runnable_sum = new_sum;
4282 
4283 	/* Update parent cfs_rq runnable */
4284 	add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4285 	add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4286 	/* See update_cfs_rq_load_avg() */
4287 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4288 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4289 }
4290 
4291 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4292 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4293 {
4294 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4295 	unsigned long load_avg;
4296 	u64 load_sum = 0;
4297 	s64 delta_sum;
4298 	u32 divider;
4299 
4300 	if (!runnable_sum)
4301 		return;
4302 
4303 	gcfs_rq->prop_runnable_sum = 0;
4304 
4305 	/*
4306 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4307 	 * See ___update_load_avg() for details.
4308 	 */
4309 	divider = get_pelt_divider(&cfs_rq->avg);
4310 
4311 	if (runnable_sum >= 0) {
4312 		/*
4313 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4314 		 * the CPU is saturated running == runnable.
4315 		 */
4316 		runnable_sum += se->avg.load_sum;
4317 		runnable_sum = min_t(long, runnable_sum, divider);
4318 	} else {
4319 		/*
4320 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4321 		 * assuming all tasks are equally runnable.
4322 		 */
4323 		if (scale_load_down(gcfs_rq->load.weight)) {
4324 			load_sum = div_u64(gcfs_rq->avg.load_sum,
4325 				scale_load_down(gcfs_rq->load.weight));
4326 		}
4327 
4328 		/* But make sure to not inflate se's runnable */
4329 		runnable_sum = min(se->avg.load_sum, load_sum);
4330 	}
4331 
4332 	/*
4333 	 * runnable_sum can't be lower than running_sum
4334 	 * Rescale running sum to be in the same range as runnable sum
4335 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
4336 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
4337 	 */
4338 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4339 	runnable_sum = max(runnable_sum, running_sum);
4340 
4341 	load_sum = se_weight(se) * runnable_sum;
4342 	load_avg = div_u64(load_sum, divider);
4343 
4344 	delta_avg = load_avg - se->avg.load_avg;
4345 	if (!delta_avg)
4346 		return;
4347 
4348 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4349 
4350 	se->avg.load_sum = runnable_sum;
4351 	se->avg.load_avg = load_avg;
4352 	add_positive(&cfs_rq->avg.load_avg, delta_avg);
4353 	add_positive(&cfs_rq->avg.load_sum, delta_sum);
4354 	/* See update_cfs_rq_load_avg() */
4355 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4356 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4357 }
4358 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4359 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4360 {
4361 	cfs_rq->propagate = 1;
4362 	cfs_rq->prop_runnable_sum += runnable_sum;
4363 }
4364 
4365 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4366 static inline int propagate_entity_load_avg(struct sched_entity *se)
4367 {
4368 	struct cfs_rq *cfs_rq, *gcfs_rq;
4369 
4370 	if (entity_is_task(se))
4371 		return 0;
4372 
4373 	gcfs_rq = group_cfs_rq(se);
4374 	if (!gcfs_rq->propagate)
4375 		return 0;
4376 
4377 	gcfs_rq->propagate = 0;
4378 
4379 	cfs_rq = cfs_rq_of(se);
4380 
4381 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4382 
4383 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4384 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4385 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4386 
4387 	trace_pelt_cfs_tp(cfs_rq);
4388 	trace_pelt_se_tp(se);
4389 
4390 	return 1;
4391 }
4392 
4393 /*
4394  * Check if we need to update the load and the utilization of a blocked
4395  * group_entity:
4396  */
skip_blocked_update(struct sched_entity * se)4397 static inline bool skip_blocked_update(struct sched_entity *se)
4398 {
4399 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4400 
4401 	/*
4402 	 * If sched_entity still have not zero load or utilization, we have to
4403 	 * decay it:
4404 	 */
4405 	if (se->avg.load_avg || se->avg.util_avg)
4406 		return false;
4407 
4408 	/*
4409 	 * If there is a pending propagation, we have to update the load and
4410 	 * the utilization of the sched_entity:
4411 	 */
4412 	if (gcfs_rq->propagate)
4413 		return false;
4414 
4415 	/*
4416 	 * Otherwise, the load and the utilization of the sched_entity is
4417 	 * already zero and there is no pending propagation, so it will be a
4418 	 * waste of time to try to decay it:
4419 	 */
4420 	return true;
4421 }
4422 
4423 #else /* !CONFIG_FAIR_GROUP_SCHED: */
4424 
update_tg_load_avg(struct cfs_rq * cfs_rq)4425 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4426 
clear_tg_offline_cfs_rqs(struct rq * rq)4427 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4428 
propagate_entity_load_avg(struct sched_entity * se)4429 static inline int propagate_entity_load_avg(struct sched_entity *se)
4430 {
4431 	return 0;
4432 }
4433 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4434 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4435 
4436 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4437 
4438 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4439 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4440 {
4441 	u64 throttled = 0, now, lut;
4442 	struct cfs_rq *cfs_rq;
4443 	struct rq *rq;
4444 	bool is_idle;
4445 
4446 	if (load_avg_is_decayed(&se->avg))
4447 		return;
4448 
4449 	cfs_rq = cfs_rq_of(se);
4450 	rq = rq_of(cfs_rq);
4451 
4452 	rcu_read_lock();
4453 	is_idle = is_idle_task(rcu_dereference(rq->curr));
4454 	rcu_read_unlock();
4455 
4456 	/*
4457 	 * The lag estimation comes with a cost we don't want to pay all the
4458 	 * time. Hence, limiting to the case where the source CPU is idle and
4459 	 * we know we are at the greatest risk to have an outdated clock.
4460 	 */
4461 	if (!is_idle)
4462 		return;
4463 
4464 	/*
4465 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4466 	 *
4467 	 *   last_update_time (the cfs_rq's last_update_time)
4468 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
4469 	 *      = rq_clock_pelt()@cfs_rq_idle
4470 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
4471 	 *
4472 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
4473 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4474 	 *
4475 	 *   rq_idle_lag (delta between now and rq's update)
4476 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
4477 	 *
4478 	 * We can then write:
4479 	 *
4480 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4481 	 *          sched_clock_cpu() - rq_clock()@rq_idle
4482 	 * Where:
4483 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4484 	 *      rq_clock()@rq_idle      is rq->clock_idle
4485 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
4486 	 *                              is cfs_rq->throttled_pelt_idle
4487 	 */
4488 
4489 #ifdef CONFIG_CFS_BANDWIDTH
4490 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4491 	/* The clock has been stopped for throttling */
4492 	if (throttled == U64_MAX)
4493 		return;
4494 #endif
4495 	now = u64_u32_load(rq->clock_pelt_idle);
4496 	/*
4497 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4498 	 * is observed the old clock_pelt_idle value and the new clock_idle,
4499 	 * which lead to an underestimation. The opposite would lead to an
4500 	 * overestimation.
4501 	 */
4502 	smp_rmb();
4503 	lut = cfs_rq_last_update_time(cfs_rq);
4504 
4505 	now -= throttled;
4506 	if (now < lut)
4507 		/*
4508 		 * cfs_rq->avg.last_update_time is more recent than our
4509 		 * estimation, let's use it.
4510 		 */
4511 		now = lut;
4512 	else
4513 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4514 
4515 	__update_load_avg_blocked_se(now, se);
4516 }
4517 #else /* !CONFIG_NO_HZ_COMMON: */
migrate_se_pelt_lag(struct sched_entity * se)4518 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4519 #endif /* !CONFIG_NO_HZ_COMMON */
4520 
4521 /**
4522  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4523  * @now: current time, as per cfs_rq_clock_pelt()
4524  * @cfs_rq: cfs_rq to update
4525  *
4526  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4527  * avg. The immediate corollary is that all (fair) tasks must be attached.
4528  *
4529  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4530  *
4531  * Return: true if the load decayed or we removed load.
4532  *
4533  * Since both these conditions indicate a changed cfs_rq->avg.load we should
4534  * call update_tg_load_avg() when this function returns true.
4535  */
4536 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4537 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4538 {
4539 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4540 	struct sched_avg *sa = &cfs_rq->avg;
4541 	int decayed = 0;
4542 
4543 	if (cfs_rq->removed.nr) {
4544 		unsigned long r;
4545 		u32 divider = get_pelt_divider(&cfs_rq->avg);
4546 
4547 		raw_spin_lock(&cfs_rq->removed.lock);
4548 		swap(cfs_rq->removed.util_avg, removed_util);
4549 		swap(cfs_rq->removed.load_avg, removed_load);
4550 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
4551 		cfs_rq->removed.nr = 0;
4552 		raw_spin_unlock(&cfs_rq->removed.lock);
4553 
4554 		r = removed_load;
4555 		sub_positive(&sa->load_avg, r);
4556 		sub_positive(&sa->load_sum, r * divider);
4557 		/* See sa->util_sum below */
4558 		sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4559 
4560 		r = removed_util;
4561 		sub_positive(&sa->util_avg, r);
4562 		sub_positive(&sa->util_sum, r * divider);
4563 		/*
4564 		 * Because of rounding, se->util_sum might ends up being +1 more than
4565 		 * cfs->util_sum. Although this is not a problem by itself, detaching
4566 		 * a lot of tasks with the rounding problem between 2 updates of
4567 		 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4568 		 * cfs_util_avg is not.
4569 		 * Check that util_sum is still above its lower bound for the new
4570 		 * util_avg. Given that period_contrib might have moved since the last
4571 		 * sync, we are only sure that util_sum must be above or equal to
4572 		 *    util_avg * minimum possible divider
4573 		 */
4574 		sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4575 
4576 		r = removed_runnable;
4577 		sub_positive(&sa->runnable_avg, r);
4578 		sub_positive(&sa->runnable_sum, r * divider);
4579 		/* See sa->util_sum above */
4580 		sa->runnable_sum = max_t(u32, sa->runnable_sum,
4581 					      sa->runnable_avg * PELT_MIN_DIVIDER);
4582 
4583 		/*
4584 		 * removed_runnable is the unweighted version of removed_load so we
4585 		 * can use it to estimate removed_load_sum.
4586 		 */
4587 		add_tg_cfs_propagate(cfs_rq,
4588 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4589 
4590 		decayed = 1;
4591 	}
4592 
4593 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4594 	u64_u32_store_copy(sa->last_update_time,
4595 			   cfs_rq->last_update_time_copy,
4596 			   sa->last_update_time);
4597 	return decayed;
4598 }
4599 
4600 /**
4601  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4602  * @cfs_rq: cfs_rq to attach to
4603  * @se: sched_entity to attach
4604  *
4605  * Must call update_cfs_rq_load_avg() before this, since we rely on
4606  * cfs_rq->avg.last_update_time being current.
4607  */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4608 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4609 {
4610 	/*
4611 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4612 	 * See ___update_load_avg() for details.
4613 	 */
4614 	u32 divider = get_pelt_divider(&cfs_rq->avg);
4615 
4616 	/*
4617 	 * When we attach the @se to the @cfs_rq, we must align the decay
4618 	 * window because without that, really weird and wonderful things can
4619 	 * happen.
4620 	 *
4621 	 * XXX illustrate
4622 	 */
4623 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
4624 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
4625 
4626 	/*
4627 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4628 	 * period_contrib. This isn't strictly correct, but since we're
4629 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4630 	 * _sum a little.
4631 	 */
4632 	se->avg.util_sum = se->avg.util_avg * divider;
4633 
4634 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
4635 
4636 	se->avg.load_sum = se->avg.load_avg * divider;
4637 	if (se_weight(se) < se->avg.load_sum)
4638 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4639 	else
4640 		se->avg.load_sum = 1;
4641 
4642 	enqueue_load_avg(cfs_rq, se);
4643 	cfs_rq->avg.util_avg += se->avg.util_avg;
4644 	cfs_rq->avg.util_sum += se->avg.util_sum;
4645 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4646 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4647 
4648 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4649 
4650 	cfs_rq_util_change(cfs_rq, 0);
4651 
4652 	trace_pelt_cfs_tp(cfs_rq);
4653 }
4654 
4655 /**
4656  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4657  * @cfs_rq: cfs_rq to detach from
4658  * @se: sched_entity to detach
4659  *
4660  * Must call update_cfs_rq_load_avg() before this, since we rely on
4661  * cfs_rq->avg.last_update_time being current.
4662  */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4663 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4664 {
4665 	dequeue_load_avg(cfs_rq, se);
4666 	sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4667 	sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4668 	/* See update_cfs_rq_load_avg() */
4669 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4670 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4671 
4672 	sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4673 	sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4674 	/* See update_cfs_rq_load_avg() */
4675 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4676 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4677 
4678 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4679 
4680 	cfs_rq_util_change(cfs_rq, 0);
4681 
4682 	trace_pelt_cfs_tp(cfs_rq);
4683 }
4684 
4685 /*
4686  * Optional action to be done while updating the load average
4687  */
4688 #define UPDATE_TG	0x1
4689 #define SKIP_AGE_LOAD	0x2
4690 #define DO_ATTACH	0x4
4691 #define DO_DETACH	0x8
4692 
4693 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4694 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4695 {
4696 	u64 now = cfs_rq_clock_pelt(cfs_rq);
4697 	int decayed;
4698 
4699 	/*
4700 	 * Track task load average for carrying it to new CPU after migrated, and
4701 	 * track group sched_entity load average for task_h_load calculation in migration
4702 	 */
4703 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4704 		__update_load_avg_se(now, cfs_rq, se);
4705 
4706 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
4707 	decayed |= propagate_entity_load_avg(se);
4708 
4709 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4710 
4711 		/*
4712 		 * DO_ATTACH means we're here from enqueue_entity().
4713 		 * !last_update_time means we've passed through
4714 		 * migrate_task_rq_fair() indicating we migrated.
4715 		 *
4716 		 * IOW we're enqueueing a task on a new CPU.
4717 		 */
4718 		attach_entity_load_avg(cfs_rq, se);
4719 		update_tg_load_avg(cfs_rq);
4720 
4721 	} else if (flags & DO_DETACH) {
4722 		/*
4723 		 * DO_DETACH means we're here from dequeue_entity()
4724 		 * and we are migrating task out of the CPU.
4725 		 */
4726 		detach_entity_load_avg(cfs_rq, se);
4727 		update_tg_load_avg(cfs_rq);
4728 	} else if (decayed) {
4729 		cfs_rq_util_change(cfs_rq, 0);
4730 
4731 		if (flags & UPDATE_TG)
4732 			update_tg_load_avg(cfs_rq);
4733 	}
4734 }
4735 
4736 /*
4737  * Synchronize entity load avg of dequeued entity without locking
4738  * the previous rq.
4739  */
sync_entity_load_avg(struct sched_entity * se)4740 static void sync_entity_load_avg(struct sched_entity *se)
4741 {
4742 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4743 	u64 last_update_time;
4744 
4745 	last_update_time = cfs_rq_last_update_time(cfs_rq);
4746 	__update_load_avg_blocked_se(last_update_time, se);
4747 }
4748 
4749 /*
4750  * Task first catches up with cfs_rq, and then subtract
4751  * itself from the cfs_rq (task must be off the queue now).
4752  */
remove_entity_load_avg(struct sched_entity * se)4753 static void remove_entity_load_avg(struct sched_entity *se)
4754 {
4755 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4756 	unsigned long flags;
4757 
4758 	/*
4759 	 * tasks cannot exit without having gone through wake_up_new_task() ->
4760 	 * enqueue_task_fair() which will have added things to the cfs_rq,
4761 	 * so we can remove unconditionally.
4762 	 */
4763 
4764 	sync_entity_load_avg(se);
4765 
4766 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4767 	++cfs_rq->removed.nr;
4768 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
4769 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
4770 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
4771 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4772 }
4773 
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4774 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4775 {
4776 	return cfs_rq->avg.runnable_avg;
4777 }
4778 
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4779 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4780 {
4781 	return cfs_rq->avg.load_avg;
4782 }
4783 
4784 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
4785 
task_util(struct task_struct * p)4786 static inline unsigned long task_util(struct task_struct *p)
4787 {
4788 	return READ_ONCE(p->se.avg.util_avg);
4789 }
4790 
task_runnable(struct task_struct * p)4791 static inline unsigned long task_runnable(struct task_struct *p)
4792 {
4793 	return READ_ONCE(p->se.avg.runnable_avg);
4794 }
4795 
_task_util_est(struct task_struct * p)4796 static inline unsigned long _task_util_est(struct task_struct *p)
4797 {
4798 	return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
4799 }
4800 
task_util_est(struct task_struct * p)4801 static inline unsigned long task_util_est(struct task_struct *p)
4802 {
4803 	return max(task_util(p), _task_util_est(p));
4804 }
4805 
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4806 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4807 				    struct task_struct *p)
4808 {
4809 	unsigned int enqueued;
4810 
4811 	if (!sched_feat(UTIL_EST))
4812 		return;
4813 
4814 	/* Update root cfs_rq's estimated utilization */
4815 	enqueued  = cfs_rq->avg.util_est;
4816 	enqueued += _task_util_est(p);
4817 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4818 
4819 	trace_sched_util_est_cfs_tp(cfs_rq);
4820 }
4821 
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4822 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4823 				    struct task_struct *p)
4824 {
4825 	unsigned int enqueued;
4826 
4827 	if (!sched_feat(UTIL_EST))
4828 		return;
4829 
4830 	/* Update root cfs_rq's estimated utilization */
4831 	enqueued  = cfs_rq->avg.util_est;
4832 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4833 	WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4834 
4835 	trace_sched_util_est_cfs_tp(cfs_rq);
4836 }
4837 
4838 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4839 
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4840 static inline void util_est_update(struct cfs_rq *cfs_rq,
4841 				   struct task_struct *p,
4842 				   bool task_sleep)
4843 {
4844 	unsigned int ewma, dequeued, last_ewma_diff;
4845 
4846 	if (!sched_feat(UTIL_EST))
4847 		return;
4848 
4849 	/*
4850 	 * Skip update of task's estimated utilization when the task has not
4851 	 * yet completed an activation, e.g. being migrated.
4852 	 */
4853 	if (!task_sleep)
4854 		return;
4855 
4856 	/* Get current estimate of utilization */
4857 	ewma = READ_ONCE(p->se.avg.util_est);
4858 
4859 	/*
4860 	 * If the PELT values haven't changed since enqueue time,
4861 	 * skip the util_est update.
4862 	 */
4863 	if (ewma & UTIL_AVG_UNCHANGED)
4864 		return;
4865 
4866 	/* Get utilization at dequeue */
4867 	dequeued = task_util(p);
4868 
4869 	/*
4870 	 * Reset EWMA on utilization increases, the moving average is used only
4871 	 * to smooth utilization decreases.
4872 	 */
4873 	if (ewma <= dequeued) {
4874 		ewma = dequeued;
4875 		goto done;
4876 	}
4877 
4878 	/*
4879 	 * Skip update of task's estimated utilization when its members are
4880 	 * already ~1% close to its last activation value.
4881 	 */
4882 	last_ewma_diff = ewma - dequeued;
4883 	if (last_ewma_diff < UTIL_EST_MARGIN)
4884 		goto done;
4885 
4886 	/*
4887 	 * To avoid underestimate of task utilization, skip updates of EWMA if
4888 	 * we cannot grant that thread got all CPU time it wanted.
4889 	 */
4890 	if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
4891 		goto done;
4892 
4893 
4894 	/*
4895 	 * Update Task's estimated utilization
4896 	 *
4897 	 * When *p completes an activation we can consolidate another sample
4898 	 * of the task size. This is done by using this value to update the
4899 	 * Exponential Weighted Moving Average (EWMA):
4900 	 *
4901 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
4902 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
4903 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
4904 	 *          = w * (      -last_ewma_diff           ) +     ewma(t-1)
4905 	 *          = w * (-last_ewma_diff +  ewma(t-1) / w)
4906 	 *
4907 	 * Where 'w' is the weight of new samples, which is configured to be
4908 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4909 	 */
4910 	ewma <<= UTIL_EST_WEIGHT_SHIFT;
4911 	ewma  -= last_ewma_diff;
4912 	ewma >>= UTIL_EST_WEIGHT_SHIFT;
4913 done:
4914 	ewma |= UTIL_AVG_UNCHANGED;
4915 	WRITE_ONCE(p->se.avg.util_est, ewma);
4916 
4917 	trace_sched_util_est_se_tp(&p->se);
4918 }
4919 
get_actual_cpu_capacity(int cpu)4920 static inline unsigned long get_actual_cpu_capacity(int cpu)
4921 {
4922 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
4923 
4924 	capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
4925 
4926 	return capacity;
4927 }
4928 
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4929 static inline int util_fits_cpu(unsigned long util,
4930 				unsigned long uclamp_min,
4931 				unsigned long uclamp_max,
4932 				int cpu)
4933 {
4934 	unsigned long capacity = capacity_of(cpu);
4935 	unsigned long capacity_orig;
4936 	bool fits, uclamp_max_fits;
4937 
4938 	/*
4939 	 * Check if the real util fits without any uclamp boost/cap applied.
4940 	 */
4941 	fits = fits_capacity(util, capacity);
4942 
4943 	if (!uclamp_is_used())
4944 		return fits;
4945 
4946 	/*
4947 	 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4948 	 * uclamp_max. We only care about capacity pressure (by using
4949 	 * capacity_of()) for comparing against the real util.
4950 	 *
4951 	 * If a task is boosted to 1024 for example, we don't want a tiny
4952 	 * pressure to skew the check whether it fits a CPU or not.
4953 	 *
4954 	 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4955 	 * should fit a little cpu even if there's some pressure.
4956 	 *
4957 	 * Only exception is for HW or cpufreq pressure since it has a direct impact
4958 	 * on available OPP of the system.
4959 	 *
4960 	 * We honour it for uclamp_min only as a drop in performance level
4961 	 * could result in not getting the requested minimum performance level.
4962 	 *
4963 	 * For uclamp_max, we can tolerate a drop in performance level as the
4964 	 * goal is to cap the task. So it's okay if it's getting less.
4965 	 */
4966 	capacity_orig = arch_scale_cpu_capacity(cpu);
4967 
4968 	/*
4969 	 * We want to force a task to fit a cpu as implied by uclamp_max.
4970 	 * But we do have some corner cases to cater for..
4971 	 *
4972 	 *
4973 	 *                                 C=z
4974 	 *   |                             ___
4975 	 *   |                  C=y       |   |
4976 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
4977 	 *   |      C=x        |   |      |   |
4978 	 *   |      ___        |   |      |   |
4979 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
4980 	 *   |     |   |       |   |      |   |
4981 	 *   |     |   |       |   |      |   |
4982 	 *   +----------------------------------------
4983 	 *         CPU0        CPU1       CPU2
4984 	 *
4985 	 *   In the above example if a task is capped to a specific performance
4986 	 *   point, y, then when:
4987 	 *
4988 	 *   * util = 80% of x then it does not fit on CPU0 and should migrate
4989 	 *     to CPU1
4990 	 *   * util = 80% of y then it is forced to fit on CPU1 to honour
4991 	 *     uclamp_max request.
4992 	 *
4993 	 *   which is what we're enforcing here. A task always fits if
4994 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4995 	 *   the normal upmigration rules should withhold still.
4996 	 *
4997 	 *   Only exception is when we are on max capacity, then we need to be
4998 	 *   careful not to block overutilized state. This is so because:
4999 	 *
5000 	 *     1. There's no concept of capping at max_capacity! We can't go
5001 	 *        beyond this performance level anyway.
5002 	 *     2. The system is being saturated when we're operating near
5003 	 *        max capacity, it doesn't make sense to block overutilized.
5004 	 */
5005 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5006 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5007 	fits = fits || uclamp_max_fits;
5008 
5009 	/*
5010 	 *
5011 	 *                                 C=z
5012 	 *   |                             ___       (region a, capped, util >= uclamp_max)
5013 	 *   |                  C=y       |   |
5014 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5015 	 *   |      C=x        |   |      |   |
5016 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
5017 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5018 	 *   |     |   |       |   |      |   |
5019 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
5020 	 *   +----------------------------------------
5021 	 *         CPU0        CPU1       CPU2
5022 	 *
5023 	 * a) If util > uclamp_max, then we're capped, we don't care about
5024 	 *    actual fitness value here. We only care if uclamp_max fits
5025 	 *    capacity without taking margin/pressure into account.
5026 	 *    See comment above.
5027 	 *
5028 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
5029 	 *    fits_capacity() rules apply. Except we need to ensure that we
5030 	 *    enforce we remain within uclamp_max, see comment above.
5031 	 *
5032 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5033 	 *    need to take into account the boosted value fits the CPU without
5034 	 *    taking margin/pressure into account.
5035 	 *
5036 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
5037 	 * just need to consider an extra check for case (c) after ensuring we
5038 	 * handle the case uclamp_min > uclamp_max.
5039 	 */
5040 	uclamp_min = min(uclamp_min, uclamp_max);
5041 	if (fits && (util < uclamp_min) &&
5042 	    (uclamp_min > get_actual_cpu_capacity(cpu)))
5043 		return -1;
5044 
5045 	return fits;
5046 }
5047 
task_fits_cpu(struct task_struct * p,int cpu)5048 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5049 {
5050 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5051 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5052 	unsigned long util = task_util_est(p);
5053 	/*
5054 	 * Return true only if the cpu fully fits the task requirements, which
5055 	 * include the utilization but also the performance hints.
5056 	 */
5057 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5058 }
5059 
update_misfit_status(struct task_struct * p,struct rq * rq)5060 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5061 {
5062 	int cpu = cpu_of(rq);
5063 
5064 	if (!sched_asym_cpucap_active())
5065 		return;
5066 
5067 	/*
5068 	 * Affinity allows us to go somewhere higher?  Or are we on biggest
5069 	 * available CPU already? Or do we fit into this CPU ?
5070 	 */
5071 	if (!p || (p->nr_cpus_allowed == 1) ||
5072 	    (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5073 	    task_fits_cpu(p, cpu)) {
5074 
5075 		rq->misfit_task_load = 0;
5076 		return;
5077 	}
5078 
5079 	/*
5080 	 * Make sure that misfit_task_load will not be null even if
5081 	 * task_h_load() returns 0.
5082 	 */
5083 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5084 }
5085 
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)5086 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5087 {
5088 	struct sched_entity *se = &p->se;
5089 
5090 	p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5091 	if (attr->sched_runtime) {
5092 		se->custom_slice = 1;
5093 		se->slice = clamp_t(u64, attr->sched_runtime,
5094 				      NSEC_PER_MSEC/10,   /* HZ=1000 * 10 */
5095 				      NSEC_PER_MSEC*100); /* HZ=100  / 10 */
5096 	} else {
5097 		se->custom_slice = 0;
5098 		se->slice = sysctl_sched_base_slice;
5099 	}
5100 }
5101 
5102 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5103 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5104 {
5105 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
5106 	s64 lag = 0;
5107 
5108 	if (!se->custom_slice)
5109 		se->slice = sysctl_sched_base_slice;
5110 	vslice = calc_delta_fair(se->slice, se);
5111 
5112 	/*
5113 	 * Due to how V is constructed as the weighted average of entities,
5114 	 * adding tasks with positive lag, or removing tasks with negative lag
5115 	 * will move 'time' backwards, this can screw around with the lag of
5116 	 * other tasks.
5117 	 *
5118 	 * EEVDF: placement strategy #1 / #2
5119 	 */
5120 	if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5121 		struct sched_entity *curr = cfs_rq->curr;
5122 		unsigned long load;
5123 
5124 		lag = se->vlag;
5125 
5126 		/*
5127 		 * If we want to place a task and preserve lag, we have to
5128 		 * consider the effect of the new entity on the weighted
5129 		 * average and compensate for this, otherwise lag can quickly
5130 		 * evaporate.
5131 		 *
5132 		 * Lag is defined as:
5133 		 *
5134 		 *   lag_i = S - s_i = w_i * (V - v_i)
5135 		 *
5136 		 * To avoid the 'w_i' term all over the place, we only track
5137 		 * the virtual lag:
5138 		 *
5139 		 *   vl_i = V - v_i <=> v_i = V - vl_i
5140 		 *
5141 		 * And we take V to be the weighted average of all v:
5142 		 *
5143 		 *   V = (\Sum w_j*v_j) / W
5144 		 *
5145 		 * Where W is: \Sum w_j
5146 		 *
5147 		 * Then, the weighted average after adding an entity with lag
5148 		 * vl_i is given by:
5149 		 *
5150 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5151 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
5152 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5153 		 *      = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
5154 		 *      = V - w_i*vl_i / (W + w_i)
5155 		 *
5156 		 * And the actual lag after adding an entity with vl_i is:
5157 		 *
5158 		 *   vl'_i = V' - v_i
5159 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5160 		 *         = vl_i - w_i*vl_i / (W + w_i)
5161 		 *
5162 		 * Which is strictly less than vl_i. So in order to preserve lag
5163 		 * we should inflate the lag before placement such that the
5164 		 * effective lag after placement comes out right.
5165 		 *
5166 		 * As such, invert the above relation for vl'_i to get the vl_i
5167 		 * we need to use such that the lag after placement is the lag
5168 		 * we computed before dequeue.
5169 		 *
5170 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
5171 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5172 		 *
5173 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5174 		 *                   = W*vl_i
5175 		 *
5176 		 *   vl_i = (W + w_i)*vl'_i / W
5177 		 */
5178 		load = cfs_rq->avg_load;
5179 		if (curr && curr->on_rq)
5180 			load += scale_load_down(curr->load.weight);
5181 
5182 		lag *= load + scale_load_down(se->load.weight);
5183 		if (WARN_ON_ONCE(!load))
5184 			load = 1;
5185 		lag = div_s64(lag, load);
5186 	}
5187 
5188 	se->vruntime = vruntime - lag;
5189 
5190 	if (se->rel_deadline) {
5191 		se->deadline += se->vruntime;
5192 		se->rel_deadline = 0;
5193 		return;
5194 	}
5195 
5196 	/*
5197 	 * When joining the competition; the existing tasks will be,
5198 	 * on average, halfway through their slice, as such start tasks
5199 	 * off with half a slice to ease into the competition.
5200 	 */
5201 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5202 		vslice /= 2;
5203 
5204 	/*
5205 	 * EEVDF: vd_i = ve_i + r_i/w_i
5206 	 */
5207 	se->deadline = se->vruntime + vslice;
5208 }
5209 
5210 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5211 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5212 
5213 static void
5214 requeue_delayed_entity(struct sched_entity *se);
5215 
5216 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5217 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5218 {
5219 	bool curr = cfs_rq->curr == se;
5220 
5221 	/*
5222 	 * If we're the current task, we must renormalise before calling
5223 	 * update_curr().
5224 	 */
5225 	if (curr)
5226 		place_entity(cfs_rq, se, flags);
5227 
5228 	update_curr(cfs_rq);
5229 
5230 	/*
5231 	 * When enqueuing a sched_entity, we must:
5232 	 *   - Update loads to have both entity and cfs_rq synced with now.
5233 	 *   - For group_entity, update its runnable_weight to reflect the new
5234 	 *     h_nr_runnable of its group cfs_rq.
5235 	 *   - For group_entity, update its weight to reflect the new share of
5236 	 *     its group cfs_rq
5237 	 *   - Add its new weight to cfs_rq->load.weight
5238 	 */
5239 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5240 	se_update_runnable(se);
5241 	/*
5242 	 * XXX update_load_avg() above will have attached us to the pelt sum;
5243 	 * but update_cfs_group() here will re-adjust the weight and have to
5244 	 * undo/redo all that. Seems wasteful.
5245 	 */
5246 	update_cfs_group(se);
5247 
5248 	/*
5249 	 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5250 	 * we can place the entity.
5251 	 */
5252 	if (!curr)
5253 		place_entity(cfs_rq, se, flags);
5254 
5255 	account_entity_enqueue(cfs_rq, se);
5256 
5257 	/* Entity has migrated, no longer consider this task hot */
5258 	if (flags & ENQUEUE_MIGRATED)
5259 		se->exec_start = 0;
5260 
5261 	check_schedstat_required();
5262 	update_stats_enqueue_fair(cfs_rq, se, flags);
5263 	if (!curr)
5264 		__enqueue_entity(cfs_rq, se);
5265 	se->on_rq = 1;
5266 
5267 	if (cfs_rq->nr_queued == 1) {
5268 		check_enqueue_throttle(cfs_rq);
5269 		list_add_leaf_cfs_rq(cfs_rq);
5270 #ifdef CONFIG_CFS_BANDWIDTH
5271 		if (cfs_rq->pelt_clock_throttled) {
5272 			struct rq *rq = rq_of(cfs_rq);
5273 
5274 			cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5275 				cfs_rq->throttled_clock_pelt;
5276 			cfs_rq->pelt_clock_throttled = 0;
5277 		}
5278 #endif
5279 	}
5280 }
5281 
__clear_buddies_next(struct sched_entity * se)5282 static void __clear_buddies_next(struct sched_entity *se)
5283 {
5284 	for_each_sched_entity(se) {
5285 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5286 		if (cfs_rq->next != se)
5287 			break;
5288 
5289 		cfs_rq->next = NULL;
5290 	}
5291 }
5292 
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5293 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5294 {
5295 	if (cfs_rq->next == se)
5296 		__clear_buddies_next(se);
5297 }
5298 
5299 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5300 
set_delayed(struct sched_entity * se)5301 static void set_delayed(struct sched_entity *se)
5302 {
5303 	se->sched_delayed = 1;
5304 
5305 	/*
5306 	 * Delayed se of cfs_rq have no tasks queued on them.
5307 	 * Do not adjust h_nr_runnable since dequeue_entities()
5308 	 * will account it for blocked tasks.
5309 	 */
5310 	if (!entity_is_task(se))
5311 		return;
5312 
5313 	for_each_sched_entity(se) {
5314 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5315 
5316 		cfs_rq->h_nr_runnable--;
5317 	}
5318 }
5319 
clear_delayed(struct sched_entity * se)5320 static void clear_delayed(struct sched_entity *se)
5321 {
5322 	se->sched_delayed = 0;
5323 
5324 	/*
5325 	 * Delayed se of cfs_rq have no tasks queued on them.
5326 	 * Do not adjust h_nr_runnable since a dequeue has
5327 	 * already accounted for it or an enqueue of a task
5328 	 * below it will account for it in enqueue_task_fair().
5329 	 */
5330 	if (!entity_is_task(se))
5331 		return;
5332 
5333 	for_each_sched_entity(se) {
5334 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5335 
5336 		cfs_rq->h_nr_runnable++;
5337 	}
5338 }
5339 
finish_delayed_dequeue_entity(struct sched_entity * se)5340 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5341 {
5342 	clear_delayed(se);
5343 	if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5344 		se->vlag = 0;
5345 }
5346 
5347 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5348 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5349 {
5350 	bool sleep = flags & DEQUEUE_SLEEP;
5351 	int action = UPDATE_TG;
5352 
5353 	update_curr(cfs_rq);
5354 	clear_buddies(cfs_rq, se);
5355 
5356 	if (flags & DEQUEUE_DELAYED) {
5357 		WARN_ON_ONCE(!se->sched_delayed);
5358 	} else {
5359 		bool delay = sleep;
5360 		/*
5361 		 * DELAY_DEQUEUE relies on spurious wakeups, special task
5362 		 * states must not suffer spurious wakeups, excempt them.
5363 		 */
5364 		if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
5365 			delay = false;
5366 
5367 		WARN_ON_ONCE(delay && se->sched_delayed);
5368 
5369 		if (sched_feat(DELAY_DEQUEUE) && delay &&
5370 		    !entity_eligible(cfs_rq, se)) {
5371 			update_load_avg(cfs_rq, se, 0);
5372 			set_delayed(se);
5373 			return false;
5374 		}
5375 	}
5376 
5377 	if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5378 		action |= DO_DETACH;
5379 
5380 	/*
5381 	 * When dequeuing a sched_entity, we must:
5382 	 *   - Update loads to have both entity and cfs_rq synced with now.
5383 	 *   - For group_entity, update its runnable_weight to reflect the new
5384 	 *     h_nr_runnable of its group cfs_rq.
5385 	 *   - Subtract its previous weight from cfs_rq->load.weight.
5386 	 *   - For group entity, update its weight to reflect the new share
5387 	 *     of its group cfs_rq.
5388 	 */
5389 	update_load_avg(cfs_rq, se, action);
5390 	se_update_runnable(se);
5391 
5392 	update_stats_dequeue_fair(cfs_rq, se, flags);
5393 
5394 	update_entity_lag(cfs_rq, se);
5395 	if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5396 		se->deadline -= se->vruntime;
5397 		se->rel_deadline = 1;
5398 	}
5399 
5400 	if (se != cfs_rq->curr)
5401 		__dequeue_entity(cfs_rq, se);
5402 	se->on_rq = 0;
5403 	account_entity_dequeue(cfs_rq, se);
5404 
5405 	/* return excess runtime on last dequeue */
5406 	return_cfs_rq_runtime(cfs_rq);
5407 
5408 	update_cfs_group(se);
5409 
5410 	if (flags & DEQUEUE_DELAYED)
5411 		finish_delayed_dequeue_entity(se);
5412 
5413 	if (cfs_rq->nr_queued == 0) {
5414 		update_idle_cfs_rq_clock_pelt(cfs_rq);
5415 #ifdef CONFIG_CFS_BANDWIDTH
5416 		if (throttled_hierarchy(cfs_rq)) {
5417 			struct rq *rq = rq_of(cfs_rq);
5418 
5419 			list_del_leaf_cfs_rq(cfs_rq);
5420 			cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5421 			cfs_rq->pelt_clock_throttled = 1;
5422 		}
5423 #endif
5424 	}
5425 
5426 	return true;
5427 }
5428 
5429 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5430 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5431 {
5432 	clear_buddies(cfs_rq, se);
5433 
5434 	/* 'current' is not kept within the tree. */
5435 	if (se->on_rq) {
5436 		/*
5437 		 * Any task has to be enqueued before it get to execute on
5438 		 * a CPU. So account for the time it spent waiting on the
5439 		 * runqueue.
5440 		 */
5441 		update_stats_wait_end_fair(cfs_rq, se);
5442 		__dequeue_entity(cfs_rq, se);
5443 		update_load_avg(cfs_rq, se, UPDATE_TG);
5444 
5445 		set_protect_slice(cfs_rq, se);
5446 	}
5447 
5448 	update_stats_curr_start(cfs_rq, se);
5449 	WARN_ON_ONCE(cfs_rq->curr);
5450 	cfs_rq->curr = se;
5451 
5452 	/*
5453 	 * Track our maximum slice length, if the CPU's load is at
5454 	 * least twice that of our own weight (i.e. don't track it
5455 	 * when there are only lesser-weight tasks around):
5456 	 */
5457 	if (schedstat_enabled() &&
5458 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5459 		struct sched_statistics *stats;
5460 
5461 		stats = __schedstats_from_se(se);
5462 		__schedstat_set(stats->slice_max,
5463 				max((u64)stats->slice_max,
5464 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
5465 	}
5466 
5467 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
5468 }
5469 
5470 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5471 
5472 /*
5473  * Pick the next process, keeping these things in mind, in this order:
5474  * 1) keep things fair between processes/task groups
5475  * 2) pick the "next" process, since someone really wants that to run
5476  * 3) pick the "last" process, for cache locality
5477  * 4) do not run the "skip" process, if something else is available
5478  */
5479 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5480 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5481 {
5482 	struct sched_entity *se;
5483 
5484 	se = pick_eevdf(cfs_rq);
5485 	if (se->sched_delayed) {
5486 		dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5487 		/*
5488 		 * Must not reference @se again, see __block_task().
5489 		 */
5490 		return NULL;
5491 	}
5492 	return se;
5493 }
5494 
5495 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5496 
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5497 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5498 {
5499 	/*
5500 	 * If still on the runqueue then deactivate_task()
5501 	 * was not called and update_curr() has to be done:
5502 	 */
5503 	if (prev->on_rq)
5504 		update_curr(cfs_rq);
5505 
5506 	/* throttle cfs_rqs exceeding runtime */
5507 	check_cfs_rq_runtime(cfs_rq);
5508 
5509 	if (prev->on_rq) {
5510 		update_stats_wait_start_fair(cfs_rq, prev);
5511 		/* Put 'current' back into the tree. */
5512 		__enqueue_entity(cfs_rq, prev);
5513 		/* in !on_rq case, update occurred at dequeue */
5514 		update_load_avg(cfs_rq, prev, 0);
5515 	}
5516 	WARN_ON_ONCE(cfs_rq->curr != prev);
5517 	cfs_rq->curr = NULL;
5518 }
5519 
5520 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5521 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5522 {
5523 	/*
5524 	 * Update run-time statistics of the 'current'.
5525 	 */
5526 	update_curr(cfs_rq);
5527 
5528 	/*
5529 	 * Ensure that runnable average is periodically updated.
5530 	 */
5531 	update_load_avg(cfs_rq, curr, UPDATE_TG);
5532 	update_cfs_group(curr);
5533 
5534 #ifdef CONFIG_SCHED_HRTICK
5535 	/*
5536 	 * queued ticks are scheduled to match the slice, so don't bother
5537 	 * validating it and just reschedule.
5538 	 */
5539 	if (queued) {
5540 		resched_curr_lazy(rq_of(cfs_rq));
5541 		return;
5542 	}
5543 #endif
5544 }
5545 
5546 
5547 /**************************************************
5548  * CFS bandwidth control machinery
5549  */
5550 
5551 #ifdef CONFIG_CFS_BANDWIDTH
5552 
5553 #ifdef CONFIG_JUMP_LABEL
5554 static struct static_key __cfs_bandwidth_used;
5555 
cfs_bandwidth_used(void)5556 static inline bool cfs_bandwidth_used(void)
5557 {
5558 	return static_key_false(&__cfs_bandwidth_used);
5559 }
5560 
cfs_bandwidth_usage_inc(void)5561 void cfs_bandwidth_usage_inc(void)
5562 {
5563 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5564 }
5565 
cfs_bandwidth_usage_dec(void)5566 void cfs_bandwidth_usage_dec(void)
5567 {
5568 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5569 }
5570 #else /* !CONFIG_JUMP_LABEL: */
cfs_bandwidth_used(void)5571 static bool cfs_bandwidth_used(void)
5572 {
5573 	return true;
5574 }
5575 
cfs_bandwidth_usage_inc(void)5576 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5577 void cfs_bandwidth_usage_dec(void) {}
5578 #endif /* !CONFIG_JUMP_LABEL */
5579 
sched_cfs_bandwidth_slice(void)5580 static inline u64 sched_cfs_bandwidth_slice(void)
5581 {
5582 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5583 }
5584 
5585 /*
5586  * Replenish runtime according to assigned quota. We use sched_clock_cpu
5587  * directly instead of rq->clock to avoid adding additional synchronization
5588  * around rq->lock.
5589  *
5590  * requires cfs_b->lock
5591  */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5592 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5593 {
5594 	s64 runtime;
5595 
5596 	if (unlikely(cfs_b->quota == RUNTIME_INF))
5597 		return;
5598 
5599 	cfs_b->runtime += cfs_b->quota;
5600 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
5601 	if (runtime > 0) {
5602 		cfs_b->burst_time += runtime;
5603 		cfs_b->nr_burst++;
5604 	}
5605 
5606 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5607 	cfs_b->runtime_snap = cfs_b->runtime;
5608 }
5609 
tg_cfs_bandwidth(struct task_group * tg)5610 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5611 {
5612 	return &tg->cfs_bandwidth;
5613 }
5614 
5615 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5616 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5617 				   struct cfs_rq *cfs_rq, u64 target_runtime)
5618 {
5619 	u64 min_amount, amount = 0;
5620 
5621 	lockdep_assert_held(&cfs_b->lock);
5622 
5623 	/* note: this is a positive sum as runtime_remaining <= 0 */
5624 	min_amount = target_runtime - cfs_rq->runtime_remaining;
5625 
5626 	if (cfs_b->quota == RUNTIME_INF)
5627 		amount = min_amount;
5628 	else {
5629 		start_cfs_bandwidth(cfs_b);
5630 
5631 		if (cfs_b->runtime > 0) {
5632 			amount = min(cfs_b->runtime, min_amount);
5633 			cfs_b->runtime -= amount;
5634 			cfs_b->idle = 0;
5635 		}
5636 	}
5637 
5638 	cfs_rq->runtime_remaining += amount;
5639 
5640 	return cfs_rq->runtime_remaining > 0;
5641 }
5642 
5643 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5644 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5645 {
5646 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5647 	int ret;
5648 
5649 	raw_spin_lock(&cfs_b->lock);
5650 	ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5651 	raw_spin_unlock(&cfs_b->lock);
5652 
5653 	return ret;
5654 }
5655 
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5656 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5657 {
5658 	/* dock delta_exec before expiring quota (as it could span periods) */
5659 	cfs_rq->runtime_remaining -= delta_exec;
5660 
5661 	if (likely(cfs_rq->runtime_remaining > 0))
5662 		return;
5663 
5664 	if (cfs_rq->throttled)
5665 		return;
5666 	/*
5667 	 * if we're unable to extend our runtime we resched so that the active
5668 	 * hierarchy can be throttled
5669 	 */
5670 	if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5671 		resched_curr(rq_of(cfs_rq));
5672 }
5673 
5674 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5675 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5676 {
5677 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5678 		return;
5679 
5680 	__account_cfs_rq_runtime(cfs_rq, delta_exec);
5681 }
5682 
cfs_rq_throttled(struct cfs_rq * cfs_rq)5683 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5684 {
5685 	return cfs_bandwidth_used() && cfs_rq->throttled;
5686 }
5687 
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)5688 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
5689 {
5690 	return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
5691 }
5692 
5693 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5694 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5695 {
5696 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
5697 }
5698 
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)5699 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
5700 {
5701 	return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]);
5702 }
5703 
task_is_throttled(struct task_struct * p)5704 static inline bool task_is_throttled(struct task_struct *p)
5705 {
5706 	return cfs_bandwidth_used() && p->throttled;
5707 }
5708 
5709 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
throttle_cfs_rq_work(struct callback_head * work)5710 static void throttle_cfs_rq_work(struct callback_head *work)
5711 {
5712 	struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
5713 	struct sched_entity *se;
5714 	struct cfs_rq *cfs_rq;
5715 	struct rq *rq;
5716 
5717 	WARN_ON_ONCE(p != current);
5718 	p->sched_throttle_work.next = &p->sched_throttle_work;
5719 
5720 	/*
5721 	 * If task is exiting, then there won't be a return to userspace, so we
5722 	 * don't have to bother with any of this.
5723 	 */
5724 	if ((p->flags & PF_EXITING))
5725 		return;
5726 
5727 	scoped_guard(task_rq_lock, p) {
5728 		se = &p->se;
5729 		cfs_rq = cfs_rq_of(se);
5730 
5731 		/* Raced, forget */
5732 		if (p->sched_class != &fair_sched_class)
5733 			return;
5734 
5735 		/*
5736 		 * If not in limbo, then either replenish has happened or this
5737 		 * task got migrated out of the throttled cfs_rq, move along.
5738 		 */
5739 		if (!cfs_rq->throttle_count)
5740 			return;
5741 		rq = scope.rq;
5742 		update_rq_clock(rq);
5743 		WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
5744 		dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
5745 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5746 		/*
5747 		 * Must not set throttled before dequeue or dequeue will
5748 		 * mistakenly regard this task as an already throttled one.
5749 		 */
5750 		p->throttled = true;
5751 		resched_curr(rq);
5752 	}
5753 }
5754 
init_cfs_throttle_work(struct task_struct * p)5755 void init_cfs_throttle_work(struct task_struct *p)
5756 {
5757 	init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
5758 	/* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
5759 	p->sched_throttle_work.next = &p->sched_throttle_work;
5760 	INIT_LIST_HEAD(&p->throttle_node);
5761 }
5762 
5763 /*
5764  * Task is throttled and someone wants to dequeue it again:
5765  * it could be sched/core when core needs to do things like
5766  * task affinity change, task group change, task sched class
5767  * change etc. and in these cases, DEQUEUE_SLEEP is not set;
5768  * or the task is blocked after throttled due to freezer etc.
5769  * and in these cases, DEQUEUE_SLEEP is set.
5770  */
5771 static void detach_task_cfs_rq(struct task_struct *p);
dequeue_throttled_task(struct task_struct * p,int flags)5772 static void dequeue_throttled_task(struct task_struct *p, int flags)
5773 {
5774 	WARN_ON_ONCE(p->se.on_rq);
5775 	list_del_init(&p->throttle_node);
5776 
5777 	/* task blocked after throttled */
5778 	if (flags & DEQUEUE_SLEEP) {
5779 		p->throttled = false;
5780 		return;
5781 	}
5782 
5783 	/*
5784 	 * task is migrating off its old cfs_rq, detach
5785 	 * the task's load from its old cfs_rq.
5786 	 */
5787 	if (task_on_rq_migrating(p))
5788 		detach_task_cfs_rq(p);
5789 }
5790 
enqueue_throttled_task(struct task_struct * p)5791 static bool enqueue_throttled_task(struct task_struct *p)
5792 {
5793 	struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
5794 
5795 	/* @p should have gone through dequeue_throttled_task() first */
5796 	WARN_ON_ONCE(!list_empty(&p->throttle_node));
5797 
5798 	/*
5799 	 * If the throttled task @p is enqueued to a throttled cfs_rq,
5800 	 * take the fast path by directly putting the task on the
5801 	 * target cfs_rq's limbo list.
5802 	 *
5803 	 * Do not do that when @p is current because the following race can
5804 	 * cause @p's group_node to be incorectly re-insterted in its rq's
5805 	 * cfs_tasks list, despite being throttled:
5806 	 *
5807 	 *     cpuX                       cpuY
5808 	 *   p ret2user
5809 	 *  throttle_cfs_rq_work()  sched_move_task(p)
5810 	 *  LOCK task_rq_lock
5811 	 *  dequeue_task_fair(p)
5812 	 *  UNLOCK task_rq_lock
5813 	 *                          LOCK task_rq_lock
5814 	 *                          task_current_donor(p) == true
5815 	 *                          task_on_rq_queued(p) == true
5816 	 *                          dequeue_task(p)
5817 	 *                          put_prev_task(p)
5818 	 *                          sched_change_group()
5819 	 *                          enqueue_task(p) -> p's new cfs_rq
5820 	 *                                             is throttled, go
5821 	 *                                             fast path and skip
5822 	 *                                             actual enqueue
5823 	 *                          set_next_task(p)
5824 	 *                    list_move(&se->group_node, &rq->cfs_tasks); // bug
5825 	 *  schedule()
5826 	 *
5827 	 * In the above race case, @p current cfs_rq is in the same rq as
5828 	 * its previous cfs_rq because sched_move_task() only moves a task
5829 	 * to a different group from the same rq, so we can use its current
5830 	 * cfs_rq to derive rq and test if the task is current.
5831 	 */
5832 	if (throttled_hierarchy(cfs_rq) &&
5833 	    !task_current_donor(rq_of(cfs_rq), p)) {
5834 		list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5835 		return true;
5836 	}
5837 
5838 	/* we can't take the fast path, do an actual enqueue*/
5839 	p->throttled = false;
5840 	return false;
5841 }
5842 
5843 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
tg_unthrottle_up(struct task_group * tg,void * data)5844 static int tg_unthrottle_up(struct task_group *tg, void *data)
5845 {
5846 	struct rq *rq = data;
5847 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5848 	struct task_struct *p, *tmp;
5849 
5850 	if (--cfs_rq->throttle_count)
5851 		return 0;
5852 
5853 	if (cfs_rq->pelt_clock_throttled) {
5854 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5855 					     cfs_rq->throttled_clock_pelt;
5856 		cfs_rq->pelt_clock_throttled = 0;
5857 	}
5858 
5859 	if (cfs_rq->throttled_clock_self) {
5860 		u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5861 
5862 		cfs_rq->throttled_clock_self = 0;
5863 
5864 		if (WARN_ON_ONCE((s64)delta < 0))
5865 			delta = 0;
5866 
5867 		cfs_rq->throttled_clock_self_time += delta;
5868 	}
5869 
5870 	/* Re-enqueue the tasks that have been throttled at this level. */
5871 	list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) {
5872 		list_del_init(&p->throttle_node);
5873 		p->throttled = false;
5874 		enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP);
5875 	}
5876 
5877 	/* Add cfs_rq with load or one or more already running entities to the list */
5878 	if (!cfs_rq_is_decayed(cfs_rq))
5879 		list_add_leaf_cfs_rq(cfs_rq);
5880 
5881 	return 0;
5882 }
5883 
task_has_throttle_work(struct task_struct * p)5884 static inline bool task_has_throttle_work(struct task_struct *p)
5885 {
5886 	return p->sched_throttle_work.next != &p->sched_throttle_work;
5887 }
5888 
task_throttle_setup_work(struct task_struct * p)5889 static inline void task_throttle_setup_work(struct task_struct *p)
5890 {
5891 	if (task_has_throttle_work(p))
5892 		return;
5893 
5894 	/*
5895 	 * Kthreads and exiting tasks don't return to userspace, so adding the
5896 	 * work is pointless
5897 	 */
5898 	if ((p->flags & (PF_EXITING | PF_KTHREAD)))
5899 		return;
5900 
5901 	task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
5902 }
5903 
record_throttle_clock(struct cfs_rq * cfs_rq)5904 static void record_throttle_clock(struct cfs_rq *cfs_rq)
5905 {
5906 	struct rq *rq = rq_of(cfs_rq);
5907 
5908 	if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5909 		cfs_rq->throttled_clock = rq_clock(rq);
5910 
5911 	if (!cfs_rq->throttled_clock_self)
5912 		cfs_rq->throttled_clock_self = rq_clock(rq);
5913 }
5914 
tg_throttle_down(struct task_group * tg,void * data)5915 static int tg_throttle_down(struct task_group *tg, void *data)
5916 {
5917 	struct rq *rq = data;
5918 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5919 
5920 	if (cfs_rq->throttle_count++)
5921 		return 0;
5922 
5923 	/*
5924 	 * For cfs_rqs that still have entities enqueued, PELT clock
5925 	 * stop happens at dequeue time when all entities are dequeued.
5926 	 */
5927 	if (!cfs_rq->nr_queued) {
5928 		list_del_leaf_cfs_rq(cfs_rq);
5929 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5930 		cfs_rq->pelt_clock_throttled = 1;
5931 	}
5932 
5933 	WARN_ON_ONCE(cfs_rq->throttled_clock_self);
5934 	WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
5935 	return 0;
5936 }
5937 
throttle_cfs_rq(struct cfs_rq * cfs_rq)5938 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5939 {
5940 	struct rq *rq = rq_of(cfs_rq);
5941 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5942 	int dequeue = 1;
5943 
5944 	raw_spin_lock(&cfs_b->lock);
5945 	/* This will start the period timer if necessary */
5946 	if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5947 		/*
5948 		 * We have raced with bandwidth becoming available, and if we
5949 		 * actually throttled the timer might not unthrottle us for an
5950 		 * entire period. We additionally needed to make sure that any
5951 		 * subsequent check_cfs_rq_runtime calls agree not to throttle
5952 		 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5953 		 * for 1ns of runtime rather than just check cfs_b.
5954 		 */
5955 		dequeue = 0;
5956 	} else {
5957 		list_add_tail_rcu(&cfs_rq->throttled_list,
5958 				  &cfs_b->throttled_cfs_rq);
5959 	}
5960 	raw_spin_unlock(&cfs_b->lock);
5961 
5962 	if (!dequeue)
5963 		return false;  /* Throttle no longer required. */
5964 
5965 	/* freeze hierarchy runnable averages while throttled */
5966 	rcu_read_lock();
5967 	walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5968 	rcu_read_unlock();
5969 
5970 	/*
5971 	 * Note: distribution will already see us throttled via the
5972 	 * throttled-list.  rq->lock protects completion.
5973 	 */
5974 	cfs_rq->throttled = 1;
5975 	WARN_ON_ONCE(cfs_rq->throttled_clock);
5976 	return true;
5977 }
5978 
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5979 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5980 {
5981 	struct rq *rq = rq_of(cfs_rq);
5982 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5983 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
5984 
5985 	/*
5986 	 * It's possible we are called with runtime_remaining < 0 due to things
5987 	 * like async unthrottled us with a positive runtime_remaining but other
5988 	 * still running entities consumed those runtime before we reached here.
5989 	 *
5990 	 * We can't unthrottle this cfs_rq without any runtime remaining because
5991 	 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
5992 	 * which is not supposed to happen on unthrottle path.
5993 	 */
5994 	if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
5995 		return;
5996 
5997 	cfs_rq->throttled = 0;
5998 
5999 	update_rq_clock(rq);
6000 
6001 	raw_spin_lock(&cfs_b->lock);
6002 	if (cfs_rq->throttled_clock) {
6003 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6004 		cfs_rq->throttled_clock = 0;
6005 	}
6006 	list_del_rcu(&cfs_rq->throttled_list);
6007 	raw_spin_unlock(&cfs_b->lock);
6008 
6009 	/* update hierarchical throttle state */
6010 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6011 
6012 	if (!cfs_rq->load.weight) {
6013 		if (!cfs_rq->on_list)
6014 			return;
6015 		/*
6016 		 * Nothing to run but something to decay (on_list)?
6017 		 * Complete the branch.
6018 		 */
6019 		for_each_sched_entity(se) {
6020 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6021 				break;
6022 		}
6023 	}
6024 
6025 	assert_list_leaf_cfs_rq(rq);
6026 
6027 	/* Determine whether we need to wake up potentially idle CPU: */
6028 	if (rq->curr == rq->idle && rq->cfs.nr_queued)
6029 		resched_curr(rq);
6030 }
6031 
__cfsb_csd_unthrottle(void * arg)6032 static void __cfsb_csd_unthrottle(void *arg)
6033 {
6034 	struct cfs_rq *cursor, *tmp;
6035 	struct rq *rq = arg;
6036 	struct rq_flags rf;
6037 
6038 	rq_lock(rq, &rf);
6039 
6040 	/*
6041 	 * Iterating over the list can trigger several call to
6042 	 * update_rq_clock() in unthrottle_cfs_rq().
6043 	 * Do it once and skip the potential next ones.
6044 	 */
6045 	update_rq_clock(rq);
6046 	rq_clock_start_loop_update(rq);
6047 
6048 	/*
6049 	 * Since we hold rq lock we're safe from concurrent manipulation of
6050 	 * the CSD list. However, this RCU critical section annotates the
6051 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
6052 	 * race with group being freed in the window between removing it
6053 	 * from the list and advancing to the next entry in the list.
6054 	 */
6055 	rcu_read_lock();
6056 
6057 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6058 				 throttled_csd_list) {
6059 		list_del_init(&cursor->throttled_csd_list);
6060 
6061 		if (cfs_rq_throttled(cursor))
6062 			unthrottle_cfs_rq(cursor);
6063 	}
6064 
6065 	rcu_read_unlock();
6066 
6067 	rq_clock_stop_loop_update(rq);
6068 	rq_unlock(rq, &rf);
6069 }
6070 
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6071 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6072 {
6073 	struct rq *rq = rq_of(cfs_rq);
6074 	bool first;
6075 
6076 	if (rq == this_rq()) {
6077 		unthrottle_cfs_rq(cfs_rq);
6078 		return;
6079 	}
6080 
6081 	/* Already enqueued */
6082 	if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
6083 		return;
6084 
6085 	first = list_empty(&rq->cfsb_csd_list);
6086 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6087 	if (first)
6088 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6089 }
6090 
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6091 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6092 {
6093 	lockdep_assert_rq_held(rq_of(cfs_rq));
6094 
6095 	if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
6096 	    cfs_rq->runtime_remaining <= 0))
6097 		return;
6098 
6099 	__unthrottle_cfs_rq_async(cfs_rq);
6100 }
6101 
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6102 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6103 {
6104 	int this_cpu = smp_processor_id();
6105 	u64 runtime, remaining = 1;
6106 	bool throttled = false;
6107 	struct cfs_rq *cfs_rq, *tmp;
6108 	struct rq_flags rf;
6109 	struct rq *rq;
6110 	LIST_HEAD(local_unthrottle);
6111 
6112 	rcu_read_lock();
6113 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6114 				throttled_list) {
6115 		rq = rq_of(cfs_rq);
6116 
6117 		if (!remaining) {
6118 			throttled = true;
6119 			break;
6120 		}
6121 
6122 		rq_lock_irqsave(rq, &rf);
6123 		if (!cfs_rq_throttled(cfs_rq))
6124 			goto next;
6125 
6126 		/* Already queued for async unthrottle */
6127 		if (!list_empty(&cfs_rq->throttled_csd_list))
6128 			goto next;
6129 
6130 		/* By the above checks, this should never be true */
6131 		WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
6132 
6133 		raw_spin_lock(&cfs_b->lock);
6134 		runtime = -cfs_rq->runtime_remaining + 1;
6135 		if (runtime > cfs_b->runtime)
6136 			runtime = cfs_b->runtime;
6137 		cfs_b->runtime -= runtime;
6138 		remaining = cfs_b->runtime;
6139 		raw_spin_unlock(&cfs_b->lock);
6140 
6141 		cfs_rq->runtime_remaining += runtime;
6142 
6143 		/* we check whether we're throttled above */
6144 		if (cfs_rq->runtime_remaining > 0) {
6145 			if (cpu_of(rq) != this_cpu) {
6146 				unthrottle_cfs_rq_async(cfs_rq);
6147 			} else {
6148 				/*
6149 				 * We currently only expect to be unthrottling
6150 				 * a single cfs_rq locally.
6151 				 */
6152 				WARN_ON_ONCE(!list_empty(&local_unthrottle));
6153 				list_add_tail(&cfs_rq->throttled_csd_list,
6154 					      &local_unthrottle);
6155 			}
6156 		} else {
6157 			throttled = true;
6158 		}
6159 
6160 next:
6161 		rq_unlock_irqrestore(rq, &rf);
6162 	}
6163 
6164 	list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6165 				 throttled_csd_list) {
6166 		struct rq *rq = rq_of(cfs_rq);
6167 
6168 		rq_lock_irqsave(rq, &rf);
6169 
6170 		list_del_init(&cfs_rq->throttled_csd_list);
6171 
6172 		if (cfs_rq_throttled(cfs_rq))
6173 			unthrottle_cfs_rq(cfs_rq);
6174 
6175 		rq_unlock_irqrestore(rq, &rf);
6176 	}
6177 	WARN_ON_ONCE(!list_empty(&local_unthrottle));
6178 
6179 	rcu_read_unlock();
6180 
6181 	return throttled;
6182 }
6183 
6184 /*
6185  * Responsible for refilling a task_group's bandwidth and unthrottling its
6186  * cfs_rqs as appropriate. If there has been no activity within the last
6187  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6188  * used to track this state.
6189  */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6190 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6191 {
6192 	int throttled;
6193 
6194 	/* no need to continue the timer with no bandwidth constraint */
6195 	if (cfs_b->quota == RUNTIME_INF)
6196 		goto out_deactivate;
6197 
6198 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6199 	cfs_b->nr_periods += overrun;
6200 
6201 	/* Refill extra burst quota even if cfs_b->idle */
6202 	__refill_cfs_bandwidth_runtime(cfs_b);
6203 
6204 	/*
6205 	 * idle depends on !throttled (for the case of a large deficit), and if
6206 	 * we're going inactive then everything else can be deferred
6207 	 */
6208 	if (cfs_b->idle && !throttled)
6209 		goto out_deactivate;
6210 
6211 	if (!throttled) {
6212 		/* mark as potentially idle for the upcoming period */
6213 		cfs_b->idle = 1;
6214 		return 0;
6215 	}
6216 
6217 	/* account preceding periods in which throttling occurred */
6218 	cfs_b->nr_throttled += overrun;
6219 
6220 	/*
6221 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
6222 	 */
6223 	while (throttled && cfs_b->runtime > 0) {
6224 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6225 		/* we can't nest cfs_b->lock while distributing bandwidth */
6226 		throttled = distribute_cfs_runtime(cfs_b);
6227 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
6228 	}
6229 
6230 	/*
6231 	 * While we are ensured activity in the period following an
6232 	 * unthrottle, this also covers the case in which the new bandwidth is
6233 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
6234 	 * timer to remain active while there are any throttled entities.)
6235 	 */
6236 	cfs_b->idle = 0;
6237 
6238 	return 0;
6239 
6240 out_deactivate:
6241 	return 1;
6242 }
6243 
6244 /* a cfs_rq won't donate quota below this amount */
6245 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6246 /* minimum remaining period time to redistribute slack quota */
6247 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6248 /* how long we wait to gather additional slack before distributing */
6249 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6250 
6251 /*
6252  * Are we near the end of the current quota period?
6253  *
6254  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6255  * hrtimer base being cleared by hrtimer_start. In the case of
6256  * migrate_hrtimers, base is never cleared, so we are fine.
6257  */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6258 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6259 {
6260 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
6261 	s64 remaining;
6262 
6263 	/* if the call-back is running a quota refresh is already occurring */
6264 	if (hrtimer_callback_running(refresh_timer))
6265 		return 1;
6266 
6267 	/* is a quota refresh about to occur? */
6268 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6269 	if (remaining < (s64)min_expire)
6270 		return 1;
6271 
6272 	return 0;
6273 }
6274 
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6275 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6276 {
6277 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6278 
6279 	/* if there's a quota refresh soon don't bother with slack */
6280 	if (runtime_refresh_within(cfs_b, min_left))
6281 		return;
6282 
6283 	/* don't push forwards an existing deferred unthrottle */
6284 	if (cfs_b->slack_started)
6285 		return;
6286 	cfs_b->slack_started = true;
6287 
6288 	hrtimer_start(&cfs_b->slack_timer,
6289 			ns_to_ktime(cfs_bandwidth_slack_period),
6290 			HRTIMER_MODE_REL);
6291 }
6292 
6293 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6294 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6295 {
6296 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6297 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6298 
6299 	if (slack_runtime <= 0)
6300 		return;
6301 
6302 	raw_spin_lock(&cfs_b->lock);
6303 	if (cfs_b->quota != RUNTIME_INF) {
6304 		cfs_b->runtime += slack_runtime;
6305 
6306 		/* we are under rq->lock, defer unthrottling using a timer */
6307 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6308 		    !list_empty(&cfs_b->throttled_cfs_rq))
6309 			start_cfs_slack_bandwidth(cfs_b);
6310 	}
6311 	raw_spin_unlock(&cfs_b->lock);
6312 
6313 	/* even if it's not valid for return we don't want to try again */
6314 	cfs_rq->runtime_remaining -= slack_runtime;
6315 }
6316 
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6317 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6318 {
6319 	if (!cfs_bandwidth_used())
6320 		return;
6321 
6322 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6323 		return;
6324 
6325 	__return_cfs_rq_runtime(cfs_rq);
6326 }
6327 
6328 /*
6329  * This is done with a timer (instead of inline with bandwidth return) since
6330  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6331  */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6332 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6333 {
6334 	u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6335 	unsigned long flags;
6336 
6337 	/* confirm we're still not at a refresh boundary */
6338 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6339 	cfs_b->slack_started = false;
6340 
6341 	if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6342 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6343 		return;
6344 	}
6345 
6346 	if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6347 		runtime = cfs_b->runtime;
6348 
6349 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6350 
6351 	if (!runtime)
6352 		return;
6353 
6354 	distribute_cfs_runtime(cfs_b);
6355 }
6356 
6357 /*
6358  * When a group wakes up we want to make sure that its quota is not already
6359  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6360  * runtime as update_curr() throttling can not trigger until it's on-rq.
6361  */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6362 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6363 {
6364 	if (!cfs_bandwidth_used())
6365 		return;
6366 
6367 	/* an active group must be handled by the update_curr()->put() path */
6368 	if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6369 		return;
6370 
6371 	/* ensure the group is not already throttled */
6372 	if (cfs_rq_throttled(cfs_rq))
6373 		return;
6374 
6375 	/* update runtime allocation */
6376 	account_cfs_rq_runtime(cfs_rq, 0);
6377 	if (cfs_rq->runtime_remaining <= 0)
6378 		throttle_cfs_rq(cfs_rq);
6379 }
6380 
sync_throttle(struct task_group * tg,int cpu)6381 static void sync_throttle(struct task_group *tg, int cpu)
6382 {
6383 	struct cfs_rq *pcfs_rq, *cfs_rq;
6384 
6385 	if (!cfs_bandwidth_used())
6386 		return;
6387 
6388 	if (!tg->parent)
6389 		return;
6390 
6391 	cfs_rq = tg->cfs_rq[cpu];
6392 	pcfs_rq = tg->parent->cfs_rq[cpu];
6393 
6394 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
6395 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6396 
6397 	/*
6398 	 * It is not enough to sync the "pelt_clock_throttled" indicator
6399 	 * with the parent cfs_rq when the hierarchy is not queued.
6400 	 * Always join a throttled hierarchy with PELT clock throttled
6401 	 * and leaf it to the first enqueue, or distribution to
6402 	 * unthrottle the PELT clock.
6403 	 */
6404 	if (cfs_rq->throttle_count)
6405 		cfs_rq->pelt_clock_throttled = 1;
6406 }
6407 
6408 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6409 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6410 {
6411 	if (!cfs_bandwidth_used())
6412 		return false;
6413 
6414 	if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6415 		return false;
6416 
6417 	/*
6418 	 * it's possible for a throttled entity to be forced into a running
6419 	 * state (e.g. set_curr_task), in this case we're finished.
6420 	 */
6421 	if (cfs_rq_throttled(cfs_rq))
6422 		return true;
6423 
6424 	return throttle_cfs_rq(cfs_rq);
6425 }
6426 
sched_cfs_slack_timer(struct hrtimer * timer)6427 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6428 {
6429 	struct cfs_bandwidth *cfs_b =
6430 		container_of(timer, struct cfs_bandwidth, slack_timer);
6431 
6432 	do_sched_cfs_slack_timer(cfs_b);
6433 
6434 	return HRTIMER_NORESTART;
6435 }
6436 
sched_cfs_period_timer(struct hrtimer * timer)6437 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6438 {
6439 	struct cfs_bandwidth *cfs_b =
6440 		container_of(timer, struct cfs_bandwidth, period_timer);
6441 	unsigned long flags;
6442 	int overrun;
6443 	int idle = 0;
6444 	int count = 0;
6445 
6446 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6447 	for (;;) {
6448 		overrun = hrtimer_forward_now(timer, cfs_b->period);
6449 		if (!overrun)
6450 			break;
6451 
6452 		idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6453 
6454 		if (++count > 3) {
6455 			u64 new, old = ktime_to_ns(cfs_b->period);
6456 
6457 			/*
6458 			 * Grow period by a factor of 2 to avoid losing precision.
6459 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6460 			 * to fail.
6461 			 */
6462 			new = old * 2;
6463 			if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
6464 				cfs_b->period = ns_to_ktime(new);
6465 				cfs_b->quota *= 2;
6466 				cfs_b->burst *= 2;
6467 
6468 				pr_warn_ratelimited(
6469 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6470 					smp_processor_id(),
6471 					div_u64(new, NSEC_PER_USEC),
6472 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6473 			} else {
6474 				pr_warn_ratelimited(
6475 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6476 					smp_processor_id(),
6477 					div_u64(old, NSEC_PER_USEC),
6478 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6479 			}
6480 
6481 			/* reset count so we don't come right back in here */
6482 			count = 0;
6483 		}
6484 	}
6485 	if (idle)
6486 		cfs_b->period_active = 0;
6487 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6488 
6489 	return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6490 }
6491 
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6492 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6493 {
6494 	raw_spin_lock_init(&cfs_b->lock);
6495 	cfs_b->runtime = 0;
6496 	cfs_b->quota = RUNTIME_INF;
6497 	cfs_b->period = us_to_ktime(default_bw_period_us());
6498 	cfs_b->burst = 0;
6499 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6500 
6501 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6502 	hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
6503 		      HRTIMER_MODE_ABS_PINNED);
6504 
6505 	/* Add a random offset so that timers interleave */
6506 	hrtimer_set_expires(&cfs_b->period_timer,
6507 			    get_random_u32_below(cfs_b->period));
6508 	hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
6509 		      HRTIMER_MODE_REL);
6510 	cfs_b->slack_started = false;
6511 }
6512 
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6513 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6514 {
6515 	cfs_rq->runtime_enabled = 0;
6516 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
6517 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6518 	INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
6519 }
6520 
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6521 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6522 {
6523 	lockdep_assert_held(&cfs_b->lock);
6524 
6525 	if (cfs_b->period_active)
6526 		return;
6527 
6528 	cfs_b->period_active = 1;
6529 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6530 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6531 }
6532 
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6533 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6534 {
6535 	int __maybe_unused i;
6536 
6537 	/* init_cfs_bandwidth() was not called */
6538 	if (!cfs_b->throttled_cfs_rq.next)
6539 		return;
6540 
6541 	hrtimer_cancel(&cfs_b->period_timer);
6542 	hrtimer_cancel(&cfs_b->slack_timer);
6543 
6544 	/*
6545 	 * It is possible that we still have some cfs_rq's pending on a CSD
6546 	 * list, though this race is very rare. In order for this to occur, we
6547 	 * must have raced with the last task leaving the group while there
6548 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
6549 	 * CSD item but the remote cpu has not yet processed it. To handle this,
6550 	 * we can simply flush all pending CSD work inline here. We're
6551 	 * guaranteed at this point that no additional cfs_rq of this group can
6552 	 * join a CSD list.
6553 	 */
6554 	for_each_possible_cpu(i) {
6555 		struct rq *rq = cpu_rq(i);
6556 		unsigned long flags;
6557 
6558 		if (list_empty(&rq->cfsb_csd_list))
6559 			continue;
6560 
6561 		local_irq_save(flags);
6562 		__cfsb_csd_unthrottle(rq);
6563 		local_irq_restore(flags);
6564 	}
6565 }
6566 
6567 /*
6568  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6569  *
6570  * The race is harmless, since modifying bandwidth settings of unhooked group
6571  * bits doesn't do much.
6572  */
6573 
6574 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6575 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6576 {
6577 	struct task_group *tg;
6578 
6579 	lockdep_assert_rq_held(rq);
6580 
6581 	rcu_read_lock();
6582 	list_for_each_entry_rcu(tg, &task_groups, list) {
6583 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6584 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6585 
6586 		raw_spin_lock(&cfs_b->lock);
6587 		cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6588 		raw_spin_unlock(&cfs_b->lock);
6589 	}
6590 	rcu_read_unlock();
6591 }
6592 
6593 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6594 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6595 {
6596 	struct task_group *tg;
6597 
6598 	lockdep_assert_rq_held(rq);
6599 
6600 	// Do not unthrottle for an active CPU
6601 	if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6602 		return;
6603 
6604 	/*
6605 	 * The rq clock has already been updated in the
6606 	 * set_rq_offline(), so we should skip updating
6607 	 * the rq clock again in unthrottle_cfs_rq().
6608 	 */
6609 	rq_clock_start_loop_update(rq);
6610 
6611 	rcu_read_lock();
6612 	list_for_each_entry_rcu(tg, &task_groups, list) {
6613 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6614 
6615 		if (!cfs_rq->runtime_enabled)
6616 			continue;
6617 
6618 		/*
6619 		 * Offline rq is schedulable till CPU is completely disabled
6620 		 * in take_cpu_down(), so we prevent new cfs throttling here.
6621 		 */
6622 		cfs_rq->runtime_enabled = 0;
6623 
6624 		if (!cfs_rq_throttled(cfs_rq))
6625 			continue;
6626 
6627 		/*
6628 		 * clock_task is not advancing so we just need to make sure
6629 		 * there's some valid quota amount
6630 		 */
6631 		cfs_rq->runtime_remaining = 1;
6632 		unthrottle_cfs_rq(cfs_rq);
6633 	}
6634 	rcu_read_unlock();
6635 
6636 	rq_clock_stop_loop_update(rq);
6637 }
6638 
cfs_task_bw_constrained(struct task_struct * p)6639 bool cfs_task_bw_constrained(struct task_struct *p)
6640 {
6641 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
6642 
6643 	if (!cfs_bandwidth_used())
6644 		return false;
6645 
6646 	if (cfs_rq->runtime_enabled ||
6647 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6648 		return true;
6649 
6650 	return false;
6651 }
6652 
6653 #ifdef CONFIG_NO_HZ_FULL
6654 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6655 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6656 {
6657 	int cpu = cpu_of(rq);
6658 
6659 	if (!cfs_bandwidth_used())
6660 		return;
6661 
6662 	if (!tick_nohz_full_cpu(cpu))
6663 		return;
6664 
6665 	if (rq->nr_running != 1)
6666 		return;
6667 
6668 	/*
6669 	 *  We know there is only one task runnable and we've just picked it. The
6670 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6671 	 *  be otherwise able to stop the tick. Just need to check if we are using
6672 	 *  bandwidth control.
6673 	 */
6674 	if (cfs_task_bw_constrained(p))
6675 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6676 }
6677 #endif /* CONFIG_NO_HZ_FULL */
6678 
6679 #else /* !CONFIG_CFS_BANDWIDTH: */
6680 
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6681 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6682 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6683 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6684 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6685 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
task_throttle_setup_work(struct task_struct * p)6686 static void task_throttle_setup_work(struct task_struct *p) {}
task_is_throttled(struct task_struct * p)6687 static bool task_is_throttled(struct task_struct *p) { return false; }
dequeue_throttled_task(struct task_struct * p,int flags)6688 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
enqueue_throttled_task(struct task_struct * p)6689 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
record_throttle_clock(struct cfs_rq * cfs_rq)6690 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
6691 
cfs_rq_throttled(struct cfs_rq * cfs_rq)6692 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6693 {
6694 	return 0;
6695 }
6696 
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)6697 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6698 {
6699 	return false;
6700 }
6701 
throttled_hierarchy(struct cfs_rq * cfs_rq)6702 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6703 {
6704 	return 0;
6705 }
6706 
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)6707 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6708 {
6709 	return 0;
6710 }
6711 
6712 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6713 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6714 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6715 #endif
6716 
tg_cfs_bandwidth(struct task_group * tg)6717 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6718 {
6719 	return NULL;
6720 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6721 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6722 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6723 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6724 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6725 bool cfs_task_bw_constrained(struct task_struct *p)
6726 {
6727 	return false;
6728 }
6729 #endif
6730 #endif /* !CONFIG_CFS_BANDWIDTH */
6731 
6732 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6733 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6734 #endif
6735 
6736 /**************************************************
6737  * CFS operations on tasks:
6738  */
6739 
6740 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6741 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6742 {
6743 	struct sched_entity *se = &p->se;
6744 
6745 	WARN_ON_ONCE(task_rq(p) != rq);
6746 
6747 	if (rq->cfs.h_nr_queued > 1) {
6748 		u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6749 		u64 slice = se->slice;
6750 		s64 delta = slice - ran;
6751 
6752 		if (delta < 0) {
6753 			if (task_current_donor(rq, p))
6754 				resched_curr(rq);
6755 			return;
6756 		}
6757 		hrtick_start(rq, delta);
6758 	}
6759 }
6760 
6761 /*
6762  * called from enqueue/dequeue and updates the hrtick when the
6763  * current task is from our class and nr_running is low enough
6764  * to matter.
6765  */
hrtick_update(struct rq * rq)6766 static void hrtick_update(struct rq *rq)
6767 {
6768 	struct task_struct *donor = rq->donor;
6769 
6770 	if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
6771 		return;
6772 
6773 	hrtick_start_fair(rq, donor);
6774 }
6775 #else /* !CONFIG_SCHED_HRTICK: */
6776 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6777 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6778 {
6779 }
6780 
hrtick_update(struct rq * rq)6781 static inline void hrtick_update(struct rq *rq)
6782 {
6783 }
6784 #endif /* !CONFIG_SCHED_HRTICK */
6785 
cpu_overutilized(int cpu)6786 static inline bool cpu_overutilized(int cpu)
6787 {
6788 	unsigned long  rq_util_min, rq_util_max;
6789 
6790 	if (!sched_energy_enabled())
6791 		return false;
6792 
6793 	rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6794 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6795 
6796 	/* Return true only if the utilization doesn't fit CPU's capacity */
6797 	return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6798 }
6799 
6800 /*
6801  * overutilized value make sense only if EAS is enabled
6802  */
is_rd_overutilized(struct root_domain * rd)6803 static inline bool is_rd_overutilized(struct root_domain *rd)
6804 {
6805 	return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
6806 }
6807 
set_rd_overutilized(struct root_domain * rd,bool flag)6808 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
6809 {
6810 	if (!sched_energy_enabled())
6811 		return;
6812 
6813 	WRITE_ONCE(rd->overutilized, flag);
6814 	trace_sched_overutilized_tp(rd, flag);
6815 }
6816 
check_update_overutilized_status(struct rq * rq)6817 static inline void check_update_overutilized_status(struct rq *rq)
6818 {
6819 	/*
6820 	 * overutilized field is used for load balancing decisions only
6821 	 * if energy aware scheduler is being used
6822 	 */
6823 
6824 	if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
6825 		set_rd_overutilized(rq->rd, 1);
6826 }
6827 
6828 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6829 static int sched_idle_rq(struct rq *rq)
6830 {
6831 	return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
6832 			rq->nr_running);
6833 }
6834 
sched_idle_cpu(int cpu)6835 static int sched_idle_cpu(int cpu)
6836 {
6837 	return sched_idle_rq(cpu_rq(cpu));
6838 }
6839 
6840 static void
requeue_delayed_entity(struct sched_entity * se)6841 requeue_delayed_entity(struct sched_entity *se)
6842 {
6843 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
6844 
6845 	/*
6846 	 * se->sched_delayed should imply: se->on_rq == 1.
6847 	 * Because a delayed entity is one that is still on
6848 	 * the runqueue competing until elegibility.
6849 	 */
6850 	WARN_ON_ONCE(!se->sched_delayed);
6851 	WARN_ON_ONCE(!se->on_rq);
6852 
6853 	if (sched_feat(DELAY_ZERO)) {
6854 		update_entity_lag(cfs_rq, se);
6855 		if (se->vlag > 0) {
6856 			cfs_rq->nr_queued--;
6857 			if (se != cfs_rq->curr)
6858 				__dequeue_entity(cfs_rq, se);
6859 			se->vlag = 0;
6860 			place_entity(cfs_rq, se, 0);
6861 			if (se != cfs_rq->curr)
6862 				__enqueue_entity(cfs_rq, se);
6863 			cfs_rq->nr_queued++;
6864 		}
6865 	}
6866 
6867 	update_load_avg(cfs_rq, se, 0);
6868 	clear_delayed(se);
6869 }
6870 
6871 /*
6872  * The enqueue_task method is called before nr_running is
6873  * increased. Here we update the fair scheduling stats and
6874  * then put the task into the rbtree:
6875  */
6876 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6877 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6878 {
6879 	struct cfs_rq *cfs_rq;
6880 	struct sched_entity *se = &p->se;
6881 	int h_nr_idle = task_has_idle_policy(p);
6882 	int h_nr_runnable = 1;
6883 	int task_new = !(flags & ENQUEUE_WAKEUP);
6884 	int rq_h_nr_queued = rq->cfs.h_nr_queued;
6885 	u64 slice = 0;
6886 
6887 	if (task_is_throttled(p) && enqueue_throttled_task(p))
6888 		return;
6889 
6890 	/*
6891 	 * The code below (indirectly) updates schedutil which looks at
6892 	 * the cfs_rq utilization to select a frequency.
6893 	 * Let's add the task's estimated utilization to the cfs_rq's
6894 	 * estimated utilization, before we update schedutil.
6895 	 */
6896 	if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
6897 		util_est_enqueue(&rq->cfs, p);
6898 
6899 	if (flags & ENQUEUE_DELAYED) {
6900 		requeue_delayed_entity(se);
6901 		return;
6902 	}
6903 
6904 	/*
6905 	 * If in_iowait is set, the code below may not trigger any cpufreq
6906 	 * utilization updates, so do it here explicitly with the IOWAIT flag
6907 	 * passed.
6908 	 */
6909 	if (p->in_iowait)
6910 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6911 
6912 	if (task_new && se->sched_delayed)
6913 		h_nr_runnable = 0;
6914 
6915 	for_each_sched_entity(se) {
6916 		if (se->on_rq) {
6917 			if (se->sched_delayed)
6918 				requeue_delayed_entity(se);
6919 			break;
6920 		}
6921 		cfs_rq = cfs_rq_of(se);
6922 
6923 		/*
6924 		 * Basically set the slice of group entries to the min_slice of
6925 		 * their respective cfs_rq. This ensures the group can service
6926 		 * its entities in the desired time-frame.
6927 		 */
6928 		if (slice) {
6929 			se->slice = slice;
6930 			se->custom_slice = 1;
6931 		}
6932 		enqueue_entity(cfs_rq, se, flags);
6933 		slice = cfs_rq_min_slice(cfs_rq);
6934 
6935 		cfs_rq->h_nr_runnable += h_nr_runnable;
6936 		cfs_rq->h_nr_queued++;
6937 		cfs_rq->h_nr_idle += h_nr_idle;
6938 
6939 		if (cfs_rq_is_idle(cfs_rq))
6940 			h_nr_idle = 1;
6941 
6942 		flags = ENQUEUE_WAKEUP;
6943 	}
6944 
6945 	for_each_sched_entity(se) {
6946 		cfs_rq = cfs_rq_of(se);
6947 
6948 		update_load_avg(cfs_rq, se, UPDATE_TG);
6949 		se_update_runnable(se);
6950 		update_cfs_group(se);
6951 
6952 		se->slice = slice;
6953 		if (se != cfs_rq->curr)
6954 			min_vruntime_cb_propagate(&se->run_node, NULL);
6955 		slice = cfs_rq_min_slice(cfs_rq);
6956 
6957 		cfs_rq->h_nr_runnable += h_nr_runnable;
6958 		cfs_rq->h_nr_queued++;
6959 		cfs_rq->h_nr_idle += h_nr_idle;
6960 
6961 		if (cfs_rq_is_idle(cfs_rq))
6962 			h_nr_idle = 1;
6963 	}
6964 
6965 	if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
6966 		dl_server_start(&rq->fair_server);
6967 
6968 	/* At this point se is NULL and we are at root level*/
6969 	add_nr_running(rq, 1);
6970 
6971 	/*
6972 	 * Since new tasks are assigned an initial util_avg equal to
6973 	 * half of the spare capacity of their CPU, tiny tasks have the
6974 	 * ability to cross the overutilized threshold, which will
6975 	 * result in the load balancer ruining all the task placement
6976 	 * done by EAS. As a way to mitigate that effect, do not account
6977 	 * for the first enqueue operation of new tasks during the
6978 	 * overutilized flag detection.
6979 	 *
6980 	 * A better way of solving this problem would be to wait for
6981 	 * the PELT signals of tasks to converge before taking them
6982 	 * into account, but that is not straightforward to implement,
6983 	 * and the following generally works well enough in practice.
6984 	 */
6985 	if (!task_new)
6986 		check_update_overutilized_status(rq);
6987 
6988 	assert_list_leaf_cfs_rq(rq);
6989 
6990 	hrtick_update(rq);
6991 }
6992 
6993 /*
6994  * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
6995  * failing half-way through and resume the dequeue later.
6996  *
6997  * Returns:
6998  * -1 - dequeue delayed
6999  *  0 - dequeue throttled
7000  *  1 - dequeue complete
7001  */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)7002 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7003 {
7004 	bool was_sched_idle = sched_idle_rq(rq);
7005 	bool task_sleep = flags & DEQUEUE_SLEEP;
7006 	bool task_delayed = flags & DEQUEUE_DELAYED;
7007 	bool task_throttled = flags & DEQUEUE_THROTTLE;
7008 	struct task_struct *p = NULL;
7009 	int h_nr_idle = 0;
7010 	int h_nr_queued = 0;
7011 	int h_nr_runnable = 0;
7012 	struct cfs_rq *cfs_rq;
7013 	u64 slice = 0;
7014 
7015 	if (entity_is_task(se)) {
7016 		p = task_of(se);
7017 		h_nr_queued = 1;
7018 		h_nr_idle = task_has_idle_policy(p);
7019 		if (task_sleep || task_delayed || !se->sched_delayed)
7020 			h_nr_runnable = 1;
7021 	}
7022 
7023 	for_each_sched_entity(se) {
7024 		cfs_rq = cfs_rq_of(se);
7025 
7026 		if (!dequeue_entity(cfs_rq, se, flags)) {
7027 			if (p && &p->se == se)
7028 				return -1;
7029 
7030 			slice = cfs_rq_min_slice(cfs_rq);
7031 			break;
7032 		}
7033 
7034 		cfs_rq->h_nr_runnable -= h_nr_runnable;
7035 		cfs_rq->h_nr_queued -= h_nr_queued;
7036 		cfs_rq->h_nr_idle -= h_nr_idle;
7037 
7038 		if (cfs_rq_is_idle(cfs_rq))
7039 			h_nr_idle = h_nr_queued;
7040 
7041 		if (throttled_hierarchy(cfs_rq) && task_throttled)
7042 			record_throttle_clock(cfs_rq);
7043 
7044 		/* Don't dequeue parent if it has other entities besides us */
7045 		if (cfs_rq->load.weight) {
7046 			slice = cfs_rq_min_slice(cfs_rq);
7047 
7048 			/* Avoid re-evaluating load for this entity: */
7049 			se = parent_entity(se);
7050 			/*
7051 			 * Bias pick_next to pick a task from this cfs_rq, as
7052 			 * p is sleeping when it is within its sched_slice.
7053 			 */
7054 			if (task_sleep && se)
7055 				set_next_buddy(se);
7056 			break;
7057 		}
7058 		flags |= DEQUEUE_SLEEP;
7059 		flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7060 	}
7061 
7062 	for_each_sched_entity(se) {
7063 		cfs_rq = cfs_rq_of(se);
7064 
7065 		update_load_avg(cfs_rq, se, UPDATE_TG);
7066 		se_update_runnable(se);
7067 		update_cfs_group(se);
7068 
7069 		se->slice = slice;
7070 		if (se != cfs_rq->curr)
7071 			min_vruntime_cb_propagate(&se->run_node, NULL);
7072 		slice = cfs_rq_min_slice(cfs_rq);
7073 
7074 		cfs_rq->h_nr_runnable -= h_nr_runnable;
7075 		cfs_rq->h_nr_queued -= h_nr_queued;
7076 		cfs_rq->h_nr_idle -= h_nr_idle;
7077 
7078 		if (cfs_rq_is_idle(cfs_rq))
7079 			h_nr_idle = h_nr_queued;
7080 
7081 		if (throttled_hierarchy(cfs_rq) && task_throttled)
7082 			record_throttle_clock(cfs_rq);
7083 	}
7084 
7085 	sub_nr_running(rq, h_nr_queued);
7086 
7087 	/* balance early to pull high priority tasks */
7088 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7089 		rq->next_balance = jiffies;
7090 
7091 	if (p && task_delayed) {
7092 		WARN_ON_ONCE(!task_sleep);
7093 		WARN_ON_ONCE(p->on_rq != 1);
7094 
7095 		/* Fix-up what dequeue_task_fair() skipped */
7096 		hrtick_update(rq);
7097 
7098 		/*
7099 		 * Fix-up what block_task() skipped.
7100 		 *
7101 		 * Must be last, @p might not be valid after this.
7102 		 */
7103 		__block_task(rq, p);
7104 	}
7105 
7106 	return 1;
7107 }
7108 
7109 /*
7110  * The dequeue_task method is called before nr_running is
7111  * decreased. We remove the task from the rbtree and
7112  * update the fair scheduling stats:
7113  */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7114 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7115 {
7116 	if (task_is_throttled(p)) {
7117 		dequeue_throttled_task(p, flags);
7118 		return true;
7119 	}
7120 
7121 	if (!p->se.sched_delayed)
7122 		util_est_dequeue(&rq->cfs, p);
7123 
7124 	util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7125 	if (dequeue_entities(rq, &p->se, flags) < 0)
7126 		return false;
7127 
7128 	/*
7129 	 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7130 	 */
7131 
7132 	hrtick_update(rq);
7133 	return true;
7134 }
7135 
cfs_h_nr_delayed(struct rq * rq)7136 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
7137 {
7138 	return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
7139 }
7140 
7141 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7142 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7143 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7144 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7145 
7146 #ifdef CONFIG_NO_HZ_COMMON
7147 
7148 static struct {
7149 	cpumask_var_t idle_cpus_mask;
7150 	atomic_t nr_cpus;
7151 	int has_blocked;		/* Idle CPUS has blocked load */
7152 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
7153 	unsigned long next_balance;     /* in jiffy units */
7154 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
7155 } nohz ____cacheline_aligned;
7156 
7157 #endif /* CONFIG_NO_HZ_COMMON */
7158 
cpu_load(struct rq * rq)7159 static unsigned long cpu_load(struct rq *rq)
7160 {
7161 	return cfs_rq_load_avg(&rq->cfs);
7162 }
7163 
7164 /*
7165  * cpu_load_without - compute CPU load without any contributions from *p
7166  * @cpu: the CPU which load is requested
7167  * @p: the task which load should be discounted
7168  *
7169  * The load of a CPU is defined by the load of tasks currently enqueued on that
7170  * CPU as well as tasks which are currently sleeping after an execution on that
7171  * CPU.
7172  *
7173  * This method returns the load of the specified CPU by discounting the load of
7174  * the specified task, whenever the task is currently contributing to the CPU
7175  * load.
7176  */
cpu_load_without(struct rq * rq,struct task_struct * p)7177 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7178 {
7179 	struct cfs_rq *cfs_rq;
7180 	unsigned int load;
7181 
7182 	/* Task has no contribution or is new */
7183 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7184 		return cpu_load(rq);
7185 
7186 	cfs_rq = &rq->cfs;
7187 	load = READ_ONCE(cfs_rq->avg.load_avg);
7188 
7189 	/* Discount task's util from CPU's util */
7190 	lsub_positive(&load, task_h_load(p));
7191 
7192 	return load;
7193 }
7194 
cpu_runnable(struct rq * rq)7195 static unsigned long cpu_runnable(struct rq *rq)
7196 {
7197 	return cfs_rq_runnable_avg(&rq->cfs);
7198 }
7199 
cpu_runnable_without(struct rq * rq,struct task_struct * p)7200 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7201 {
7202 	struct cfs_rq *cfs_rq;
7203 	unsigned int runnable;
7204 
7205 	/* Task has no contribution or is new */
7206 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7207 		return cpu_runnable(rq);
7208 
7209 	cfs_rq = &rq->cfs;
7210 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7211 
7212 	/* Discount task's runnable from CPU's runnable */
7213 	lsub_positive(&runnable, p->se.avg.runnable_avg);
7214 
7215 	return runnable;
7216 }
7217 
capacity_of(int cpu)7218 static unsigned long capacity_of(int cpu)
7219 {
7220 	return cpu_rq(cpu)->cpu_capacity;
7221 }
7222 
record_wakee(struct task_struct * p)7223 static void record_wakee(struct task_struct *p)
7224 {
7225 	/*
7226 	 * Only decay a single time; tasks that have less then 1 wakeup per
7227 	 * jiffy will not have built up many flips.
7228 	 */
7229 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7230 		current->wakee_flips >>= 1;
7231 		current->wakee_flip_decay_ts = jiffies;
7232 	}
7233 
7234 	if (current->last_wakee != p) {
7235 		current->last_wakee = p;
7236 		current->wakee_flips++;
7237 	}
7238 }
7239 
7240 /*
7241  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7242  *
7243  * A waker of many should wake a different task than the one last awakened
7244  * at a frequency roughly N times higher than one of its wakees.
7245  *
7246  * In order to determine whether we should let the load spread vs consolidating
7247  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7248  * partner, and a factor of lls_size higher frequency in the other.
7249  *
7250  * With both conditions met, we can be relatively sure that the relationship is
7251  * non-monogamous, with partner count exceeding socket size.
7252  *
7253  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7254  * whatever is irrelevant, spread criteria is apparent partner count exceeds
7255  * socket size.
7256  */
wake_wide(struct task_struct * p)7257 static int wake_wide(struct task_struct *p)
7258 {
7259 	unsigned int master = current->wakee_flips;
7260 	unsigned int slave = p->wakee_flips;
7261 	int factor = __this_cpu_read(sd_llc_size);
7262 
7263 	if (master < slave)
7264 		swap(master, slave);
7265 	if (slave < factor || master < slave * factor)
7266 		return 0;
7267 	return 1;
7268 }
7269 
7270 /*
7271  * The purpose of wake_affine() is to quickly determine on which CPU we can run
7272  * soonest. For the purpose of speed we only consider the waking and previous
7273  * CPU.
7274  *
7275  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7276  *			cache-affine and is (or	will be) idle.
7277  *
7278  * wake_affine_weight() - considers the weight to reflect the average
7279  *			  scheduling latency of the CPUs. This seems to work
7280  *			  for the overloaded case.
7281  */
7282 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7283 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7284 {
7285 	/*
7286 	 * If this_cpu is idle, it implies the wakeup is from interrupt
7287 	 * context. Only allow the move if cache is shared. Otherwise an
7288 	 * interrupt intensive workload could force all tasks onto one
7289 	 * node depending on the IO topology or IRQ affinity settings.
7290 	 *
7291 	 * If the prev_cpu is idle and cache affine then avoid a migration.
7292 	 * There is no guarantee that the cache hot data from an interrupt
7293 	 * is more important than cache hot data on the prev_cpu and from
7294 	 * a cpufreq perspective, it's better to have higher utilisation
7295 	 * on one CPU.
7296 	 */
7297 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7298 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7299 
7300 	if (sync) {
7301 		struct rq *rq = cpu_rq(this_cpu);
7302 
7303 		if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
7304 			return this_cpu;
7305 	}
7306 
7307 	if (available_idle_cpu(prev_cpu))
7308 		return prev_cpu;
7309 
7310 	return nr_cpumask_bits;
7311 }
7312 
7313 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7314 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7315 		   int this_cpu, int prev_cpu, int sync)
7316 {
7317 	s64 this_eff_load, prev_eff_load;
7318 	unsigned long task_load;
7319 
7320 	this_eff_load = cpu_load(cpu_rq(this_cpu));
7321 
7322 	if (sync) {
7323 		unsigned long current_load = task_h_load(current);
7324 
7325 		if (current_load > this_eff_load)
7326 			return this_cpu;
7327 
7328 		this_eff_load -= current_load;
7329 	}
7330 
7331 	task_load = task_h_load(p);
7332 
7333 	this_eff_load += task_load;
7334 	if (sched_feat(WA_BIAS))
7335 		this_eff_load *= 100;
7336 	this_eff_load *= capacity_of(prev_cpu);
7337 
7338 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7339 	prev_eff_load -= task_load;
7340 	if (sched_feat(WA_BIAS))
7341 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7342 	prev_eff_load *= capacity_of(this_cpu);
7343 
7344 	/*
7345 	 * If sync, adjust the weight of prev_eff_load such that if
7346 	 * prev_eff == this_eff that select_idle_sibling() will consider
7347 	 * stacking the wakee on top of the waker if no other CPU is
7348 	 * idle.
7349 	 */
7350 	if (sync)
7351 		prev_eff_load += 1;
7352 
7353 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7354 }
7355 
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7356 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7357 		       int this_cpu, int prev_cpu, int sync)
7358 {
7359 	int target = nr_cpumask_bits;
7360 
7361 	if (sched_feat(WA_IDLE))
7362 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
7363 
7364 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7365 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7366 
7367 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7368 	if (target != this_cpu)
7369 		return prev_cpu;
7370 
7371 	schedstat_inc(sd->ttwu_move_affine);
7372 	schedstat_inc(p->stats.nr_wakeups_affine);
7373 	return target;
7374 }
7375 
7376 static struct sched_group *
7377 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7378 
7379 /*
7380  * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7381  */
7382 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7383 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7384 {
7385 	unsigned long load, min_load = ULONG_MAX;
7386 	unsigned int min_exit_latency = UINT_MAX;
7387 	u64 latest_idle_timestamp = 0;
7388 	int least_loaded_cpu = this_cpu;
7389 	int shallowest_idle_cpu = -1;
7390 	int i;
7391 
7392 	/* Check if we have any choice: */
7393 	if (group->group_weight == 1)
7394 		return cpumask_first(sched_group_span(group));
7395 
7396 	/* Traverse only the allowed CPUs */
7397 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7398 		struct rq *rq = cpu_rq(i);
7399 
7400 		if (!sched_core_cookie_match(rq, p))
7401 			continue;
7402 
7403 		if (sched_idle_cpu(i))
7404 			return i;
7405 
7406 		if (available_idle_cpu(i)) {
7407 			struct cpuidle_state *idle = idle_get_state(rq);
7408 			if (idle && idle->exit_latency < min_exit_latency) {
7409 				/*
7410 				 * We give priority to a CPU whose idle state
7411 				 * has the smallest exit latency irrespective
7412 				 * of any idle timestamp.
7413 				 */
7414 				min_exit_latency = idle->exit_latency;
7415 				latest_idle_timestamp = rq->idle_stamp;
7416 				shallowest_idle_cpu = i;
7417 			} else if ((!idle || idle->exit_latency == min_exit_latency) &&
7418 				   rq->idle_stamp > latest_idle_timestamp) {
7419 				/*
7420 				 * If equal or no active idle state, then
7421 				 * the most recently idled CPU might have
7422 				 * a warmer cache.
7423 				 */
7424 				latest_idle_timestamp = rq->idle_stamp;
7425 				shallowest_idle_cpu = i;
7426 			}
7427 		} else if (shallowest_idle_cpu == -1) {
7428 			load = cpu_load(cpu_rq(i));
7429 			if (load < min_load) {
7430 				min_load = load;
7431 				least_loaded_cpu = i;
7432 			}
7433 		}
7434 	}
7435 
7436 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7437 }
7438 
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7439 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7440 				  int cpu, int prev_cpu, int sd_flag)
7441 {
7442 	int new_cpu = cpu;
7443 
7444 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7445 		return prev_cpu;
7446 
7447 	/*
7448 	 * We need task's util for cpu_util_without, sync it up to
7449 	 * prev_cpu's last_update_time.
7450 	 */
7451 	if (!(sd_flag & SD_BALANCE_FORK))
7452 		sync_entity_load_avg(&p->se);
7453 
7454 	while (sd) {
7455 		struct sched_group *group;
7456 		struct sched_domain *tmp;
7457 		int weight;
7458 
7459 		if (!(sd->flags & sd_flag)) {
7460 			sd = sd->child;
7461 			continue;
7462 		}
7463 
7464 		group = sched_balance_find_dst_group(sd, p, cpu);
7465 		if (!group) {
7466 			sd = sd->child;
7467 			continue;
7468 		}
7469 
7470 		new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7471 		if (new_cpu == cpu) {
7472 			/* Now try balancing at a lower domain level of 'cpu': */
7473 			sd = sd->child;
7474 			continue;
7475 		}
7476 
7477 		/* Now try balancing at a lower domain level of 'new_cpu': */
7478 		cpu = new_cpu;
7479 		weight = sd->span_weight;
7480 		sd = NULL;
7481 		for_each_domain(cpu, tmp) {
7482 			if (weight <= tmp->span_weight)
7483 				break;
7484 			if (tmp->flags & sd_flag)
7485 				sd = tmp;
7486 		}
7487 	}
7488 
7489 	return new_cpu;
7490 }
7491 
__select_idle_cpu(int cpu,struct task_struct * p)7492 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7493 {
7494 	if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7495 	    sched_cpu_cookie_match(cpu_rq(cpu), p))
7496 		return cpu;
7497 
7498 	return -1;
7499 }
7500 
7501 #ifdef CONFIG_SCHED_SMT
7502 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7503 EXPORT_SYMBOL_GPL(sched_smt_present);
7504 
set_idle_cores(int cpu,int val)7505 static inline void set_idle_cores(int cpu, int val)
7506 {
7507 	struct sched_domain_shared *sds;
7508 
7509 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7510 	if (sds)
7511 		WRITE_ONCE(sds->has_idle_cores, val);
7512 }
7513 
test_idle_cores(int cpu)7514 static inline bool test_idle_cores(int cpu)
7515 {
7516 	struct sched_domain_shared *sds;
7517 
7518 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7519 	if (sds)
7520 		return READ_ONCE(sds->has_idle_cores);
7521 
7522 	return false;
7523 }
7524 
7525 /*
7526  * Scans the local SMT mask to see if the entire core is idle, and records this
7527  * information in sd_llc_shared->has_idle_cores.
7528  *
7529  * Since SMT siblings share all cache levels, inspecting this limited remote
7530  * state should be fairly cheap.
7531  */
__update_idle_core(struct rq * rq)7532 void __update_idle_core(struct rq *rq)
7533 {
7534 	int core = cpu_of(rq);
7535 	int cpu;
7536 
7537 	rcu_read_lock();
7538 	if (test_idle_cores(core))
7539 		goto unlock;
7540 
7541 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7542 		if (cpu == core)
7543 			continue;
7544 
7545 		if (!available_idle_cpu(cpu))
7546 			goto unlock;
7547 	}
7548 
7549 	set_idle_cores(core, 1);
7550 unlock:
7551 	rcu_read_unlock();
7552 }
7553 
7554 /*
7555  * Scan the entire LLC domain for idle cores; this dynamically switches off if
7556  * there are no idle cores left in the system; tracked through
7557  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7558  */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7559 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7560 {
7561 	bool idle = true;
7562 	int cpu;
7563 
7564 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7565 		if (!available_idle_cpu(cpu)) {
7566 			idle = false;
7567 			if (*idle_cpu == -1) {
7568 				if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7569 					*idle_cpu = cpu;
7570 					break;
7571 				}
7572 				continue;
7573 			}
7574 			break;
7575 		}
7576 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7577 			*idle_cpu = cpu;
7578 	}
7579 
7580 	if (idle)
7581 		return core;
7582 
7583 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7584 	return -1;
7585 }
7586 
7587 /*
7588  * Scan the local SMT mask for idle CPUs.
7589  */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7590 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7591 {
7592 	int cpu;
7593 
7594 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7595 		if (cpu == target)
7596 			continue;
7597 		/*
7598 		 * Check if the CPU is in the LLC scheduling domain of @target.
7599 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7600 		 */
7601 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7602 			continue;
7603 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7604 			return cpu;
7605 	}
7606 
7607 	return -1;
7608 }
7609 
7610 #else /* !CONFIG_SCHED_SMT: */
7611 
set_idle_cores(int cpu,int val)7612 static inline void set_idle_cores(int cpu, int val)
7613 {
7614 }
7615 
test_idle_cores(int cpu)7616 static inline bool test_idle_cores(int cpu)
7617 {
7618 	return false;
7619 }
7620 
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7621 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7622 {
7623 	return __select_idle_cpu(core, p);
7624 }
7625 
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7626 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7627 {
7628 	return -1;
7629 }
7630 
7631 #endif /* !CONFIG_SCHED_SMT */
7632 
7633 /*
7634  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7635  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7636  * average idle time for this rq (as found in rq->avg_idle).
7637  */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7638 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7639 {
7640 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7641 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
7642 	struct sched_domain_shared *sd_share;
7643 
7644 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7645 
7646 	if (sched_feat(SIS_UTIL)) {
7647 		sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7648 		if (sd_share) {
7649 			/* because !--nr is the condition to stop scan */
7650 			nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7651 			/* overloaded LLC is unlikely to have idle cpu/core */
7652 			if (nr == 1)
7653 				return -1;
7654 		}
7655 	}
7656 
7657 	if (static_branch_unlikely(&sched_cluster_active)) {
7658 		struct sched_group *sg = sd->groups;
7659 
7660 		if (sg->flags & SD_CLUSTER) {
7661 			for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7662 				if (!cpumask_test_cpu(cpu, cpus))
7663 					continue;
7664 
7665 				if (has_idle_core) {
7666 					i = select_idle_core(p, cpu, cpus, &idle_cpu);
7667 					if ((unsigned int)i < nr_cpumask_bits)
7668 						return i;
7669 				} else {
7670 					if (--nr <= 0)
7671 						return -1;
7672 					idle_cpu = __select_idle_cpu(cpu, p);
7673 					if ((unsigned int)idle_cpu < nr_cpumask_bits)
7674 						return idle_cpu;
7675 				}
7676 			}
7677 			cpumask_andnot(cpus, cpus, sched_group_span(sg));
7678 		}
7679 	}
7680 
7681 	for_each_cpu_wrap(cpu, cpus, target + 1) {
7682 		if (has_idle_core) {
7683 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
7684 			if ((unsigned int)i < nr_cpumask_bits)
7685 				return i;
7686 
7687 		} else {
7688 			if (--nr <= 0)
7689 				return -1;
7690 			idle_cpu = __select_idle_cpu(cpu, p);
7691 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
7692 				break;
7693 		}
7694 	}
7695 
7696 	if (has_idle_core)
7697 		set_idle_cores(target, false);
7698 
7699 	return idle_cpu;
7700 }
7701 
7702 /*
7703  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7704  * the task fits. If no CPU is big enough, but there are idle ones, try to
7705  * maximize capacity.
7706  */
7707 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7708 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7709 {
7710 	unsigned long task_util, util_min, util_max, best_cap = 0;
7711 	int fits, best_fits = 0;
7712 	int cpu, best_cpu = -1;
7713 	struct cpumask *cpus;
7714 
7715 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7716 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7717 
7718 	task_util = task_util_est(p);
7719 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
7720 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
7721 
7722 	for_each_cpu_wrap(cpu, cpus, target) {
7723 		unsigned long cpu_cap = capacity_of(cpu);
7724 
7725 		if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7726 			continue;
7727 
7728 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7729 
7730 		/* This CPU fits with all requirements */
7731 		if (fits > 0)
7732 			return cpu;
7733 		/*
7734 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7735 		 * Look for the CPU with best capacity.
7736 		 */
7737 		else if (fits < 0)
7738 			cpu_cap = get_actual_cpu_capacity(cpu);
7739 
7740 		/*
7741 		 * First, select CPU which fits better (-1 being better than 0).
7742 		 * Then, select the one with best capacity at same level.
7743 		 */
7744 		if ((fits < best_fits) ||
7745 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
7746 			best_cap = cpu_cap;
7747 			best_cpu = cpu;
7748 			best_fits = fits;
7749 		}
7750 	}
7751 
7752 	return best_cpu;
7753 }
7754 
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7755 static inline bool asym_fits_cpu(unsigned long util,
7756 				 unsigned long util_min,
7757 				 unsigned long util_max,
7758 				 int cpu)
7759 {
7760 	if (sched_asym_cpucap_active())
7761 		/*
7762 		 * Return true only if the cpu fully fits the task requirements
7763 		 * which include the utilization and the performance hints.
7764 		 */
7765 		return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7766 
7767 	return true;
7768 }
7769 
7770 /*
7771  * Try and locate an idle core/thread in the LLC cache domain.
7772  */
select_idle_sibling(struct task_struct * p,int prev,int target)7773 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7774 {
7775 	bool has_idle_core = false;
7776 	struct sched_domain *sd;
7777 	unsigned long task_util, util_min, util_max;
7778 	int i, recent_used_cpu, prev_aff = -1;
7779 
7780 	/*
7781 	 * On asymmetric system, update task utilization because we will check
7782 	 * that the task fits with CPU's capacity.
7783 	 */
7784 	if (sched_asym_cpucap_active()) {
7785 		sync_entity_load_avg(&p->se);
7786 		task_util = task_util_est(p);
7787 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
7788 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
7789 	}
7790 
7791 	/*
7792 	 * per-cpu select_rq_mask usage
7793 	 */
7794 	lockdep_assert_irqs_disabled();
7795 
7796 	if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7797 	    asym_fits_cpu(task_util, util_min, util_max, target))
7798 		return target;
7799 
7800 	/*
7801 	 * If the previous CPU is cache affine and idle, don't be stupid:
7802 	 */
7803 	if (prev != target && cpus_share_cache(prev, target) &&
7804 	    (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7805 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
7806 
7807 		if (!static_branch_unlikely(&sched_cluster_active) ||
7808 		    cpus_share_resources(prev, target))
7809 			return prev;
7810 
7811 		prev_aff = prev;
7812 	}
7813 
7814 	/*
7815 	 * Allow a per-cpu kthread to stack with the wakee if the
7816 	 * kworker thread and the tasks previous CPUs are the same.
7817 	 * The assumption is that the wakee queued work for the
7818 	 * per-cpu kthread that is now complete and the wakeup is
7819 	 * essentially a sync wakeup. An obvious example of this
7820 	 * pattern is IO completions.
7821 	 */
7822 	if (is_per_cpu_kthread(current) &&
7823 	    in_task() &&
7824 	    prev == smp_processor_id() &&
7825 	    this_rq()->nr_running <= 1 &&
7826 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
7827 		return prev;
7828 	}
7829 
7830 	/* Check a recently used CPU as a potential idle candidate: */
7831 	recent_used_cpu = p->recent_used_cpu;
7832 	p->recent_used_cpu = prev;
7833 	if (recent_used_cpu != prev &&
7834 	    recent_used_cpu != target &&
7835 	    cpus_share_cache(recent_used_cpu, target) &&
7836 	    (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7837 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7838 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7839 
7840 		if (!static_branch_unlikely(&sched_cluster_active) ||
7841 		    cpus_share_resources(recent_used_cpu, target))
7842 			return recent_used_cpu;
7843 
7844 	} else {
7845 		recent_used_cpu = -1;
7846 	}
7847 
7848 	/*
7849 	 * For asymmetric CPU capacity systems, our domain of interest is
7850 	 * sd_asym_cpucapacity rather than sd_llc.
7851 	 */
7852 	if (sched_asym_cpucap_active()) {
7853 		sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7854 		/*
7855 		 * On an asymmetric CPU capacity system where an exclusive
7856 		 * cpuset defines a symmetric island (i.e. one unique
7857 		 * capacity_orig value through the cpuset), the key will be set
7858 		 * but the CPUs within that cpuset will not have a domain with
7859 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7860 		 * capacity path.
7861 		 */
7862 		if (sd) {
7863 			i = select_idle_capacity(p, sd, target);
7864 			return ((unsigned)i < nr_cpumask_bits) ? i : target;
7865 		}
7866 	}
7867 
7868 	sd = rcu_dereference(per_cpu(sd_llc, target));
7869 	if (!sd)
7870 		return target;
7871 
7872 	if (sched_smt_active()) {
7873 		has_idle_core = test_idle_cores(target);
7874 
7875 		if (!has_idle_core && cpus_share_cache(prev, target)) {
7876 			i = select_idle_smt(p, sd, prev);
7877 			if ((unsigned int)i < nr_cpumask_bits)
7878 				return i;
7879 		}
7880 	}
7881 
7882 	i = select_idle_cpu(p, sd, has_idle_core, target);
7883 	if ((unsigned)i < nr_cpumask_bits)
7884 		return i;
7885 
7886 	/*
7887 	 * For cluster machines which have lower sharing cache like L2 or
7888 	 * LLC Tag, we tend to find an idle CPU in the target's cluster
7889 	 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7890 	 * use them if possible when no idle CPU found in select_idle_cpu().
7891 	 */
7892 	if ((unsigned int)prev_aff < nr_cpumask_bits)
7893 		return prev_aff;
7894 	if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7895 		return recent_used_cpu;
7896 
7897 	return target;
7898 }
7899 
7900 /**
7901  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7902  * @cpu: the CPU to get the utilization for
7903  * @p: task for which the CPU utilization should be predicted or NULL
7904  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7905  * @boost: 1 to enable boosting, otherwise 0
7906  *
7907  * The unit of the return value must be the same as the one of CPU capacity
7908  * so that CPU utilization can be compared with CPU capacity.
7909  *
7910  * CPU utilization is the sum of running time of runnable tasks plus the
7911  * recent utilization of currently non-runnable tasks on that CPU.
7912  * It represents the amount of CPU capacity currently used by CFS tasks in
7913  * the range [0..max CPU capacity] with max CPU capacity being the CPU
7914  * capacity at f_max.
7915  *
7916  * The estimated CPU utilization is defined as the maximum between CPU
7917  * utilization and sum of the estimated utilization of the currently
7918  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7919  * previously-executed tasks, which helps better deduce how busy a CPU will
7920  * be when a long-sleeping task wakes up. The contribution to CPU utilization
7921  * of such a task would be significantly decayed at this point of time.
7922  *
7923  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7924  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7925  * utilization. Boosting is implemented in cpu_util() so that internal
7926  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7927  * latter via cpu_util_cfs_boost().
7928  *
7929  * CPU utilization can be higher than the current CPU capacity
7930  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7931  * of rounding errors as well as task migrations or wakeups of new tasks.
7932  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7933  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7934  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7935  * capacity. CPU utilization is allowed to overshoot current CPU capacity
7936  * though since this is useful for predicting the CPU capacity required
7937  * after task migrations (scheduler-driven DVFS).
7938  *
7939  * Return: (Boosted) (estimated) utilization for the specified CPU.
7940  */
7941 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7942 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7943 {
7944 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7945 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7946 	unsigned long runnable;
7947 
7948 	if (boost) {
7949 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7950 		util = max(util, runnable);
7951 	}
7952 
7953 	/*
7954 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7955 	 * contribution. If @p migrates from another CPU to @cpu add its
7956 	 * contribution. In all the other cases @cpu is not impacted by the
7957 	 * migration so its util_avg is already correct.
7958 	 */
7959 	if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7960 		lsub_positive(&util, task_util(p));
7961 	else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7962 		util += task_util(p);
7963 
7964 	if (sched_feat(UTIL_EST)) {
7965 		unsigned long util_est;
7966 
7967 		util_est = READ_ONCE(cfs_rq->avg.util_est);
7968 
7969 		/*
7970 		 * During wake-up @p isn't enqueued yet and doesn't contribute
7971 		 * to any cpu_rq(cpu)->cfs.avg.util_est.
7972 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7973 		 * has been enqueued.
7974 		 *
7975 		 * During exec (@dst_cpu = -1) @p is enqueued and does
7976 		 * contribute to cpu_rq(cpu)->cfs.util_est.
7977 		 * Remove it to "simulate" cpu_util without @p's contribution.
7978 		 *
7979 		 * Despite the task_on_rq_queued(@p) check there is still a
7980 		 * small window for a possible race when an exec
7981 		 * select_task_rq_fair() races with LB's detach_task().
7982 		 *
7983 		 *   detach_task()
7984 		 *     deactivate_task()
7985 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
7986 		 *       -------------------------------- A
7987 		 *       dequeue_task()                    \
7988 		 *         dequeue_task_fair()              + Race Time
7989 		 *           util_est_dequeue()            /
7990 		 *       -------------------------------- B
7991 		 *
7992 		 * The additional check "current == p" is required to further
7993 		 * reduce the race window.
7994 		 */
7995 		if (dst_cpu == cpu)
7996 			util_est += _task_util_est(p);
7997 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
7998 			lsub_positive(&util_est, _task_util_est(p));
7999 
8000 		util = max(util, util_est);
8001 	}
8002 
8003 	return min(util, arch_scale_cpu_capacity(cpu));
8004 }
8005 
cpu_util_cfs(int cpu)8006 unsigned long cpu_util_cfs(int cpu)
8007 {
8008 	return cpu_util(cpu, NULL, -1, 0);
8009 }
8010 
cpu_util_cfs_boost(int cpu)8011 unsigned long cpu_util_cfs_boost(int cpu)
8012 {
8013 	return cpu_util(cpu, NULL, -1, 1);
8014 }
8015 
8016 /*
8017  * cpu_util_without: compute cpu utilization without any contributions from *p
8018  * @cpu: the CPU which utilization is requested
8019  * @p: the task which utilization should be discounted
8020  *
8021  * The utilization of a CPU is defined by the utilization of tasks currently
8022  * enqueued on that CPU as well as tasks which are currently sleeping after an
8023  * execution on that CPU.
8024  *
8025  * This method returns the utilization of the specified CPU by discounting the
8026  * utilization of the specified task, whenever the task is currently
8027  * contributing to the CPU utilization.
8028  */
cpu_util_without(int cpu,struct task_struct * p)8029 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8030 {
8031 	/* Task has no contribution or is new */
8032 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8033 		p = NULL;
8034 
8035 	return cpu_util(cpu, p, -1, 0);
8036 }
8037 
8038 /*
8039  * This function computes an effective utilization for the given CPU, to be
8040  * used for frequency selection given the linear relation: f = u * f_max.
8041  *
8042  * The scheduler tracks the following metrics:
8043  *
8044  *   cpu_util_{cfs,rt,dl,irq}()
8045  *   cpu_bw_dl()
8046  *
8047  * Where the cfs,rt and dl util numbers are tracked with the same metric and
8048  * synchronized windows and are thus directly comparable.
8049  *
8050  * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8051  * which excludes things like IRQ and steal-time. These latter are then accrued
8052  * in the IRQ utilization.
8053  *
8054  * The DL bandwidth number OTOH is not a measured metric but a value computed
8055  * based on the task model parameters and gives the minimal utilization
8056  * required to meet deadlines.
8057  */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8058 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8059 				 unsigned long *min,
8060 				 unsigned long *max)
8061 {
8062 	unsigned long util, irq, scale;
8063 	struct rq *rq = cpu_rq(cpu);
8064 
8065 	scale = arch_scale_cpu_capacity(cpu);
8066 
8067 	/*
8068 	 * Early check to see if IRQ/steal time saturates the CPU, can be
8069 	 * because of inaccuracies in how we track these -- see
8070 	 * update_irq_load_avg().
8071 	 */
8072 	irq = cpu_util_irq(rq);
8073 	if (unlikely(irq >= scale)) {
8074 		if (min)
8075 			*min = scale;
8076 		if (max)
8077 			*max = scale;
8078 		return scale;
8079 	}
8080 
8081 	if (min) {
8082 		/*
8083 		 * The minimum utilization returns the highest level between:
8084 		 * - the computed DL bandwidth needed with the IRQ pressure which
8085 		 *   steals time to the deadline task.
8086 		 * - The minimum performance requirement for CFS and/or RT.
8087 		 */
8088 		*min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8089 
8090 		/*
8091 		 * When an RT task is runnable and uclamp is not used, we must
8092 		 * ensure that the task will run at maximum compute capacity.
8093 		 */
8094 		if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8095 			*min = max(*min, scale);
8096 	}
8097 
8098 	/*
8099 	 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8100 	 * CFS tasks and we use the same metric to track the effective
8101 	 * utilization (PELT windows are synchronized) we can directly add them
8102 	 * to obtain the CPU's actual utilization.
8103 	 */
8104 	util = util_cfs + cpu_util_rt(rq);
8105 	util += cpu_util_dl(rq);
8106 
8107 	/*
8108 	 * The maximum hint is a soft bandwidth requirement, which can be lower
8109 	 * than the actual utilization because of uclamp_max requirements.
8110 	 */
8111 	if (max)
8112 		*max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8113 
8114 	if (util >= scale)
8115 		return scale;
8116 
8117 	/*
8118 	 * There is still idle time; further improve the number by using the
8119 	 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8120 	 * need to scale the task numbers:
8121 	 *
8122 	 *              max - irq
8123 	 *   U' = irq + --------- * U
8124 	 *                 max
8125 	 */
8126 	util = scale_irq_capacity(util, irq, scale);
8127 	util += irq;
8128 
8129 	return min(scale, util);
8130 }
8131 
sched_cpu_util(int cpu)8132 unsigned long sched_cpu_util(int cpu)
8133 {
8134 	return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8135 }
8136 
8137 /*
8138  * energy_env - Utilization landscape for energy estimation.
8139  * @task_busy_time: Utilization contribution by the task for which we test the
8140  *                  placement. Given by eenv_task_busy_time().
8141  * @pd_busy_time:   Utilization of the whole perf domain without the task
8142  *                  contribution. Given by eenv_pd_busy_time().
8143  * @cpu_cap:        Maximum CPU capacity for the perf domain.
8144  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8145  */
8146 struct energy_env {
8147 	unsigned long task_busy_time;
8148 	unsigned long pd_busy_time;
8149 	unsigned long cpu_cap;
8150 	unsigned long pd_cap;
8151 };
8152 
8153 /*
8154  * Compute the task busy time for compute_energy(). This time cannot be
8155  * injected directly into effective_cpu_util() because of the IRQ scaling.
8156  * The latter only makes sense with the most recent CPUs where the task has
8157  * run.
8158  */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8159 static inline void eenv_task_busy_time(struct energy_env *eenv,
8160 				       struct task_struct *p, int prev_cpu)
8161 {
8162 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8163 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8164 
8165 	if (unlikely(irq >= max_cap))
8166 		busy_time = max_cap;
8167 	else
8168 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8169 
8170 	eenv->task_busy_time = busy_time;
8171 }
8172 
8173 /*
8174  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8175  * utilization for each @pd_cpus, it however doesn't take into account
8176  * clamping since the ratio (utilization / cpu_capacity) is already enough to
8177  * scale the EM reported power consumption at the (eventually clamped)
8178  * cpu_capacity.
8179  *
8180  * The contribution of the task @p for which we want to estimate the
8181  * energy cost is removed (by cpu_util()) and must be calculated
8182  * separately (see eenv_task_busy_time). This ensures:
8183  *
8184  *   - A stable PD utilization, no matter which CPU of that PD we want to place
8185  *     the task on.
8186  *
8187  *   - A fair comparison between CPUs as the task contribution (task_util())
8188  *     will always be the same no matter which CPU utilization we rely on
8189  *     (util_avg or util_est).
8190  *
8191  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8192  * exceed @eenv->pd_cap.
8193  */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8194 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8195 				     struct cpumask *pd_cpus,
8196 				     struct task_struct *p)
8197 {
8198 	unsigned long busy_time = 0;
8199 	int cpu;
8200 
8201 	for_each_cpu(cpu, pd_cpus) {
8202 		unsigned long util = cpu_util(cpu, p, -1, 0);
8203 
8204 		busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8205 	}
8206 
8207 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8208 }
8209 
8210 /*
8211  * Compute the maximum utilization for compute_energy() when the task @p
8212  * is placed on the cpu @dst_cpu.
8213  *
8214  * Returns the maximum utilization among @eenv->cpus. This utilization can't
8215  * exceed @eenv->cpu_cap.
8216  */
8217 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8218 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8219 		 struct task_struct *p, int dst_cpu)
8220 {
8221 	unsigned long max_util = 0;
8222 	int cpu;
8223 
8224 	for_each_cpu(cpu, pd_cpus) {
8225 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8226 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8227 		unsigned long eff_util, min, max;
8228 
8229 		/*
8230 		 * Performance domain frequency: utilization clamping
8231 		 * must be considered since it affects the selection
8232 		 * of the performance domain frequency.
8233 		 * NOTE: in case RT tasks are running, by default the min
8234 		 * utilization can be max OPP.
8235 		 */
8236 		eff_util = effective_cpu_util(cpu, util, &min, &max);
8237 
8238 		/* Task's uclamp can modify min and max value */
8239 		if (tsk && uclamp_is_used()) {
8240 			min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8241 
8242 			/*
8243 			 * If there is no active max uclamp constraint,
8244 			 * directly use task's one, otherwise keep max.
8245 			 */
8246 			if (uclamp_rq_is_idle(cpu_rq(cpu)))
8247 				max = uclamp_eff_value(p, UCLAMP_MAX);
8248 			else
8249 				max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8250 		}
8251 
8252 		eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8253 		max_util = max(max_util, eff_util);
8254 	}
8255 
8256 	return min(max_util, eenv->cpu_cap);
8257 }
8258 
8259 /*
8260  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8261  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8262  * contribution is ignored.
8263  */
8264 static inline unsigned long
compute_energy(struct energy_env * eenv,struct perf_domain * pd,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8265 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8266 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8267 {
8268 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8269 	unsigned long busy_time = eenv->pd_busy_time;
8270 	unsigned long energy;
8271 
8272 	if (dst_cpu >= 0)
8273 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8274 
8275 	energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8276 
8277 	trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8278 
8279 	return energy;
8280 }
8281 
8282 /*
8283  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8284  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8285  * spare capacity in each performance domain and uses it as a potential
8286  * candidate to execute the task. Then, it uses the Energy Model to figure
8287  * out which of the CPU candidates is the most energy-efficient.
8288  *
8289  * The rationale for this heuristic is as follows. In a performance domain,
8290  * all the most energy efficient CPU candidates (according to the Energy
8291  * Model) are those for which we'll request a low frequency. When there are
8292  * several CPUs for which the frequency request will be the same, we don't
8293  * have enough data to break the tie between them, because the Energy Model
8294  * only includes active power costs. With this model, if we assume that
8295  * frequency requests follow utilization (e.g. using schedutil), the CPU with
8296  * the maximum spare capacity in a performance domain is guaranteed to be among
8297  * the best candidates of the performance domain.
8298  *
8299  * In practice, it could be preferable from an energy standpoint to pack
8300  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8301  * but that could also hurt our chances to go cluster idle, and we have no
8302  * ways to tell with the current Energy Model if this is actually a good
8303  * idea or not. So, find_energy_efficient_cpu() basically favors
8304  * cluster-packing, and spreading inside a cluster. That should at least be
8305  * a good thing for latency, and this is consistent with the idea that most
8306  * of the energy savings of EAS come from the asymmetry of the system, and
8307  * not so much from breaking the tie between identical CPUs. That's also the
8308  * reason why EAS is enabled in the topology code only for systems where
8309  * SD_ASYM_CPUCAPACITY is set.
8310  *
8311  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8312  * they don't have any useful utilization data yet and it's not possible to
8313  * forecast their impact on energy consumption. Consequently, they will be
8314  * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8315  * to be energy-inefficient in some use-cases. The alternative would be to
8316  * bias new tasks towards specific types of CPUs first, or to try to infer
8317  * their util_avg from the parent task, but those heuristics could hurt
8318  * other use-cases too. So, until someone finds a better way to solve this,
8319  * let's keep things simple by re-using the existing slow path.
8320  */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8321 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8322 {
8323 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8324 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8325 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8326 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8327 	struct root_domain *rd = this_rq()->rd;
8328 	int cpu, best_energy_cpu, target = -1;
8329 	int prev_fits = -1, best_fits = -1;
8330 	unsigned long best_actual_cap = 0;
8331 	unsigned long prev_actual_cap = 0;
8332 	struct sched_domain *sd;
8333 	struct perf_domain *pd;
8334 	struct energy_env eenv;
8335 
8336 	rcu_read_lock();
8337 	pd = rcu_dereference(rd->pd);
8338 	if (!pd)
8339 		goto unlock;
8340 
8341 	/*
8342 	 * Energy-aware wake-up happens on the lowest sched_domain starting
8343 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8344 	 */
8345 	sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8346 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8347 		sd = sd->parent;
8348 	if (!sd)
8349 		goto unlock;
8350 
8351 	target = prev_cpu;
8352 
8353 	sync_entity_load_avg(&p->se);
8354 	if (!task_util_est(p) && p_util_min == 0)
8355 		goto unlock;
8356 
8357 	eenv_task_busy_time(&eenv, p, prev_cpu);
8358 
8359 	for (; pd; pd = pd->next) {
8360 		unsigned long util_min = p_util_min, util_max = p_util_max;
8361 		unsigned long cpu_cap, cpu_actual_cap, util;
8362 		long prev_spare_cap = -1, max_spare_cap = -1;
8363 		unsigned long rq_util_min, rq_util_max;
8364 		unsigned long cur_delta, base_energy;
8365 		int max_spare_cap_cpu = -1;
8366 		int fits, max_fits = -1;
8367 
8368 		cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8369 
8370 		if (cpumask_empty(cpus))
8371 			continue;
8372 
8373 		/* Account external pressure for the energy estimation */
8374 		cpu = cpumask_first(cpus);
8375 		cpu_actual_cap = get_actual_cpu_capacity(cpu);
8376 
8377 		eenv.cpu_cap = cpu_actual_cap;
8378 		eenv.pd_cap = 0;
8379 
8380 		for_each_cpu(cpu, cpus) {
8381 			struct rq *rq = cpu_rq(cpu);
8382 
8383 			eenv.pd_cap += cpu_actual_cap;
8384 
8385 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8386 				continue;
8387 
8388 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8389 				continue;
8390 
8391 			util = cpu_util(cpu, p, cpu, 0);
8392 			cpu_cap = capacity_of(cpu);
8393 
8394 			/*
8395 			 * Skip CPUs that cannot satisfy the capacity request.
8396 			 * IOW, placing the task there would make the CPU
8397 			 * overutilized. Take uclamp into account to see how
8398 			 * much capacity we can get out of the CPU; this is
8399 			 * aligned with sched_cpu_util().
8400 			 */
8401 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8402 				/*
8403 				 * Open code uclamp_rq_util_with() except for
8404 				 * the clamp() part. I.e.: apply max aggregation
8405 				 * only. util_fits_cpu() logic requires to
8406 				 * operate on non clamped util but must use the
8407 				 * max-aggregated uclamp_{min, max}.
8408 				 */
8409 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8410 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8411 
8412 				util_min = max(rq_util_min, p_util_min);
8413 				util_max = max(rq_util_max, p_util_max);
8414 			}
8415 
8416 			fits = util_fits_cpu(util, util_min, util_max, cpu);
8417 			if (!fits)
8418 				continue;
8419 
8420 			lsub_positive(&cpu_cap, util);
8421 
8422 			if (cpu == prev_cpu) {
8423 				/* Always use prev_cpu as a candidate. */
8424 				prev_spare_cap = cpu_cap;
8425 				prev_fits = fits;
8426 			} else if ((fits > max_fits) ||
8427 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8428 				/*
8429 				 * Find the CPU with the maximum spare capacity
8430 				 * among the remaining CPUs in the performance
8431 				 * domain.
8432 				 */
8433 				max_spare_cap = cpu_cap;
8434 				max_spare_cap_cpu = cpu;
8435 				max_fits = fits;
8436 			}
8437 		}
8438 
8439 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8440 			continue;
8441 
8442 		eenv_pd_busy_time(&eenv, cpus, p);
8443 		/* Compute the 'base' energy of the pd, without @p */
8444 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8445 
8446 		/* Evaluate the energy impact of using prev_cpu. */
8447 		if (prev_spare_cap > -1) {
8448 			prev_delta = compute_energy(&eenv, pd, cpus, p,
8449 						    prev_cpu);
8450 			/* CPU utilization has changed */
8451 			if (prev_delta < base_energy)
8452 				goto unlock;
8453 			prev_delta -= base_energy;
8454 			prev_actual_cap = cpu_actual_cap;
8455 			best_delta = min(best_delta, prev_delta);
8456 		}
8457 
8458 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
8459 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8460 			/* Current best energy cpu fits better */
8461 			if (max_fits < best_fits)
8462 				continue;
8463 
8464 			/*
8465 			 * Both don't fit performance hint (i.e. uclamp_min)
8466 			 * but best energy cpu has better capacity.
8467 			 */
8468 			if ((max_fits < 0) &&
8469 			    (cpu_actual_cap <= best_actual_cap))
8470 				continue;
8471 
8472 			cur_delta = compute_energy(&eenv, pd, cpus, p,
8473 						   max_spare_cap_cpu);
8474 			/* CPU utilization has changed */
8475 			if (cur_delta < base_energy)
8476 				goto unlock;
8477 			cur_delta -= base_energy;
8478 
8479 			/*
8480 			 * Both fit for the task but best energy cpu has lower
8481 			 * energy impact.
8482 			 */
8483 			if ((max_fits > 0) && (best_fits > 0) &&
8484 			    (cur_delta >= best_delta))
8485 				continue;
8486 
8487 			best_delta = cur_delta;
8488 			best_energy_cpu = max_spare_cap_cpu;
8489 			best_fits = max_fits;
8490 			best_actual_cap = cpu_actual_cap;
8491 		}
8492 	}
8493 	rcu_read_unlock();
8494 
8495 	if ((best_fits > prev_fits) ||
8496 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
8497 	    ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8498 		target = best_energy_cpu;
8499 
8500 	return target;
8501 
8502 unlock:
8503 	rcu_read_unlock();
8504 
8505 	return target;
8506 }
8507 
8508 /*
8509  * select_task_rq_fair: Select target runqueue for the waking task in domains
8510  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8511  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8512  *
8513  * Balances load by selecting the idlest CPU in the idlest group, or under
8514  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8515  *
8516  * Returns the target CPU number.
8517  */
8518 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8519 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8520 {
8521 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8522 	struct sched_domain *tmp, *sd = NULL;
8523 	int cpu = smp_processor_id();
8524 	int new_cpu = prev_cpu;
8525 	int want_affine = 0;
8526 	/* SD_flags and WF_flags share the first nibble */
8527 	int sd_flag = wake_flags & 0xF;
8528 
8529 	/*
8530 	 * required for stable ->cpus_allowed
8531 	 */
8532 	lockdep_assert_held(&p->pi_lock);
8533 	if (wake_flags & WF_TTWU) {
8534 		record_wakee(p);
8535 
8536 		if ((wake_flags & WF_CURRENT_CPU) &&
8537 		    cpumask_test_cpu(cpu, p->cpus_ptr))
8538 			return cpu;
8539 
8540 		if (!is_rd_overutilized(this_rq()->rd)) {
8541 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8542 			if (new_cpu >= 0)
8543 				return new_cpu;
8544 			new_cpu = prev_cpu;
8545 		}
8546 
8547 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8548 	}
8549 
8550 	rcu_read_lock();
8551 	for_each_domain(cpu, tmp) {
8552 		/*
8553 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
8554 		 * cpu is a valid SD_WAKE_AFFINE target.
8555 		 */
8556 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8557 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8558 			if (cpu != prev_cpu)
8559 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8560 
8561 			sd = NULL; /* Prefer wake_affine over balance flags */
8562 			break;
8563 		}
8564 
8565 		/*
8566 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8567 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8568 		 * will usually go to the fast path.
8569 		 */
8570 		if (tmp->flags & sd_flag)
8571 			sd = tmp;
8572 		else if (!want_affine)
8573 			break;
8574 	}
8575 
8576 	if (unlikely(sd)) {
8577 		/* Slow path */
8578 		new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8579 	} else if (wake_flags & WF_TTWU) { /* XXX always ? */
8580 		/* Fast path */
8581 		new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8582 	}
8583 	rcu_read_unlock();
8584 
8585 	return new_cpu;
8586 }
8587 
8588 /*
8589  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8590  * cfs_rq_of(p) references at time of call are still valid and identify the
8591  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8592  */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8593 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8594 {
8595 	struct sched_entity *se = &p->se;
8596 
8597 	if (!task_on_rq_migrating(p)) {
8598 		remove_entity_load_avg(se);
8599 
8600 		/*
8601 		 * Here, the task's PELT values have been updated according to
8602 		 * the current rq's clock. But if that clock hasn't been
8603 		 * updated in a while, a substantial idle time will be missed,
8604 		 * leading to an inflation after wake-up on the new rq.
8605 		 *
8606 		 * Estimate the missing time from the cfs_rq last_update_time
8607 		 * and update sched_avg to improve the PELT continuity after
8608 		 * migration.
8609 		 */
8610 		migrate_se_pelt_lag(se);
8611 	}
8612 
8613 	/* Tell new CPU we are migrated */
8614 	se->avg.last_update_time = 0;
8615 
8616 	update_scan_period(p, new_cpu);
8617 }
8618 
task_dead_fair(struct task_struct * p)8619 static void task_dead_fair(struct task_struct *p)
8620 {
8621 	struct sched_entity *se = &p->se;
8622 
8623 	if (se->sched_delayed) {
8624 		struct rq_flags rf;
8625 		struct rq *rq;
8626 
8627 		rq = task_rq_lock(p, &rf);
8628 		if (se->sched_delayed) {
8629 			update_rq_clock(rq);
8630 			dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8631 		}
8632 		task_rq_unlock(rq, p, &rf);
8633 	}
8634 
8635 	remove_entity_load_avg(se);
8636 }
8637 
8638 /*
8639  * Set the max capacity the task is allowed to run at for misfit detection.
8640  */
set_task_max_allowed_capacity(struct task_struct * p)8641 static void set_task_max_allowed_capacity(struct task_struct *p)
8642 {
8643 	struct asym_cap_data *entry;
8644 
8645 	if (!sched_asym_cpucap_active())
8646 		return;
8647 
8648 	rcu_read_lock();
8649 	list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8650 		cpumask_t *cpumask;
8651 
8652 		cpumask = cpu_capacity_span(entry);
8653 		if (!cpumask_intersects(p->cpus_ptr, cpumask))
8654 			continue;
8655 
8656 		p->max_allowed_capacity = entry->capacity;
8657 		break;
8658 	}
8659 	rcu_read_unlock();
8660 }
8661 
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8662 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8663 {
8664 	set_cpus_allowed_common(p, ctx);
8665 	set_task_max_allowed_capacity(p);
8666 }
8667 
set_next_buddy(struct sched_entity * se)8668 static void set_next_buddy(struct sched_entity *se)
8669 {
8670 	for_each_sched_entity(se) {
8671 		if (WARN_ON_ONCE(!se->on_rq))
8672 			return;
8673 		if (se_is_idle(se))
8674 			return;
8675 		cfs_rq_of(se)->next = se;
8676 	}
8677 }
8678 
8679 enum preempt_wakeup_action {
8680 	PREEMPT_WAKEUP_NONE,	/* No preemption. */
8681 	PREEMPT_WAKEUP_SHORT,	/* Ignore slice protection. */
8682 	PREEMPT_WAKEUP_PICK,	/* Let __pick_eevdf() decide. */
8683 	PREEMPT_WAKEUP_RESCHED,	/* Force reschedule. */
8684 };
8685 
8686 static inline bool
set_preempt_buddy(struct cfs_rq * cfs_rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8687 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags,
8688 		  struct sched_entity *pse, struct sched_entity *se)
8689 {
8690 	/*
8691 	 * Keep existing buddy if the deadline is sooner than pse.
8692 	 * The older buddy may be cache cold and completely unrelated
8693 	 * to the current wakeup but that is unpredictable where as
8694 	 * obeying the deadline is more in line with EEVDF objectives.
8695 	 */
8696 	if (cfs_rq->next && entity_before(cfs_rq->next, pse))
8697 		return false;
8698 
8699 	set_next_buddy(pse);
8700 	return true;
8701 }
8702 
8703 /*
8704  * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
8705  * strictly enforced because the hint is either misunderstood or
8706  * multiple tasks must be woken up.
8707  */
8708 static inline enum preempt_wakeup_action
preempt_sync(struct rq * rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8709 preempt_sync(struct rq *rq, int wake_flags,
8710 	     struct sched_entity *pse, struct sched_entity *se)
8711 {
8712 	u64 threshold, delta;
8713 
8714 	/*
8715 	 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
8716 	 * though it is likely harmless.
8717 	 */
8718 	WARN_ON_ONCE(!(wake_flags & WF_TTWU));
8719 
8720 	threshold = sysctl_sched_migration_cost;
8721 	delta = rq_clock_task(rq) - se->exec_start;
8722 	if ((s64)delta < 0)
8723 		delta = 0;
8724 
8725 	/*
8726 	 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
8727 	 * could run on other CPUs. Reduce the threshold before preemption is
8728 	 * allowed to an arbitrary lower value as it is more likely (but not
8729 	 * guaranteed) the waker requires the wakee to finish.
8730 	 */
8731 	if (wake_flags & WF_RQ_SELECTED)
8732 		threshold >>= 2;
8733 
8734 	/*
8735 	 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
8736 	 * wakeups to be issued.
8737 	 */
8738 	if (entity_before(pse, se) && delta >= threshold)
8739 		return PREEMPT_WAKEUP_RESCHED;
8740 
8741 	return PREEMPT_WAKEUP_NONE;
8742 }
8743 
8744 /*
8745  * Preempt the current task with a newly woken task if needed:
8746  */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8747 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8748 {
8749 	enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
8750 	struct task_struct *donor = rq->donor;
8751 	struct sched_entity *se = &donor->se, *pse = &p->se;
8752 	struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8753 	int cse_is_idle, pse_is_idle;
8754 
8755 	if (unlikely(se == pse))
8756 		return;
8757 
8758 	/*
8759 	 * This is possible from callers such as attach_tasks(), in which we
8760 	 * unconditionally wakeup_preempt() after an enqueue (which may have
8761 	 * lead to a throttle).  This both saves work and prevents false
8762 	 * next-buddy nomination below.
8763 	 */
8764 	if (task_is_throttled(p))
8765 		return;
8766 
8767 	/*
8768 	 * We can come here with TIF_NEED_RESCHED already set from new task
8769 	 * wake up path.
8770 	 *
8771 	 * Note: this also catches the edge-case of curr being in a throttled
8772 	 * group (e.g. via set_curr_task), since update_curr() (in the
8773 	 * enqueue of curr) will have resulted in resched being set.  This
8774 	 * prevents us from potentially nominating it as a false LAST_BUDDY
8775 	 * below.
8776 	 */
8777 	if (test_tsk_need_resched(rq->curr))
8778 		return;
8779 
8780 	if (!sched_feat(WAKEUP_PREEMPTION))
8781 		return;
8782 
8783 	find_matching_se(&se, &pse);
8784 	WARN_ON_ONCE(!pse);
8785 
8786 	cse_is_idle = se_is_idle(se);
8787 	pse_is_idle = se_is_idle(pse);
8788 
8789 	/*
8790 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8791 	 * in the inverse case).
8792 	 */
8793 	if (cse_is_idle && !pse_is_idle) {
8794 		/*
8795 		 * When non-idle entity preempt an idle entity,
8796 		 * don't give idle entity slice protection.
8797 		 */
8798 		preempt_action = PREEMPT_WAKEUP_SHORT;
8799 		goto preempt;
8800 	}
8801 
8802 	if (cse_is_idle != pse_is_idle)
8803 		return;
8804 
8805 	/*
8806 	 * BATCH and IDLE tasks do not preempt others.
8807 	 */
8808 	if (unlikely(!normal_policy(p->policy)))
8809 		return;
8810 
8811 	cfs_rq = cfs_rq_of(se);
8812 	update_curr(cfs_rq);
8813 	/*
8814 	 * If @p has a shorter slice than current and @p is eligible, override
8815 	 * current's slice protection in order to allow preemption.
8816 	 */
8817 	if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
8818 		preempt_action = PREEMPT_WAKEUP_SHORT;
8819 		goto pick;
8820 	}
8821 
8822 	/*
8823 	 * Ignore wakee preemption on WF_FORK as it is less likely that
8824 	 * there is shared data as exec often follow fork. Do not
8825 	 * preempt for tasks that are sched_delayed as it would violate
8826 	 * EEVDF to forcibly queue an ineligible task.
8827 	 */
8828 	if ((wake_flags & WF_FORK) || pse->sched_delayed)
8829 		return;
8830 
8831 	/* Prefer picking wakee soon if appropriate. */
8832 	if (sched_feat(NEXT_BUDDY) &&
8833 	    set_preempt_buddy(cfs_rq, wake_flags, pse, se)) {
8834 
8835 		/*
8836 		 * Decide whether to obey WF_SYNC hint for a new buddy. Old
8837 		 * buddies are ignored as they may not be relevant to the
8838 		 * waker and less likely to be cache hot.
8839 		 */
8840 		if (wake_flags & WF_SYNC)
8841 			preempt_action = preempt_sync(rq, wake_flags, pse, se);
8842 	}
8843 
8844 	switch (preempt_action) {
8845 	case PREEMPT_WAKEUP_NONE:
8846 		return;
8847 	case PREEMPT_WAKEUP_RESCHED:
8848 		goto preempt;
8849 	case PREEMPT_WAKEUP_SHORT:
8850 		fallthrough;
8851 	case PREEMPT_WAKEUP_PICK:
8852 		break;
8853 	}
8854 
8855 pick:
8856 	/*
8857 	 * If @p has become the most eligible task, force preemption.
8858 	 */
8859 	if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse)
8860 		goto preempt;
8861 
8862 	if (sched_feat(RUN_TO_PARITY))
8863 		update_protect_slice(cfs_rq, se);
8864 
8865 	return;
8866 
8867 preempt:
8868 	if (preempt_action == PREEMPT_WAKEUP_SHORT)
8869 		cancel_protect_slice(se);
8870 
8871 	resched_curr_lazy(rq);
8872 }
8873 
pick_task_fair(struct rq * rq,struct rq_flags * rf)8874 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
8875 {
8876 	struct sched_entity *se;
8877 	struct cfs_rq *cfs_rq;
8878 	struct task_struct *p;
8879 	bool throttled;
8880 
8881 again:
8882 	cfs_rq = &rq->cfs;
8883 	if (!cfs_rq->nr_queued)
8884 		return NULL;
8885 
8886 	throttled = false;
8887 
8888 	do {
8889 		/* Might not have done put_prev_entity() */
8890 		if (cfs_rq->curr && cfs_rq->curr->on_rq)
8891 			update_curr(cfs_rq);
8892 
8893 		throttled |= check_cfs_rq_runtime(cfs_rq);
8894 
8895 		se = pick_next_entity(rq, cfs_rq);
8896 		if (!se)
8897 			goto again;
8898 		cfs_rq = group_cfs_rq(se);
8899 	} while (cfs_rq);
8900 
8901 	p = task_of(se);
8902 	if (unlikely(throttled))
8903 		task_throttle_setup_work(p);
8904 	return p;
8905 }
8906 
8907 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8908 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8909 
8910 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8911 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8912 {
8913 	struct sched_entity *se;
8914 	struct task_struct *p;
8915 	int new_tasks;
8916 
8917 again:
8918 	p = pick_task_fair(rq, rf);
8919 	if (!p)
8920 		goto idle;
8921 	se = &p->se;
8922 
8923 #ifdef CONFIG_FAIR_GROUP_SCHED
8924 	if (prev->sched_class != &fair_sched_class)
8925 		goto simple;
8926 
8927 	__put_prev_set_next_dl_server(rq, prev, p);
8928 
8929 	/*
8930 	 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8931 	 * likely that a next task is from the same cgroup as the current.
8932 	 *
8933 	 * Therefore attempt to avoid putting and setting the entire cgroup
8934 	 * hierarchy, only change the part that actually changes.
8935 	 *
8936 	 * Since we haven't yet done put_prev_entity and if the selected task
8937 	 * is a different task than we started out with, try and touch the
8938 	 * least amount of cfs_rqs.
8939 	 */
8940 	if (prev != p) {
8941 		struct sched_entity *pse = &prev->se;
8942 		struct cfs_rq *cfs_rq;
8943 
8944 		while (!(cfs_rq = is_same_group(se, pse))) {
8945 			int se_depth = se->depth;
8946 			int pse_depth = pse->depth;
8947 
8948 			if (se_depth <= pse_depth) {
8949 				put_prev_entity(cfs_rq_of(pse), pse);
8950 				pse = parent_entity(pse);
8951 			}
8952 			if (se_depth >= pse_depth) {
8953 				set_next_entity(cfs_rq_of(se), se);
8954 				se = parent_entity(se);
8955 			}
8956 		}
8957 
8958 		put_prev_entity(cfs_rq, pse);
8959 		set_next_entity(cfs_rq, se);
8960 
8961 		__set_next_task_fair(rq, p, true);
8962 	}
8963 
8964 	return p;
8965 
8966 simple:
8967 #endif /* CONFIG_FAIR_GROUP_SCHED */
8968 	put_prev_set_next_task(rq, prev, p);
8969 	return p;
8970 
8971 idle:
8972 	if (rf) {
8973 		new_tasks = sched_balance_newidle(rq, rf);
8974 
8975 		/*
8976 		 * Because sched_balance_newidle() releases (and re-acquires)
8977 		 * rq->lock, it is possible for any higher priority task to
8978 		 * appear. In that case we must re-start the pick_next_entity()
8979 		 * loop.
8980 		 */
8981 		if (new_tasks < 0)
8982 			return RETRY_TASK;
8983 
8984 		if (new_tasks > 0)
8985 			goto again;
8986 	}
8987 
8988 	return NULL;
8989 }
8990 
8991 static struct task_struct *
fair_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)8992 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
8993 {
8994 	return pick_task_fair(dl_se->rq, rf);
8995 }
8996 
fair_server_init(struct rq * rq)8997 void fair_server_init(struct rq *rq)
8998 {
8999 	struct sched_dl_entity *dl_se = &rq->fair_server;
9000 
9001 	init_dl_entity(dl_se);
9002 
9003 	dl_server_init(dl_se, rq, fair_server_pick_task);
9004 }
9005 
9006 /*
9007  * Account for a descheduled task:
9008  */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)9009 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9010 {
9011 	struct sched_entity *se = &prev->se;
9012 	struct cfs_rq *cfs_rq;
9013 
9014 	for_each_sched_entity(se) {
9015 		cfs_rq = cfs_rq_of(se);
9016 		put_prev_entity(cfs_rq, se);
9017 	}
9018 }
9019 
9020 /*
9021  * sched_yield() is very simple
9022  */
yield_task_fair(struct rq * rq)9023 static void yield_task_fair(struct rq *rq)
9024 {
9025 	struct task_struct *curr = rq->donor;
9026 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9027 	struct sched_entity *se = &curr->se;
9028 
9029 	/*
9030 	 * Are we the only task in the tree?
9031 	 */
9032 	if (unlikely(rq->nr_running == 1))
9033 		return;
9034 
9035 	clear_buddies(cfs_rq, se);
9036 
9037 	update_rq_clock(rq);
9038 	/*
9039 	 * Update run-time statistics of the 'current'.
9040 	 */
9041 	update_curr(cfs_rq);
9042 	/*
9043 	 * Tell update_rq_clock() that we've just updated,
9044 	 * so we don't do microscopic update in schedule()
9045 	 * and double the fastpath cost.
9046 	 */
9047 	rq_clock_skip_update(rq);
9048 
9049 	/*
9050 	 * Forfeit the remaining vruntime, only if the entity is eligible. This
9051 	 * condition is necessary because in core scheduling we prefer to run
9052 	 * ineligible tasks rather than force idling. If this happens we may
9053 	 * end up in a loop where the core scheduler picks the yielding task,
9054 	 * which yields immediately again; without the condition the vruntime
9055 	 * ends up quickly running away.
9056 	 */
9057 	if (entity_eligible(cfs_rq, se)) {
9058 		se->vruntime = se->deadline;
9059 		se->deadline += calc_delta_fair(se->slice, se);
9060 	}
9061 }
9062 
yield_to_task_fair(struct rq * rq,struct task_struct * p)9063 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9064 {
9065 	struct sched_entity *se = &p->se;
9066 
9067 	/* !se->on_rq also covers throttled task */
9068 	if (!se->on_rq)
9069 		return false;
9070 
9071 	/* Tell the scheduler that we'd really like se to run next. */
9072 	set_next_buddy(se);
9073 
9074 	yield_task_fair(rq);
9075 
9076 	return true;
9077 }
9078 
9079 /**************************************************
9080  * Fair scheduling class load-balancing methods.
9081  *
9082  * BASICS
9083  *
9084  * The purpose of load-balancing is to achieve the same basic fairness the
9085  * per-CPU scheduler provides, namely provide a proportional amount of compute
9086  * time to each task. This is expressed in the following equation:
9087  *
9088  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
9089  *
9090  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9091  * W_i,0 is defined as:
9092  *
9093  *   W_i,0 = \Sum_j w_i,j                                             (2)
9094  *
9095  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9096  * is derived from the nice value as per sched_prio_to_weight[].
9097  *
9098  * The weight average is an exponential decay average of the instantaneous
9099  * weight:
9100  *
9101  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
9102  *
9103  * C_i is the compute capacity of CPU i, typically it is the
9104  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9105  * can also include other factors [XXX].
9106  *
9107  * To achieve this balance we define a measure of imbalance which follows
9108  * directly from (1):
9109  *
9110  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
9111  *
9112  * We them move tasks around to minimize the imbalance. In the continuous
9113  * function space it is obvious this converges, in the discrete case we get
9114  * a few fun cases generally called infeasible weight scenarios.
9115  *
9116  * [XXX expand on:
9117  *     - infeasible weights;
9118  *     - local vs global optima in the discrete case. ]
9119  *
9120  *
9121  * SCHED DOMAINS
9122  *
9123  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9124  * for all i,j solution, we create a tree of CPUs that follows the hardware
9125  * topology where each level pairs two lower groups (or better). This results
9126  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9127  * tree to only the first of the previous level and we decrease the frequency
9128  * of load-balance at each level inversely proportional to the number of CPUs in
9129  * the groups.
9130  *
9131  * This yields:
9132  *
9133  *     log_2 n     1     n
9134  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
9135  *     i = 0      2^i   2^i
9136  *                               `- size of each group
9137  *         |         |     `- number of CPUs doing load-balance
9138  *         |         `- freq
9139  *         `- sum over all levels
9140  *
9141  * Coupled with a limit on how many tasks we can migrate every balance pass,
9142  * this makes (5) the runtime complexity of the balancer.
9143  *
9144  * An important property here is that each CPU is still (indirectly) connected
9145  * to every other CPU in at most O(log n) steps:
9146  *
9147  * The adjacency matrix of the resulting graph is given by:
9148  *
9149  *             log_2 n
9150  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
9151  *             k = 0
9152  *
9153  * And you'll find that:
9154  *
9155  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
9156  *
9157  * Showing there's indeed a path between every CPU in at most O(log n) steps.
9158  * The task movement gives a factor of O(m), giving a convergence complexity
9159  * of:
9160  *
9161  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
9162  *
9163  *
9164  * WORK CONSERVING
9165  *
9166  * In order to avoid CPUs going idle while there's still work to do, new idle
9167  * balancing is more aggressive and has the newly idle CPU iterate up the domain
9168  * tree itself instead of relying on other CPUs to bring it work.
9169  *
9170  * This adds some complexity to both (5) and (8) but it reduces the total idle
9171  * time.
9172  *
9173  * [XXX more?]
9174  *
9175  *
9176  * CGROUPS
9177  *
9178  * Cgroups make a horror show out of (2), instead of a simple sum we get:
9179  *
9180  *                                s_k,i
9181  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
9182  *                                 S_k
9183  *
9184  * Where
9185  *
9186  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
9187  *
9188  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9189  *
9190  * The big problem is S_k, its a global sum needed to compute a local (W_i)
9191  * property.
9192  *
9193  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9194  *      rewrite all of this once again.]
9195  */
9196 
9197 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9198 
9199 enum fbq_type { regular, remote, all };
9200 
9201 /*
9202  * 'group_type' describes the group of CPUs at the moment of load balancing.
9203  *
9204  * The enum is ordered by pulling priority, with the group with lowest priority
9205  * first so the group_type can simply be compared when selecting the busiest
9206  * group. See update_sd_pick_busiest().
9207  */
9208 enum group_type {
9209 	/* The group has spare capacity that can be used to run more tasks.  */
9210 	group_has_spare = 0,
9211 	/*
9212 	 * The group is fully used and the tasks don't compete for more CPU
9213 	 * cycles. Nevertheless, some tasks might wait before running.
9214 	 */
9215 	group_fully_busy,
9216 	/*
9217 	 * One task doesn't fit with CPU's capacity and must be migrated to a
9218 	 * more powerful CPU.
9219 	 */
9220 	group_misfit_task,
9221 	/*
9222 	 * Balance SMT group that's fully busy. Can benefit from migration
9223 	 * a task on SMT with busy sibling to another CPU on idle core.
9224 	 */
9225 	group_smt_balance,
9226 	/*
9227 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9228 	 * and the task should be migrated to it instead of running on the
9229 	 * current CPU.
9230 	 */
9231 	group_asym_packing,
9232 	/*
9233 	 * The tasks' affinity constraints previously prevented the scheduler
9234 	 * from balancing the load across the system.
9235 	 */
9236 	group_imbalanced,
9237 	/*
9238 	 * The CPU is overloaded and can't provide expected CPU cycles to all
9239 	 * tasks.
9240 	 */
9241 	group_overloaded
9242 };
9243 
9244 enum migration_type {
9245 	migrate_load = 0,
9246 	migrate_util,
9247 	migrate_task,
9248 	migrate_misfit
9249 };
9250 
9251 #define LBF_ALL_PINNED	0x01
9252 #define LBF_NEED_BREAK	0x02
9253 #define LBF_DST_PINNED  0x04
9254 #define LBF_SOME_PINNED	0x08
9255 #define LBF_ACTIVE_LB	0x10
9256 
9257 struct lb_env {
9258 	struct sched_domain	*sd;
9259 
9260 	struct rq		*src_rq;
9261 	int			src_cpu;
9262 
9263 	int			dst_cpu;
9264 	struct rq		*dst_rq;
9265 
9266 	struct cpumask		*dst_grpmask;
9267 	int			new_dst_cpu;
9268 	enum cpu_idle_type	idle;
9269 	long			imbalance;
9270 	/* The set of CPUs under consideration for load-balancing */
9271 	struct cpumask		*cpus;
9272 
9273 	unsigned int		flags;
9274 
9275 	unsigned int		loop;
9276 	unsigned int		loop_break;
9277 	unsigned int		loop_max;
9278 
9279 	enum fbq_type		fbq_type;
9280 	enum migration_type	migration_type;
9281 	struct list_head	tasks;
9282 };
9283 
9284 /*
9285  * Is this task likely cache-hot:
9286  */
task_hot(struct task_struct * p,struct lb_env * env)9287 static int task_hot(struct task_struct *p, struct lb_env *env)
9288 {
9289 	s64 delta;
9290 
9291 	lockdep_assert_rq_held(env->src_rq);
9292 
9293 	if (p->sched_class != &fair_sched_class)
9294 		return 0;
9295 
9296 	if (unlikely(task_has_idle_policy(p)))
9297 		return 0;
9298 
9299 	/* SMT siblings share cache */
9300 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9301 		return 0;
9302 
9303 	/*
9304 	 * Buddy candidates are cache hot:
9305 	 */
9306 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9307 	    (&p->se == cfs_rq_of(&p->se)->next))
9308 		return 1;
9309 
9310 	if (sysctl_sched_migration_cost == -1)
9311 		return 1;
9312 
9313 	/*
9314 	 * Don't migrate task if the task's cookie does not match
9315 	 * with the destination CPU's core cookie.
9316 	 */
9317 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9318 		return 1;
9319 
9320 	if (sysctl_sched_migration_cost == 0)
9321 		return 0;
9322 
9323 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9324 
9325 	return delta < (s64)sysctl_sched_migration_cost;
9326 }
9327 
9328 #ifdef CONFIG_NUMA_BALANCING
9329 /*
9330  * Returns a positive value, if task migration degrades locality.
9331  * Returns 0, if task migration is not affected by locality.
9332  * Returns a negative value, if task migration improves locality i.e migration preferred.
9333  */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9334 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9335 {
9336 	struct numa_group *numa_group = rcu_dereference(p->numa_group);
9337 	unsigned long src_weight, dst_weight;
9338 	int src_nid, dst_nid, dist;
9339 
9340 	if (!static_branch_likely(&sched_numa_balancing))
9341 		return 0;
9342 
9343 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9344 		return 0;
9345 
9346 	src_nid = cpu_to_node(env->src_cpu);
9347 	dst_nid = cpu_to_node(env->dst_cpu);
9348 
9349 	if (src_nid == dst_nid)
9350 		return 0;
9351 
9352 	/* Migrating away from the preferred node is always bad. */
9353 	if (src_nid == p->numa_preferred_nid) {
9354 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9355 			return 1;
9356 		else
9357 			return 0;
9358 	}
9359 
9360 	/* Encourage migration to the preferred node. */
9361 	if (dst_nid == p->numa_preferred_nid)
9362 		return -1;
9363 
9364 	/* Leaving a core idle is often worse than degrading locality. */
9365 	if (env->idle == CPU_IDLE)
9366 		return 0;
9367 
9368 	dist = node_distance(src_nid, dst_nid);
9369 	if (numa_group) {
9370 		src_weight = group_weight(p, src_nid, dist);
9371 		dst_weight = group_weight(p, dst_nid, dist);
9372 	} else {
9373 		src_weight = task_weight(p, src_nid, dist);
9374 		dst_weight = task_weight(p, dst_nid, dist);
9375 	}
9376 
9377 	return src_weight - dst_weight;
9378 }
9379 
9380 #else /* !CONFIG_NUMA_BALANCING: */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9381 static inline long migrate_degrades_locality(struct task_struct *p,
9382 					     struct lb_env *env)
9383 {
9384 	return 0;
9385 }
9386 #endif /* !CONFIG_NUMA_BALANCING */
9387 
9388 /*
9389  * Check whether the task is ineligible on the destination cpu
9390  *
9391  * When the PLACE_LAG scheduling feature is enabled and
9392  * dst_cfs_rq->nr_queued is greater than 1, if the task
9393  * is ineligible, it will also be ineligible when
9394  * it is migrated to the destination cpu.
9395  */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9396 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9397 {
9398 	struct cfs_rq *dst_cfs_rq;
9399 
9400 #ifdef CONFIG_FAIR_GROUP_SCHED
9401 	dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9402 #else
9403 	dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9404 #endif
9405 	if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9406 	    !entity_eligible(task_cfs_rq(p), &p->se))
9407 		return 1;
9408 
9409 	return 0;
9410 }
9411 
9412 /*
9413  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9414  */
9415 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9416 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9417 {
9418 	long degrades, hot;
9419 
9420 	lockdep_assert_rq_held(env->src_rq);
9421 	if (p->sched_task_hot)
9422 		p->sched_task_hot = 0;
9423 
9424 	/*
9425 	 * We do not migrate tasks that are:
9426 	 * 1) delayed dequeued unless we migrate load, or
9427 	 * 2) target cfs_rq is in throttled hierarchy, or
9428 	 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9429 	 * 4) running (obviously), or
9430 	 * 5) are cache-hot on their current CPU, or
9431 	 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9432 	 */
9433 	if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9434 		return 0;
9435 
9436 	if (lb_throttled_hierarchy(p, env->dst_cpu))
9437 		return 0;
9438 
9439 	/*
9440 	 * We want to prioritize the migration of eligible tasks.
9441 	 * For ineligible tasks we soft-limit them and only allow
9442 	 * them to migrate when nr_balance_failed is non-zero to
9443 	 * avoid load-balancing trying very hard to balance the load.
9444 	 */
9445 	if (!env->sd->nr_balance_failed &&
9446 	    task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9447 		return 0;
9448 
9449 	/* Disregard percpu kthreads; they are where they need to be. */
9450 	if (kthread_is_per_cpu(p))
9451 		return 0;
9452 
9453 	if (task_is_blocked(p))
9454 		return 0;
9455 
9456 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9457 		int cpu;
9458 
9459 		schedstat_inc(p->stats.nr_failed_migrations_affine);
9460 
9461 		env->flags |= LBF_SOME_PINNED;
9462 
9463 		/*
9464 		 * Remember if this task can be migrated to any other CPU in
9465 		 * our sched_group. We may want to revisit it if we couldn't
9466 		 * meet load balance goals by pulling other tasks on src_cpu.
9467 		 *
9468 		 * Avoid computing new_dst_cpu
9469 		 * - for NEWLY_IDLE
9470 		 * - if we have already computed one in current iteration
9471 		 * - if it's an active balance
9472 		 */
9473 		if (env->idle == CPU_NEWLY_IDLE ||
9474 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9475 			return 0;
9476 
9477 		/* Prevent to re-select dst_cpu via env's CPUs: */
9478 		cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
9479 
9480 		if (cpu < nr_cpu_ids) {
9481 			env->flags |= LBF_DST_PINNED;
9482 			env->new_dst_cpu = cpu;
9483 		}
9484 
9485 		return 0;
9486 	}
9487 
9488 	/* Record that we found at least one task that could run on dst_cpu */
9489 	env->flags &= ~LBF_ALL_PINNED;
9490 
9491 	if (task_on_cpu(env->src_rq, p) ||
9492 	    task_current_donor(env->src_rq, p)) {
9493 		schedstat_inc(p->stats.nr_failed_migrations_running);
9494 		return 0;
9495 	}
9496 
9497 	/*
9498 	 * Aggressive migration if:
9499 	 * 1) active balance
9500 	 * 2) destination numa is preferred
9501 	 * 3) task is cache cold, or
9502 	 * 4) too many balance attempts have failed.
9503 	 */
9504 	if (env->flags & LBF_ACTIVE_LB)
9505 		return 1;
9506 
9507 	degrades = migrate_degrades_locality(p, env);
9508 	if (!degrades)
9509 		hot = task_hot(p, env);
9510 	else
9511 		hot = degrades > 0;
9512 
9513 	if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9514 		if (hot)
9515 			p->sched_task_hot = 1;
9516 		return 1;
9517 	}
9518 
9519 	schedstat_inc(p->stats.nr_failed_migrations_hot);
9520 	return 0;
9521 }
9522 
9523 /*
9524  * detach_task() -- detach the task for the migration specified in env
9525  */
detach_task(struct task_struct * p,struct lb_env * env)9526 static void detach_task(struct task_struct *p, struct lb_env *env)
9527 {
9528 	lockdep_assert_rq_held(env->src_rq);
9529 
9530 	if (p->sched_task_hot) {
9531 		p->sched_task_hot = 0;
9532 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9533 		schedstat_inc(p->stats.nr_forced_migrations);
9534 	}
9535 
9536 	WARN_ON(task_current(env->src_rq, p));
9537 	WARN_ON(task_current_donor(env->src_rq, p));
9538 
9539 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9540 	set_task_cpu(p, env->dst_cpu);
9541 }
9542 
9543 /*
9544  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9545  * part of active balancing operations within "domain".
9546  *
9547  * Returns a task if successful and NULL otherwise.
9548  */
detach_one_task(struct lb_env * env)9549 static struct task_struct *detach_one_task(struct lb_env *env)
9550 {
9551 	struct task_struct *p;
9552 
9553 	lockdep_assert_rq_held(env->src_rq);
9554 
9555 	list_for_each_entry_reverse(p,
9556 			&env->src_rq->cfs_tasks, se.group_node) {
9557 		if (!can_migrate_task(p, env))
9558 			continue;
9559 
9560 		detach_task(p, env);
9561 
9562 		/*
9563 		 * Right now, this is only the second place where
9564 		 * lb_gained[env->idle] is updated (other is detach_tasks)
9565 		 * so we can safely collect stats here rather than
9566 		 * inside detach_tasks().
9567 		 */
9568 		schedstat_inc(env->sd->lb_gained[env->idle]);
9569 		return p;
9570 	}
9571 	return NULL;
9572 }
9573 
9574 /*
9575  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9576  * busiest_rq, as part of a balancing operation within domain "sd".
9577  *
9578  * Returns number of detached tasks if successful and 0 otherwise.
9579  */
detach_tasks(struct lb_env * env)9580 static int detach_tasks(struct lb_env *env)
9581 {
9582 	struct list_head *tasks = &env->src_rq->cfs_tasks;
9583 	unsigned long util, load;
9584 	struct task_struct *p;
9585 	int detached = 0;
9586 
9587 	lockdep_assert_rq_held(env->src_rq);
9588 
9589 	/*
9590 	 * Source run queue has been emptied by another CPU, clear
9591 	 * LBF_ALL_PINNED flag as we will not test any task.
9592 	 */
9593 	if (env->src_rq->nr_running <= 1) {
9594 		env->flags &= ~LBF_ALL_PINNED;
9595 		return 0;
9596 	}
9597 
9598 	if (env->imbalance <= 0)
9599 		return 0;
9600 
9601 	while (!list_empty(tasks)) {
9602 		/*
9603 		 * We don't want to steal all, otherwise we may be treated likewise,
9604 		 * which could at worst lead to a livelock crash.
9605 		 */
9606 		if (env->idle && env->src_rq->nr_running <= 1)
9607 			break;
9608 
9609 		env->loop++;
9610 		/* We've more or less seen every task there is, call it quits */
9611 		if (env->loop > env->loop_max)
9612 			break;
9613 
9614 		/* take a breather every nr_migrate tasks */
9615 		if (env->loop > env->loop_break) {
9616 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
9617 			env->flags |= LBF_NEED_BREAK;
9618 			break;
9619 		}
9620 
9621 		p = list_last_entry(tasks, struct task_struct, se.group_node);
9622 
9623 		if (!can_migrate_task(p, env))
9624 			goto next;
9625 
9626 		switch (env->migration_type) {
9627 		case migrate_load:
9628 			/*
9629 			 * Depending of the number of CPUs and tasks and the
9630 			 * cgroup hierarchy, task_h_load() can return a null
9631 			 * value. Make sure that env->imbalance decreases
9632 			 * otherwise detach_tasks() will stop only after
9633 			 * detaching up to loop_max tasks.
9634 			 */
9635 			load = max_t(unsigned long, task_h_load(p), 1);
9636 
9637 			if (sched_feat(LB_MIN) &&
9638 			    load < 16 && !env->sd->nr_balance_failed)
9639 				goto next;
9640 
9641 			/*
9642 			 * Make sure that we don't migrate too much load.
9643 			 * Nevertheless, let relax the constraint if
9644 			 * scheduler fails to find a good waiting task to
9645 			 * migrate.
9646 			 */
9647 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9648 				goto next;
9649 
9650 			env->imbalance -= load;
9651 			break;
9652 
9653 		case migrate_util:
9654 			util = task_util_est(p);
9655 
9656 			if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9657 				goto next;
9658 
9659 			env->imbalance -= util;
9660 			break;
9661 
9662 		case migrate_task:
9663 			env->imbalance--;
9664 			break;
9665 
9666 		case migrate_misfit:
9667 			/* This is not a misfit task */
9668 			if (task_fits_cpu(p, env->src_cpu))
9669 				goto next;
9670 
9671 			env->imbalance = 0;
9672 			break;
9673 		}
9674 
9675 		detach_task(p, env);
9676 		list_add(&p->se.group_node, &env->tasks);
9677 
9678 		detached++;
9679 
9680 #ifdef CONFIG_PREEMPTION
9681 		/*
9682 		 * NEWIDLE balancing is a source of latency, so preemptible
9683 		 * kernels will stop after the first task is detached to minimize
9684 		 * the critical section.
9685 		 */
9686 		if (env->idle == CPU_NEWLY_IDLE)
9687 			break;
9688 #endif
9689 
9690 		/*
9691 		 * We only want to steal up to the prescribed amount of
9692 		 * load/util/tasks.
9693 		 */
9694 		if (env->imbalance <= 0)
9695 			break;
9696 
9697 		continue;
9698 next:
9699 		if (p->sched_task_hot)
9700 			schedstat_inc(p->stats.nr_failed_migrations_hot);
9701 
9702 		list_move(&p->se.group_node, tasks);
9703 	}
9704 
9705 	/*
9706 	 * Right now, this is one of only two places we collect this stat
9707 	 * so we can safely collect detach_one_task() stats here rather
9708 	 * than inside detach_one_task().
9709 	 */
9710 	schedstat_add(env->sd->lb_gained[env->idle], detached);
9711 
9712 	return detached;
9713 }
9714 
9715 /*
9716  * attach_task() -- attach the task detached by detach_task() to its new rq.
9717  */
attach_task(struct rq * rq,struct task_struct * p)9718 static void attach_task(struct rq *rq, struct task_struct *p)
9719 {
9720 	lockdep_assert_rq_held(rq);
9721 
9722 	WARN_ON_ONCE(task_rq(p) != rq);
9723 	activate_task(rq, p, ENQUEUE_NOCLOCK);
9724 	wakeup_preempt(rq, p, 0);
9725 }
9726 
9727 /*
9728  * attach_one_task() -- attaches the task returned from detach_one_task() to
9729  * its new rq.
9730  */
attach_one_task(struct rq * rq,struct task_struct * p)9731 static void attach_one_task(struct rq *rq, struct task_struct *p)
9732 {
9733 	struct rq_flags rf;
9734 
9735 	rq_lock(rq, &rf);
9736 	update_rq_clock(rq);
9737 	attach_task(rq, p);
9738 	rq_unlock(rq, &rf);
9739 }
9740 
9741 /*
9742  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9743  * new rq.
9744  */
attach_tasks(struct lb_env * env)9745 static void attach_tasks(struct lb_env *env)
9746 {
9747 	struct list_head *tasks = &env->tasks;
9748 	struct task_struct *p;
9749 	struct rq_flags rf;
9750 
9751 	rq_lock(env->dst_rq, &rf);
9752 	update_rq_clock(env->dst_rq);
9753 
9754 	while (!list_empty(tasks)) {
9755 		p = list_first_entry(tasks, struct task_struct, se.group_node);
9756 		list_del_init(&p->se.group_node);
9757 
9758 		attach_task(env->dst_rq, p);
9759 	}
9760 
9761 	rq_unlock(env->dst_rq, &rf);
9762 }
9763 
9764 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9765 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9766 {
9767 	if (cfs_rq->avg.load_avg)
9768 		return true;
9769 
9770 	if (cfs_rq->avg.util_avg)
9771 		return true;
9772 
9773 	return false;
9774 }
9775 
others_have_blocked(struct rq * rq)9776 static inline bool others_have_blocked(struct rq *rq)
9777 {
9778 	if (cpu_util_rt(rq))
9779 		return true;
9780 
9781 	if (cpu_util_dl(rq))
9782 		return true;
9783 
9784 	if (hw_load_avg(rq))
9785 		return true;
9786 
9787 	if (cpu_util_irq(rq))
9788 		return true;
9789 
9790 	return false;
9791 }
9792 
update_blocked_load_tick(struct rq * rq)9793 static inline void update_blocked_load_tick(struct rq *rq)
9794 {
9795 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9796 }
9797 
update_blocked_load_status(struct rq * rq,bool has_blocked)9798 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9799 {
9800 	if (!has_blocked)
9801 		rq->has_blocked_load = 0;
9802 }
9803 #else /* !CONFIG_NO_HZ_COMMON: */
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9804 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9805 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9806 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9807 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9808 #endif /* !CONFIG_NO_HZ_COMMON */
9809 
__update_blocked_others(struct rq * rq,bool * done)9810 static bool __update_blocked_others(struct rq *rq, bool *done)
9811 {
9812 	bool updated;
9813 
9814 	/*
9815 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9816 	 * DL and IRQ signals have been updated before updating CFS.
9817 	 */
9818 	updated = update_other_load_avgs(rq);
9819 
9820 	if (others_have_blocked(rq))
9821 		*done = false;
9822 
9823 	return updated;
9824 }
9825 
9826 #ifdef CONFIG_FAIR_GROUP_SCHED
9827 
__update_blocked_fair(struct rq * rq,bool * done)9828 static bool __update_blocked_fair(struct rq *rq, bool *done)
9829 {
9830 	struct cfs_rq *cfs_rq, *pos;
9831 	bool decayed = false;
9832 	int cpu = cpu_of(rq);
9833 
9834 	/*
9835 	 * Iterates the task_group tree in a bottom up fashion, see
9836 	 * list_add_leaf_cfs_rq() for details.
9837 	 */
9838 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9839 		struct sched_entity *se;
9840 
9841 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9842 			update_tg_load_avg(cfs_rq);
9843 
9844 			if (cfs_rq->nr_queued == 0)
9845 				update_idle_cfs_rq_clock_pelt(cfs_rq);
9846 
9847 			if (cfs_rq == &rq->cfs)
9848 				decayed = true;
9849 		}
9850 
9851 		/* Propagate pending load changes to the parent, if any: */
9852 		se = cfs_rq->tg->se[cpu];
9853 		if (se && !skip_blocked_update(se))
9854 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9855 
9856 		/*
9857 		 * There can be a lot of idle CPU cgroups.  Don't let fully
9858 		 * decayed cfs_rqs linger on the list.
9859 		 */
9860 		if (cfs_rq_is_decayed(cfs_rq))
9861 			list_del_leaf_cfs_rq(cfs_rq);
9862 
9863 		/* Don't need periodic decay once load/util_avg are null */
9864 		if (cfs_rq_has_blocked(cfs_rq))
9865 			*done = false;
9866 	}
9867 
9868 	return decayed;
9869 }
9870 
9871 /*
9872  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9873  * This needs to be done in a top-down fashion because the load of a child
9874  * group is a fraction of its parents load.
9875  */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9876 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9877 {
9878 	struct rq *rq = rq_of(cfs_rq);
9879 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9880 	unsigned long now = jiffies;
9881 	unsigned long load;
9882 
9883 	if (cfs_rq->last_h_load_update == now)
9884 		return;
9885 
9886 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
9887 	for_each_sched_entity(se) {
9888 		cfs_rq = cfs_rq_of(se);
9889 		WRITE_ONCE(cfs_rq->h_load_next, se);
9890 		if (cfs_rq->last_h_load_update == now)
9891 			break;
9892 	}
9893 
9894 	if (!se) {
9895 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9896 		cfs_rq->last_h_load_update = now;
9897 	}
9898 
9899 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9900 		load = cfs_rq->h_load;
9901 		load = div64_ul(load * se->avg.load_avg,
9902 			cfs_rq_load_avg(cfs_rq) + 1);
9903 		cfs_rq = group_cfs_rq(se);
9904 		cfs_rq->h_load = load;
9905 		cfs_rq->last_h_load_update = now;
9906 	}
9907 }
9908 
task_h_load(struct task_struct * p)9909 static unsigned long task_h_load(struct task_struct *p)
9910 {
9911 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
9912 
9913 	update_cfs_rq_h_load(cfs_rq);
9914 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9915 			cfs_rq_load_avg(cfs_rq) + 1);
9916 }
9917 #else /* !CONFIG_FAIR_GROUP_SCHED: */
__update_blocked_fair(struct rq * rq,bool * done)9918 static bool __update_blocked_fair(struct rq *rq, bool *done)
9919 {
9920 	struct cfs_rq *cfs_rq = &rq->cfs;
9921 	bool decayed;
9922 
9923 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9924 	if (cfs_rq_has_blocked(cfs_rq))
9925 		*done = false;
9926 
9927 	return decayed;
9928 }
9929 
task_h_load(struct task_struct * p)9930 static unsigned long task_h_load(struct task_struct *p)
9931 {
9932 	return p->se.avg.load_avg;
9933 }
9934 #endif /* !CONFIG_FAIR_GROUP_SCHED */
9935 
sched_balance_update_blocked_averages(int cpu)9936 static void sched_balance_update_blocked_averages(int cpu)
9937 {
9938 	bool decayed = false, done = true;
9939 	struct rq *rq = cpu_rq(cpu);
9940 	struct rq_flags rf;
9941 
9942 	rq_lock_irqsave(rq, &rf);
9943 	update_blocked_load_tick(rq);
9944 	update_rq_clock(rq);
9945 
9946 	decayed |= __update_blocked_others(rq, &done);
9947 	decayed |= __update_blocked_fair(rq, &done);
9948 
9949 	update_blocked_load_status(rq, !done);
9950 	if (decayed)
9951 		cpufreq_update_util(rq, 0);
9952 	rq_unlock_irqrestore(rq, &rf);
9953 }
9954 
9955 /********** Helpers for sched_balance_find_src_group ************************/
9956 
9957 /*
9958  * sg_lb_stats - stats of a sched_group required for load-balancing:
9959  */
9960 struct sg_lb_stats {
9961 	unsigned long avg_load;			/* Avg load            over the CPUs of the group */
9962 	unsigned long group_load;		/* Total load          over the CPUs of the group */
9963 	unsigned long group_capacity;		/* Capacity            over the CPUs of the group */
9964 	unsigned long group_util;		/* Total utilization   over the CPUs of the group */
9965 	unsigned long group_runnable;		/* Total runnable time over the CPUs of the group */
9966 	unsigned int sum_nr_running;		/* Nr of all tasks running in the group */
9967 	unsigned int sum_h_nr_running;		/* Nr of CFS tasks running in the group */
9968 	unsigned int idle_cpus;                 /* Nr of idle CPUs         in the group */
9969 	unsigned int group_weight;
9970 	enum group_type group_type;
9971 	unsigned int group_asym_packing;	/* Tasks should be moved to preferred CPU */
9972 	unsigned int group_smt_balance;		/* Task on busy SMT be moved */
9973 	unsigned long group_misfit_task_load;	/* A CPU has a task too big for its capacity */
9974 #ifdef CONFIG_NUMA_BALANCING
9975 	unsigned int nr_numa_running;
9976 	unsigned int nr_preferred_running;
9977 #endif
9978 };
9979 
9980 /*
9981  * sd_lb_stats - stats of a sched_domain required for load-balancing:
9982  */
9983 struct sd_lb_stats {
9984 	struct sched_group *busiest;		/* Busiest group in this sd */
9985 	struct sched_group *local;		/* Local group in this sd */
9986 	unsigned long total_load;		/* Total load of all groups in sd */
9987 	unsigned long total_capacity;		/* Total capacity of all groups in sd */
9988 	unsigned long avg_load;			/* Average load across all groups in sd */
9989 	unsigned int prefer_sibling;		/* Tasks should go to sibling first */
9990 
9991 	struct sg_lb_stats busiest_stat;	/* Statistics of the busiest group */
9992 	struct sg_lb_stats local_stat;		/* Statistics of the local group */
9993 };
9994 
init_sd_lb_stats(struct sd_lb_stats * sds)9995 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9996 {
9997 	/*
9998 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9999 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10000 	 * We must however set busiest_stat::group_type and
10001 	 * busiest_stat::idle_cpus to the worst busiest group because
10002 	 * update_sd_pick_busiest() reads these before assignment.
10003 	 */
10004 	*sds = (struct sd_lb_stats){
10005 		.busiest = NULL,
10006 		.local = NULL,
10007 		.total_load = 0UL,
10008 		.total_capacity = 0UL,
10009 		.busiest_stat = {
10010 			.idle_cpus = UINT_MAX,
10011 			.group_type = group_has_spare,
10012 		},
10013 	};
10014 }
10015 
scale_rt_capacity(int cpu)10016 static unsigned long scale_rt_capacity(int cpu)
10017 {
10018 	unsigned long max = get_actual_cpu_capacity(cpu);
10019 	struct rq *rq = cpu_rq(cpu);
10020 	unsigned long used, free;
10021 	unsigned long irq;
10022 
10023 	irq = cpu_util_irq(rq);
10024 
10025 	if (unlikely(irq >= max))
10026 		return 1;
10027 
10028 	/*
10029 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10030 	 * (running and not running) with weights 0 and 1024 respectively.
10031 	 */
10032 	used = cpu_util_rt(rq);
10033 	used += cpu_util_dl(rq);
10034 
10035 	if (unlikely(used >= max))
10036 		return 1;
10037 
10038 	free = max - used;
10039 
10040 	return scale_irq_capacity(free, irq, max);
10041 }
10042 
update_cpu_capacity(struct sched_domain * sd,int cpu)10043 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10044 {
10045 	unsigned long capacity = scale_rt_capacity(cpu);
10046 	struct sched_group *sdg = sd->groups;
10047 
10048 	if (!capacity)
10049 		capacity = 1;
10050 
10051 	cpu_rq(cpu)->cpu_capacity = capacity;
10052 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10053 
10054 	sdg->sgc->capacity = capacity;
10055 	sdg->sgc->min_capacity = capacity;
10056 	sdg->sgc->max_capacity = capacity;
10057 }
10058 
update_group_capacity(struct sched_domain * sd,int cpu)10059 void update_group_capacity(struct sched_domain *sd, int cpu)
10060 {
10061 	struct sched_domain *child = sd->child;
10062 	struct sched_group *group, *sdg = sd->groups;
10063 	unsigned long capacity, min_capacity, max_capacity;
10064 	unsigned long interval;
10065 
10066 	interval = msecs_to_jiffies(sd->balance_interval);
10067 	interval = clamp(interval, 1UL, max_load_balance_interval);
10068 	sdg->sgc->next_update = jiffies + interval;
10069 
10070 	if (!child) {
10071 		update_cpu_capacity(sd, cpu);
10072 		return;
10073 	}
10074 
10075 	capacity = 0;
10076 	min_capacity = ULONG_MAX;
10077 	max_capacity = 0;
10078 
10079 	if (child->flags & SD_NUMA) {
10080 		/*
10081 		 * SD_NUMA domains cannot assume that child groups
10082 		 * span the current group.
10083 		 */
10084 
10085 		for_each_cpu(cpu, sched_group_span(sdg)) {
10086 			unsigned long cpu_cap = capacity_of(cpu);
10087 
10088 			capacity += cpu_cap;
10089 			min_capacity = min(cpu_cap, min_capacity);
10090 			max_capacity = max(cpu_cap, max_capacity);
10091 		}
10092 	} else  {
10093 		/*
10094 		 * !SD_NUMA domains can assume that child groups
10095 		 * span the current group.
10096 		 */
10097 
10098 		group = child->groups;
10099 		do {
10100 			struct sched_group_capacity *sgc = group->sgc;
10101 
10102 			capacity += sgc->capacity;
10103 			min_capacity = min(sgc->min_capacity, min_capacity);
10104 			max_capacity = max(sgc->max_capacity, max_capacity);
10105 			group = group->next;
10106 		} while (group != child->groups);
10107 	}
10108 
10109 	sdg->sgc->capacity = capacity;
10110 	sdg->sgc->min_capacity = min_capacity;
10111 	sdg->sgc->max_capacity = max_capacity;
10112 }
10113 
10114 /*
10115  * Check whether the capacity of the rq has been noticeably reduced by side
10116  * activity. The imbalance_pct is used for the threshold.
10117  * Return true is the capacity is reduced
10118  */
10119 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10120 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10121 {
10122 	return ((rq->cpu_capacity * sd->imbalance_pct) <
10123 				(arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10124 }
10125 
10126 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10127 static inline bool check_misfit_status(struct rq *rq)
10128 {
10129 	return rq->misfit_task_load;
10130 }
10131 
10132 /*
10133  * Group imbalance indicates (and tries to solve) the problem where balancing
10134  * groups is inadequate due to ->cpus_ptr constraints.
10135  *
10136  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10137  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10138  * Something like:
10139  *
10140  *	{ 0 1 2 3 } { 4 5 6 7 }
10141  *	        *     * * *
10142  *
10143  * If we were to balance group-wise we'd place two tasks in the first group and
10144  * two tasks in the second group. Clearly this is undesired as it will overload
10145  * cpu 3 and leave one of the CPUs in the second group unused.
10146  *
10147  * The current solution to this issue is detecting the skew in the first group
10148  * by noticing the lower domain failed to reach balance and had difficulty
10149  * moving tasks due to affinity constraints.
10150  *
10151  * When this is so detected; this group becomes a candidate for busiest; see
10152  * update_sd_pick_busiest(). And calculate_imbalance() and
10153  * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10154  * to create an effective group imbalance.
10155  *
10156  * This is a somewhat tricky proposition since the next run might not find the
10157  * group imbalance and decide the groups need to be balanced again. A most
10158  * subtle and fragile situation.
10159  */
10160 
sg_imbalanced(struct sched_group * group)10161 static inline int sg_imbalanced(struct sched_group *group)
10162 {
10163 	return group->sgc->imbalance;
10164 }
10165 
10166 /*
10167  * group_has_capacity returns true if the group has spare capacity that could
10168  * be used by some tasks.
10169  * We consider that a group has spare capacity if the number of task is
10170  * smaller than the number of CPUs or if the utilization is lower than the
10171  * available capacity for CFS tasks.
10172  * For the latter, we use a threshold to stabilize the state, to take into
10173  * account the variance of the tasks' load and to return true if the available
10174  * capacity in meaningful for the load balancer.
10175  * As an example, an available capacity of 1% can appear but it doesn't make
10176  * any benefit for the load balance.
10177  */
10178 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10179 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10180 {
10181 	if (sgs->sum_nr_running < sgs->group_weight)
10182 		return true;
10183 
10184 	if ((sgs->group_capacity * imbalance_pct) <
10185 			(sgs->group_runnable * 100))
10186 		return false;
10187 
10188 	if ((sgs->group_capacity * 100) >
10189 			(sgs->group_util * imbalance_pct))
10190 		return true;
10191 
10192 	return false;
10193 }
10194 
10195 /*
10196  *  group_is_overloaded returns true if the group has more tasks than it can
10197  *  handle.
10198  *  group_is_overloaded is not equals to !group_has_capacity because a group
10199  *  with the exact right number of tasks, has no more spare capacity but is not
10200  *  overloaded so both group_has_capacity and group_is_overloaded return
10201  *  false.
10202  */
10203 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10204 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10205 {
10206 	if (sgs->sum_nr_running <= sgs->group_weight)
10207 		return false;
10208 
10209 	if ((sgs->group_capacity * 100) <
10210 			(sgs->group_util * imbalance_pct))
10211 		return true;
10212 
10213 	if ((sgs->group_capacity * imbalance_pct) <
10214 			(sgs->group_runnable * 100))
10215 		return true;
10216 
10217 	return false;
10218 }
10219 
10220 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10221 group_type group_classify(unsigned int imbalance_pct,
10222 			  struct sched_group *group,
10223 			  struct sg_lb_stats *sgs)
10224 {
10225 	if (group_is_overloaded(imbalance_pct, sgs))
10226 		return group_overloaded;
10227 
10228 	if (sg_imbalanced(group))
10229 		return group_imbalanced;
10230 
10231 	if (sgs->group_asym_packing)
10232 		return group_asym_packing;
10233 
10234 	if (sgs->group_smt_balance)
10235 		return group_smt_balance;
10236 
10237 	if (sgs->group_misfit_task_load)
10238 		return group_misfit_task;
10239 
10240 	if (!group_has_capacity(imbalance_pct, sgs))
10241 		return group_fully_busy;
10242 
10243 	return group_has_spare;
10244 }
10245 
10246 /**
10247  * sched_use_asym_prio - Check whether asym_packing priority must be used
10248  * @sd:		The scheduling domain of the load balancing
10249  * @cpu:	A CPU
10250  *
10251  * Always use CPU priority when balancing load between SMT siblings. When
10252  * balancing load between cores, it is not sufficient that @cpu is idle. Only
10253  * use CPU priority if the whole core is idle.
10254  *
10255  * Returns: True if the priority of @cpu must be followed. False otherwise.
10256  */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10257 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10258 {
10259 	if (!(sd->flags & SD_ASYM_PACKING))
10260 		return false;
10261 
10262 	if (!sched_smt_active())
10263 		return true;
10264 
10265 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10266 }
10267 
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10268 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10269 {
10270 	/*
10271 	 * First check if @dst_cpu can do asym_packing load balance. Only do it
10272 	 * if it has higher priority than @src_cpu.
10273 	 */
10274 	return sched_use_asym_prio(sd, dst_cpu) &&
10275 		sched_asym_prefer(dst_cpu, src_cpu);
10276 }
10277 
10278 /**
10279  * sched_group_asym - Check if the destination CPU can do asym_packing balance
10280  * @env:	The load balancing environment
10281  * @sgs:	Load-balancing statistics of the candidate busiest group
10282  * @group:	The candidate busiest group
10283  *
10284  * @env::dst_cpu can do asym_packing if it has higher priority than the
10285  * preferred CPU of @group.
10286  *
10287  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10288  * otherwise.
10289  */
10290 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10291 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10292 {
10293 	/*
10294 	 * CPU priorities do not make sense for SMT cores with more than one
10295 	 * busy sibling.
10296 	 */
10297 	if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10298 	    (sgs->group_weight - sgs->idle_cpus != 1))
10299 		return false;
10300 
10301 	return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
10302 }
10303 
10304 /* One group has more than one SMT CPU while the other group does not */
smt_vs_nonsmt_groups(struct sched_group * sg1,struct sched_group * sg2)10305 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10306 				    struct sched_group *sg2)
10307 {
10308 	if (!sg1 || !sg2)
10309 		return false;
10310 
10311 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10312 		(sg2->flags & SD_SHARE_CPUCAPACITY);
10313 }
10314 
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10315 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10316 			       struct sched_group *group)
10317 {
10318 	if (!env->idle)
10319 		return false;
10320 
10321 	/*
10322 	 * For SMT source group, it is better to move a task
10323 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10324 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10325 	 * will not be on.
10326 	 */
10327 	if (group->flags & SD_SHARE_CPUCAPACITY &&
10328 	    sgs->sum_h_nr_running > 1)
10329 		return true;
10330 
10331 	return false;
10332 }
10333 
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10334 static inline long sibling_imbalance(struct lb_env *env,
10335 				    struct sd_lb_stats *sds,
10336 				    struct sg_lb_stats *busiest,
10337 				    struct sg_lb_stats *local)
10338 {
10339 	int ncores_busiest, ncores_local;
10340 	long imbalance;
10341 
10342 	if (!env->idle || !busiest->sum_nr_running)
10343 		return 0;
10344 
10345 	ncores_busiest = sds->busiest->cores;
10346 	ncores_local = sds->local->cores;
10347 
10348 	if (ncores_busiest == ncores_local) {
10349 		imbalance = busiest->sum_nr_running;
10350 		lsub_positive(&imbalance, local->sum_nr_running);
10351 		return imbalance;
10352 	}
10353 
10354 	/* Balance such that nr_running/ncores ratio are same on both groups */
10355 	imbalance = ncores_local * busiest->sum_nr_running;
10356 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10357 	/* Normalize imbalance and do rounding on normalization */
10358 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10359 	imbalance /= ncores_local + ncores_busiest;
10360 
10361 	/* Take advantage of resource in an empty sched group */
10362 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
10363 	    busiest->sum_nr_running > 1)
10364 		imbalance = 2;
10365 
10366 	return imbalance;
10367 }
10368 
10369 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10370 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10371 {
10372 	/*
10373 	 * When there is more than 1 task, the group_overloaded case already
10374 	 * takes care of cpu with reduced capacity
10375 	 */
10376 	if (rq->cfs.h_nr_runnable != 1)
10377 		return false;
10378 
10379 	return check_cpu_capacity(rq, sd);
10380 }
10381 
10382 /**
10383  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10384  * @env: The load balancing environment.
10385  * @sds: Load-balancing data with statistics of the local group.
10386  * @group: sched_group whose statistics are to be updated.
10387  * @sgs: variable to hold the statistics for this group.
10388  * @sg_overloaded: sched_group is overloaded
10389  * @sg_overutilized: sched_group is overutilized
10390  */
update_sg_lb_stats(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * group,struct sg_lb_stats * sgs,bool * sg_overloaded,bool * sg_overutilized)10391 static inline void update_sg_lb_stats(struct lb_env *env,
10392 				      struct sd_lb_stats *sds,
10393 				      struct sched_group *group,
10394 				      struct sg_lb_stats *sgs,
10395 				      bool *sg_overloaded,
10396 				      bool *sg_overutilized)
10397 {
10398 	int i, nr_running, local_group, sd_flags = env->sd->flags;
10399 	bool balancing_at_rd = !env->sd->parent;
10400 
10401 	memset(sgs, 0, sizeof(*sgs));
10402 
10403 	local_group = group == sds->local;
10404 
10405 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10406 		struct rq *rq = cpu_rq(i);
10407 		unsigned long load = cpu_load(rq);
10408 
10409 		sgs->group_load += load;
10410 		sgs->group_util += cpu_util_cfs(i);
10411 		sgs->group_runnable += cpu_runnable(rq);
10412 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10413 
10414 		nr_running = rq->nr_running;
10415 		sgs->sum_nr_running += nr_running;
10416 
10417 		if (cpu_overutilized(i))
10418 			*sg_overutilized = 1;
10419 
10420 		/*
10421 		 * No need to call idle_cpu() if nr_running is not 0
10422 		 */
10423 		if (!nr_running && idle_cpu(i)) {
10424 			sgs->idle_cpus++;
10425 			/* Idle cpu can't have misfit task */
10426 			continue;
10427 		}
10428 
10429 		/* Overload indicator is only updated at root domain */
10430 		if (balancing_at_rd && nr_running > 1)
10431 			*sg_overloaded = 1;
10432 
10433 #ifdef CONFIG_NUMA_BALANCING
10434 		/* Only fbq_classify_group() uses this to classify NUMA groups */
10435 		if (sd_flags & SD_NUMA) {
10436 			sgs->nr_numa_running += rq->nr_numa_running;
10437 			sgs->nr_preferred_running += rq->nr_preferred_running;
10438 		}
10439 #endif
10440 		if (local_group)
10441 			continue;
10442 
10443 		if (sd_flags & SD_ASYM_CPUCAPACITY) {
10444 			/* Check for a misfit task on the cpu */
10445 			if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10446 				sgs->group_misfit_task_load = rq->misfit_task_load;
10447 				*sg_overloaded = 1;
10448 			}
10449 		} else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10450 			/* Check for a task running on a CPU with reduced capacity */
10451 			if (sgs->group_misfit_task_load < load)
10452 				sgs->group_misfit_task_load = load;
10453 		}
10454 	}
10455 
10456 	sgs->group_capacity = group->sgc->capacity;
10457 
10458 	sgs->group_weight = group->group_weight;
10459 
10460 	/* Check if dst CPU is idle and preferred to this group */
10461 	if (!local_group && env->idle && sgs->sum_h_nr_running &&
10462 	    sched_group_asym(env, sgs, group))
10463 		sgs->group_asym_packing = 1;
10464 
10465 	/* Check for loaded SMT group to be balanced to dst CPU */
10466 	if (!local_group && smt_balance(env, sgs, group))
10467 		sgs->group_smt_balance = 1;
10468 
10469 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10470 
10471 	/* Computing avg_load makes sense only when group is overloaded */
10472 	if (sgs->group_type == group_overloaded)
10473 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10474 				sgs->group_capacity;
10475 }
10476 
10477 /**
10478  * update_sd_pick_busiest - return 1 on busiest group
10479  * @env: The load balancing environment.
10480  * @sds: sched_domain statistics
10481  * @sg: sched_group candidate to be checked for being the busiest
10482  * @sgs: sched_group statistics
10483  *
10484  * Determine if @sg is a busier group than the previously selected
10485  * busiest group.
10486  *
10487  * Return: %true if @sg is a busier group than the previously selected
10488  * busiest group. %false otherwise.
10489  */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10490 static bool update_sd_pick_busiest(struct lb_env *env,
10491 				   struct sd_lb_stats *sds,
10492 				   struct sched_group *sg,
10493 				   struct sg_lb_stats *sgs)
10494 {
10495 	struct sg_lb_stats *busiest = &sds->busiest_stat;
10496 
10497 	/* Make sure that there is at least one task to pull */
10498 	if (!sgs->sum_h_nr_running)
10499 		return false;
10500 
10501 	/*
10502 	 * Don't try to pull misfit tasks we can't help.
10503 	 * We can use max_capacity here as reduction in capacity on some
10504 	 * CPUs in the group should either be possible to resolve
10505 	 * internally or be covered by avg_load imbalance (eventually).
10506 	 */
10507 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10508 	    (sgs->group_type == group_misfit_task) &&
10509 	    (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10510 	     sds->local_stat.group_type != group_has_spare))
10511 		return false;
10512 
10513 	if (sgs->group_type > busiest->group_type)
10514 		return true;
10515 
10516 	if (sgs->group_type < busiest->group_type)
10517 		return false;
10518 
10519 	/*
10520 	 * The candidate and the current busiest group are the same type of
10521 	 * group. Let check which one is the busiest according to the type.
10522 	 */
10523 
10524 	switch (sgs->group_type) {
10525 	case group_overloaded:
10526 		/* Select the overloaded group with highest avg_load. */
10527 		return sgs->avg_load > busiest->avg_load;
10528 
10529 	case group_imbalanced:
10530 		/*
10531 		 * Select the 1st imbalanced group as we don't have any way to
10532 		 * choose one more than another.
10533 		 */
10534 		return false;
10535 
10536 	case group_asym_packing:
10537 		/* Prefer to move from lowest priority CPU's work */
10538 		return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
10539 					 READ_ONCE(sg->asym_prefer_cpu));
10540 
10541 	case group_misfit_task:
10542 		/*
10543 		 * If we have more than one misfit sg go with the biggest
10544 		 * misfit.
10545 		 */
10546 		return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10547 
10548 	case group_smt_balance:
10549 		/*
10550 		 * Check if we have spare CPUs on either SMT group to
10551 		 * choose has spare or fully busy handling.
10552 		 */
10553 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10554 			goto has_spare;
10555 
10556 		fallthrough;
10557 
10558 	case group_fully_busy:
10559 		/*
10560 		 * Select the fully busy group with highest avg_load. In
10561 		 * theory, there is no need to pull task from such kind of
10562 		 * group because tasks have all compute capacity that they need
10563 		 * but we can still improve the overall throughput by reducing
10564 		 * contention when accessing shared HW resources.
10565 		 *
10566 		 * XXX for now avg_load is not computed and always 0 so we
10567 		 * select the 1st one, except if @sg is composed of SMT
10568 		 * siblings.
10569 		 */
10570 
10571 		if (sgs->avg_load < busiest->avg_load)
10572 			return false;
10573 
10574 		if (sgs->avg_load == busiest->avg_load) {
10575 			/*
10576 			 * SMT sched groups need more help than non-SMT groups.
10577 			 * If @sg happens to also be SMT, either choice is good.
10578 			 */
10579 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10580 				return false;
10581 		}
10582 
10583 		break;
10584 
10585 	case group_has_spare:
10586 		/*
10587 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10588 		 * as we do not want to pull task off SMT core with one task
10589 		 * and make the core idle.
10590 		 */
10591 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10592 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10593 				return false;
10594 			else
10595 				return true;
10596 		}
10597 has_spare:
10598 
10599 		/*
10600 		 * Select not overloaded group with lowest number of idle CPUs
10601 		 * and highest number of running tasks. We could also compare
10602 		 * the spare capacity which is more stable but it can end up
10603 		 * that the group has less spare capacity but finally more idle
10604 		 * CPUs which means less opportunity to pull tasks.
10605 		 */
10606 		if (sgs->idle_cpus > busiest->idle_cpus)
10607 			return false;
10608 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10609 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
10610 			return false;
10611 
10612 		break;
10613 	}
10614 
10615 	/*
10616 	 * Candidate sg has no more than one task per CPU and has higher
10617 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10618 	 * throughput. Maximize throughput, power/energy consequences are not
10619 	 * considered.
10620 	 */
10621 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10622 	    (sgs->group_type <= group_fully_busy) &&
10623 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10624 		return false;
10625 
10626 	return true;
10627 }
10628 
10629 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10630 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10631 {
10632 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10633 		return regular;
10634 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10635 		return remote;
10636 	return all;
10637 }
10638 
fbq_classify_rq(struct rq * rq)10639 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10640 {
10641 	if (rq->nr_running > rq->nr_numa_running)
10642 		return regular;
10643 	if (rq->nr_running > rq->nr_preferred_running)
10644 		return remote;
10645 	return all;
10646 }
10647 #else /* !CONFIG_NUMA_BALANCING: */
fbq_classify_group(struct sg_lb_stats * sgs)10648 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10649 {
10650 	return all;
10651 }
10652 
fbq_classify_rq(struct rq * rq)10653 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10654 {
10655 	return regular;
10656 }
10657 #endif /* !CONFIG_NUMA_BALANCING */
10658 
10659 
10660 struct sg_lb_stats;
10661 
10662 /*
10663  * task_running_on_cpu - return 1 if @p is running on @cpu.
10664  */
10665 
task_running_on_cpu(int cpu,struct task_struct * p)10666 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10667 {
10668 	/* Task has no contribution or is new */
10669 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10670 		return 0;
10671 
10672 	if (task_on_rq_queued(p))
10673 		return 1;
10674 
10675 	return 0;
10676 }
10677 
10678 /**
10679  * idle_cpu_without - would a given CPU be idle without p ?
10680  * @cpu: the processor on which idleness is tested.
10681  * @p: task which should be ignored.
10682  *
10683  * Return: 1 if the CPU would be idle. 0 otherwise.
10684  */
idle_cpu_without(int cpu,struct task_struct * p)10685 static int idle_cpu_without(int cpu, struct task_struct *p)
10686 {
10687 	struct rq *rq = cpu_rq(cpu);
10688 
10689 	if (rq->curr != rq->idle && rq->curr != p)
10690 		return 0;
10691 
10692 	/*
10693 	 * rq->nr_running can't be used but an updated version without the
10694 	 * impact of p on cpu must be used instead. The updated nr_running
10695 	 * be computed and tested before calling idle_cpu_without().
10696 	 */
10697 
10698 	if (rq->ttwu_pending)
10699 		return 0;
10700 
10701 	return 1;
10702 }
10703 
10704 /*
10705  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10706  * @sd: The sched_domain level to look for idlest group.
10707  * @group: sched_group whose statistics are to be updated.
10708  * @sgs: variable to hold the statistics for this group.
10709  * @p: The task for which we look for the idlest group/CPU.
10710  */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10711 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10712 					  struct sched_group *group,
10713 					  struct sg_lb_stats *sgs,
10714 					  struct task_struct *p)
10715 {
10716 	int i, nr_running;
10717 
10718 	memset(sgs, 0, sizeof(*sgs));
10719 
10720 	/* Assume that task can't fit any CPU of the group */
10721 	if (sd->flags & SD_ASYM_CPUCAPACITY)
10722 		sgs->group_misfit_task_load = 1;
10723 
10724 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
10725 		struct rq *rq = cpu_rq(i);
10726 		unsigned int local;
10727 
10728 		sgs->group_load += cpu_load_without(rq, p);
10729 		sgs->group_util += cpu_util_without(i, p);
10730 		sgs->group_runnable += cpu_runnable_without(rq, p);
10731 		local = task_running_on_cpu(i, p);
10732 		sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
10733 
10734 		nr_running = rq->nr_running - local;
10735 		sgs->sum_nr_running += nr_running;
10736 
10737 		/*
10738 		 * No need to call idle_cpu_without() if nr_running is not 0
10739 		 */
10740 		if (!nr_running && idle_cpu_without(i, p))
10741 			sgs->idle_cpus++;
10742 
10743 		/* Check if task fits in the CPU */
10744 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
10745 		    sgs->group_misfit_task_load &&
10746 		    task_fits_cpu(p, i))
10747 			sgs->group_misfit_task_load = 0;
10748 
10749 	}
10750 
10751 	sgs->group_capacity = group->sgc->capacity;
10752 
10753 	sgs->group_weight = group->group_weight;
10754 
10755 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10756 
10757 	/*
10758 	 * Computing avg_load makes sense only when group is fully busy or
10759 	 * overloaded
10760 	 */
10761 	if (sgs->group_type == group_fully_busy ||
10762 		sgs->group_type == group_overloaded)
10763 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10764 				sgs->group_capacity;
10765 }
10766 
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10767 static bool update_pick_idlest(struct sched_group *idlest,
10768 			       struct sg_lb_stats *idlest_sgs,
10769 			       struct sched_group *group,
10770 			       struct sg_lb_stats *sgs)
10771 {
10772 	if (sgs->group_type < idlest_sgs->group_type)
10773 		return true;
10774 
10775 	if (sgs->group_type > idlest_sgs->group_type)
10776 		return false;
10777 
10778 	/*
10779 	 * The candidate and the current idlest group are the same type of
10780 	 * group. Let check which one is the idlest according to the type.
10781 	 */
10782 
10783 	switch (sgs->group_type) {
10784 	case group_overloaded:
10785 	case group_fully_busy:
10786 		/* Select the group with lowest avg_load. */
10787 		if (idlest_sgs->avg_load <= sgs->avg_load)
10788 			return false;
10789 		break;
10790 
10791 	case group_imbalanced:
10792 	case group_asym_packing:
10793 	case group_smt_balance:
10794 		/* Those types are not used in the slow wakeup path */
10795 		return false;
10796 
10797 	case group_misfit_task:
10798 		/* Select group with the highest max capacity */
10799 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10800 			return false;
10801 		break;
10802 
10803 	case group_has_spare:
10804 		/* Select group with most idle CPUs */
10805 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10806 			return false;
10807 
10808 		/* Select group with lowest group_util */
10809 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10810 			idlest_sgs->group_util <= sgs->group_util)
10811 			return false;
10812 
10813 		break;
10814 	}
10815 
10816 	return true;
10817 }
10818 
10819 /*
10820  * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
10821  * domain.
10822  *
10823  * Assumes p is allowed on at least one CPU in sd.
10824  */
10825 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10826 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10827 {
10828 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10829 	struct sg_lb_stats local_sgs, tmp_sgs;
10830 	struct sg_lb_stats *sgs;
10831 	unsigned long imbalance;
10832 	struct sg_lb_stats idlest_sgs = {
10833 			.avg_load = UINT_MAX,
10834 			.group_type = group_overloaded,
10835 	};
10836 
10837 	do {
10838 		int local_group;
10839 
10840 		/* Skip over this group if it has no CPUs allowed */
10841 		if (!cpumask_intersects(sched_group_span(group),
10842 					p->cpus_ptr))
10843 			continue;
10844 
10845 		/* Skip over this group if no cookie matched */
10846 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10847 			continue;
10848 
10849 		local_group = cpumask_test_cpu(this_cpu,
10850 					       sched_group_span(group));
10851 
10852 		if (local_group) {
10853 			sgs = &local_sgs;
10854 			local = group;
10855 		} else {
10856 			sgs = &tmp_sgs;
10857 		}
10858 
10859 		update_sg_wakeup_stats(sd, group, sgs, p);
10860 
10861 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10862 			idlest = group;
10863 			idlest_sgs = *sgs;
10864 		}
10865 
10866 	} while (group = group->next, group != sd->groups);
10867 
10868 
10869 	/* There is no idlest group to push tasks to */
10870 	if (!idlest)
10871 		return NULL;
10872 
10873 	/* The local group has been skipped because of CPU affinity */
10874 	if (!local)
10875 		return idlest;
10876 
10877 	/*
10878 	 * If the local group is idler than the selected idlest group
10879 	 * don't try and push the task.
10880 	 */
10881 	if (local_sgs.group_type < idlest_sgs.group_type)
10882 		return NULL;
10883 
10884 	/*
10885 	 * If the local group is busier than the selected idlest group
10886 	 * try and push the task.
10887 	 */
10888 	if (local_sgs.group_type > idlest_sgs.group_type)
10889 		return idlest;
10890 
10891 	switch (local_sgs.group_type) {
10892 	case group_overloaded:
10893 	case group_fully_busy:
10894 
10895 		/* Calculate allowed imbalance based on load */
10896 		imbalance = scale_load_down(NICE_0_LOAD) *
10897 				(sd->imbalance_pct-100) / 100;
10898 
10899 		/*
10900 		 * When comparing groups across NUMA domains, it's possible for
10901 		 * the local domain to be very lightly loaded relative to the
10902 		 * remote domains but "imbalance" skews the comparison making
10903 		 * remote CPUs look much more favourable. When considering
10904 		 * cross-domain, add imbalance to the load on the remote node
10905 		 * and consider staying local.
10906 		 */
10907 
10908 		if ((sd->flags & SD_NUMA) &&
10909 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10910 			return NULL;
10911 
10912 		/*
10913 		 * If the local group is less loaded than the selected
10914 		 * idlest group don't try and push any tasks.
10915 		 */
10916 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10917 			return NULL;
10918 
10919 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10920 			return NULL;
10921 		break;
10922 
10923 	case group_imbalanced:
10924 	case group_asym_packing:
10925 	case group_smt_balance:
10926 		/* Those type are not used in the slow wakeup path */
10927 		return NULL;
10928 
10929 	case group_misfit_task:
10930 		/* Select group with the highest max capacity */
10931 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10932 			return NULL;
10933 		break;
10934 
10935 	case group_has_spare:
10936 #ifdef CONFIG_NUMA
10937 		if (sd->flags & SD_NUMA) {
10938 			int imb_numa_nr = sd->imb_numa_nr;
10939 #ifdef CONFIG_NUMA_BALANCING
10940 			int idlest_cpu;
10941 			/*
10942 			 * If there is spare capacity at NUMA, try to select
10943 			 * the preferred node
10944 			 */
10945 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10946 				return NULL;
10947 
10948 			idlest_cpu = cpumask_first(sched_group_span(idlest));
10949 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10950 				return idlest;
10951 #endif /* CONFIG_NUMA_BALANCING */
10952 			/*
10953 			 * Otherwise, keep the task close to the wakeup source
10954 			 * and improve locality if the number of running tasks
10955 			 * would remain below threshold where an imbalance is
10956 			 * allowed while accounting for the possibility the
10957 			 * task is pinned to a subset of CPUs. If there is a
10958 			 * real need of migration, periodic load balance will
10959 			 * take care of it.
10960 			 */
10961 			if (p->nr_cpus_allowed != NR_CPUS) {
10962 				struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10963 
10964 				cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10965 				imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10966 			}
10967 
10968 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10969 			if (!adjust_numa_imbalance(imbalance,
10970 						   local_sgs.sum_nr_running + 1,
10971 						   imb_numa_nr)) {
10972 				return NULL;
10973 			}
10974 		}
10975 #endif /* CONFIG_NUMA */
10976 
10977 		/*
10978 		 * Select group with highest number of idle CPUs. We could also
10979 		 * compare the utilization which is more stable but it can end
10980 		 * up that the group has less spare capacity but finally more
10981 		 * idle CPUs which means more opportunity to run task.
10982 		 */
10983 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10984 			return NULL;
10985 		break;
10986 	}
10987 
10988 	return idlest;
10989 }
10990 
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)10991 static void update_idle_cpu_scan(struct lb_env *env,
10992 				 unsigned long sum_util)
10993 {
10994 	struct sched_domain_shared *sd_share;
10995 	int llc_weight, pct;
10996 	u64 x, y, tmp;
10997 	/*
10998 	 * Update the number of CPUs to scan in LLC domain, which could
10999 	 * be used as a hint in select_idle_cpu(). The update of sd_share
11000 	 * could be expensive because it is within a shared cache line.
11001 	 * So the write of this hint only occurs during periodic load
11002 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11003 	 * can fire way more frequently than the former.
11004 	 */
11005 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11006 		return;
11007 
11008 	llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
11009 	if (env->sd->span_weight != llc_weight)
11010 		return;
11011 
11012 	sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
11013 	if (!sd_share)
11014 		return;
11015 
11016 	/*
11017 	 * The number of CPUs to search drops as sum_util increases, when
11018 	 * sum_util hits 85% or above, the scan stops.
11019 	 * The reason to choose 85% as the threshold is because this is the
11020 	 * imbalance_pct(117) when a LLC sched group is overloaded.
11021 	 *
11022 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
11023 	 * and y'= y / SCHED_CAPACITY_SCALE
11024 	 *
11025 	 * x is the ratio of sum_util compared to the CPU capacity:
11026 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11027 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
11028 	 * and the number of CPUs to scan is calculated by:
11029 	 *
11030 	 * nr_scan = llc_weight * y'                                    [2]
11031 	 *
11032 	 * When x hits the threshold of overloaded, AKA, when
11033 	 * x = 100 / pct, y drops to 0. According to [1],
11034 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11035 	 *
11036 	 * Scale x by SCHED_CAPACITY_SCALE:
11037 	 * x' = sum_util / llc_weight;                                  [3]
11038 	 *
11039 	 * and finally [1] becomes:
11040 	 * y = SCHED_CAPACITY_SCALE -
11041 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
11042 	 *
11043 	 */
11044 	/* equation [3] */
11045 	x = sum_util;
11046 	do_div(x, llc_weight);
11047 
11048 	/* equation [4] */
11049 	pct = env->sd->imbalance_pct;
11050 	tmp = x * x * pct * pct;
11051 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11052 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11053 	y = SCHED_CAPACITY_SCALE - tmp;
11054 
11055 	/* equation [2] */
11056 	y *= llc_weight;
11057 	do_div(y, SCHED_CAPACITY_SCALE);
11058 	if ((int)y != sd_share->nr_idle_scan)
11059 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11060 }
11061 
11062 /**
11063  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11064  * @env: The load balancing environment.
11065  * @sds: variable to hold the statistics for this sched_domain.
11066  */
11067 
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11068 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11069 {
11070 	struct sched_group *sg = env->sd->groups;
11071 	struct sg_lb_stats *local = &sds->local_stat;
11072 	struct sg_lb_stats tmp_sgs;
11073 	unsigned long sum_util = 0;
11074 	bool sg_overloaded = 0, sg_overutilized = 0;
11075 
11076 	do {
11077 		struct sg_lb_stats *sgs = &tmp_sgs;
11078 		int local_group;
11079 
11080 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11081 		if (local_group) {
11082 			sds->local = sg;
11083 			sgs = local;
11084 
11085 			if (env->idle != CPU_NEWLY_IDLE ||
11086 			    time_after_eq(jiffies, sg->sgc->next_update))
11087 				update_group_capacity(env->sd, env->dst_cpu);
11088 		}
11089 
11090 		update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11091 
11092 		if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11093 			sds->busiest = sg;
11094 			sds->busiest_stat = *sgs;
11095 		}
11096 
11097 		/* Now, start updating sd_lb_stats */
11098 		sds->total_load += sgs->group_load;
11099 		sds->total_capacity += sgs->group_capacity;
11100 
11101 		sum_util += sgs->group_util;
11102 		sg = sg->next;
11103 	} while (sg != env->sd->groups);
11104 
11105 	/*
11106 	 * Indicate that the child domain of the busiest group prefers tasks
11107 	 * go to a child's sibling domains first. NB the flags of a sched group
11108 	 * are those of the child domain.
11109 	 */
11110 	if (sds->busiest)
11111 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11112 
11113 
11114 	if (env->sd->flags & SD_NUMA)
11115 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11116 
11117 	if (!env->sd->parent) {
11118 		/* update overload indicator if we are at root domain */
11119 		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11120 
11121 		/* Update over-utilization (tipping point, U >= 0) indicator */
11122 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11123 	} else if (sg_overutilized) {
11124 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11125 	}
11126 
11127 	update_idle_cpu_scan(env, sum_util);
11128 }
11129 
11130 /**
11131  * calculate_imbalance - Calculate the amount of imbalance present within the
11132  *			 groups of a given sched_domain during load balance.
11133  * @env: load balance environment
11134  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11135  */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11136 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11137 {
11138 	struct sg_lb_stats *local, *busiest;
11139 
11140 	local = &sds->local_stat;
11141 	busiest = &sds->busiest_stat;
11142 
11143 	if (busiest->group_type == group_misfit_task) {
11144 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11145 			/* Set imbalance to allow misfit tasks to be balanced. */
11146 			env->migration_type = migrate_misfit;
11147 			env->imbalance = 1;
11148 		} else {
11149 			/*
11150 			 * Set load imbalance to allow moving task from cpu
11151 			 * with reduced capacity.
11152 			 */
11153 			env->migration_type = migrate_load;
11154 			env->imbalance = busiest->group_misfit_task_load;
11155 		}
11156 		return;
11157 	}
11158 
11159 	if (busiest->group_type == group_asym_packing) {
11160 		/*
11161 		 * In case of asym capacity, we will try to migrate all load to
11162 		 * the preferred CPU.
11163 		 */
11164 		env->migration_type = migrate_task;
11165 		env->imbalance = busiest->sum_h_nr_running;
11166 		return;
11167 	}
11168 
11169 	if (busiest->group_type == group_smt_balance) {
11170 		/* Reduce number of tasks sharing CPU capacity */
11171 		env->migration_type = migrate_task;
11172 		env->imbalance = 1;
11173 		return;
11174 	}
11175 
11176 	if (busiest->group_type == group_imbalanced) {
11177 		/*
11178 		 * In the group_imb case we cannot rely on group-wide averages
11179 		 * to ensure CPU-load equilibrium, try to move any task to fix
11180 		 * the imbalance. The next load balance will take care of
11181 		 * balancing back the system.
11182 		 */
11183 		env->migration_type = migrate_task;
11184 		env->imbalance = 1;
11185 		return;
11186 	}
11187 
11188 	/*
11189 	 * Try to use spare capacity of local group without overloading it or
11190 	 * emptying busiest.
11191 	 */
11192 	if (local->group_type == group_has_spare) {
11193 		if ((busiest->group_type > group_fully_busy) &&
11194 		    !(env->sd->flags & SD_SHARE_LLC)) {
11195 			/*
11196 			 * If busiest is overloaded, try to fill spare
11197 			 * capacity. This might end up creating spare capacity
11198 			 * in busiest or busiest still being overloaded but
11199 			 * there is no simple way to directly compute the
11200 			 * amount of load to migrate in order to balance the
11201 			 * system.
11202 			 */
11203 			env->migration_type = migrate_util;
11204 			env->imbalance = max(local->group_capacity, local->group_util) -
11205 					 local->group_util;
11206 
11207 			/*
11208 			 * In some cases, the group's utilization is max or even
11209 			 * higher than capacity because of migrations but the
11210 			 * local CPU is (newly) idle. There is at least one
11211 			 * waiting task in this overloaded busiest group. Let's
11212 			 * try to pull it.
11213 			 */
11214 			if (env->idle && env->imbalance == 0) {
11215 				env->migration_type = migrate_task;
11216 				env->imbalance = 1;
11217 			}
11218 
11219 			return;
11220 		}
11221 
11222 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
11223 			/*
11224 			 * When prefer sibling, evenly spread running tasks on
11225 			 * groups.
11226 			 */
11227 			env->migration_type = migrate_task;
11228 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
11229 		} else {
11230 
11231 			/*
11232 			 * If there is no overload, we just want to even the number of
11233 			 * idle CPUs.
11234 			 */
11235 			env->migration_type = migrate_task;
11236 			env->imbalance = max_t(long, 0,
11237 					       (local->idle_cpus - busiest->idle_cpus));
11238 		}
11239 
11240 #ifdef CONFIG_NUMA
11241 		/* Consider allowing a small imbalance between NUMA groups */
11242 		if (env->sd->flags & SD_NUMA) {
11243 			env->imbalance = adjust_numa_imbalance(env->imbalance,
11244 							       local->sum_nr_running + 1,
11245 							       env->sd->imb_numa_nr);
11246 		}
11247 #endif
11248 
11249 		/* Number of tasks to move to restore balance */
11250 		env->imbalance >>= 1;
11251 
11252 		return;
11253 	}
11254 
11255 	/*
11256 	 * Local is fully busy but has to take more load to relieve the
11257 	 * busiest group
11258 	 */
11259 	if (local->group_type < group_overloaded) {
11260 		/*
11261 		 * Local will become overloaded so the avg_load metrics are
11262 		 * finally needed.
11263 		 */
11264 
11265 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11266 				  local->group_capacity;
11267 
11268 		/*
11269 		 * If the local group is more loaded than the selected
11270 		 * busiest group don't try to pull any tasks.
11271 		 */
11272 		if (local->avg_load >= busiest->avg_load) {
11273 			env->imbalance = 0;
11274 			return;
11275 		}
11276 
11277 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11278 				sds->total_capacity;
11279 
11280 		/*
11281 		 * If the local group is more loaded than the average system
11282 		 * load, don't try to pull any tasks.
11283 		 */
11284 		if (local->avg_load >= sds->avg_load) {
11285 			env->imbalance = 0;
11286 			return;
11287 		}
11288 
11289 	}
11290 
11291 	/*
11292 	 * Both group are or will become overloaded and we're trying to get all
11293 	 * the CPUs to the average_load, so we don't want to push ourselves
11294 	 * above the average load, nor do we wish to reduce the max loaded CPU
11295 	 * below the average load. At the same time, we also don't want to
11296 	 * reduce the group load below the group capacity. Thus we look for
11297 	 * the minimum possible imbalance.
11298 	 */
11299 	env->migration_type = migrate_load;
11300 	env->imbalance = min(
11301 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11302 		(sds->avg_load - local->avg_load) * local->group_capacity
11303 	) / SCHED_CAPACITY_SCALE;
11304 }
11305 
11306 /******* sched_balance_find_src_group() helpers end here *********************/
11307 
11308 /*
11309  * Decision matrix according to the local and busiest group type:
11310  *
11311  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11312  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
11313  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
11314  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
11315  * asym_packing     force     force      N/A    N/A  force      force
11316  * imbalanced       force     force      N/A    N/A  force      force
11317  * overloaded       force     force      N/A    N/A  force      avg_load
11318  *
11319  * N/A :      Not Applicable because already filtered while updating
11320  *            statistics.
11321  * balanced : The system is balanced for these 2 groups.
11322  * force :    Calculate the imbalance as load migration is probably needed.
11323  * avg_load : Only if imbalance is significant enough.
11324  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
11325  *            different in groups.
11326  */
11327 
11328 /**
11329  * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11330  * if there is an imbalance.
11331  * @env: The load balancing environment.
11332  *
11333  * Also calculates the amount of runnable load which should be moved
11334  * to restore balance.
11335  *
11336  * Return:	- The busiest group if imbalance exists.
11337  */
sched_balance_find_src_group(struct lb_env * env)11338 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11339 {
11340 	struct sg_lb_stats *local, *busiest;
11341 	struct sd_lb_stats sds;
11342 
11343 	init_sd_lb_stats(&sds);
11344 
11345 	/*
11346 	 * Compute the various statistics relevant for load balancing at
11347 	 * this level.
11348 	 */
11349 	update_sd_lb_stats(env, &sds);
11350 
11351 	/* There is no busy sibling group to pull tasks from */
11352 	if (!sds.busiest)
11353 		goto out_balanced;
11354 
11355 	busiest = &sds.busiest_stat;
11356 
11357 	/* Misfit tasks should be dealt with regardless of the avg load */
11358 	if (busiest->group_type == group_misfit_task)
11359 		goto force_balance;
11360 
11361 	if (!is_rd_overutilized(env->dst_rq->rd) &&
11362 	    rcu_dereference(env->dst_rq->rd->pd))
11363 		goto out_balanced;
11364 
11365 	/* ASYM feature bypasses nice load balance check */
11366 	if (busiest->group_type == group_asym_packing)
11367 		goto force_balance;
11368 
11369 	/*
11370 	 * If the busiest group is imbalanced the below checks don't
11371 	 * work because they assume all things are equal, which typically
11372 	 * isn't true due to cpus_ptr constraints and the like.
11373 	 */
11374 	if (busiest->group_type == group_imbalanced)
11375 		goto force_balance;
11376 
11377 	local = &sds.local_stat;
11378 	/*
11379 	 * If the local group is busier than the selected busiest group
11380 	 * don't try and pull any tasks.
11381 	 */
11382 	if (local->group_type > busiest->group_type)
11383 		goto out_balanced;
11384 
11385 	/*
11386 	 * When groups are overloaded, use the avg_load to ensure fairness
11387 	 * between tasks.
11388 	 */
11389 	if (local->group_type == group_overloaded) {
11390 		/*
11391 		 * If the local group is more loaded than the selected
11392 		 * busiest group don't try to pull any tasks.
11393 		 */
11394 		if (local->avg_load >= busiest->avg_load)
11395 			goto out_balanced;
11396 
11397 		/* XXX broken for overlapping NUMA groups */
11398 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11399 				sds.total_capacity;
11400 
11401 		/*
11402 		 * Don't pull any tasks if this group is already above the
11403 		 * domain average load.
11404 		 */
11405 		if (local->avg_load >= sds.avg_load)
11406 			goto out_balanced;
11407 
11408 		/*
11409 		 * If the busiest group is more loaded, use imbalance_pct to be
11410 		 * conservative.
11411 		 */
11412 		if (100 * busiest->avg_load <=
11413 				env->sd->imbalance_pct * local->avg_load)
11414 			goto out_balanced;
11415 	}
11416 
11417 	/*
11418 	 * Try to move all excess tasks to a sibling domain of the busiest
11419 	 * group's child domain.
11420 	 */
11421 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
11422 	    sibling_imbalance(env, &sds, busiest, local) > 1)
11423 		goto force_balance;
11424 
11425 	if (busiest->group_type != group_overloaded) {
11426 		if (!env->idle) {
11427 			/*
11428 			 * If the busiest group is not overloaded (and as a
11429 			 * result the local one too) but this CPU is already
11430 			 * busy, let another idle CPU try to pull task.
11431 			 */
11432 			goto out_balanced;
11433 		}
11434 
11435 		if (busiest->group_type == group_smt_balance &&
11436 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11437 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
11438 			goto force_balance;
11439 		}
11440 
11441 		if (busiest->group_weight > 1 &&
11442 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
11443 			/*
11444 			 * If the busiest group is not overloaded
11445 			 * and there is no imbalance between this and busiest
11446 			 * group wrt idle CPUs, it is balanced. The imbalance
11447 			 * becomes significant if the diff is greater than 1
11448 			 * otherwise we might end up to just move the imbalance
11449 			 * on another group. Of course this applies only if
11450 			 * there is more than 1 CPU per group.
11451 			 */
11452 			goto out_balanced;
11453 		}
11454 
11455 		if (busiest->sum_h_nr_running == 1) {
11456 			/*
11457 			 * busiest doesn't have any tasks waiting to run
11458 			 */
11459 			goto out_balanced;
11460 		}
11461 	}
11462 
11463 force_balance:
11464 	/* Looks like there is an imbalance. Compute it */
11465 	calculate_imbalance(env, &sds);
11466 	return env->imbalance ? sds.busiest : NULL;
11467 
11468 out_balanced:
11469 	env->imbalance = 0;
11470 	return NULL;
11471 }
11472 
11473 /*
11474  * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11475  */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11476 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11477 				     struct sched_group *group)
11478 {
11479 	struct rq *busiest = NULL, *rq;
11480 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11481 	unsigned int busiest_nr = 0;
11482 	int i;
11483 
11484 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11485 		unsigned long capacity, load, util;
11486 		unsigned int nr_running;
11487 		enum fbq_type rt;
11488 
11489 		rq = cpu_rq(i);
11490 		rt = fbq_classify_rq(rq);
11491 
11492 		/*
11493 		 * We classify groups/runqueues into three groups:
11494 		 *  - regular: there are !numa tasks
11495 		 *  - remote:  there are numa tasks that run on the 'wrong' node
11496 		 *  - all:     there is no distinction
11497 		 *
11498 		 * In order to avoid migrating ideally placed numa tasks,
11499 		 * ignore those when there's better options.
11500 		 *
11501 		 * If we ignore the actual busiest queue to migrate another
11502 		 * task, the next balance pass can still reduce the busiest
11503 		 * queue by moving tasks around inside the node.
11504 		 *
11505 		 * If we cannot move enough load due to this classification
11506 		 * the next pass will adjust the group classification and
11507 		 * allow migration of more tasks.
11508 		 *
11509 		 * Both cases only affect the total convergence complexity.
11510 		 */
11511 		if (rt > env->fbq_type)
11512 			continue;
11513 
11514 		nr_running = rq->cfs.h_nr_runnable;
11515 		if (!nr_running)
11516 			continue;
11517 
11518 		capacity = capacity_of(i);
11519 
11520 		/*
11521 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11522 		 * eventually lead to active_balancing high->low capacity.
11523 		 * Higher per-CPU capacity is considered better than balancing
11524 		 * average load.
11525 		 */
11526 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11527 		    !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11528 		    nr_running == 1)
11529 			continue;
11530 
11531 		/*
11532 		 * Make sure we only pull tasks from a CPU of lower priority
11533 		 * when balancing between SMT siblings.
11534 		 *
11535 		 * If balancing between cores, let lower priority CPUs help
11536 		 * SMT cores with more than one busy sibling.
11537 		 */
11538 		if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11539 			continue;
11540 
11541 		switch (env->migration_type) {
11542 		case migrate_load:
11543 			/*
11544 			 * When comparing with load imbalance, use cpu_load()
11545 			 * which is not scaled with the CPU capacity.
11546 			 */
11547 			load = cpu_load(rq);
11548 
11549 			if (nr_running == 1 && load > env->imbalance &&
11550 			    !check_cpu_capacity(rq, env->sd))
11551 				break;
11552 
11553 			/*
11554 			 * For the load comparisons with the other CPUs,
11555 			 * consider the cpu_load() scaled with the CPU
11556 			 * capacity, so that the load can be moved away
11557 			 * from the CPU that is potentially running at a
11558 			 * lower capacity.
11559 			 *
11560 			 * Thus we're looking for max(load_i / capacity_i),
11561 			 * crosswise multiplication to rid ourselves of the
11562 			 * division works out to:
11563 			 * load_i * capacity_j > load_j * capacity_i;
11564 			 * where j is our previous maximum.
11565 			 */
11566 			if (load * busiest_capacity > busiest_load * capacity) {
11567 				busiest_load = load;
11568 				busiest_capacity = capacity;
11569 				busiest = rq;
11570 			}
11571 			break;
11572 
11573 		case migrate_util:
11574 			util = cpu_util_cfs_boost(i);
11575 
11576 			/*
11577 			 * Don't try to pull utilization from a CPU with one
11578 			 * running task. Whatever its utilization, we will fail
11579 			 * detach the task.
11580 			 */
11581 			if (nr_running <= 1)
11582 				continue;
11583 
11584 			if (busiest_util < util) {
11585 				busiest_util = util;
11586 				busiest = rq;
11587 			}
11588 			break;
11589 
11590 		case migrate_task:
11591 			if (busiest_nr < nr_running) {
11592 				busiest_nr = nr_running;
11593 				busiest = rq;
11594 			}
11595 			break;
11596 
11597 		case migrate_misfit:
11598 			/*
11599 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
11600 			 * simply seek the "biggest" misfit task.
11601 			 */
11602 			if (rq->misfit_task_load > busiest_load) {
11603 				busiest_load = rq->misfit_task_load;
11604 				busiest = rq;
11605 			}
11606 
11607 			break;
11608 
11609 		}
11610 	}
11611 
11612 	return busiest;
11613 }
11614 
11615 /*
11616  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11617  * so long as it is large enough.
11618  */
11619 #define MAX_PINNED_INTERVAL	512
11620 
11621 static inline bool
asym_active_balance(struct lb_env * env)11622 asym_active_balance(struct lb_env *env)
11623 {
11624 	/*
11625 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
11626 	 * priority CPUs in order to pack all tasks in the highest priority
11627 	 * CPUs. When done between cores, do it only if the whole core if the
11628 	 * whole core is idle.
11629 	 *
11630 	 * If @env::src_cpu is an SMT core with busy siblings, let
11631 	 * the lower priority @env::dst_cpu help it. Do not follow
11632 	 * CPU priority.
11633 	 */
11634 	return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11635 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11636 		!sched_use_asym_prio(env->sd, env->src_cpu));
11637 }
11638 
11639 static inline bool
imbalanced_active_balance(struct lb_env * env)11640 imbalanced_active_balance(struct lb_env *env)
11641 {
11642 	struct sched_domain *sd = env->sd;
11643 
11644 	/*
11645 	 * The imbalanced case includes the case of pinned tasks preventing a fair
11646 	 * distribution of the load on the system but also the even distribution of the
11647 	 * threads on a system with spare capacity
11648 	 */
11649 	if ((env->migration_type == migrate_task) &&
11650 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
11651 		return 1;
11652 
11653 	return 0;
11654 }
11655 
need_active_balance(struct lb_env * env)11656 static int need_active_balance(struct lb_env *env)
11657 {
11658 	struct sched_domain *sd = env->sd;
11659 
11660 	if (asym_active_balance(env))
11661 		return 1;
11662 
11663 	if (imbalanced_active_balance(env))
11664 		return 1;
11665 
11666 	/*
11667 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11668 	 * It's worth migrating the task if the src_cpu's capacity is reduced
11669 	 * because of other sched_class or IRQs if more capacity stays
11670 	 * available on dst_cpu.
11671 	 */
11672 	if (env->idle &&
11673 	    (env->src_rq->cfs.h_nr_runnable == 1)) {
11674 		if ((check_cpu_capacity(env->src_rq, sd)) &&
11675 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11676 			return 1;
11677 	}
11678 
11679 	if (env->migration_type == migrate_misfit)
11680 		return 1;
11681 
11682 	return 0;
11683 }
11684 
11685 static int active_load_balance_cpu_stop(void *data);
11686 
should_we_balance(struct lb_env * env)11687 static int should_we_balance(struct lb_env *env)
11688 {
11689 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11690 	struct sched_group *sg = env->sd->groups;
11691 	int cpu, idle_smt = -1;
11692 
11693 	/*
11694 	 * Ensure the balancing environment is consistent; can happen
11695 	 * when the softirq triggers 'during' hotplug.
11696 	 */
11697 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11698 		return 0;
11699 
11700 	/*
11701 	 * In the newly idle case, we will allow all the CPUs
11702 	 * to do the newly idle load balance.
11703 	 *
11704 	 * However, we bail out if we already have tasks or a wakeup pending,
11705 	 * to optimize wakeup latency.
11706 	 */
11707 	if (env->idle == CPU_NEWLY_IDLE) {
11708 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11709 			return 0;
11710 		return 1;
11711 	}
11712 
11713 	cpumask_copy(swb_cpus, group_balance_mask(sg));
11714 	/* Try to find first idle CPU */
11715 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11716 		if (!idle_cpu(cpu))
11717 			continue;
11718 
11719 		/*
11720 		 * Don't balance to idle SMT in busy core right away when
11721 		 * balancing cores, but remember the first idle SMT CPU for
11722 		 * later consideration.  Find CPU on an idle core first.
11723 		 */
11724 		if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11725 			if (idle_smt == -1)
11726 				idle_smt = cpu;
11727 			/*
11728 			 * If the core is not idle, and first SMT sibling which is
11729 			 * idle has been found, then its not needed to check other
11730 			 * SMT siblings for idleness:
11731 			 */
11732 #ifdef CONFIG_SCHED_SMT
11733 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11734 #endif
11735 			continue;
11736 		}
11737 
11738 		/*
11739 		 * Are we the first idle core in a non-SMT domain or higher,
11740 		 * or the first idle CPU in a SMT domain?
11741 		 */
11742 		return cpu == env->dst_cpu;
11743 	}
11744 
11745 	/* Are we the first idle CPU with busy siblings? */
11746 	if (idle_smt != -1)
11747 		return idle_smt == env->dst_cpu;
11748 
11749 	/* Are we the first CPU of this group ? */
11750 	return group_balance_cpu(sg) == env->dst_cpu;
11751 }
11752 
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)11753 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
11754 				     enum cpu_idle_type idle)
11755 {
11756 	if (!schedstat_enabled())
11757 		return;
11758 
11759 	switch (env->migration_type) {
11760 	case migrate_load:
11761 		__schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
11762 		break;
11763 	case migrate_util:
11764 		__schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
11765 		break;
11766 	case migrate_task:
11767 		__schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
11768 		break;
11769 	case migrate_misfit:
11770 		__schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
11771 		break;
11772 	}
11773 }
11774 
11775 /*
11776  * This flag serializes load-balancing passes over large domains
11777  * (above the NODE topology level) - only one load-balancing instance
11778  * may run at a time, to reduce overhead on very large systems with
11779  * lots of CPUs and large NUMA distances.
11780  *
11781  * - Note that load-balancing passes triggered while another one
11782  *   is executing are skipped and not re-tried.
11783  *
11784  * - Also note that this does not serialize rebalance_domains()
11785  *   execution, as non-SD_SERIALIZE domains will still be
11786  *   load-balanced in parallel.
11787  */
11788 static atomic_t sched_balance_running = ATOMIC_INIT(0);
11789 
11790 /*
11791  * Check this_cpu to ensure it is balanced within domain. Attempt to move
11792  * tasks if there is an imbalance.
11793  */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11794 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11795 			struct sched_domain *sd, enum cpu_idle_type idle,
11796 			int *continue_balancing)
11797 {
11798 	int ld_moved, cur_ld_moved, active_balance = 0;
11799 	struct sched_domain *sd_parent = sd->parent;
11800 	struct sched_group *group;
11801 	struct rq *busiest;
11802 	struct rq_flags rf;
11803 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11804 	struct lb_env env = {
11805 		.sd		= sd,
11806 		.dst_cpu	= this_cpu,
11807 		.dst_rq		= this_rq,
11808 		.dst_grpmask    = group_balance_mask(sd->groups),
11809 		.idle		= idle,
11810 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
11811 		.cpus		= cpus,
11812 		.fbq_type	= all,
11813 		.tasks		= LIST_HEAD_INIT(env.tasks),
11814 	};
11815 	bool need_unlock = false;
11816 
11817 	cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11818 
11819 	schedstat_inc(sd->lb_count[idle]);
11820 
11821 redo:
11822 	if (!should_we_balance(&env)) {
11823 		*continue_balancing = 0;
11824 		goto out_balanced;
11825 	}
11826 
11827 	if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
11828 		int zero = 0;
11829 		if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
11830 			goto out_balanced;
11831 
11832 		need_unlock = true;
11833 	}
11834 
11835 	group = sched_balance_find_src_group(&env);
11836 	if (!group) {
11837 		schedstat_inc(sd->lb_nobusyg[idle]);
11838 		goto out_balanced;
11839 	}
11840 
11841 	busiest = sched_balance_find_src_rq(&env, group);
11842 	if (!busiest) {
11843 		schedstat_inc(sd->lb_nobusyq[idle]);
11844 		goto out_balanced;
11845 	}
11846 
11847 	WARN_ON_ONCE(busiest == env.dst_rq);
11848 
11849 	update_lb_imbalance_stat(&env, sd, idle);
11850 
11851 	env.src_cpu = busiest->cpu;
11852 	env.src_rq = busiest;
11853 
11854 	ld_moved = 0;
11855 	/* Clear this flag as soon as we find a pullable task */
11856 	env.flags |= LBF_ALL_PINNED;
11857 	if (busiest->nr_running > 1) {
11858 		/*
11859 		 * Attempt to move tasks. If sched_balance_find_src_group has found
11860 		 * an imbalance but busiest->nr_running <= 1, the group is
11861 		 * still unbalanced. ld_moved simply stays zero, so it is
11862 		 * correctly treated as an imbalance.
11863 		 */
11864 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
11865 
11866 more_balance:
11867 		rq_lock_irqsave(busiest, &rf);
11868 		update_rq_clock(busiest);
11869 
11870 		/*
11871 		 * cur_ld_moved - load moved in current iteration
11872 		 * ld_moved     - cumulative load moved across iterations
11873 		 */
11874 		cur_ld_moved = detach_tasks(&env);
11875 
11876 		/*
11877 		 * We've detached some tasks from busiest_rq. Every
11878 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11879 		 * unlock busiest->lock, and we are able to be sure
11880 		 * that nobody can manipulate the tasks in parallel.
11881 		 * See task_rq_lock() family for the details.
11882 		 */
11883 
11884 		rq_unlock(busiest, &rf);
11885 
11886 		if (cur_ld_moved) {
11887 			attach_tasks(&env);
11888 			ld_moved += cur_ld_moved;
11889 		}
11890 
11891 		local_irq_restore(rf.flags);
11892 
11893 		if (env.flags & LBF_NEED_BREAK) {
11894 			env.flags &= ~LBF_NEED_BREAK;
11895 			goto more_balance;
11896 		}
11897 
11898 		/*
11899 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11900 		 * us and move them to an alternate dst_cpu in our sched_group
11901 		 * where they can run. The upper limit on how many times we
11902 		 * iterate on same src_cpu is dependent on number of CPUs in our
11903 		 * sched_group.
11904 		 *
11905 		 * This changes load balance semantics a bit on who can move
11906 		 * load to a given_cpu. In addition to the given_cpu itself
11907 		 * (or a ilb_cpu acting on its behalf where given_cpu is
11908 		 * nohz-idle), we now have balance_cpu in a position to move
11909 		 * load to given_cpu. In rare situations, this may cause
11910 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11911 		 * _independently_ and at _same_ time to move some load to
11912 		 * given_cpu) causing excess load to be moved to given_cpu.
11913 		 * This however should not happen so much in practice and
11914 		 * moreover subsequent load balance cycles should correct the
11915 		 * excess load moved.
11916 		 */
11917 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11918 
11919 			/* Prevent to re-select dst_cpu via env's CPUs */
11920 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
11921 
11922 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
11923 			env.dst_cpu	 = env.new_dst_cpu;
11924 			env.flags	&= ~LBF_DST_PINNED;
11925 			env.loop	 = 0;
11926 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
11927 
11928 			/*
11929 			 * Go back to "more_balance" rather than "redo" since we
11930 			 * need to continue with same src_cpu.
11931 			 */
11932 			goto more_balance;
11933 		}
11934 
11935 		/*
11936 		 * We failed to reach balance because of affinity.
11937 		 */
11938 		if (sd_parent) {
11939 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11940 
11941 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11942 				*group_imbalance = 1;
11943 		}
11944 
11945 		/* All tasks on this runqueue were pinned by CPU affinity */
11946 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
11947 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
11948 			/*
11949 			 * Attempting to continue load balancing at the current
11950 			 * sched_domain level only makes sense if there are
11951 			 * active CPUs remaining as possible busiest CPUs to
11952 			 * pull load from which are not contained within the
11953 			 * destination group that is receiving any migrated
11954 			 * load.
11955 			 */
11956 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
11957 				env.loop = 0;
11958 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
11959 				goto redo;
11960 			}
11961 			goto out_all_pinned;
11962 		}
11963 	}
11964 
11965 	if (!ld_moved) {
11966 		schedstat_inc(sd->lb_failed[idle]);
11967 		/*
11968 		 * Increment the failure counter only on periodic balance.
11969 		 * We do not want newidle balance, which can be very
11970 		 * frequent, pollute the failure counter causing
11971 		 * excessive cache_hot migrations and active balances.
11972 		 *
11973 		 * Similarly for migration_misfit which is not related to
11974 		 * load/util migration, don't pollute nr_balance_failed.
11975 		 */
11976 		if (idle != CPU_NEWLY_IDLE &&
11977 		    env.migration_type != migrate_misfit)
11978 			sd->nr_balance_failed++;
11979 
11980 		if (need_active_balance(&env)) {
11981 			unsigned long flags;
11982 
11983 			raw_spin_rq_lock_irqsave(busiest, flags);
11984 
11985 			/*
11986 			 * Don't kick the active_load_balance_cpu_stop,
11987 			 * if the curr task on busiest CPU can't be
11988 			 * moved to this_cpu:
11989 			 */
11990 			if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11991 				raw_spin_rq_unlock_irqrestore(busiest, flags);
11992 				goto out_one_pinned;
11993 			}
11994 
11995 			/* Record that we found at least one task that could run on this_cpu */
11996 			env.flags &= ~LBF_ALL_PINNED;
11997 
11998 			/*
11999 			 * ->active_balance synchronizes accesses to
12000 			 * ->active_balance_work.  Once set, it's cleared
12001 			 * only after active load balance is finished.
12002 			 */
12003 			if (!busiest->active_balance) {
12004 				busiest->active_balance = 1;
12005 				busiest->push_cpu = this_cpu;
12006 				active_balance = 1;
12007 			}
12008 
12009 			preempt_disable();
12010 			raw_spin_rq_unlock_irqrestore(busiest, flags);
12011 			if (active_balance) {
12012 				stop_one_cpu_nowait(cpu_of(busiest),
12013 					active_load_balance_cpu_stop, busiest,
12014 					&busiest->active_balance_work);
12015 			}
12016 			preempt_enable();
12017 		}
12018 	} else {
12019 		sd->nr_balance_failed = 0;
12020 	}
12021 
12022 	if (likely(!active_balance) || need_active_balance(&env)) {
12023 		/* We were unbalanced, so reset the balancing interval */
12024 		sd->balance_interval = sd->min_interval;
12025 	}
12026 
12027 	goto out;
12028 
12029 out_balanced:
12030 	/*
12031 	 * We reach balance although we may have faced some affinity
12032 	 * constraints. Clear the imbalance flag only if other tasks got
12033 	 * a chance to move and fix the imbalance.
12034 	 */
12035 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12036 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12037 
12038 		if (*group_imbalance)
12039 			*group_imbalance = 0;
12040 	}
12041 
12042 out_all_pinned:
12043 	/*
12044 	 * We reach balance because all tasks are pinned at this level so
12045 	 * we can't migrate them. Let the imbalance flag set so parent level
12046 	 * can try to migrate them.
12047 	 */
12048 	schedstat_inc(sd->lb_balanced[idle]);
12049 
12050 	sd->nr_balance_failed = 0;
12051 
12052 out_one_pinned:
12053 	ld_moved = 0;
12054 
12055 	/*
12056 	 * sched_balance_newidle() disregards balance intervals, so we could
12057 	 * repeatedly reach this code, which would lead to balance_interval
12058 	 * skyrocketing in a short amount of time. Skip the balance_interval
12059 	 * increase logic to avoid that.
12060 	 *
12061 	 * Similarly misfit migration which is not necessarily an indication of
12062 	 * the system being busy and requires lb to backoff to let it settle
12063 	 * down.
12064 	 */
12065 	if (env.idle == CPU_NEWLY_IDLE ||
12066 	    env.migration_type == migrate_misfit)
12067 		goto out;
12068 
12069 	/* tune up the balancing interval */
12070 	if ((env.flags & LBF_ALL_PINNED &&
12071 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
12072 	    sd->balance_interval < sd->max_interval)
12073 		sd->balance_interval *= 2;
12074 out:
12075 	if (need_unlock)
12076 		atomic_set_release(&sched_balance_running, 0);
12077 
12078 	return ld_moved;
12079 }
12080 
12081 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)12082 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12083 {
12084 	unsigned long interval = sd->balance_interval;
12085 
12086 	if (cpu_busy)
12087 		interval *= sd->busy_factor;
12088 
12089 	/* scale ms to jiffies */
12090 	interval = msecs_to_jiffies(interval);
12091 
12092 	/*
12093 	 * Reduce likelihood of busy balancing at higher domains racing with
12094 	 * balancing at lower domains by preventing their balancing periods
12095 	 * from being multiples of each other.
12096 	 */
12097 	if (cpu_busy)
12098 		interval -= 1;
12099 
12100 	interval = clamp(interval, 1UL, max_load_balance_interval);
12101 
12102 	return interval;
12103 }
12104 
12105 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12106 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12107 {
12108 	unsigned long interval, next;
12109 
12110 	/* used by idle balance, so cpu_busy = 0 */
12111 	interval = get_sd_balance_interval(sd, 0);
12112 	next = sd->last_balance + interval;
12113 
12114 	if (time_after(*next_balance, next))
12115 		*next_balance = next;
12116 }
12117 
12118 /*
12119  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12120  * running tasks off the busiest CPU onto idle CPUs. It requires at
12121  * least 1 task to be running on each physical CPU where possible, and
12122  * avoids physical / logical imbalances.
12123  */
active_load_balance_cpu_stop(void * data)12124 static int active_load_balance_cpu_stop(void *data)
12125 {
12126 	struct rq *busiest_rq = data;
12127 	int busiest_cpu = cpu_of(busiest_rq);
12128 	int target_cpu = busiest_rq->push_cpu;
12129 	struct rq *target_rq = cpu_rq(target_cpu);
12130 	struct sched_domain *sd;
12131 	struct task_struct *p = NULL;
12132 	struct rq_flags rf;
12133 
12134 	rq_lock_irq(busiest_rq, &rf);
12135 	/*
12136 	 * Between queueing the stop-work and running it is a hole in which
12137 	 * CPUs can become inactive. We should not move tasks from or to
12138 	 * inactive CPUs.
12139 	 */
12140 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12141 		goto out_unlock;
12142 
12143 	/* Make sure the requested CPU hasn't gone down in the meantime: */
12144 	if (unlikely(busiest_cpu != smp_processor_id() ||
12145 		     !busiest_rq->active_balance))
12146 		goto out_unlock;
12147 
12148 	/* Is there any task to move? */
12149 	if (busiest_rq->nr_running <= 1)
12150 		goto out_unlock;
12151 
12152 	/*
12153 	 * This condition is "impossible", if it occurs
12154 	 * we need to fix it. Originally reported by
12155 	 * Bjorn Helgaas on a 128-CPU setup.
12156 	 */
12157 	WARN_ON_ONCE(busiest_rq == target_rq);
12158 
12159 	/* Search for an sd spanning us and the target CPU. */
12160 	rcu_read_lock();
12161 	for_each_domain(target_cpu, sd) {
12162 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12163 			break;
12164 	}
12165 
12166 	if (likely(sd)) {
12167 		struct lb_env env = {
12168 			.sd		= sd,
12169 			.dst_cpu	= target_cpu,
12170 			.dst_rq		= target_rq,
12171 			.src_cpu	= busiest_rq->cpu,
12172 			.src_rq		= busiest_rq,
12173 			.idle		= CPU_IDLE,
12174 			.flags		= LBF_ACTIVE_LB,
12175 		};
12176 
12177 		schedstat_inc(sd->alb_count);
12178 		update_rq_clock(busiest_rq);
12179 
12180 		p = detach_one_task(&env);
12181 		if (p) {
12182 			schedstat_inc(sd->alb_pushed);
12183 			/* Active balancing done, reset the failure counter. */
12184 			sd->nr_balance_failed = 0;
12185 		} else {
12186 			schedstat_inc(sd->alb_failed);
12187 		}
12188 	}
12189 	rcu_read_unlock();
12190 out_unlock:
12191 	busiest_rq->active_balance = 0;
12192 	rq_unlock(busiest_rq, &rf);
12193 
12194 	if (p)
12195 		attach_one_task(target_rq, p);
12196 
12197 	local_irq_enable();
12198 
12199 	return 0;
12200 }
12201 
12202 /*
12203  * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12204  * This trades load-balance latency on larger machines for less cross talk.
12205  */
update_max_interval(void)12206 void update_max_interval(void)
12207 {
12208 	max_load_balance_interval = HZ*num_online_cpus()/10;
12209 }
12210 
update_newidle_stats(struct sched_domain * sd,unsigned int success)12211 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
12212 {
12213 	sd->newidle_call++;
12214 	sd->newidle_success += success;
12215 
12216 	if (sd->newidle_call >= 1024) {
12217 		sd->newidle_ratio = sd->newidle_success;
12218 		sd->newidle_call /= 2;
12219 		sd->newidle_success /= 2;
12220 	}
12221 }
12222 
12223 static inline bool
update_newidle_cost(struct sched_domain * sd,u64 cost,unsigned int success)12224 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
12225 {
12226 	unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
12227 	unsigned long now = jiffies;
12228 
12229 	if (cost)
12230 		update_newidle_stats(sd, success);
12231 
12232 	if (cost > sd->max_newidle_lb_cost) {
12233 		/*
12234 		 * Track max cost of a domain to make sure to not delay the
12235 		 * next wakeup on the CPU.
12236 		 */
12237 		sd->max_newidle_lb_cost = cost;
12238 		sd->last_decay_max_lb_cost = now;
12239 
12240 	} else if (time_after(now, next_decay)) {
12241 		/*
12242 		 * Decay the newidle max times by ~1% per second to ensure that
12243 		 * it is not outdated and the current max cost is actually
12244 		 * shorter.
12245 		 */
12246 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12247 		sd->last_decay_max_lb_cost = now;
12248 		return true;
12249 	}
12250 
12251 	return false;
12252 }
12253 
12254 /*
12255  * It checks each scheduling domain to see if it is due to be balanced,
12256  * and initiates a balancing operation if so.
12257  *
12258  * Balancing parameters are set up in init_sched_domains.
12259  */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12260 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12261 {
12262 	int continue_balancing = 1;
12263 	int cpu = rq->cpu;
12264 	int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12265 	unsigned long interval;
12266 	struct sched_domain *sd;
12267 	/* Earliest time when we have to do rebalance again */
12268 	unsigned long next_balance = jiffies + 60*HZ;
12269 	int update_next_balance = 0;
12270 	int need_decay = 0;
12271 	u64 max_cost = 0;
12272 
12273 	rcu_read_lock();
12274 	for_each_domain(cpu, sd) {
12275 		/*
12276 		 * Decay the newidle max times here because this is a regular
12277 		 * visit to all the domains.
12278 		 */
12279 		need_decay = update_newidle_cost(sd, 0, 0);
12280 		max_cost += sd->max_newidle_lb_cost;
12281 
12282 		/*
12283 		 * Stop the load balance at this level. There is another
12284 		 * CPU in our sched group which is doing load balancing more
12285 		 * actively.
12286 		 */
12287 		if (!continue_balancing) {
12288 			if (need_decay)
12289 				continue;
12290 			break;
12291 		}
12292 
12293 		interval = get_sd_balance_interval(sd, busy);
12294 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
12295 			if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12296 				/*
12297 				 * The LBF_DST_PINNED logic could have changed
12298 				 * env->dst_cpu, so we can't know our idle
12299 				 * state even if we migrated tasks. Update it.
12300 				 */
12301 				idle = idle_cpu(cpu);
12302 				busy = !idle && !sched_idle_cpu(cpu);
12303 			}
12304 			sd->last_balance = jiffies;
12305 			interval = get_sd_balance_interval(sd, busy);
12306 		}
12307 		if (time_after(next_balance, sd->last_balance + interval)) {
12308 			next_balance = sd->last_balance + interval;
12309 			update_next_balance = 1;
12310 		}
12311 	}
12312 	if (need_decay) {
12313 		/*
12314 		 * Ensure the rq-wide value also decays but keep it at a
12315 		 * reasonable floor to avoid funnies with rq->avg_idle.
12316 		 */
12317 		rq->max_idle_balance_cost =
12318 			max((u64)sysctl_sched_migration_cost, max_cost);
12319 	}
12320 	rcu_read_unlock();
12321 
12322 	/*
12323 	 * next_balance will be updated only when there is a need.
12324 	 * When the cpu is attached to null domain for ex, it will not be
12325 	 * updated.
12326 	 */
12327 	if (likely(update_next_balance))
12328 		rq->next_balance = next_balance;
12329 
12330 }
12331 
on_null_domain(struct rq * rq)12332 static inline int on_null_domain(struct rq *rq)
12333 {
12334 	return unlikely(!rcu_dereference_sched(rq->sd));
12335 }
12336 
12337 #ifdef CONFIG_NO_HZ_COMMON
12338 /*
12339  * NOHZ idle load balancing (ILB) details:
12340  *
12341  * - When one of the busy CPUs notices that there may be an idle rebalancing
12342  *   needed, they will kick the idle load balancer, which then does idle
12343  *   load balancing for all the idle CPUs.
12344  */
find_new_ilb(void)12345 static inline int find_new_ilb(void)
12346 {
12347 	const struct cpumask *hk_mask;
12348 	int ilb_cpu;
12349 
12350 	hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12351 
12352 	for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12353 
12354 		if (ilb_cpu == smp_processor_id())
12355 			continue;
12356 
12357 		if (idle_cpu(ilb_cpu))
12358 			return ilb_cpu;
12359 	}
12360 
12361 	return -1;
12362 }
12363 
12364 /*
12365  * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12366  * SMP function call (IPI).
12367  *
12368  * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12369  * (if there is one).
12370  */
kick_ilb(unsigned int flags)12371 static void kick_ilb(unsigned int flags)
12372 {
12373 	int ilb_cpu;
12374 
12375 	/*
12376 	 * Increase nohz.next_balance only when if full ilb is triggered but
12377 	 * not if we only update stats.
12378 	 */
12379 	if (flags & NOHZ_BALANCE_KICK)
12380 		nohz.next_balance = jiffies+1;
12381 
12382 	ilb_cpu = find_new_ilb();
12383 	if (ilb_cpu < 0)
12384 		return;
12385 
12386 	/*
12387 	 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12388 	 * i.e. all bits in flags are already set in ilb_cpu.
12389 	 */
12390 	if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12391 		return;
12392 
12393 	/*
12394 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12395 	 * the first flag owns it; cleared by nohz_csd_func().
12396 	 */
12397 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12398 	if (flags & NOHZ_KICK_MASK)
12399 		return;
12400 
12401 	/*
12402 	 * This way we generate an IPI on the target CPU which
12403 	 * is idle, and the softirq performing NOHZ idle load balancing
12404 	 * will be run before returning from the IPI.
12405 	 */
12406 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12407 }
12408 
12409 /*
12410  * Current decision point for kicking the idle load balancer in the presence
12411  * of idle CPUs in the system.
12412  */
nohz_balancer_kick(struct rq * rq)12413 static void nohz_balancer_kick(struct rq *rq)
12414 {
12415 	unsigned long now = jiffies;
12416 	struct sched_domain_shared *sds;
12417 	struct sched_domain *sd;
12418 	int nr_busy, i, cpu = rq->cpu;
12419 	unsigned int flags = 0;
12420 
12421 	if (unlikely(rq->idle_balance))
12422 		return;
12423 
12424 	/*
12425 	 * We may be recently in ticked or tickless idle mode. At the first
12426 	 * busy tick after returning from idle, we will update the busy stats.
12427 	 */
12428 	nohz_balance_exit_idle(rq);
12429 
12430 	/*
12431 	 * None are in tickless mode and hence no need for NOHZ idle load
12432 	 * balancing:
12433 	 */
12434 	if (likely(!atomic_read(&nohz.nr_cpus)))
12435 		return;
12436 
12437 	if (READ_ONCE(nohz.has_blocked) &&
12438 	    time_after(now, READ_ONCE(nohz.next_blocked)))
12439 		flags = NOHZ_STATS_KICK;
12440 
12441 	if (time_before(now, nohz.next_balance))
12442 		goto out;
12443 
12444 	if (rq->nr_running >= 2) {
12445 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12446 		goto out;
12447 	}
12448 
12449 	rcu_read_lock();
12450 
12451 	sd = rcu_dereference(rq->sd);
12452 	if (sd) {
12453 		/*
12454 		 * If there's a runnable CFS task and the current CPU has reduced
12455 		 * capacity, kick the ILB to see if there's a better CPU to run on:
12456 		 */
12457 		if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12458 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12459 			goto unlock;
12460 		}
12461 	}
12462 
12463 	sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12464 	if (sd) {
12465 		/*
12466 		 * When ASYM_PACKING; see if there's a more preferred CPU
12467 		 * currently idle; in which case, kick the ILB to move tasks
12468 		 * around.
12469 		 *
12470 		 * When balancing between cores, all the SMT siblings of the
12471 		 * preferred CPU must be idle.
12472 		 */
12473 		for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12474 			if (sched_asym(sd, i, cpu)) {
12475 				flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12476 				goto unlock;
12477 			}
12478 		}
12479 	}
12480 
12481 	sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12482 	if (sd) {
12483 		/*
12484 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12485 		 * to run the misfit task on.
12486 		 */
12487 		if (check_misfit_status(rq)) {
12488 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12489 			goto unlock;
12490 		}
12491 
12492 		/*
12493 		 * For asymmetric systems, we do not want to nicely balance
12494 		 * cache use, instead we want to embrace asymmetry and only
12495 		 * ensure tasks have enough CPU capacity.
12496 		 *
12497 		 * Skip the LLC logic because it's not relevant in that case.
12498 		 */
12499 		goto unlock;
12500 	}
12501 
12502 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12503 	if (sds) {
12504 		/*
12505 		 * If there is an imbalance between LLC domains (IOW we could
12506 		 * increase the overall cache utilization), we need a less-loaded LLC
12507 		 * domain to pull some load from. Likewise, we may need to spread
12508 		 * load within the current LLC domain (e.g. packed SMT cores but
12509 		 * other CPUs are idle). We can't really know from here how busy
12510 		 * the others are - so just get a NOHZ balance going if it looks
12511 		 * like this LLC domain has tasks we could move.
12512 		 */
12513 		nr_busy = atomic_read(&sds->nr_busy_cpus);
12514 		if (nr_busy > 1) {
12515 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12516 			goto unlock;
12517 		}
12518 	}
12519 unlock:
12520 	rcu_read_unlock();
12521 out:
12522 	if (READ_ONCE(nohz.needs_update))
12523 		flags |= NOHZ_NEXT_KICK;
12524 
12525 	if (flags)
12526 		kick_ilb(flags);
12527 }
12528 
set_cpu_sd_state_busy(int cpu)12529 static void set_cpu_sd_state_busy(int cpu)
12530 {
12531 	struct sched_domain *sd;
12532 
12533 	rcu_read_lock();
12534 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12535 
12536 	if (!sd || !sd->nohz_idle)
12537 		goto unlock;
12538 	sd->nohz_idle = 0;
12539 
12540 	atomic_inc(&sd->shared->nr_busy_cpus);
12541 unlock:
12542 	rcu_read_unlock();
12543 }
12544 
nohz_balance_exit_idle(struct rq * rq)12545 void nohz_balance_exit_idle(struct rq *rq)
12546 {
12547 	WARN_ON_ONCE(rq != this_rq());
12548 
12549 	if (likely(!rq->nohz_tick_stopped))
12550 		return;
12551 
12552 	rq->nohz_tick_stopped = 0;
12553 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12554 	atomic_dec(&nohz.nr_cpus);
12555 
12556 	set_cpu_sd_state_busy(rq->cpu);
12557 }
12558 
set_cpu_sd_state_idle(int cpu)12559 static void set_cpu_sd_state_idle(int cpu)
12560 {
12561 	struct sched_domain *sd;
12562 
12563 	rcu_read_lock();
12564 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12565 
12566 	if (!sd || sd->nohz_idle)
12567 		goto unlock;
12568 	sd->nohz_idle = 1;
12569 
12570 	atomic_dec(&sd->shared->nr_busy_cpus);
12571 unlock:
12572 	rcu_read_unlock();
12573 }
12574 
12575 /*
12576  * This routine will record that the CPU is going idle with tick stopped.
12577  * This info will be used in performing idle load balancing in the future.
12578  */
nohz_balance_enter_idle(int cpu)12579 void nohz_balance_enter_idle(int cpu)
12580 {
12581 	struct rq *rq = cpu_rq(cpu);
12582 
12583 	WARN_ON_ONCE(cpu != smp_processor_id());
12584 
12585 	/* If this CPU is going down, then nothing needs to be done: */
12586 	if (!cpu_active(cpu))
12587 		return;
12588 
12589 	/*
12590 	 * Can be set safely without rq->lock held
12591 	 * If a clear happens, it will have evaluated last additions because
12592 	 * rq->lock is held during the check and the clear
12593 	 */
12594 	rq->has_blocked_load = 1;
12595 
12596 	/*
12597 	 * The tick is still stopped but load could have been added in the
12598 	 * meantime. We set the nohz.has_blocked flag to trig a check of the
12599 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12600 	 * of nohz.has_blocked can only happen after checking the new load
12601 	 */
12602 	if (rq->nohz_tick_stopped)
12603 		goto out;
12604 
12605 	/* If we're a completely isolated CPU, we don't play: */
12606 	if (on_null_domain(rq))
12607 		return;
12608 
12609 	rq->nohz_tick_stopped = 1;
12610 
12611 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12612 	atomic_inc(&nohz.nr_cpus);
12613 
12614 	/*
12615 	 * Ensures that if nohz_idle_balance() fails to observe our
12616 	 * @idle_cpus_mask store, it must observe the @has_blocked
12617 	 * and @needs_update stores.
12618 	 */
12619 	smp_mb__after_atomic();
12620 
12621 	set_cpu_sd_state_idle(cpu);
12622 
12623 	WRITE_ONCE(nohz.needs_update, 1);
12624 out:
12625 	/*
12626 	 * Each time a cpu enter idle, we assume that it has blocked load and
12627 	 * enable the periodic update of the load of idle CPUs
12628 	 */
12629 	WRITE_ONCE(nohz.has_blocked, 1);
12630 }
12631 
update_nohz_stats(struct rq * rq)12632 static bool update_nohz_stats(struct rq *rq)
12633 {
12634 	unsigned int cpu = rq->cpu;
12635 
12636 	if (!rq->has_blocked_load)
12637 		return false;
12638 
12639 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12640 		return false;
12641 
12642 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12643 		return true;
12644 
12645 	sched_balance_update_blocked_averages(cpu);
12646 
12647 	return rq->has_blocked_load;
12648 }
12649 
12650 /*
12651  * Internal function that runs load balance for all idle CPUs. The load balance
12652  * can be a simple update of blocked load or a complete load balance with
12653  * tasks movement depending of flags.
12654  */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12655 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12656 {
12657 	/* Earliest time when we have to do rebalance again */
12658 	unsigned long now = jiffies;
12659 	unsigned long next_balance = now + 60*HZ;
12660 	bool has_blocked_load = false;
12661 	int update_next_balance = 0;
12662 	int this_cpu = this_rq->cpu;
12663 	int balance_cpu;
12664 	struct rq *rq;
12665 
12666 	WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12667 
12668 	/*
12669 	 * We assume there will be no idle load after this update and clear
12670 	 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12671 	 * set the has_blocked flag and trigger another update of idle load.
12672 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12673 	 * setting the flag, we are sure to not clear the state and not
12674 	 * check the load of an idle cpu.
12675 	 *
12676 	 * Same applies to idle_cpus_mask vs needs_update.
12677 	 */
12678 	if (flags & NOHZ_STATS_KICK)
12679 		WRITE_ONCE(nohz.has_blocked, 0);
12680 	if (flags & NOHZ_NEXT_KICK)
12681 		WRITE_ONCE(nohz.needs_update, 0);
12682 
12683 	/*
12684 	 * Ensures that if we miss the CPU, we must see the has_blocked
12685 	 * store from nohz_balance_enter_idle().
12686 	 */
12687 	smp_mb();
12688 
12689 	/*
12690 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12691 	 * chance for other idle cpu to pull load.
12692 	 */
12693 	for_each_cpu_wrap(balance_cpu,  nohz.idle_cpus_mask, this_cpu+1) {
12694 		if (!idle_cpu(balance_cpu))
12695 			continue;
12696 
12697 		/*
12698 		 * If this CPU gets work to do, stop the load balancing
12699 		 * work being done for other CPUs. Next load
12700 		 * balancing owner will pick it up.
12701 		 */
12702 		if (!idle_cpu(this_cpu) && need_resched()) {
12703 			if (flags & NOHZ_STATS_KICK)
12704 				has_blocked_load = true;
12705 			if (flags & NOHZ_NEXT_KICK)
12706 				WRITE_ONCE(nohz.needs_update, 1);
12707 			goto abort;
12708 		}
12709 
12710 		rq = cpu_rq(balance_cpu);
12711 
12712 		if (flags & NOHZ_STATS_KICK)
12713 			has_blocked_load |= update_nohz_stats(rq);
12714 
12715 		/*
12716 		 * If time for next balance is due,
12717 		 * do the balance.
12718 		 */
12719 		if (time_after_eq(jiffies, rq->next_balance)) {
12720 			struct rq_flags rf;
12721 
12722 			rq_lock_irqsave(rq, &rf);
12723 			update_rq_clock(rq);
12724 			rq_unlock_irqrestore(rq, &rf);
12725 
12726 			if (flags & NOHZ_BALANCE_KICK)
12727 				sched_balance_domains(rq, CPU_IDLE);
12728 		}
12729 
12730 		if (time_after(next_balance, rq->next_balance)) {
12731 			next_balance = rq->next_balance;
12732 			update_next_balance = 1;
12733 		}
12734 	}
12735 
12736 	/*
12737 	 * next_balance will be updated only when there is a need.
12738 	 * When the CPU is attached to null domain for ex, it will not be
12739 	 * updated.
12740 	 */
12741 	if (likely(update_next_balance))
12742 		nohz.next_balance = next_balance;
12743 
12744 	if (flags & NOHZ_STATS_KICK)
12745 		WRITE_ONCE(nohz.next_blocked,
12746 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12747 
12748 abort:
12749 	/* There is still blocked load, enable periodic update */
12750 	if (has_blocked_load)
12751 		WRITE_ONCE(nohz.has_blocked, 1);
12752 }
12753 
12754 /*
12755  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12756  * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12757  */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12758 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12759 {
12760 	unsigned int flags = this_rq->nohz_idle_balance;
12761 
12762 	if (!flags)
12763 		return false;
12764 
12765 	this_rq->nohz_idle_balance = 0;
12766 
12767 	if (idle != CPU_IDLE)
12768 		return false;
12769 
12770 	_nohz_idle_balance(this_rq, flags);
12771 
12772 	return true;
12773 }
12774 
12775 /*
12776  * Check if we need to directly run the ILB for updating blocked load before
12777  * entering idle state. Here we run ILB directly without issuing IPIs.
12778  *
12779  * Note that when this function is called, the tick may not yet be stopped on
12780  * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12781  * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12782  * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12783  * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12784  * called from this function on (this) CPU that's not yet in the mask. That's
12785  * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12786  * updating the blocked load of already idle CPUs without waking up one of
12787  * those idle CPUs and outside the preempt disable / IRQ off phase of the local
12788  * cpu about to enter idle, because it can take a long time.
12789  */
nohz_run_idle_balance(int cpu)12790 void nohz_run_idle_balance(int cpu)
12791 {
12792 	unsigned int flags;
12793 
12794 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12795 
12796 	/*
12797 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12798 	 * (i.e. NOHZ_STATS_KICK set) and will do the same.
12799 	 */
12800 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12801 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12802 }
12803 
nohz_newidle_balance(struct rq * this_rq)12804 static void nohz_newidle_balance(struct rq *this_rq)
12805 {
12806 	int this_cpu = this_rq->cpu;
12807 
12808 	/* Will wake up very soon. No time for doing anything else*/
12809 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
12810 		return;
12811 
12812 	/* Don't need to update blocked load of idle CPUs*/
12813 	if (!READ_ONCE(nohz.has_blocked) ||
12814 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12815 		return;
12816 
12817 	/*
12818 	 * Set the need to trigger ILB in order to update blocked load
12819 	 * before entering idle state.
12820 	 */
12821 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12822 }
12823 
12824 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balancer_kick(struct rq * rq)12825 static inline void nohz_balancer_kick(struct rq *rq) { }
12826 
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12827 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12828 {
12829 	return false;
12830 }
12831 
nohz_newidle_balance(struct rq * this_rq)12832 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12833 #endif /* !CONFIG_NO_HZ_COMMON */
12834 
12835 /*
12836  * sched_balance_newidle is called by schedule() if this_cpu is about to become
12837  * idle. Attempts to pull tasks from other CPUs.
12838  *
12839  * Returns:
12840  *   < 0 - we released the lock and there are !fair tasks present
12841  *     0 - failed, no new tasks
12842  *   > 0 - success, new (fair) tasks present
12843  */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)12844 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
12845 {
12846 	unsigned long next_balance = jiffies + HZ;
12847 	int this_cpu = this_rq->cpu;
12848 	int continue_balancing = 1;
12849 	u64 t0, t1, curr_cost = 0;
12850 	struct sched_domain *sd;
12851 	int pulled_task = 0;
12852 
12853 	update_misfit_status(NULL, this_rq);
12854 
12855 	/*
12856 	 * There is a task waiting to run. No need to search for one.
12857 	 * Return 0; the task will be enqueued when switching to idle.
12858 	 */
12859 	if (this_rq->ttwu_pending)
12860 		return 0;
12861 
12862 	/*
12863 	 * We must set idle_stamp _before_ calling sched_balance_rq()
12864 	 * for CPU_NEWLY_IDLE, such that we measure the this duration
12865 	 * as idle time.
12866 	 */
12867 	this_rq->idle_stamp = rq_clock(this_rq);
12868 
12869 	/*
12870 	 * Do not pull tasks towards !active CPUs...
12871 	 */
12872 	if (!cpu_active(this_cpu))
12873 		return 0;
12874 
12875 	/*
12876 	 * This is OK, because current is on_cpu, which avoids it being picked
12877 	 * for load-balance and preemption/IRQs are still disabled avoiding
12878 	 * further scheduler activity on it and we're being very careful to
12879 	 * re-start the picking loop.
12880 	 */
12881 	rq_unpin_lock(this_rq, rf);
12882 
12883 	rcu_read_lock();
12884 	sd = rcu_dereference_check_sched_domain(this_rq->sd);
12885 	if (!sd) {
12886 		rcu_read_unlock();
12887 		goto out;
12888 	}
12889 
12890 	if (!get_rd_overloaded(this_rq->rd) ||
12891 	    this_rq->avg_idle < sd->max_newidle_lb_cost) {
12892 
12893 		update_next_balance(sd, &next_balance);
12894 		rcu_read_unlock();
12895 		goto out;
12896 	}
12897 	rcu_read_unlock();
12898 
12899 	rq_modified_clear(this_rq);
12900 	raw_spin_rq_unlock(this_rq);
12901 
12902 	t0 = sched_clock_cpu(this_cpu);
12903 	sched_balance_update_blocked_averages(this_cpu);
12904 
12905 	rcu_read_lock();
12906 	for_each_domain(this_cpu, sd) {
12907 		u64 domain_cost;
12908 
12909 		update_next_balance(sd, &next_balance);
12910 
12911 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12912 			break;
12913 
12914 		if (sd->flags & SD_BALANCE_NEWIDLE) {
12915 			unsigned int weight = 1;
12916 
12917 			if (sched_feat(NI_RANDOM)) {
12918 				/*
12919 				 * Throw a 1k sided dice; and only run
12920 				 * newidle_balance according to the success
12921 				 * rate.
12922 				 */
12923 				u32 d1k = sched_rng() % 1024;
12924 				weight = 1 + sd->newidle_ratio;
12925 				if (d1k > weight) {
12926 					update_newidle_stats(sd, 0);
12927 					continue;
12928 				}
12929 				weight = (1024 + weight/2) / weight;
12930 			}
12931 
12932 			pulled_task = sched_balance_rq(this_cpu, this_rq,
12933 						   sd, CPU_NEWLY_IDLE,
12934 						   &continue_balancing);
12935 
12936 			t1 = sched_clock_cpu(this_cpu);
12937 			domain_cost = t1 - t0;
12938 			curr_cost += domain_cost;
12939 			t0 = t1;
12940 
12941 			/*
12942 			 * Track max cost of a domain to make sure to not delay the
12943 			 * next wakeup on the CPU.
12944 			 */
12945 			update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
12946 		}
12947 
12948 		/*
12949 		 * Stop searching for tasks to pull if there are
12950 		 * now runnable tasks on this rq.
12951 		 */
12952 		if (pulled_task || !continue_balancing)
12953 			break;
12954 	}
12955 	rcu_read_unlock();
12956 
12957 	raw_spin_rq_lock(this_rq);
12958 
12959 	if (curr_cost > this_rq->max_idle_balance_cost)
12960 		this_rq->max_idle_balance_cost = curr_cost;
12961 
12962 	/*
12963 	 * While browsing the domains, we released the rq lock, a task could
12964 	 * have been enqueued in the meantime. Since we're not going idle,
12965 	 * pretend we pulled a task.
12966 	 */
12967 	if (this_rq->cfs.h_nr_queued && !pulled_task)
12968 		pulled_task = 1;
12969 
12970 	/* If a higher prio class was modified, restart the pick */
12971 	if (rq_modified_above(this_rq, &fair_sched_class))
12972 		pulled_task = -1;
12973 
12974 out:
12975 	/* Move the next balance forward */
12976 	if (time_after(this_rq->next_balance, next_balance))
12977 		this_rq->next_balance = next_balance;
12978 
12979 	if (pulled_task)
12980 		this_rq->idle_stamp = 0;
12981 	else
12982 		nohz_newidle_balance(this_rq);
12983 
12984 	rq_repin_lock(this_rq, rf);
12985 
12986 	return pulled_task;
12987 }
12988 
12989 /*
12990  * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
12991  *
12992  * - directly from the local sched_tick() for periodic load balancing
12993  *
12994  * - indirectly from a remote sched_tick() for NOHZ idle balancing
12995  *   through the SMP cross-call nohz_csd_func()
12996  */
sched_balance_softirq(void)12997 static __latent_entropy void sched_balance_softirq(void)
12998 {
12999 	struct rq *this_rq = this_rq();
13000 	enum cpu_idle_type idle = this_rq->idle_balance;
13001 	/*
13002 	 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13003 	 * balancing on behalf of the other idle CPUs whose ticks are
13004 	 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13005 	 * give the idle CPUs a chance to load balance. Else we may
13006 	 * load balance only within the local sched_domain hierarchy
13007 	 * and abort nohz_idle_balance altogether if we pull some load.
13008 	 */
13009 	if (nohz_idle_balance(this_rq, idle))
13010 		return;
13011 
13012 	/* normal load balance */
13013 	sched_balance_update_blocked_averages(this_rq->cpu);
13014 	sched_balance_domains(this_rq, idle);
13015 }
13016 
13017 /*
13018  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13019  */
sched_balance_trigger(struct rq * rq)13020 void sched_balance_trigger(struct rq *rq)
13021 {
13022 	/*
13023 	 * Don't need to rebalance while attached to NULL domain or
13024 	 * runqueue CPU is not active
13025 	 */
13026 	if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13027 		return;
13028 
13029 	if (time_after_eq(jiffies, rq->next_balance))
13030 		raise_softirq(SCHED_SOFTIRQ);
13031 
13032 	nohz_balancer_kick(rq);
13033 }
13034 
rq_online_fair(struct rq * rq)13035 static void rq_online_fair(struct rq *rq)
13036 {
13037 	update_sysctl();
13038 
13039 	update_runtime_enabled(rq);
13040 }
13041 
rq_offline_fair(struct rq * rq)13042 static void rq_offline_fair(struct rq *rq)
13043 {
13044 	update_sysctl();
13045 
13046 	/* Ensure any throttled groups are reachable by pick_next_task */
13047 	unthrottle_offline_cfs_rqs(rq);
13048 
13049 	/* Ensure that we remove rq contribution to group share: */
13050 	clear_tg_offline_cfs_rqs(rq);
13051 }
13052 
13053 #ifdef CONFIG_SCHED_CORE
13054 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13055 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13056 {
13057 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13058 	u64 slice = se->slice;
13059 
13060 	return (rtime * min_nr_tasks > slice);
13061 }
13062 
13063 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
task_tick_core(struct rq * rq,struct task_struct * curr)13064 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13065 {
13066 	if (!sched_core_enabled(rq))
13067 		return;
13068 
13069 	/*
13070 	 * If runqueue has only one task which used up its slice and
13071 	 * if the sibling is forced idle, then trigger schedule to
13072 	 * give forced idle task a chance.
13073 	 *
13074 	 * sched_slice() considers only this active rq and it gets the
13075 	 * whole slice. But during force idle, we have siblings acting
13076 	 * like a single runqueue and hence we need to consider runnable
13077 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
13078 	 * go through the forced idle rq, but that would be a perf hit.
13079 	 * We can assume that the forced idle CPU has at least
13080 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13081 	 * if we need to give up the CPU.
13082 	 */
13083 	if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
13084 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13085 		resched_curr(rq);
13086 }
13087 
13088 /*
13089  * Consider any infeasible weight scenario. Take for instance two tasks,
13090  * each bound to their respective sibling, one with weight 1 and one with
13091  * weight 2. Then the lower weight task will run ahead of the higher weight
13092  * task without bound.
13093  *
13094  * This utterly destroys the concept of a shared time base.
13095  *
13096  * Remember; all this is about a proportionally fair scheduling, where each
13097  * tasks receives:
13098  *
13099  *              w_i
13100  *   dt_i = ---------- dt                                     (1)
13101  *          \Sum_j w_j
13102  *
13103  * which we do by tracking a virtual time, s_i:
13104  *
13105  *          1
13106  *   s_i = --- d[t]_i                                         (2)
13107  *         w_i
13108  *
13109  * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
13110  * The immediate corollary is that the ideal schedule S, where (2) to use
13111  * an infinitesimal delta, is:
13112  *
13113  *           1
13114  *   S = ---------- dt                                        (3)
13115  *       \Sum_i w_i
13116  *
13117  * From which we can define the lag, or deviation from the ideal, as:
13118  *
13119  *   lag(i) = S - s_i                                         (4)
13120  *
13121  * And since the one and only purpose is to approximate S, we get that:
13122  *
13123  *   \Sum_i w_i lag(i) := 0                                   (5)
13124  *
13125  * If this were not so, we no longer converge to S, and we can no longer
13126  * claim our scheduler has any of the properties we derive from S. This is
13127  * exactly what you did above, you broke it!
13128  *
13129  *
13130  * Let's continue for a while though; to see if there is anything useful to
13131  * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
13132  *
13133  *       \Sum_i w_i s_i
13134  *   S = --------------                                       (6)
13135  *         \Sum_i w_i
13136  *
13137  * Which gives us a way to compute S, given our s_i. Now, if you've read
13138  * our code, you know that we do not in fact do this, the reason for this
13139  * is two-fold. Firstly, computing S in that way requires a 64bit division
13140  * for every time we'd use it (see 12), and secondly, this only describes
13141  * the steady-state, it doesn't handle dynamics.
13142  *
13143  * Anyway, in (6):  s_i -> x + (s_i - x), to get:
13144  *
13145  *           \Sum_i w_i (s_i - x)
13146  *   S - x = --------------------                             (7)
13147  *              \Sum_i w_i
13148  *
13149  * Which shows that S and s_i transform alike (which makes perfect sense
13150  * given that S is basically the (weighted) average of s_i).
13151  *
13152  * So the thing to remember is that the above is strictly UP. It is
13153  * possible to generalize to multiple runqueues -- however it gets really
13154  * yuck when you have to add affinity support, as illustrated by our very
13155  * first counter-example.
13156  *
13157  * Luckily I think we can avoid needing a full multi-queue variant for
13158  * core-scheduling (or load-balancing). The crucial observation is that we
13159  * only actually need this comparison in the presence of forced-idle; only
13160  * then do we need to tell if the stalled rq has higher priority over the
13161  * other.
13162  *
13163  * [XXX assumes SMT2; better consider the more general case, I suspect
13164  * it'll work out because our comparison is always between 2 rqs and the
13165  * answer is only interesting if one of them is forced-idle]
13166  *
13167  * And (under assumption of SMT2) when there is forced-idle, there is only
13168  * a single queue, so everything works like normal.
13169  *
13170  * Let, for our runqueue 'k':
13171  *
13172  *   T_k = \Sum_i w_i s_i
13173  *   W_k = \Sum_i w_i      ; for all i of k                  (8)
13174  *
13175  * Then we can write (6) like:
13176  *
13177  *         T_k
13178  *   S_k = ---                                               (9)
13179  *         W_k
13180  *
13181  * From which immediately follows that:
13182  *
13183  *           T_k + T_l
13184  *   S_k+l = ---------                                       (10)
13185  *           W_k + W_l
13186  *
13187  * On which we can define a combined lag:
13188  *
13189  *   lag_k+l(i) := S_k+l - s_i                               (11)
13190  *
13191  * And that gives us the tools to compare tasks across a combined runqueue.
13192  *
13193  *
13194  * Combined this gives the following:
13195  *
13196  *  a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
13197  *     using (7); this only requires storing single 'time'-stamps.
13198  *
13199  *  b) when comparing tasks between 2 runqueues of which one is forced-idle,
13200  *     compare the combined lag, per (11).
13201  *
13202  * Now, of course cgroups (I so hate them) make this more interesting in
13203  * that a) seems to suggest we need to iterate all cgroup on a CPU at such
13204  * boundaries, but I think we can avoid that. The force-idle is for the
13205  * whole CPU, all it's rqs. So we can mark it in the root and lazily
13206  * propagate downward on demand.
13207  */
13208 
13209 /*
13210  * So this sync is basically a relative reset of S to 0.
13211  *
13212  * So with 2 queues, when one goes idle, we drop them both to 0 and one
13213  * then increases due to not being idle, and the idle one builds up lag to
13214  * get re-elected. So far so simple, right?
13215  *
13216  * When there's 3, we can have the situation where 2 run and one is idle,
13217  * we sync to 0 and let the idle one build up lag to get re-election. Now
13218  * suppose another one also drops idle. At this point dropping all to 0
13219  * again would destroy the built-up lag from the queue that was already
13220  * idle, not good.
13221  *
13222  * So instead of syncing everything, we can:
13223  *
13224  *   less := !((s64)(s_a - s_b) <= 0)
13225  *
13226  *   (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
13227  *                             == v_a - (v_b - S_a + S_b)
13228  *
13229  * IOW, we can recast the (lag) comparison to a one-sided difference.
13230  * So if then, instead of syncing the whole queue, sync the idle queue
13231  * against the active queue with S_a + S_b at the point where we sync.
13232  *
13233  * (XXX consider the implication of living in a cyclic group: N / 2^n N)
13234  *
13235  * This gives us means of syncing single queues against the active queue,
13236  * and for already idle queues to preserve their build-up lag.
13237  *
13238  * Of course, then we get the situation where there's 2 active and one
13239  * going idle, who do we pick to sync against? Theory would have us sync
13240  * against the combined S, but as we've already demonstrated, there is no
13241  * such thing in infeasible weight scenarios.
13242  *
13243  * One thing I've considered; and this is where that core_active rudiment
13244  * came from, is having active queues sync up between themselves after
13245  * every tick. This limits the observed divergence due to the work
13246  * conservancy.
13247  *
13248  * On top of that, we can improve upon things by employing (10) here.
13249  */
13250 
13251 /*
13252  * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
13253  */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13254 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13255 			 bool forceidle)
13256 {
13257 	for_each_sched_entity(se) {
13258 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13259 
13260 		if (forceidle) {
13261 			if (cfs_rq->forceidle_seq == fi_seq)
13262 				break;
13263 			cfs_rq->forceidle_seq = fi_seq;
13264 		}
13265 
13266 		cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
13267 	}
13268 }
13269 
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13270 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13271 {
13272 	struct sched_entity *se = &p->se;
13273 
13274 	if (p->sched_class != &fair_sched_class)
13275 		return;
13276 
13277 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13278 }
13279 
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13280 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13281 			bool in_fi)
13282 {
13283 	struct rq *rq = task_rq(a);
13284 	const struct sched_entity *sea = &a->se;
13285 	const struct sched_entity *seb = &b->se;
13286 	struct cfs_rq *cfs_rqa;
13287 	struct cfs_rq *cfs_rqb;
13288 	s64 delta;
13289 
13290 	WARN_ON_ONCE(task_rq(b)->core != rq->core);
13291 
13292 #ifdef CONFIG_FAIR_GROUP_SCHED
13293 	/*
13294 	 * Find an se in the hierarchy for tasks a and b, such that the se's
13295 	 * are immediate siblings.
13296 	 */
13297 	while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13298 		int sea_depth = sea->depth;
13299 		int seb_depth = seb->depth;
13300 
13301 		if (sea_depth >= seb_depth)
13302 			sea = parent_entity(sea);
13303 		if (sea_depth <= seb_depth)
13304 			seb = parent_entity(seb);
13305 	}
13306 
13307 	se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13308 	se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13309 
13310 	cfs_rqa = sea->cfs_rq;
13311 	cfs_rqb = seb->cfs_rq;
13312 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13313 	cfs_rqa = &task_rq(a)->cfs;
13314 	cfs_rqb = &task_rq(b)->cfs;
13315 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13316 
13317 	/*
13318 	 * Find delta after normalizing se's vruntime with its cfs_rq's
13319 	 * zero_vruntime_fi, which would have been updated in prior calls
13320 	 * to se_fi_update().
13321 	 */
13322 	delta = (s64)(sea->vruntime - seb->vruntime) +
13323 		(s64)(cfs_rqb->zero_vruntime_fi - cfs_rqa->zero_vruntime_fi);
13324 
13325 	return delta > 0;
13326 }
13327 
task_is_throttled_fair(struct task_struct * p,int cpu)13328 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13329 {
13330 	struct cfs_rq *cfs_rq;
13331 
13332 #ifdef CONFIG_FAIR_GROUP_SCHED
13333 	cfs_rq = task_group(p)->cfs_rq[cpu];
13334 #else
13335 	cfs_rq = &cpu_rq(cpu)->cfs;
13336 #endif
13337 	return throttled_hierarchy(cfs_rq);
13338 }
13339 #else /* !CONFIG_SCHED_CORE: */
task_tick_core(struct rq * rq,struct task_struct * curr)13340 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13341 #endif /* !CONFIG_SCHED_CORE */
13342 
13343 /*
13344  * scheduler tick hitting a task of our scheduling class.
13345  *
13346  * NOTE: This function can be called remotely by the tick offload that
13347  * goes along full dynticks. Therefore no local assumption can be made
13348  * and everything must be accessed through the @rq and @curr passed in
13349  * parameters.
13350  */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13351 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13352 {
13353 	struct cfs_rq *cfs_rq;
13354 	struct sched_entity *se = &curr->se;
13355 
13356 	for_each_sched_entity(se) {
13357 		cfs_rq = cfs_rq_of(se);
13358 		entity_tick(cfs_rq, se, queued);
13359 	}
13360 
13361 	if (static_branch_unlikely(&sched_numa_balancing))
13362 		task_tick_numa(rq, curr);
13363 
13364 	update_misfit_status(curr, rq);
13365 	check_update_overutilized_status(task_rq(curr));
13366 
13367 	task_tick_core(rq, curr);
13368 }
13369 
13370 /*
13371  * called on fork with the child task as argument from the parent's context
13372  *  - child not yet on the tasklist
13373  *  - preemption disabled
13374  */
task_fork_fair(struct task_struct * p)13375 static void task_fork_fair(struct task_struct *p)
13376 {
13377 	set_task_max_allowed_capacity(p);
13378 }
13379 
13380 /*
13381  * Priority of the task has changed. Check to see if we preempt
13382  * the current task.
13383  */
13384 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,u64 oldprio)13385 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
13386 {
13387 	if (!task_on_rq_queued(p))
13388 		return;
13389 
13390 	if (p->prio == oldprio)
13391 		return;
13392 
13393 	if (rq->cfs.nr_queued == 1)
13394 		return;
13395 
13396 	/*
13397 	 * Reschedule if we are currently running on this runqueue and
13398 	 * our priority decreased, or if we are not currently running on
13399 	 * this runqueue and our priority is higher than the current's
13400 	 */
13401 	if (task_current_donor(rq, p)) {
13402 		if (p->prio > oldprio)
13403 			resched_curr(rq);
13404 	} else {
13405 		wakeup_preempt(rq, p, 0);
13406 	}
13407 }
13408 
13409 #ifdef CONFIG_FAIR_GROUP_SCHED
13410 /*
13411  * Propagate the changes of the sched_entity across the tg tree to make it
13412  * visible to the root
13413  */
propagate_entity_cfs_rq(struct sched_entity * se)13414 static void propagate_entity_cfs_rq(struct sched_entity *se)
13415 {
13416 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13417 
13418 	/*
13419 	 * If a task gets attached to this cfs_rq and before being queued,
13420 	 * it gets migrated to another CPU due to reasons like affinity
13421 	 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
13422 	 * that removed load decayed or it can cause faireness problem.
13423 	 */
13424 	if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13425 		list_add_leaf_cfs_rq(cfs_rq);
13426 
13427 	/* Start to propagate at parent */
13428 	se = se->parent;
13429 
13430 	for_each_sched_entity(se) {
13431 		cfs_rq = cfs_rq_of(se);
13432 
13433 		update_load_avg(cfs_rq, se, UPDATE_TG);
13434 
13435 		if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13436 			list_add_leaf_cfs_rq(cfs_rq);
13437 	}
13438 
13439 	assert_list_leaf_cfs_rq(rq_of(cfs_rq));
13440 }
13441 #else /* !CONFIG_FAIR_GROUP_SCHED: */
propagate_entity_cfs_rq(struct sched_entity * se)13442 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13443 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13444 
detach_entity_cfs_rq(struct sched_entity * se)13445 static void detach_entity_cfs_rq(struct sched_entity *se)
13446 {
13447 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13448 
13449 	/*
13450 	 * In case the task sched_avg hasn't been attached:
13451 	 * - A forked task which hasn't been woken up by wake_up_new_task().
13452 	 * - A task which has been woken up by try_to_wake_up() but is
13453 	 *   waiting for actually being woken up by sched_ttwu_pending().
13454 	 */
13455 	if (!se->avg.last_update_time)
13456 		return;
13457 
13458 	/* Catch up with the cfs_rq and remove our load when we leave */
13459 	update_load_avg(cfs_rq, se, 0);
13460 	detach_entity_load_avg(cfs_rq, se);
13461 	update_tg_load_avg(cfs_rq);
13462 	propagate_entity_cfs_rq(se);
13463 }
13464 
attach_entity_cfs_rq(struct sched_entity * se)13465 static void attach_entity_cfs_rq(struct sched_entity *se)
13466 {
13467 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13468 
13469 	/* Synchronize entity with its cfs_rq */
13470 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13471 	attach_entity_load_avg(cfs_rq, se);
13472 	update_tg_load_avg(cfs_rq);
13473 	propagate_entity_cfs_rq(se);
13474 }
13475 
detach_task_cfs_rq(struct task_struct * p)13476 static void detach_task_cfs_rq(struct task_struct *p)
13477 {
13478 	struct sched_entity *se = &p->se;
13479 
13480 	detach_entity_cfs_rq(se);
13481 }
13482 
attach_task_cfs_rq(struct task_struct * p)13483 static void attach_task_cfs_rq(struct task_struct *p)
13484 {
13485 	struct sched_entity *se = &p->se;
13486 
13487 	attach_entity_cfs_rq(se);
13488 }
13489 
switching_from_fair(struct rq * rq,struct task_struct * p)13490 static void switching_from_fair(struct rq *rq, struct task_struct *p)
13491 {
13492 	if (p->se.sched_delayed)
13493 		dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
13494 }
13495 
switched_from_fair(struct rq * rq,struct task_struct * p)13496 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13497 {
13498 	detach_task_cfs_rq(p);
13499 }
13500 
switched_to_fair(struct rq * rq,struct task_struct * p)13501 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13502 {
13503 	WARN_ON_ONCE(p->se.sched_delayed);
13504 
13505 	attach_task_cfs_rq(p);
13506 
13507 	set_task_max_allowed_capacity(p);
13508 
13509 	if (task_on_rq_queued(p)) {
13510 		/*
13511 		 * We were most likely switched from sched_rt, so
13512 		 * kick off the schedule if running, otherwise just see
13513 		 * if we can still preempt the current task.
13514 		 */
13515 		if (task_current_donor(rq, p))
13516 			resched_curr(rq);
13517 		else
13518 			wakeup_preempt(rq, p, 0);
13519 	}
13520 }
13521 
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13522 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13523 {
13524 	struct sched_entity *se = &p->se;
13525 
13526 	if (task_on_rq_queued(p)) {
13527 		/*
13528 		 * Move the next running task to the front of the list, so our
13529 		 * cfs_tasks list becomes MRU one.
13530 		 */
13531 		list_move(&se->group_node, &rq->cfs_tasks);
13532 	}
13533 	if (!first)
13534 		return;
13535 
13536 	WARN_ON_ONCE(se->sched_delayed);
13537 
13538 	if (hrtick_enabled_fair(rq))
13539 		hrtick_start_fair(rq, p);
13540 
13541 	update_misfit_status(p, rq);
13542 	sched_fair_update_stop_tick(rq, p);
13543 }
13544 
13545 /*
13546  * Account for a task changing its policy or group.
13547  *
13548  * This routine is mostly called to set cfs_rq->curr field when a task
13549  * migrates between groups/classes.
13550  */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13551 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13552 {
13553 	struct sched_entity *se = &p->se;
13554 
13555 	for_each_sched_entity(se) {
13556 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13557 
13558 		set_next_entity(cfs_rq, se);
13559 		/* ensure bandwidth has been allocated on our new cfs_rq */
13560 		account_cfs_rq_runtime(cfs_rq, 0);
13561 	}
13562 
13563 	__set_next_task_fair(rq, p, first);
13564 }
13565 
init_cfs_rq(struct cfs_rq * cfs_rq)13566 void init_cfs_rq(struct cfs_rq *cfs_rq)
13567 {
13568 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13569 	cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
13570 	raw_spin_lock_init(&cfs_rq->removed.lock);
13571 }
13572 
13573 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13574 static void task_change_group_fair(struct task_struct *p)
13575 {
13576 	/*
13577 	 * We couldn't detach or attach a forked task which
13578 	 * hasn't been woken up by wake_up_new_task().
13579 	 */
13580 	if (READ_ONCE(p->__state) == TASK_NEW)
13581 		return;
13582 
13583 	detach_task_cfs_rq(p);
13584 
13585 	/* Tell se's cfs_rq has been changed -- migrated */
13586 	p->se.avg.last_update_time = 0;
13587 	set_task_rq(p, task_cpu(p));
13588 	attach_task_cfs_rq(p);
13589 }
13590 
free_fair_sched_group(struct task_group * tg)13591 void free_fair_sched_group(struct task_group *tg)
13592 {
13593 	int i;
13594 
13595 	for_each_possible_cpu(i) {
13596 		if (tg->cfs_rq)
13597 			kfree(tg->cfs_rq[i]);
13598 		if (tg->se)
13599 			kfree(tg->se[i]);
13600 	}
13601 
13602 	kfree(tg->cfs_rq);
13603 	kfree(tg->se);
13604 }
13605 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13606 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13607 {
13608 	struct sched_entity *se;
13609 	struct cfs_rq *cfs_rq;
13610 	int i;
13611 
13612 	tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13613 	if (!tg->cfs_rq)
13614 		goto err;
13615 	tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13616 	if (!tg->se)
13617 		goto err;
13618 
13619 	tg->shares = NICE_0_LOAD;
13620 
13621 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13622 
13623 	for_each_possible_cpu(i) {
13624 		cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13625 				      GFP_KERNEL, cpu_to_node(i));
13626 		if (!cfs_rq)
13627 			goto err;
13628 
13629 		se = kzalloc_node(sizeof(struct sched_entity_stats),
13630 				  GFP_KERNEL, cpu_to_node(i));
13631 		if (!se)
13632 			goto err_free_rq;
13633 
13634 		init_cfs_rq(cfs_rq);
13635 		init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13636 		init_entity_runnable_average(se);
13637 	}
13638 
13639 	return 1;
13640 
13641 err_free_rq:
13642 	kfree(cfs_rq);
13643 err:
13644 	return 0;
13645 }
13646 
online_fair_sched_group(struct task_group * tg)13647 void online_fair_sched_group(struct task_group *tg)
13648 {
13649 	struct sched_entity *se;
13650 	struct rq_flags rf;
13651 	struct rq *rq;
13652 	int i;
13653 
13654 	for_each_possible_cpu(i) {
13655 		rq = cpu_rq(i);
13656 		se = tg->se[i];
13657 		rq_lock_irq(rq, &rf);
13658 		update_rq_clock(rq);
13659 		attach_entity_cfs_rq(se);
13660 		sync_throttle(tg, i);
13661 		rq_unlock_irq(rq, &rf);
13662 	}
13663 }
13664 
unregister_fair_sched_group(struct task_group * tg)13665 void unregister_fair_sched_group(struct task_group *tg)
13666 {
13667 	int cpu;
13668 
13669 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13670 
13671 	for_each_possible_cpu(cpu) {
13672 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13673 		struct sched_entity *se = tg->se[cpu];
13674 		struct rq *rq = cpu_rq(cpu);
13675 
13676 		if (se) {
13677 			if (se->sched_delayed) {
13678 				guard(rq_lock_irqsave)(rq);
13679 				if (se->sched_delayed) {
13680 					update_rq_clock(rq);
13681 					dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13682 				}
13683 				list_del_leaf_cfs_rq(cfs_rq);
13684 			}
13685 			remove_entity_load_avg(se);
13686 		}
13687 
13688 		/*
13689 		 * Only empty task groups can be destroyed; so we can speculatively
13690 		 * check on_list without danger of it being re-added.
13691 		 */
13692 		if (cfs_rq->on_list) {
13693 			guard(rq_lock_irqsave)(rq);
13694 			list_del_leaf_cfs_rq(cfs_rq);
13695 		}
13696 	}
13697 }
13698 
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13699 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13700 			struct sched_entity *se, int cpu,
13701 			struct sched_entity *parent)
13702 {
13703 	struct rq *rq = cpu_rq(cpu);
13704 
13705 	cfs_rq->tg = tg;
13706 	cfs_rq->rq = rq;
13707 	init_cfs_rq_runtime(cfs_rq);
13708 
13709 	tg->cfs_rq[cpu] = cfs_rq;
13710 	tg->se[cpu] = se;
13711 
13712 	/* se could be NULL for root_task_group */
13713 	if (!se)
13714 		return;
13715 
13716 	if (!parent) {
13717 		se->cfs_rq = &rq->cfs;
13718 		se->depth = 0;
13719 	} else {
13720 		se->cfs_rq = parent->my_q;
13721 		se->depth = parent->depth + 1;
13722 	}
13723 
13724 	se->my_q = cfs_rq;
13725 	/* guarantee group entities always have weight */
13726 	update_load_set(&se->load, NICE_0_LOAD);
13727 	se->parent = parent;
13728 }
13729 
13730 static DEFINE_MUTEX(shares_mutex);
13731 
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13732 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13733 {
13734 	int i;
13735 
13736 	lockdep_assert_held(&shares_mutex);
13737 
13738 	/*
13739 	 * We can't change the weight of the root cgroup.
13740 	 */
13741 	if (!tg->se[0])
13742 		return -EINVAL;
13743 
13744 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13745 
13746 	if (tg->shares == shares)
13747 		return 0;
13748 
13749 	tg->shares = shares;
13750 	for_each_possible_cpu(i) {
13751 		struct rq *rq = cpu_rq(i);
13752 		struct sched_entity *se = tg->se[i];
13753 		struct rq_flags rf;
13754 
13755 		/* Propagate contribution to hierarchy */
13756 		rq_lock_irqsave(rq, &rf);
13757 		update_rq_clock(rq);
13758 		for_each_sched_entity(se) {
13759 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13760 			update_cfs_group(se);
13761 		}
13762 		rq_unlock_irqrestore(rq, &rf);
13763 	}
13764 
13765 	return 0;
13766 }
13767 
sched_group_set_shares(struct task_group * tg,unsigned long shares)13768 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13769 {
13770 	int ret;
13771 
13772 	mutex_lock(&shares_mutex);
13773 	if (tg_is_idle(tg))
13774 		ret = -EINVAL;
13775 	else
13776 		ret = __sched_group_set_shares(tg, shares);
13777 	mutex_unlock(&shares_mutex);
13778 
13779 	return ret;
13780 }
13781 
sched_group_set_idle(struct task_group * tg,long idle)13782 int sched_group_set_idle(struct task_group *tg, long idle)
13783 {
13784 	int i;
13785 
13786 	if (tg == &root_task_group)
13787 		return -EINVAL;
13788 
13789 	if (idle < 0 || idle > 1)
13790 		return -EINVAL;
13791 
13792 	mutex_lock(&shares_mutex);
13793 
13794 	if (tg->idle == idle) {
13795 		mutex_unlock(&shares_mutex);
13796 		return 0;
13797 	}
13798 
13799 	tg->idle = idle;
13800 
13801 	for_each_possible_cpu(i) {
13802 		struct rq *rq = cpu_rq(i);
13803 		struct sched_entity *se = tg->se[i];
13804 		struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
13805 		bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13806 		long idle_task_delta;
13807 		struct rq_flags rf;
13808 
13809 		rq_lock_irqsave(rq, &rf);
13810 
13811 		grp_cfs_rq->idle = idle;
13812 		if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13813 			goto next_cpu;
13814 
13815 		idle_task_delta = grp_cfs_rq->h_nr_queued -
13816 				  grp_cfs_rq->h_nr_idle;
13817 		if (!cfs_rq_is_idle(grp_cfs_rq))
13818 			idle_task_delta *= -1;
13819 
13820 		for_each_sched_entity(se) {
13821 			struct cfs_rq *cfs_rq = cfs_rq_of(se);
13822 
13823 			if (!se->on_rq)
13824 				break;
13825 
13826 			cfs_rq->h_nr_idle += idle_task_delta;
13827 
13828 			/* Already accounted at parent level and above. */
13829 			if (cfs_rq_is_idle(cfs_rq))
13830 				break;
13831 		}
13832 
13833 next_cpu:
13834 		rq_unlock_irqrestore(rq, &rf);
13835 	}
13836 
13837 	/* Idle groups have minimum weight. */
13838 	if (tg_is_idle(tg))
13839 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13840 	else
13841 		__sched_group_set_shares(tg, NICE_0_LOAD);
13842 
13843 	mutex_unlock(&shares_mutex);
13844 	return 0;
13845 }
13846 
13847 #endif /* CONFIG_FAIR_GROUP_SCHED */
13848 
13849 
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13850 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13851 {
13852 	struct sched_entity *se = &task->se;
13853 	unsigned int rr_interval = 0;
13854 
13855 	/*
13856 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13857 	 * idle runqueue:
13858 	 */
13859 	if (rq->cfs.load.weight)
13860 		rr_interval = NS_TO_JIFFIES(se->slice);
13861 
13862 	return rr_interval;
13863 }
13864 
13865 /*
13866  * All the scheduling class methods:
13867  */
13868 DEFINE_SCHED_CLASS(fair) = {
13869 
13870 	.queue_mask		= 2,
13871 
13872 	.enqueue_task		= enqueue_task_fair,
13873 	.dequeue_task		= dequeue_task_fair,
13874 	.yield_task		= yield_task_fair,
13875 	.yield_to_task		= yield_to_task_fair,
13876 
13877 	.wakeup_preempt		= check_preempt_wakeup_fair,
13878 
13879 	.pick_task		= pick_task_fair,
13880 	.pick_next_task		= pick_next_task_fair,
13881 	.put_prev_task		= put_prev_task_fair,
13882 	.set_next_task          = set_next_task_fair,
13883 
13884 	.select_task_rq		= select_task_rq_fair,
13885 	.migrate_task_rq	= migrate_task_rq_fair,
13886 
13887 	.rq_online		= rq_online_fair,
13888 	.rq_offline		= rq_offline_fair,
13889 
13890 	.task_dead		= task_dead_fair,
13891 	.set_cpus_allowed	= set_cpus_allowed_fair,
13892 
13893 	.task_tick		= task_tick_fair,
13894 	.task_fork		= task_fork_fair,
13895 
13896 	.reweight_task		= reweight_task_fair,
13897 	.prio_changed		= prio_changed_fair,
13898 	.switching_from		= switching_from_fair,
13899 	.switched_from		= switched_from_fair,
13900 	.switched_to		= switched_to_fair,
13901 
13902 	.get_rr_interval	= get_rr_interval_fair,
13903 
13904 	.update_curr		= update_curr_fair,
13905 
13906 #ifdef CONFIG_FAIR_GROUP_SCHED
13907 	.task_change_group	= task_change_group_fair,
13908 #endif
13909 
13910 #ifdef CONFIG_SCHED_CORE
13911 	.task_is_throttled	= task_is_throttled_fair,
13912 #endif
13913 
13914 #ifdef CONFIG_UCLAMP_TASK
13915 	.uclamp_enabled		= 1,
13916 #endif
13917 };
13918 
print_cfs_stats(struct seq_file * m,int cpu)13919 void print_cfs_stats(struct seq_file *m, int cpu)
13920 {
13921 	struct cfs_rq *cfs_rq, *pos;
13922 
13923 	rcu_read_lock();
13924 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13925 		print_cfs_rq(m, cpu, cfs_rq);
13926 	rcu_read_unlock();
13927 }
13928 
13929 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13930 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13931 {
13932 	int node;
13933 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13934 	struct numa_group *ng;
13935 
13936 	rcu_read_lock();
13937 	ng = rcu_dereference(p->numa_group);
13938 	for_each_online_node(node) {
13939 		if (p->numa_faults) {
13940 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13941 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13942 		}
13943 		if (ng) {
13944 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13945 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13946 		}
13947 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13948 	}
13949 	rcu_read_unlock();
13950 }
13951 #endif /* CONFIG_NUMA_BALANCING */
13952 
init_sched_fair_class(void)13953 __init void init_sched_fair_class(void)
13954 {
13955 	int i;
13956 
13957 	for_each_possible_cpu(i) {
13958 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13959 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
13960 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13961 					GFP_KERNEL, cpu_to_node(i));
13962 
13963 #ifdef CONFIG_CFS_BANDWIDTH
13964 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13965 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13966 #endif
13967 	}
13968 
13969 	open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
13970 
13971 #ifdef CONFIG_NO_HZ_COMMON
13972 	nohz.next_balance = jiffies;
13973 	nohz.next_blocked = jiffies;
13974 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13975 #endif
13976 }
13977