• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4  *
5  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6  *
7  *  Interactivity improvements by Mike Galbraith
8  *  (C) 2007 Mike Galbraith <efault@gmx.de>
9  *
10  *  Various enhancements by Dmitry Adamushko.
11  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12  *
13  *  Group scheduling enhancements by Srivatsa Vaddagiri
14  *  Copyright IBM Corporation, 2007
15  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16  *
17  *  Scaled math optimizations by Thomas Gleixner
18  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19  *
20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22  */
23 #include <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 
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
51 
52 #include <asm/switch_to.h>
53 
54 #include <linux/sched/cond_resched.h>
55 #ifdef CONFIG_SCHED_RTG
56 #include <linux/sched/rtg.h>
57 #endif
58 
59 #include "sched.h"
60 #include "stats.h"
61 #include "autogroup.h"
62 #include "walt.h"
63 #include "rtg/rtg.h"
64 
65 #ifdef CONFIG_SCHED_WALT
66 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
67 					u16 updated_demand_scaled);
68 #endif
69 
70 #if defined(CONFIG_SCHED_WALT) && defined(CONFIG_CFS_BANDWIDTH)
71 static void walt_init_cfs_rq_stats(struct cfs_rq *cfs_rq);
72 static void walt_inc_cfs_rq_stats(struct cfs_rq *cfs_rq,
73 				  struct task_struct *p);
74 static void walt_dec_cfs_rq_stats(struct cfs_rq *cfs_rq,
75 				  struct task_struct *p);
76 static void walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
77 					    struct cfs_rq *cfs_rq);
78 static void walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
79 					    struct cfs_rq *cfs_rq);
80 #else
walt_init_cfs_rq_stats(struct cfs_rq * cfs_rq)81 static inline void walt_init_cfs_rq_stats(struct cfs_rq *cfs_rq) {}
82 static inline void
walt_inc_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)83 walt_inc_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p) {}
84 static inline void
walt_dec_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)85 walt_dec_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p) {}
86 
87 #define walt_inc_throttled_cfs_rq_stats(...)
88 #define walt_dec_throttled_cfs_rq_stats(...)
89 
90 #endif
91 
92 /*
93  * Targeted preemption latency for CPU-bound tasks:
94  *
95  * NOTE: this latency value is not the same as the concept of
96  * 'timeslice length' - timeslices in CFS are of variable length
97  * and have no persistent notion like in traditional, time-slice
98  * based scheduling concepts.
99  *
100  * (to see the precise effective timeslice length of your workload,
101  *  run vmstat and monitor the context-switches (cs) field)
102  *
103  * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
104  */
105 unsigned int sysctl_sched_latency			= 6000000ULL;
106 static unsigned int normalized_sysctl_sched_latency	= 6000000ULL;
107 
108 /*
109  * The initial- and re-scaling of tunables is configurable
110  *
111  * Options are:
112  *
113  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
114  *   SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
115  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
116  *
117  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
118  */
119 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
120 
121 /*
122  * Minimal preemption granularity for CPU-bound tasks:
123  *
124  * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
125  */
126 unsigned int sysctl_sched_base_slice			= 700000ULL;
127 static unsigned int normalized_sysctl_sched_base_slice	= 700000ULL;
128 
129 /*
130  * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
131  */
132 static unsigned int sched_nr_latency = 8;
133 
134 /*
135  * After fork, child runs first. If set to 0 (default) then
136  * parent will (try to) run first.
137  */
138 unsigned int sysctl_sched_child_runs_first __read_mostly;
139 
140 /*
141  * SCHED_OTHER wake-up granularity.
142  *
143  * This option delays the preemption effects of decoupled workloads
144  * and reduces their over-scheduling. Synchronous workloads will still
145  * have immediate wakeup/sleep latencies.
146  *
147  * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
148  */
149 unsigned int sysctl_sched_wakeup_granularity			= 1000000UL;
150 static unsigned int normalized_sysctl_sched_wakeup_granularity	= 1000000UL;
151 
152 const_debug unsigned int sysctl_sched_migration_cost	= 500000UL;
153 
154 int sched_thermal_decay_shift;
setup_sched_thermal_decay_shift(char * str)155 static int __init setup_sched_thermal_decay_shift(char *str)
156 {
157 	int _shift = 0;
158 
159 	if (kstrtoint(str, 0, &_shift))
160 		pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
161 
162 	sched_thermal_decay_shift = clamp(_shift, 0, 10);
163 	return 1;
164 }
165 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
166 
167 #ifdef CONFIG_SMP
168 /*
169  * For asym packing, by default the lower numbered CPU has higher priority.
170  */
arch_asym_cpu_priority(int cpu)171 int __weak arch_asym_cpu_priority(int cpu)
172 {
173 	return -cpu;
174 }
175 
176 /*
177  * The margin used when comparing utilization with CPU capacity.
178  *
179  * (default: ~20%)
180  */
181 #define fits_capacity(cap, max)	((cap) * 1280 < (max) * 1024)
182 
183 /*
184  * The margin used when comparing CPU capacities.
185  * is 'cap1' noticeably greater than 'cap2'
186  *
187  * (default: ~5%)
188  */
189 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
190 #endif
191 
192 #ifdef CONFIG_CFS_BANDWIDTH
193 /*
194  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
195  * each time a cfs_rq requests quota.
196  *
197  * Note: in the case that the slice exceeds the runtime remaining (either due
198  * to consumption or the quota being specified to be smaller than the slice)
199  * we will always only issue the remaining available time.
200  *
201  * (default: 5 msec, units: microseconds)
202  */
203 static unsigned int sysctl_sched_cfs_bandwidth_slice		= 5000UL;
204 #endif
205 
206 #ifdef CONFIG_NUMA_BALANCING
207 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
208 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
209 #endif
210 
211 #ifdef CONFIG_SYSCTL
212 static struct ctl_table sched_fair_sysctls[] = {
213 	{
214 		.procname       = "sched_child_runs_first",
215 		.data           = &sysctl_sched_child_runs_first,
216 		.maxlen         = sizeof(unsigned int),
217 		.mode           = 0644,
218 		.proc_handler   = proc_dointvec,
219 	},
220 #ifdef CONFIG_CFS_BANDWIDTH
221 	{
222 		.procname       = "sched_cfs_bandwidth_slice_us",
223 		.data           = &sysctl_sched_cfs_bandwidth_slice,
224 		.maxlen         = sizeof(unsigned int),
225 		.mode           = 0644,
226 		.proc_handler   = proc_dointvec_minmax,
227 		.extra1         = SYSCTL_ONE,
228 	},
229 #endif
230 #ifdef CONFIG_NUMA_BALANCING
231 	{
232 		.procname	= "numa_balancing_promote_rate_limit_MBps",
233 		.data		= &sysctl_numa_balancing_promote_rate_limit,
234 		.maxlen		= sizeof(unsigned int),
235 		.mode		= 0644,
236 		.proc_handler	= proc_dointvec_minmax,
237 		.extra1		= SYSCTL_ZERO,
238 	},
239 #endif /* CONFIG_NUMA_BALANCING */
240 	{}
241 };
242 
sched_fair_sysctl_init(void)243 static int __init sched_fair_sysctl_init(void)
244 {
245 	register_sysctl_init("kernel", sched_fair_sysctls);
246 	return 0;
247 }
248 late_initcall(sched_fair_sysctl_init);
249 #endif
250 
update_load_add(struct load_weight * lw,unsigned long inc)251 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
252 {
253 	lw->weight += inc;
254 	lw->inv_weight = 0;
255 }
256 
update_load_sub(struct load_weight * lw,unsigned long dec)257 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
258 {
259 	lw->weight -= dec;
260 	lw->inv_weight = 0;
261 }
262 
update_load_set(struct load_weight * lw,unsigned long w)263 static inline void update_load_set(struct load_weight *lw, unsigned long w)
264 {
265 	lw->weight = w;
266 	lw->inv_weight = 0;
267 }
268 
269 /*
270  * Increase the granularity value when there are more CPUs,
271  * because with more CPUs the 'effective latency' as visible
272  * to users decreases. But the relationship is not linear,
273  * so pick a second-best guess by going with the log2 of the
274  * number of CPUs.
275  *
276  * This idea comes from the SD scheduler of Con Kolivas:
277  */
get_update_sysctl_factor(void)278 static unsigned int get_update_sysctl_factor(void)
279 {
280 	unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
281 	unsigned int factor;
282 
283 	switch (sysctl_sched_tunable_scaling) {
284 	case SCHED_TUNABLESCALING_NONE:
285 		factor = 1;
286 		break;
287 	case SCHED_TUNABLESCALING_LINEAR:
288 		factor = cpus;
289 		break;
290 	case SCHED_TUNABLESCALING_LOG:
291 	default:
292 		factor = 1 + ilog2(cpus);
293 		break;
294 	}
295 
296 	return factor;
297 }
298 
update_sysctl(void)299 static void update_sysctl(void)
300 {
301 	unsigned int factor = get_update_sysctl_factor();
302 
303 #define SET_SYSCTL(name) \
304 	(sysctl_##name = (factor) * normalized_sysctl_##name)
305 	SET_SYSCTL(sched_base_slice);
306 	SET_SYSCTL(sched_latency);
307 	SET_SYSCTL(sched_wakeup_granularity);
308 #undef SET_SYSCTL
309 }
310 
sched_init_granularity(void)311 void __init sched_init_granularity(void)
312 {
313 	update_sysctl();
314 }
315 
316 #define WMULT_CONST	(~0U)
317 #define WMULT_SHIFT	32
318 
__update_inv_weight(struct load_weight * lw)319 static void __update_inv_weight(struct load_weight *lw)
320 {
321 	unsigned long w;
322 
323 	if (likely(lw->inv_weight))
324 		return;
325 
326 	w = scale_load_down(lw->weight);
327 
328 	if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
329 		lw->inv_weight = 1;
330 	else if (unlikely(!w))
331 		lw->inv_weight = WMULT_CONST;
332 	else
333 		lw->inv_weight = WMULT_CONST / w;
334 }
335 
336 /*
337  * delta_exec * weight / lw.weight
338  *   OR
339  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
340  *
341  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
342  * we're guaranteed shift stays positive because inv_weight is guaranteed to
343  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
344  *
345  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
346  * weight/lw.weight <= 1, and therefore our shift will also be positive.
347  */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)348 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
349 {
350 	u64 fact = scale_load_down(weight);
351 	u32 fact_hi = (u32)(fact >> 32);
352 	int shift = WMULT_SHIFT;
353 	int fs;
354 
355 	__update_inv_weight(lw);
356 
357 	if (unlikely(fact_hi)) {
358 		fs = fls(fact_hi);
359 		shift -= fs;
360 		fact >>= fs;
361 	}
362 
363 	fact = mul_u32_u32(fact, lw->inv_weight);
364 
365 	fact_hi = (u32)(fact >> 32);
366 	if (fact_hi) {
367 		fs = fls(fact_hi);
368 		shift -= fs;
369 		fact >>= fs;
370 	}
371 
372 	return mul_u64_u32_shr(delta_exec, fact, shift);
373 }
374 
375 /*
376  * delta /= w
377  */
calc_delta_fair(u64 delta,struct sched_entity * se)378 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
379 {
380 	if (unlikely(se->load.weight != NICE_0_LOAD))
381 		delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
382 
383 	return delta;
384 }
385 
386 const struct sched_class fair_sched_class;
387 
388 /**************************************************************
389  * CFS operations on generic schedulable entities:
390  */
391 
392 #ifdef CONFIG_FAIR_GROUP_SCHED
393 
394 /* Walk up scheduling entities hierarchy */
395 #define for_each_sched_entity(se) \
396 		for (; se; se = se->parent)
397 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)398 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
399 {
400 	struct rq *rq = rq_of(cfs_rq);
401 	int cpu = cpu_of(rq);
402 
403 	if (cfs_rq->on_list)
404 		return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
405 
406 	cfs_rq->on_list = 1;
407 
408 	/*
409 	 * Ensure we either appear before our parent (if already
410 	 * enqueued) or force our parent to appear after us when it is
411 	 * enqueued. The fact that we always enqueue bottom-up
412 	 * reduces this to two cases and a special case for the root
413 	 * cfs_rq. Furthermore, it also means that we will always reset
414 	 * tmp_alone_branch either when the branch is connected
415 	 * to a tree or when we reach the top of the tree
416 	 */
417 	if (cfs_rq->tg->parent &&
418 	    cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
419 		/*
420 		 * If parent is already on the list, we add the child
421 		 * just before. Thanks to circular linked property of
422 		 * the list, this means to put the child at the tail
423 		 * of the list that starts by parent.
424 		 */
425 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
426 			&(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
427 		/*
428 		 * The branch is now connected to its tree so we can
429 		 * reset tmp_alone_branch to the beginning of the
430 		 * list.
431 		 */
432 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
433 		return true;
434 	}
435 
436 	if (!cfs_rq->tg->parent) {
437 		/*
438 		 * cfs rq without parent should be put
439 		 * at the tail of the list.
440 		 */
441 		list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
442 			&rq->leaf_cfs_rq_list);
443 		/*
444 		 * We have reach the top of a tree so we can reset
445 		 * tmp_alone_branch to the beginning of the list.
446 		 */
447 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
448 		return true;
449 	}
450 
451 	/*
452 	 * The parent has not already been added so we want to
453 	 * make sure that it will be put after us.
454 	 * tmp_alone_branch points to the begin of the branch
455 	 * where we will add parent.
456 	 */
457 	list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
458 	/*
459 	 * update tmp_alone_branch to points to the new begin
460 	 * of the branch
461 	 */
462 	rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
463 	return false;
464 }
465 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)466 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
467 {
468 	if (cfs_rq->on_list) {
469 		struct rq *rq = rq_of(cfs_rq);
470 
471 		/*
472 		 * With cfs_rq being unthrottled/throttled during an enqueue,
473 		 * it can happen the tmp_alone_branch points the a leaf that
474 		 * we finally want to del. In this case, tmp_alone_branch moves
475 		 * to the prev element but it will point to rq->leaf_cfs_rq_list
476 		 * at the end of the enqueue.
477 		 */
478 		if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
479 			rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
480 
481 		list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
482 		cfs_rq->on_list = 0;
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 	SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
489 }
490 
491 /* Iterate thr' all leaf cfs_rq's on a runqueue */
492 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)			\
493 	list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list,	\
494 				 leaf_cfs_rq_list)
495 
496 /* Do the two (enqueued) entities belong to the same group ? */
497 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)498 is_same_group(struct sched_entity *se, struct sched_entity *pse)
499 {
500 	if (se->cfs_rq == pse->cfs_rq)
501 		return se->cfs_rq;
502 
503 	return NULL;
504 }
505 
parent_entity(const struct sched_entity * se)506 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
507 {
508 	return se->parent;
509 }
510 
511 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)512 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
513 {
514 	int se_depth, pse_depth;
515 
516 	/*
517 	 * preemption test can be made between sibling entities who are in the
518 	 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
519 	 * both tasks until we find their ancestors who are siblings of common
520 	 * parent.
521 	 */
522 
523 	/* First walk up until both entities are at same depth */
524 	se_depth = (*se)->depth;
525 	pse_depth = (*pse)->depth;
526 
527 	while (se_depth > pse_depth) {
528 		se_depth--;
529 		*se = parent_entity(*se);
530 	}
531 
532 	while (pse_depth > se_depth) {
533 		pse_depth--;
534 		*pse = parent_entity(*pse);
535 	}
536 
537 	while (!is_same_group(*se, *pse)) {
538 		*se = parent_entity(*se);
539 		*pse = parent_entity(*pse);
540 	}
541 }
542 
tg_is_idle(struct task_group * tg)543 static int tg_is_idle(struct task_group *tg)
544 {
545 	return tg->idle > 0;
546 }
547 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)548 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
549 {
550 	return cfs_rq->idle > 0;
551 }
552 
se_is_idle(struct sched_entity * se)553 static int se_is_idle(struct sched_entity *se)
554 {
555 	if (entity_is_task(se))
556 		return task_has_idle_policy(task_of(se));
557 	return cfs_rq_is_idle(group_cfs_rq(se));
558 }
559 
560 #else	/* !CONFIG_FAIR_GROUP_SCHED */
561 
562 #define for_each_sched_entity(se) \
563 		for (; se; se = NULL)
564 
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)565 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
566 {
567 	return true;
568 }
569 
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)570 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
571 {
572 }
573 
assert_list_leaf_cfs_rq(struct rq * rq)574 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
575 {
576 }
577 
578 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos)	\
579 		for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
580 
parent_entity(struct sched_entity * se)581 static inline struct sched_entity *parent_entity(struct sched_entity *se)
582 {
583 	return NULL;
584 }
585 
586 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)587 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
588 {
589 }
590 
tg_is_idle(struct task_group * tg)591 static inline int tg_is_idle(struct task_group *tg)
592 {
593 	return 0;
594 }
595 
cfs_rq_is_idle(struct cfs_rq * cfs_rq)596 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
597 {
598 	return 0;
599 }
600 
se_is_idle(struct sched_entity * se)601 static int se_is_idle(struct sched_entity *se)
602 {
603 	return task_has_idle_policy(task_of(se));
604 }
605 
606 #endif	/* CONFIG_FAIR_GROUP_SCHED */
607 
608 static __always_inline
609 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
610 
611 /**************************************************************
612  * Scheduling class tree data structure manipulation methods:
613  */
614 
max_vruntime(u64 max_vruntime,u64 vruntime)615 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
616 {
617 	s64 delta = (s64)(vruntime - max_vruntime);
618 	if (delta > 0)
619 		max_vruntime = vruntime;
620 
621 	return max_vruntime;
622 }
623 
min_vruntime(u64 min_vruntime,u64 vruntime)624 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
625 {
626 	s64 delta = (s64)(vruntime - min_vruntime);
627 	if (delta < 0)
628 		min_vruntime = vruntime;
629 
630 	return min_vruntime;
631 }
632 
entity_before(const struct sched_entity * a,const struct sched_entity * b)633 static inline bool entity_before(const struct sched_entity *a,
634 				 const struct sched_entity *b)
635 {
636 	return (s64)(a->vruntime - b->vruntime) < 0;
637 }
638 
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)639 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
640 {
641 	return (s64)(se->vruntime - cfs_rq->min_vruntime);
642 }
643 
644 #define __node_2_se(node) \
645 	rb_entry((node), struct sched_entity, run_node)
646 
647 /*
648  * Compute virtual time from the per-task service numbers:
649  *
650  * Fair schedulers conserve lag:
651  *
652  *   \Sum lag_i = 0
653  *
654  * Where lag_i is given by:
655  *
656  *   lag_i = S - s_i = w_i * (V - v_i)
657  *
658  * Where S is the ideal service time and V is it's virtual time counterpart.
659  * Therefore:
660  *
661  *   \Sum lag_i = 0
662  *   \Sum w_i * (V - v_i) = 0
663  *   \Sum w_i * V - w_i * v_i = 0
664  *
665  * From which we can solve an expression for V in v_i (which we have in
666  * se->vruntime):
667  *
668  *       \Sum v_i * w_i   \Sum v_i * w_i
669  *   V = -------------- = --------------
670  *          \Sum w_i            W
671  *
672  * Specifically, this is the weighted average of all entity virtual runtimes.
673  *
674  * [[ NOTE: this is only equal to the ideal scheduler under the condition
675  *          that join/leave operations happen at lag_i = 0, otherwise the
676  *          virtual time has non-continguous motion equivalent to:
677  *
678  *	      V +-= lag_i / W
679  *
680  *	    Also see the comment in place_entity() that deals with this. ]]
681  *
682  * However, since v_i is u64, and the multiplcation could easily overflow
683  * transform it into a relative form that uses smaller quantities:
684  *
685  * Substitute: v_i == (v_i - v0) + v0
686  *
687  *     \Sum ((v_i - v0) + v0) * w_i   \Sum (v_i - v0) * w_i
688  * V = ---------------------------- = --------------------- + v0
689  *                  W                            W
690  *
691  * Which we track using:
692  *
693  *                    v0 := cfs_rq->min_vruntime
694  * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
695  *              \Sum w_i := cfs_rq->avg_load
696  *
697  * Since min_vruntime is a monotonic increasing variable that closely tracks
698  * the per-task service, these deltas: (v_i - v), will be in the order of the
699  * maximal (virtual) lag induced in the system due to quantisation.
700  *
701  * Also, we use scale_load_down() to reduce the size.
702  *
703  * As measured, the max (key * weight) value was ~44 bits for a kernel build.
704  */
705 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)706 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
707 {
708 	unsigned long weight = scale_load_down(se->load.weight);
709 	s64 key = entity_key(cfs_rq, se);
710 
711 	cfs_rq->avg_vruntime += key * weight;
712 	cfs_rq->avg_load += weight;
713 }
714 
715 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)716 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
717 {
718 	unsigned long weight = scale_load_down(se->load.weight);
719 	s64 key = entity_key(cfs_rq, se);
720 
721 	cfs_rq->avg_vruntime -= key * weight;
722 	cfs_rq->avg_load -= weight;
723 }
724 
725 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)726 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
727 {
728 	/*
729 	 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
730 	 */
731 	cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
732 }
733 
734 /*
735  * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
736  * For this to be so, the result of this function must have a left bias.
737  */
avg_vruntime(struct cfs_rq * cfs_rq)738 u64 avg_vruntime(struct cfs_rq *cfs_rq)
739 {
740 	struct sched_entity *curr = cfs_rq->curr;
741 	s64 avg = cfs_rq->avg_vruntime;
742 	long load = cfs_rq->avg_load;
743 
744 	if (curr && curr->on_rq) {
745 		unsigned long weight = scale_load_down(curr->load.weight);
746 
747 		avg += entity_key(cfs_rq, curr) * weight;
748 		load += weight;
749 	}
750 
751 	if (load) {
752 		/* sign flips effective floor / ceil */
753 		if (avg < 0)
754 			avg -= (load - 1);
755 		avg = div_s64(avg, load);
756 	}
757 
758 	return cfs_rq->min_vruntime + avg;
759 }
760 
761 /*
762  * lag_i = S - s_i = w_i * (V - v_i)
763  *
764  * However, since V is approximated by the weighted average of all entities it
765  * is possible -- by addition/removal/reweight to the tree -- to move V around
766  * and end up with a larger lag than we started with.
767  *
768  * Limit this to either double the slice length with a minimum of TICK_NSEC
769  * since that is the timing granularity.
770  *
771  * EEVDF gives the following limit for a steady state system:
772  *
773  *   -r_max < lag < max(r_max, q)
774  *
775  * XXX could add max_slice to the augmented data to track this.
776  */
entity_lag(u64 avruntime,struct sched_entity * se)777 static s64 entity_lag(u64 avruntime, struct sched_entity *se)
778 {
779 	s64 vlag, limit;
780 
781 	vlag = avruntime - se->vruntime;
782 	limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
783 
784 	return clamp(vlag, -limit, limit);
785 }
786 
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)787 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
788 {
789 	SCHED_WARN_ON(!se->on_rq);
790 
791 	se->vlag = entity_lag(avg_vruntime(cfs_rq), se);
792 }
793 
794 /*
795  * Entity is eligible once it received less service than it ought to have,
796  * eg. lag >= 0.
797  *
798  * lag_i = S - s_i = w_i*(V - v_i)
799  *
800  * lag_i >= 0 -> V >= v_i
801  *
802  *     \Sum (v_i - v)*w_i
803  * V = ------------------ + v
804  *          \Sum w_i
805  *
806  * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
807  *
808  * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
809  *       to the loss in precision caused by the division.
810  */
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)811 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
812 {
813 	struct sched_entity *curr = cfs_rq->curr;
814 	s64 avg = cfs_rq->avg_vruntime;
815 	long load = cfs_rq->avg_load;
816 
817 	if (curr && curr->on_rq) {
818 		unsigned long weight = scale_load_down(curr->load.weight);
819 
820 		avg += entity_key(cfs_rq, curr) * weight;
821 		load += weight;
822 	}
823 
824 	return avg >= entity_key(cfs_rq, se) * load;
825 }
826 
__update_min_vruntime(struct cfs_rq * cfs_rq,u64 vruntime)827 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
828 {
829 	u64 min_vruntime = cfs_rq->min_vruntime;
830 	/*
831 	 * open coded max_vruntime() to allow updating avg_vruntime
832 	 */
833 	s64 delta = (s64)(vruntime - min_vruntime);
834 	if (delta > 0) {
835 		avg_vruntime_update(cfs_rq, delta);
836 		min_vruntime = vruntime;
837 	}
838 	return min_vruntime;
839 }
840 
update_min_vruntime(struct cfs_rq * cfs_rq)841 static void update_min_vruntime(struct cfs_rq *cfs_rq)
842 {
843 	struct sched_entity *se = __pick_first_entity(cfs_rq);
844 	struct sched_entity *curr = cfs_rq->curr;
845 
846 	u64 vruntime = cfs_rq->min_vruntime;
847 
848 	if (curr) {
849 		if (curr->on_rq)
850 			vruntime = curr->vruntime;
851 		else
852 			curr = NULL;
853 	}
854 
855 	if (se) {
856 		if (!curr)
857 			vruntime = se->vruntime;
858 		else
859 			vruntime = min_vruntime(vruntime, se->vruntime);
860 	}
861 
862 	/* ensure we never gain time by being placed backwards. */
863 	u64_u32_store(cfs_rq->min_vruntime,
864 		      __update_min_vruntime(cfs_rq, vruntime));
865 }
866 
__entity_less(struct rb_node * a,const struct rb_node * b)867 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
868 {
869 	return entity_before(__node_2_se(a), __node_2_se(b));
870 }
871 
872 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
873 
__update_min_deadline(struct sched_entity * se,struct rb_node * node)874 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
875 {
876 	if (node) {
877 		struct sched_entity *rse = __node_2_se(node);
878 		if (deadline_gt(min_deadline, se, rse))
879 			se->min_deadline = rse->min_deadline;
880 	}
881 }
882 
883 /*
884  * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
885  */
min_deadline_update(struct sched_entity * se,bool exit)886 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
887 {
888 	u64 old_min_deadline = se->min_deadline;
889 	struct rb_node *node = &se->run_node;
890 
891 	se->min_deadline = se->deadline;
892 	__update_min_deadline(se, node->rb_right);
893 	__update_min_deadline(se, node->rb_left);
894 
895 	return se->min_deadline == old_min_deadline;
896 }
897 
898 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
899 		     run_node, min_deadline, min_deadline_update);
900 
901 /*
902  * Enqueue an entity into the rb-tree:
903  */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)904 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
905 {
906 	avg_vruntime_add(cfs_rq, se);
907 	se->min_deadline = se->deadline;
908 	rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
909 				__entity_less, &min_deadline_cb);
910 }
911 
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)912 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
913 {
914 	rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
915 				  &min_deadline_cb);
916 	avg_vruntime_sub(cfs_rq, se);
917 }
918 
__pick_first_entity(struct cfs_rq * cfs_rq)919 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
920 {
921 	struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
922 
923 	if (!left)
924 		return NULL;
925 
926 	return __node_2_se(left);
927 }
928 
929 /*
930  * Earliest Eligible Virtual Deadline First
931  *
932  * In order to provide latency guarantees for different request sizes
933  * EEVDF selects the best runnable task from two criteria:
934  *
935  *  1) the task must be eligible (must be owed service)
936  *
937  *  2) from those tasks that meet 1), we select the one
938  *     with the earliest virtual deadline.
939  *
940  * We can do this in O(log n) time due to an augmented RB-tree. The
941  * tree keeps the entries sorted on service, but also functions as a
942  * heap based on the deadline by keeping:
943  *
944  *  se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
945  *
946  * Which allows an EDF like search on (sub)trees.
947  */
__pick_eevdf(struct cfs_rq * cfs_rq)948 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq)
949 {
950 	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
951 	struct sched_entity *curr = cfs_rq->curr;
952 	struct sched_entity *best = NULL;
953 	struct sched_entity *best_left = NULL;
954 
955 	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
956 		curr = NULL;
957 	best = curr;
958 
959 	/*
960 	 * Once selected, run a task until it either becomes non-eligible or
961 	 * until it gets a new slice. See the HACK in set_next_entity().
962 	 */
963 	if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
964 		return curr;
965 
966 	while (node) {
967 		struct sched_entity *se = __node_2_se(node);
968 
969 		/*
970 		 * If this entity is not eligible, try the left subtree.
971 		 */
972 		if (!entity_eligible(cfs_rq, se)) {
973 			node = node->rb_left;
974 			continue;
975 		}
976 
977 		/*
978 		 * Now we heap search eligible trees for the best (min_)deadline
979 		 */
980 		if (!best || deadline_gt(deadline, best, se))
981 			best = se;
982 
983 		/*
984 		 * Every se in a left branch is eligible, keep track of the
985 		 * branch with the best min_deadline
986 		 */
987 		if (node->rb_left) {
988 			struct sched_entity *left = __node_2_se(node->rb_left);
989 
990 			if (!best_left || deadline_gt(min_deadline, best_left, left))
991 				best_left = left;
992 
993 			/*
994 			 * min_deadline is in the left branch. rb_left and all
995 			 * descendants are eligible, so immediately switch to the second
996 			 * loop.
997 			 */
998 			if (left->min_deadline == se->min_deadline)
999 				break;
1000 		}
1001 
1002 		/* min_deadline is at this node, no need to look right */
1003 		if (se->deadline == se->min_deadline)
1004 			break;
1005 
1006 		/* else min_deadline is in the right branch. */
1007 		node = node->rb_right;
1008 	}
1009 
1010 	/*
1011 	 * We ran into an eligible node which is itself the best.
1012 	 * (Or nr_running == 0 and both are NULL)
1013 	 */
1014 	if (!best_left || (s64)(best_left->min_deadline - best->deadline) > 0)
1015 		return best;
1016 
1017 	/*
1018 	 * Now best_left and all of its children are eligible, and we are just
1019 	 * looking for deadline == min_deadline
1020 	 */
1021 	node = &best_left->run_node;
1022 	while (node) {
1023 		struct sched_entity *se = __node_2_se(node);
1024 
1025 		/* min_deadline is the current node */
1026 		if (se->deadline == se->min_deadline)
1027 			return se;
1028 
1029 		/* min_deadline is in the left branch */
1030 		if (node->rb_left &&
1031 		    __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
1032 			node = node->rb_left;
1033 			continue;
1034 		}
1035 
1036 		/* else min_deadline is in the right branch */
1037 		node = node->rb_right;
1038 	}
1039 	return NULL;
1040 }
1041 
pick_eevdf(struct cfs_rq * cfs_rq)1042 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
1043 {
1044 	struct sched_entity *se = __pick_eevdf(cfs_rq);
1045 
1046 	if (!se) {
1047 		struct sched_entity *left = __pick_first_entity(cfs_rq);
1048 		if (left) {
1049 			pr_err("EEVDF scheduling fail, picking leftmost\n");
1050 			return left;
1051 		}
1052 	}
1053 
1054 	return se;
1055 }
1056 
1057 #ifdef CONFIG_SCHED_DEBUG
__pick_last_entity(struct cfs_rq * cfs_rq)1058 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1059 {
1060 	struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1061 
1062 	if (!last)
1063 		return NULL;
1064 
1065 	return __node_2_se(last);
1066 }
1067 
1068 /**************************************************************
1069  * Scheduling class statistics methods:
1070  */
1071 #ifdef CONFIG_SMP
sched_update_scaling(void)1072 int sched_update_scaling(void)
1073 {
1074 	unsigned int factor = get_update_sysctl_factor();
1075 
1076 #define WRT_SYSCTL(name) \
1077 	(normalized_sysctl_##name = sysctl_##name / (factor))
1078 	WRT_SYSCTL(sched_base_slice);
1079 	WRT_SYSCTL(sched_latency);
1080 	WRT_SYSCTL(sched_wakeup_granularity);
1081 #undef WRT_SYSCTL
1082 
1083 	return 0;
1084 }
1085 #endif
1086 #endif
1087 
1088 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1089 
1090 /*
1091  * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1092  * this is probably good enough.
1093  */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1094 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1095 {
1096 	if ((s64)(se->vruntime - se->deadline) < 0)
1097 		return;
1098 
1099 	/*
1100 	 * For EEVDF the virtual time slope is determined by w_i (iow.
1101 	 * nice) while the request time r_i is determined by
1102 	 * sysctl_sched_base_slice.
1103 	 */
1104 	se->slice = sysctl_sched_base_slice;
1105 
1106 	/*
1107 	 * EEVDF: vd_i = ve_i + r_i / w_i
1108 	 */
1109 	se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1110 
1111 	/*
1112 	 * The task has consumed its request, reschedule.
1113 	 */
1114 	if (cfs_rq->nr_running > 1) {
1115 		resched_curr(rq_of(cfs_rq));
1116 		clear_buddies(cfs_rq, se);
1117 	}
1118 }
1119 
1120 #include "pelt.h"
1121 #ifdef CONFIG_SMP
1122 
1123 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1124 static unsigned long task_h_load(struct task_struct *p);
1125 static unsigned long capacity_of(int cpu);
1126 
1127 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1128 void init_entity_runnable_average(struct sched_entity *se)
1129 {
1130 	struct sched_avg *sa = &se->avg;
1131 
1132 	memset(sa, 0, sizeof(*sa));
1133 
1134 	/*
1135 	 * Tasks are initialized with full load to be seen as heavy tasks until
1136 	 * they get a chance to stabilize to their real load level.
1137 	 * Group entities are initialized with zero load to reflect the fact that
1138 	 * nothing has been attached to the task group yet.
1139 	 */
1140 	if (entity_is_task(se))
1141 		sa->load_avg = scale_load_down(se->load.weight);
1142 
1143 	/* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1144 }
1145 
1146 /*
1147  * With new tasks being created, their initial util_avgs are extrapolated
1148  * based on the cfs_rq's current util_avg:
1149  *
1150  *   util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1151  *
1152  * However, in many cases, the above util_avg does not give a desired
1153  * value. Moreover, the sum of the util_avgs may be divergent, such
1154  * as when the series is a harmonic series.
1155  *
1156  * To solve this problem, we also cap the util_avg of successive tasks to
1157  * only 1/2 of the left utilization budget:
1158  *
1159  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1160  *
1161  * where n denotes the nth task and cpu_scale the CPU capacity.
1162  *
1163  * For example, for a CPU with 1024 of capacity, a simplest series from
1164  * the beginning would be like:
1165  *
1166  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
1167  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1168  *
1169  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1170  * if util_avg > util_avg_cap.
1171  */
post_init_entity_util_avg(struct task_struct * p)1172 void post_init_entity_util_avg(struct task_struct *p)
1173 {
1174 	struct sched_entity *se = &p->se;
1175 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
1176 	struct sched_avg *sa = &se->avg;
1177 	long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1178 	long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1179 
1180 	if (p->sched_class != &fair_sched_class) {
1181 		/*
1182 		 * For !fair tasks do:
1183 		 *
1184 		update_cfs_rq_load_avg(now, cfs_rq);
1185 		attach_entity_load_avg(cfs_rq, se);
1186 		switched_from_fair(rq, p);
1187 		 *
1188 		 * such that the next switched_to_fair() has the
1189 		 * expected state.
1190 		 */
1191 		se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1192 		return;
1193 	}
1194 
1195 	if (cap > 0) {
1196 		if (cfs_rq->avg.util_avg != 0) {
1197 			sa->util_avg  = cfs_rq->avg.util_avg * se->load.weight;
1198 			sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1199 
1200 			if (sa->util_avg > cap)
1201 				sa->util_avg = cap;
1202 		} else {
1203 			sa->util_avg = cap;
1204 		}
1205 	}
1206 
1207 	sa->runnable_avg = sa->util_avg;
1208 }
1209 
1210 #else /* !CONFIG_SMP */
init_entity_runnable_average(struct sched_entity * se)1211 void init_entity_runnable_average(struct sched_entity *se)
1212 {
1213 }
post_init_entity_util_avg(struct task_struct * p)1214 void post_init_entity_util_avg(struct task_struct *p)
1215 {
1216 }
update_tg_load_avg(struct cfs_rq * cfs_rq)1217 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1218 {
1219 }
1220 #endif /* CONFIG_SMP */
1221 
update_curr_se(struct rq * rq,struct sched_entity * curr)1222 static s64 update_curr_se(struct rq *rq, struct sched_entity *curr)
1223 {
1224 	u64 now = rq_clock_task(rq);
1225 	s64 delta_exec;
1226 
1227 	delta_exec = now - curr->exec_start;
1228 	if (unlikely(delta_exec <= 0))
1229 		return delta_exec;
1230 
1231 	curr->exec_start = now;
1232 	curr->sum_exec_runtime += delta_exec;
1233 
1234 	if (schedstat_enabled()) {
1235 		struct sched_statistics *stats;
1236 
1237 		stats = __schedstats_from_se(curr);
1238 		__schedstat_set(stats->exec_max,
1239 				max(delta_exec, stats->exec_max));
1240 	}
1241 
1242 	return delta_exec;
1243 }
1244 
update_curr_task(struct task_struct * p,s64 delta_exec)1245 static inline void update_curr_task(struct task_struct *p, s64 delta_exec)
1246 {
1247 	trace_sched_stat_runtime(p, delta_exec);
1248 	account_group_exec_runtime(p, delta_exec);
1249 	cgroup_account_cputime(p, delta_exec);
1250 }
1251 
1252 /*
1253  * Used by other classes to account runtime.
1254  */
update_curr_common(struct rq * rq)1255 s64 update_curr_common(struct rq *rq)
1256 {
1257 	struct task_struct *curr = rq->curr;
1258 	s64 delta_exec;
1259 
1260 	delta_exec = update_curr_se(rq, &curr->se);
1261 	if (likely(delta_exec > 0))
1262 		update_curr_task(curr, delta_exec);
1263 
1264 	return delta_exec;
1265 }
1266 
1267 /*
1268  * Update the current task's runtime statistics.
1269  */
update_curr(struct cfs_rq * cfs_rq)1270 static void update_curr(struct cfs_rq *cfs_rq)
1271 {
1272 	struct sched_entity *curr = cfs_rq->curr;
1273 	s64 delta_exec;
1274 
1275 	if (unlikely(!curr))
1276 		return;
1277 
1278 	delta_exec = update_curr_se(rq_of(cfs_rq), curr);
1279 	if (unlikely(delta_exec <= 0))
1280 		return;
1281 
1282 	curr->vruntime += calc_delta_fair(delta_exec, curr);
1283 	update_deadline(cfs_rq, curr);
1284 	update_min_vruntime(cfs_rq);
1285 
1286 	if (entity_is_task(curr))
1287 		update_curr_task(task_of(curr), delta_exec);
1288 
1289 	account_cfs_rq_runtime(cfs_rq, delta_exec);
1290 }
1291 
update_curr_fair(struct rq * rq)1292 static void update_curr_fair(struct rq *rq)
1293 {
1294 	update_curr(cfs_rq_of(&rq->curr->se));
1295 }
1296 
1297 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1298 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1299 {
1300 	struct sched_statistics *stats;
1301 	struct task_struct *p = NULL;
1302 
1303 	if (!schedstat_enabled())
1304 		return;
1305 
1306 	stats = __schedstats_from_se(se);
1307 
1308 	if (entity_is_task(se))
1309 		p = task_of(se);
1310 
1311 	__update_stats_wait_start(rq_of(cfs_rq), p, stats);
1312 }
1313 
1314 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1315 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1316 {
1317 	struct sched_statistics *stats;
1318 	struct task_struct *p = NULL;
1319 
1320 	if (!schedstat_enabled())
1321 		return;
1322 
1323 	stats = __schedstats_from_se(se);
1324 
1325 	/*
1326 	 * When the sched_schedstat changes from 0 to 1, some sched se
1327 	 * maybe already in the runqueue, the se->statistics.wait_start
1328 	 * will be 0.So it will let the delta wrong. We need to avoid this
1329 	 * scenario.
1330 	 */
1331 	if (unlikely(!schedstat_val(stats->wait_start)))
1332 		return;
1333 
1334 	if (entity_is_task(se))
1335 		p = task_of(se);
1336 
1337 	__update_stats_wait_end(rq_of(cfs_rq), p, stats);
1338 }
1339 
1340 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1341 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1342 {
1343 	struct sched_statistics *stats;
1344 	struct task_struct *tsk = NULL;
1345 
1346 	if (!schedstat_enabled())
1347 		return;
1348 
1349 	stats = __schedstats_from_se(se);
1350 
1351 	if (entity_is_task(se))
1352 		tsk = task_of(se);
1353 
1354 	__update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1355 }
1356 
1357 /*
1358  * Task is being enqueued - update stats:
1359  */
1360 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1361 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1362 {
1363 	if (!schedstat_enabled())
1364 		return;
1365 
1366 	/*
1367 	 * Are we enqueueing a waiting task? (for current tasks
1368 	 * a dequeue/enqueue event is a NOP)
1369 	 */
1370 	if (se != cfs_rq->curr)
1371 		update_stats_wait_start_fair(cfs_rq, se);
1372 
1373 	if (flags & ENQUEUE_WAKEUP)
1374 		update_stats_enqueue_sleeper_fair(cfs_rq, se);
1375 }
1376 
1377 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1378 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1379 {
1380 
1381 	if (!schedstat_enabled())
1382 		return;
1383 
1384 	/*
1385 	 * Mark the end of the wait period if dequeueing a
1386 	 * waiting task:
1387 	 */
1388 	if (se != cfs_rq->curr)
1389 		update_stats_wait_end_fair(cfs_rq, se);
1390 
1391 	if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1392 		struct task_struct *tsk = task_of(se);
1393 		unsigned int state;
1394 
1395 		/* XXX racy against TTWU */
1396 		state = READ_ONCE(tsk->__state);
1397 		if (state & TASK_INTERRUPTIBLE)
1398 			__schedstat_set(tsk->stats.sleep_start,
1399 				      rq_clock(rq_of(cfs_rq)));
1400 		if (state & TASK_UNINTERRUPTIBLE)
1401 			__schedstat_set(tsk->stats.block_start,
1402 				      rq_clock(rq_of(cfs_rq)));
1403 	}
1404 }
1405 
1406 /*
1407  * We are picking a new current task - update its stats:
1408  */
1409 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1410 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1411 {
1412 	/*
1413 	 * We are starting a new run period:
1414 	 */
1415 	se->exec_start = rq_clock_task(rq_of(cfs_rq));
1416 }
1417 
1418 /**************************************************
1419  * Scheduling class queueing methods:
1420  */
1421 
is_core_idle(int cpu)1422 static inline bool is_core_idle(int cpu)
1423 {
1424 #ifdef CONFIG_SCHED_SMT
1425 	int sibling;
1426 
1427 	for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1428 		if (cpu == sibling)
1429 			continue;
1430 
1431 		if (!idle_cpu(sibling))
1432 			return false;
1433 	}
1434 #endif
1435 
1436 	return true;
1437 }
1438 
1439 #ifdef CONFIG_NUMA
1440 #define NUMA_IMBALANCE_MIN 2
1441 
1442 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1443 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1444 {
1445 	/*
1446 	 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1447 	 * threshold. Above this threshold, individual tasks may be contending
1448 	 * for both memory bandwidth and any shared HT resources.  This is an
1449 	 * approximation as the number of running tasks may not be related to
1450 	 * the number of busy CPUs due to sched_setaffinity.
1451 	 */
1452 	if (dst_running > imb_numa_nr)
1453 		return imbalance;
1454 
1455 	/*
1456 	 * Allow a small imbalance based on a simple pair of communicating
1457 	 * tasks that remain local when the destination is lightly loaded.
1458 	 */
1459 	if (imbalance <= NUMA_IMBALANCE_MIN)
1460 		return 0;
1461 
1462 	return imbalance;
1463 }
1464 #endif /* CONFIG_NUMA */
1465 
1466 #ifdef CONFIG_NUMA_BALANCING
1467 /*
1468  * Approximate time to scan a full NUMA task in ms. The task scan period is
1469  * calculated based on the tasks virtual memory size and
1470  * numa_balancing_scan_size.
1471  */
1472 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1473 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1474 
1475 /* Portion of address space to scan in MB */
1476 unsigned int sysctl_numa_balancing_scan_size = 256;
1477 
1478 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1479 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1480 
1481 /* The page with hint page fault latency < threshold in ms is considered hot */
1482 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1483 
1484 struct numa_group {
1485 	refcount_t refcount;
1486 
1487 	spinlock_t lock; /* nr_tasks, tasks */
1488 	int nr_tasks;
1489 	pid_t gid;
1490 	int active_nodes;
1491 
1492 	struct rcu_head rcu;
1493 	unsigned long total_faults;
1494 	unsigned long max_faults_cpu;
1495 	/*
1496 	 * faults[] array is split into two regions: faults_mem and faults_cpu.
1497 	 *
1498 	 * Faults_cpu is used to decide whether memory should move
1499 	 * towards the CPU. As a consequence, these stats are weighted
1500 	 * more by CPU use than by memory faults.
1501 	 */
1502 	unsigned long faults[];
1503 };
1504 
1505 /*
1506  * For functions that can be called in multiple contexts that permit reading
1507  * ->numa_group (see struct task_struct for locking rules).
1508  */
deref_task_numa_group(struct task_struct * p)1509 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1510 {
1511 	return rcu_dereference_check(p->numa_group, p == current ||
1512 		(lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1513 }
1514 
deref_curr_numa_group(struct task_struct * p)1515 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1516 {
1517 	return rcu_dereference_protected(p->numa_group, p == current);
1518 }
1519 
1520 static inline unsigned long group_faults_priv(struct numa_group *ng);
1521 static inline unsigned long group_faults_shared(struct numa_group *ng);
1522 
task_nr_scan_windows(struct task_struct * p)1523 static unsigned int task_nr_scan_windows(struct task_struct *p)
1524 {
1525 	unsigned long rss = 0;
1526 	unsigned long nr_scan_pages;
1527 
1528 	/*
1529 	 * Calculations based on RSS as non-present and empty pages are skipped
1530 	 * by the PTE scanner and NUMA hinting faults should be trapped based
1531 	 * on resident pages
1532 	 */
1533 	nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1534 	rss = get_mm_rss(p->mm);
1535 	if (!rss)
1536 		rss = nr_scan_pages;
1537 
1538 	rss = round_up(rss, nr_scan_pages);
1539 	return rss / nr_scan_pages;
1540 }
1541 
1542 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1543 #define MAX_SCAN_WINDOW 2560
1544 
task_scan_min(struct task_struct * p)1545 static unsigned int task_scan_min(struct task_struct *p)
1546 {
1547 	unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1548 	unsigned int scan, floor;
1549 	unsigned int windows = 1;
1550 
1551 	if (scan_size < MAX_SCAN_WINDOW)
1552 		windows = MAX_SCAN_WINDOW / scan_size;
1553 	floor = 1000 / windows;
1554 
1555 	scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1556 	return max_t(unsigned int, floor, scan);
1557 }
1558 
task_scan_start(struct task_struct * p)1559 static unsigned int task_scan_start(struct task_struct *p)
1560 {
1561 	unsigned long smin = task_scan_min(p);
1562 	unsigned long period = smin;
1563 	struct numa_group *ng;
1564 
1565 	/* Scale the maximum scan period with the amount of shared memory. */
1566 	rcu_read_lock();
1567 	ng = rcu_dereference(p->numa_group);
1568 	if (ng) {
1569 		unsigned long shared = group_faults_shared(ng);
1570 		unsigned long private = group_faults_priv(ng);
1571 
1572 		period *= refcount_read(&ng->refcount);
1573 		period *= shared + 1;
1574 		period /= private + shared + 1;
1575 	}
1576 	rcu_read_unlock();
1577 
1578 	return max(smin, period);
1579 }
1580 
task_scan_max(struct task_struct * p)1581 static unsigned int task_scan_max(struct task_struct *p)
1582 {
1583 	unsigned long smin = task_scan_min(p);
1584 	unsigned long smax;
1585 	struct numa_group *ng;
1586 
1587 	/* Watch for min being lower than max due to floor calculations */
1588 	smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1589 
1590 	/* Scale the maximum scan period with the amount of shared memory. */
1591 	ng = deref_curr_numa_group(p);
1592 	if (ng) {
1593 		unsigned long shared = group_faults_shared(ng);
1594 		unsigned long private = group_faults_priv(ng);
1595 		unsigned long period = smax;
1596 
1597 		period *= refcount_read(&ng->refcount);
1598 		period *= shared + 1;
1599 		period /= private + shared + 1;
1600 
1601 		smax = max(smax, period);
1602 	}
1603 
1604 	return max(smin, smax);
1605 }
1606 
account_numa_enqueue(struct rq * rq,struct task_struct * p)1607 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1608 {
1609 	rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1610 	rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1611 }
1612 
account_numa_dequeue(struct rq * rq,struct task_struct * p)1613 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1614 {
1615 	rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1616 	rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1617 }
1618 
1619 /* Shared or private faults. */
1620 #define NR_NUMA_HINT_FAULT_TYPES 2
1621 
1622 /* Memory and CPU locality */
1623 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1624 
1625 /* Averaged statistics, and temporary buffers. */
1626 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1627 
task_numa_group_id(struct task_struct * p)1628 pid_t task_numa_group_id(struct task_struct *p)
1629 {
1630 	struct numa_group *ng;
1631 	pid_t gid = 0;
1632 
1633 	rcu_read_lock();
1634 	ng = rcu_dereference(p->numa_group);
1635 	if (ng)
1636 		gid = ng->gid;
1637 	rcu_read_unlock();
1638 
1639 	return gid;
1640 }
1641 
1642 /*
1643  * The averaged statistics, shared & private, memory & CPU,
1644  * occupy the first half of the array. The second half of the
1645  * array is for current counters, which are averaged into the
1646  * first set by task_numa_placement.
1647  */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1648 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1649 {
1650 	return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1651 }
1652 
task_faults(struct task_struct * p,int nid)1653 static inline unsigned long task_faults(struct task_struct *p, int nid)
1654 {
1655 	if (!p->numa_faults)
1656 		return 0;
1657 
1658 	return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1659 		p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1660 }
1661 
group_faults(struct task_struct * p,int nid)1662 static inline unsigned long group_faults(struct task_struct *p, int nid)
1663 {
1664 	struct numa_group *ng = deref_task_numa_group(p);
1665 
1666 	if (!ng)
1667 		return 0;
1668 
1669 	return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1670 		ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1671 }
1672 
group_faults_cpu(struct numa_group * group,int nid)1673 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1674 {
1675 	return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1676 		group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1677 }
1678 
group_faults_priv(struct numa_group * ng)1679 static inline unsigned long group_faults_priv(struct numa_group *ng)
1680 {
1681 	unsigned long faults = 0;
1682 	int node;
1683 
1684 	for_each_online_node(node) {
1685 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1686 	}
1687 
1688 	return faults;
1689 }
1690 
group_faults_shared(struct numa_group * ng)1691 static inline unsigned long group_faults_shared(struct numa_group *ng)
1692 {
1693 	unsigned long faults = 0;
1694 	int node;
1695 
1696 	for_each_online_node(node) {
1697 		faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1698 	}
1699 
1700 	return faults;
1701 }
1702 
1703 /*
1704  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1705  * considered part of a numa group's pseudo-interleaving set. Migrations
1706  * between these nodes are slowed down, to allow things to settle down.
1707  */
1708 #define ACTIVE_NODE_FRACTION 3
1709 
numa_is_active_node(int nid,struct numa_group * ng)1710 static bool numa_is_active_node(int nid, struct numa_group *ng)
1711 {
1712 	return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1713 }
1714 
1715 /* 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)1716 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1717 					int lim_dist, bool task)
1718 {
1719 	unsigned long score = 0;
1720 	int node, max_dist;
1721 
1722 	/*
1723 	 * All nodes are directly connected, and the same distance
1724 	 * from each other. No need for fancy placement algorithms.
1725 	 */
1726 	if (sched_numa_topology_type == NUMA_DIRECT)
1727 		return 0;
1728 
1729 	/* sched_max_numa_distance may be changed in parallel. */
1730 	max_dist = READ_ONCE(sched_max_numa_distance);
1731 	/*
1732 	 * This code is called for each node, introducing N^2 complexity,
1733 	 * which should be ok given the number of nodes rarely exceeds 8.
1734 	 */
1735 	for_each_online_node(node) {
1736 		unsigned long faults;
1737 		int dist = node_distance(nid, node);
1738 
1739 		/*
1740 		 * The furthest away nodes in the system are not interesting
1741 		 * for placement; nid was already counted.
1742 		 */
1743 		if (dist >= max_dist || node == nid)
1744 			continue;
1745 
1746 		/*
1747 		 * On systems with a backplane NUMA topology, compare groups
1748 		 * of nodes, and move tasks towards the group with the most
1749 		 * memory accesses. When comparing two nodes at distance
1750 		 * "hoplimit", only nodes closer by than "hoplimit" are part
1751 		 * of each group. Skip other nodes.
1752 		 */
1753 		if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1754 			continue;
1755 
1756 		/* Add up the faults from nearby nodes. */
1757 		if (task)
1758 			faults = task_faults(p, node);
1759 		else
1760 			faults = group_faults(p, node);
1761 
1762 		/*
1763 		 * On systems with a glueless mesh NUMA topology, there are
1764 		 * no fixed "groups of nodes". Instead, nodes that are not
1765 		 * directly connected bounce traffic through intermediate
1766 		 * nodes; a numa_group can occupy any set of nodes.
1767 		 * The further away a node is, the less the faults count.
1768 		 * This seems to result in good task placement.
1769 		 */
1770 		if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1771 			faults *= (max_dist - dist);
1772 			faults /= (max_dist - LOCAL_DISTANCE);
1773 		}
1774 
1775 		score += faults;
1776 	}
1777 
1778 	return score;
1779 }
1780 
1781 /*
1782  * These return the fraction of accesses done by a particular task, or
1783  * task group, on a particular numa node.  The group weight is given a
1784  * larger multiplier, in order to group tasks together that are almost
1785  * evenly spread out between numa nodes.
1786  */
task_weight(struct task_struct * p,int nid,int dist)1787 static inline unsigned long task_weight(struct task_struct *p, int nid,
1788 					int dist)
1789 {
1790 	unsigned long faults, total_faults;
1791 
1792 	if (!p->numa_faults)
1793 		return 0;
1794 
1795 	total_faults = p->total_numa_faults;
1796 
1797 	if (!total_faults)
1798 		return 0;
1799 
1800 	faults = task_faults(p, nid);
1801 	faults += score_nearby_nodes(p, nid, dist, true);
1802 
1803 	return 1000 * faults / total_faults;
1804 }
1805 
group_weight(struct task_struct * p,int nid,int dist)1806 static inline unsigned long group_weight(struct task_struct *p, int nid,
1807 					 int dist)
1808 {
1809 	struct numa_group *ng = deref_task_numa_group(p);
1810 	unsigned long faults, total_faults;
1811 
1812 	if (!ng)
1813 		return 0;
1814 
1815 	total_faults = ng->total_faults;
1816 
1817 	if (!total_faults)
1818 		return 0;
1819 
1820 	faults = group_faults(p, nid);
1821 	faults += score_nearby_nodes(p, nid, dist, false);
1822 
1823 	return 1000 * faults / total_faults;
1824 }
1825 
1826 /*
1827  * If memory tiering mode is enabled, cpupid of slow memory page is
1828  * used to record scan time instead of CPU and PID.  When tiering mode
1829  * is disabled at run time, the scan time (in cpupid) will be
1830  * interpreted as CPU and PID.  So CPU needs to be checked to avoid to
1831  * access out of array bound.
1832  */
cpupid_valid(int cpupid)1833 static inline bool cpupid_valid(int cpupid)
1834 {
1835 	return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1836 }
1837 
1838 /*
1839  * For memory tiering mode, if there are enough free pages (more than
1840  * enough watermark defined here) in fast memory node, to take full
1841  * advantage of fast memory capacity, all recently accessed slow
1842  * memory pages will be migrated to fast memory node without
1843  * considering hot threshold.
1844  */
pgdat_free_space_enough(struct pglist_data * pgdat)1845 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1846 {
1847 	int z;
1848 	unsigned long enough_wmark;
1849 
1850 	enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1851 			   pgdat->node_present_pages >> 4);
1852 	for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1853 		struct zone *zone = pgdat->node_zones + z;
1854 
1855 		if (!populated_zone(zone))
1856 			continue;
1857 
1858 		if (zone_watermark_ok(zone, 0,
1859 				      wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1860 				      ZONE_MOVABLE, 0))
1861 			return true;
1862 	}
1863 	return false;
1864 }
1865 
1866 /*
1867  * For memory tiering mode, when page tables are scanned, the scan
1868  * time will be recorded in struct page in addition to make page
1869  * PROT_NONE for slow memory page.  So when the page is accessed, in
1870  * hint page fault handler, the hint page fault latency is calculated
1871  * via,
1872  *
1873  *	hint page fault latency = hint page fault time - scan time
1874  *
1875  * The smaller the hint page fault latency, the higher the possibility
1876  * for the page to be hot.
1877  */
numa_hint_fault_latency(struct page * page)1878 static int numa_hint_fault_latency(struct page *page)
1879 {
1880 	int last_time, time;
1881 
1882 	time = jiffies_to_msecs(jiffies);
1883 	last_time = xchg_page_access_time(page, time);
1884 
1885 	return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1886 }
1887 
1888 /*
1889  * For memory tiering mode, too high promotion/demotion throughput may
1890  * hurt application latency.  So we provide a mechanism to rate limit
1891  * the number of pages that are tried to be promoted.
1892  */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1893 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1894 				      unsigned long rate_limit, int nr)
1895 {
1896 	unsigned long nr_cand;
1897 	unsigned int now, start;
1898 
1899 	now = jiffies_to_msecs(jiffies);
1900 	mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1901 	nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1902 	start = pgdat->nbp_rl_start;
1903 	if (now - start > MSEC_PER_SEC &&
1904 	    cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1905 		pgdat->nbp_rl_nr_cand = nr_cand;
1906 	if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1907 		return true;
1908 	return false;
1909 }
1910 
1911 #define NUMA_MIGRATION_ADJUST_STEPS	16
1912 
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1913 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1914 					    unsigned long rate_limit,
1915 					    unsigned int ref_th)
1916 {
1917 	unsigned int now, start, th_period, unit_th, th;
1918 	unsigned long nr_cand, ref_cand, diff_cand;
1919 
1920 	now = jiffies_to_msecs(jiffies);
1921 	th_period = sysctl_numa_balancing_scan_period_max;
1922 	start = pgdat->nbp_th_start;
1923 	if (now - start > th_period &&
1924 	    cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1925 		ref_cand = rate_limit *
1926 			sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1927 		nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1928 		diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1929 		unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1930 		th = pgdat->nbp_threshold ? : ref_th;
1931 		if (diff_cand > ref_cand * 11 / 10)
1932 			th = max(th - unit_th, unit_th);
1933 		else if (diff_cand < ref_cand * 9 / 10)
1934 			th = min(th + unit_th, ref_th * 2);
1935 		pgdat->nbp_th_nr_cand = nr_cand;
1936 		pgdat->nbp_threshold = th;
1937 	}
1938 }
1939 
should_numa_migrate_memory(struct task_struct * p,struct page * page,int src_nid,int dst_cpu)1940 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1941 				int src_nid, int dst_cpu)
1942 {
1943 	struct numa_group *ng = deref_curr_numa_group(p);
1944 	int dst_nid = cpu_to_node(dst_cpu);
1945 	int last_cpupid, this_cpupid;
1946 
1947 	/*
1948 	 * The pages in slow memory node should be migrated according
1949 	 * to hot/cold instead of private/shared.
1950 	 */
1951 	if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1952 	    !node_is_toptier(src_nid)) {
1953 		struct pglist_data *pgdat;
1954 		unsigned long rate_limit;
1955 		unsigned int latency, th, def_th;
1956 
1957 		pgdat = NODE_DATA(dst_nid);
1958 		if (pgdat_free_space_enough(pgdat)) {
1959 			/* workload changed, reset hot threshold */
1960 			pgdat->nbp_threshold = 0;
1961 			return true;
1962 		}
1963 
1964 		def_th = sysctl_numa_balancing_hot_threshold;
1965 		rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1966 			(20 - PAGE_SHIFT);
1967 		numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1968 
1969 		th = pgdat->nbp_threshold ? : def_th;
1970 		latency = numa_hint_fault_latency(page);
1971 		if (latency >= th)
1972 			return false;
1973 
1974 		return !numa_promotion_rate_limit(pgdat, rate_limit,
1975 						  thp_nr_pages(page));
1976 	}
1977 
1978 	this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1979 	last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1980 
1981 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1982 	    !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1983 		return false;
1984 
1985 	/*
1986 	 * Allow first faults or private faults to migrate immediately early in
1987 	 * the lifetime of a task. The magic number 4 is based on waiting for
1988 	 * two full passes of the "multi-stage node selection" test that is
1989 	 * executed below.
1990 	 */
1991 	if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1992 	    (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1993 		return true;
1994 
1995 	/*
1996 	 * Multi-stage node selection is used in conjunction with a periodic
1997 	 * migration fault to build a temporal task<->page relation. By using
1998 	 * a two-stage filter we remove short/unlikely relations.
1999 	 *
2000 	 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2001 	 * a task's usage of a particular page (n_p) per total usage of this
2002 	 * page (n_t) (in a given time-span) to a probability.
2003 	 *
2004 	 * Our periodic faults will sample this probability and getting the
2005 	 * same result twice in a row, given these samples are fully
2006 	 * independent, is then given by P(n)^2, provided our sample period
2007 	 * is sufficiently short compared to the usage pattern.
2008 	 *
2009 	 * This quadric squishes small probabilities, making it less likely we
2010 	 * act on an unlikely task<->page relation.
2011 	 */
2012 	if (!cpupid_pid_unset(last_cpupid) &&
2013 				cpupid_to_nid(last_cpupid) != dst_nid)
2014 		return false;
2015 
2016 	/* Always allow migrate on private faults */
2017 	if (cpupid_match_pid(p, last_cpupid))
2018 		return true;
2019 
2020 	/* A shared fault, but p->numa_group has not been set up yet. */
2021 	if (!ng)
2022 		return true;
2023 
2024 	/*
2025 	 * Destination node is much more heavily used than the source
2026 	 * node? Allow migration.
2027 	 */
2028 	if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2029 					ACTIVE_NODE_FRACTION)
2030 		return true;
2031 
2032 	/*
2033 	 * Distribute memory according to CPU & memory use on each node,
2034 	 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2035 	 *
2036 	 * faults_cpu(dst)   3   faults_cpu(src)
2037 	 * --------------- * - > ---------------
2038 	 * faults_mem(dst)   4   faults_mem(src)
2039 	 */
2040 	return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2041 	       group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2042 }
2043 
2044 /*
2045  * 'numa_type' describes the node at the moment of load balancing.
2046  */
2047 enum numa_type {
2048 	/* The node has spare capacity that can be used to run more tasks.  */
2049 	node_has_spare = 0,
2050 	/*
2051 	 * The node is fully used and the tasks don't compete for more CPU
2052 	 * cycles. Nevertheless, some tasks might wait before running.
2053 	 */
2054 	node_fully_busy,
2055 	/*
2056 	 * The node is overloaded and can't provide expected CPU cycles to all
2057 	 * tasks.
2058 	 */
2059 	node_overloaded
2060 };
2061 
2062 /* Cached statistics for all CPUs within a node */
2063 struct numa_stats {
2064 	unsigned long load;
2065 	unsigned long runnable;
2066 	unsigned long util;
2067 	/* Total compute capacity of CPUs on a node */
2068 	unsigned long compute_capacity;
2069 	unsigned int nr_running;
2070 	unsigned int weight;
2071 	enum numa_type node_type;
2072 	int idle_cpu;
2073 };
2074 
2075 struct task_numa_env {
2076 	struct task_struct *p;
2077 
2078 	int src_cpu, src_nid;
2079 	int dst_cpu, dst_nid;
2080 	int imb_numa_nr;
2081 
2082 	struct numa_stats src_stats, dst_stats;
2083 
2084 	int imbalance_pct;
2085 	int dist;
2086 
2087 	struct task_struct *best_task;
2088 	long best_imp;
2089 	int best_cpu;
2090 };
2091 
2092 static unsigned long cpu_load(struct rq *rq);
2093 static unsigned long cpu_runnable(struct rq *rq);
2094 
2095 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2096 numa_type numa_classify(unsigned int imbalance_pct,
2097 			 struct numa_stats *ns)
2098 {
2099 	if ((ns->nr_running > ns->weight) &&
2100 	    (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2101 	     ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2102 		return node_overloaded;
2103 
2104 	if ((ns->nr_running < ns->weight) ||
2105 	    (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2106 	     ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2107 		return node_has_spare;
2108 
2109 	return node_fully_busy;
2110 }
2111 
2112 #ifdef CONFIG_SCHED_SMT
2113 /* Forward declarations of select_idle_sibling helpers */
2114 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2115 static inline int numa_idle_core(int idle_core, int cpu)
2116 {
2117 	if (!static_branch_likely(&sched_smt_present) ||
2118 	    idle_core >= 0 || !test_idle_cores(cpu))
2119 		return idle_core;
2120 
2121 	/*
2122 	 * Prefer cores instead of packing HT siblings
2123 	 * and triggering future load balancing.
2124 	 */
2125 	if (is_core_idle(cpu))
2126 		idle_core = cpu;
2127 
2128 	return idle_core;
2129 }
2130 #else
numa_idle_core(int idle_core,int cpu)2131 static inline int numa_idle_core(int idle_core, int cpu)
2132 {
2133 	return idle_core;
2134 }
2135 #endif
2136 
2137 /*
2138  * Gather all necessary information to make NUMA balancing placement
2139  * decisions that are compatible with standard load balancer. This
2140  * borrows code and logic from update_sg_lb_stats but sharing a
2141  * common implementation is impractical.
2142  */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2143 static void update_numa_stats(struct task_numa_env *env,
2144 			      struct numa_stats *ns, int nid,
2145 			      bool find_idle)
2146 {
2147 	int cpu, idle_core = -1;
2148 
2149 	memset(ns, 0, sizeof(*ns));
2150 	ns->idle_cpu = -1;
2151 
2152 	rcu_read_lock();
2153 	for_each_cpu(cpu, cpumask_of_node(nid)) {
2154 		struct rq *rq = cpu_rq(cpu);
2155 
2156 		ns->load += cpu_load(rq);
2157 		ns->runnable += cpu_runnable(rq);
2158 		ns->util += cpu_util_cfs(cpu);
2159 		ns->nr_running += rq->cfs.h_nr_running;
2160 		ns->compute_capacity += capacity_of(cpu);
2161 
2162 		if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2163 			if (READ_ONCE(rq->numa_migrate_on) ||
2164 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2165 				continue;
2166 
2167 			if (ns->idle_cpu == -1)
2168 				ns->idle_cpu = cpu;
2169 
2170 			idle_core = numa_idle_core(idle_core, cpu);
2171 		}
2172 	}
2173 	rcu_read_unlock();
2174 
2175 	ns->weight = cpumask_weight(cpumask_of_node(nid));
2176 
2177 	ns->node_type = numa_classify(env->imbalance_pct, ns);
2178 
2179 	if (idle_core >= 0)
2180 		ns->idle_cpu = idle_core;
2181 }
2182 
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2183 static void task_numa_assign(struct task_numa_env *env,
2184 			     struct task_struct *p, long imp)
2185 {
2186 	struct rq *rq = cpu_rq(env->dst_cpu);
2187 
2188 	/* Check if run-queue part of active NUMA balance. */
2189 	if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2190 		int cpu;
2191 		int start = env->dst_cpu;
2192 
2193 		/* Find alternative idle CPU. */
2194 		for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2195 			if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2196 			    !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2197 				continue;
2198 			}
2199 
2200 			env->dst_cpu = cpu;
2201 			rq = cpu_rq(env->dst_cpu);
2202 			if (!xchg(&rq->numa_migrate_on, 1))
2203 				goto assign;
2204 		}
2205 
2206 		/* Failed to find an alternative idle CPU */
2207 		return;
2208 	}
2209 
2210 assign:
2211 	/*
2212 	 * Clear previous best_cpu/rq numa-migrate flag, since task now
2213 	 * found a better CPU to move/swap.
2214 	 */
2215 	if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2216 		rq = cpu_rq(env->best_cpu);
2217 		WRITE_ONCE(rq->numa_migrate_on, 0);
2218 	}
2219 
2220 	if (env->best_task)
2221 		put_task_struct(env->best_task);
2222 	if (p)
2223 		get_task_struct(p);
2224 
2225 	env->best_task = p;
2226 	env->best_imp = imp;
2227 	env->best_cpu = env->dst_cpu;
2228 }
2229 
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2230 static bool load_too_imbalanced(long src_load, long dst_load,
2231 				struct task_numa_env *env)
2232 {
2233 	long imb, old_imb;
2234 	long orig_src_load, orig_dst_load;
2235 	long src_capacity, dst_capacity;
2236 
2237 	/*
2238 	 * The load is corrected for the CPU capacity available on each node.
2239 	 *
2240 	 * src_load        dst_load
2241 	 * ------------ vs ---------
2242 	 * src_capacity    dst_capacity
2243 	 */
2244 	src_capacity = env->src_stats.compute_capacity;
2245 	dst_capacity = env->dst_stats.compute_capacity;
2246 
2247 	imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2248 
2249 	orig_src_load = env->src_stats.load;
2250 	orig_dst_load = env->dst_stats.load;
2251 
2252 	old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2253 
2254 	/* Would this change make things worse? */
2255 	return (imb > old_imb);
2256 }
2257 
2258 /*
2259  * Maximum NUMA importance can be 1998 (2*999);
2260  * SMALLIMP @ 30 would be close to 1998/64.
2261  * Used to deter task migration.
2262  */
2263 #define SMALLIMP	30
2264 
2265 /*
2266  * This checks if the overall compute and NUMA accesses of the system would
2267  * be improved if the source tasks was migrated to the target dst_cpu taking
2268  * into account that it might be best if task running on the dst_cpu should
2269  * be exchanged with the source task
2270  */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2271 static bool task_numa_compare(struct task_numa_env *env,
2272 			      long taskimp, long groupimp, bool maymove)
2273 {
2274 	struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2275 	struct rq *dst_rq = cpu_rq(env->dst_cpu);
2276 	long imp = p_ng ? groupimp : taskimp;
2277 	struct task_struct *cur;
2278 	long src_load, dst_load;
2279 	int dist = env->dist;
2280 	long moveimp = imp;
2281 	long load;
2282 	bool stopsearch = false;
2283 
2284 	if (READ_ONCE(dst_rq->numa_migrate_on))
2285 		return false;
2286 
2287 	rcu_read_lock();
2288 	cur = rcu_dereference(dst_rq->curr);
2289 	if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2290 		cur = NULL;
2291 
2292 	/*
2293 	 * Because we have preemption enabled we can get migrated around and
2294 	 * end try selecting ourselves (current == env->p) as a swap candidate.
2295 	 */
2296 	if (cur == env->p) {
2297 		stopsearch = true;
2298 		goto unlock;
2299 	}
2300 
2301 	if (!cur) {
2302 		if (maymove && moveimp >= env->best_imp)
2303 			goto assign;
2304 		else
2305 			goto unlock;
2306 	}
2307 
2308 	/* Skip this swap candidate if cannot move to the source cpu. */
2309 	if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2310 		goto unlock;
2311 
2312 	/*
2313 	 * Skip this swap candidate if it is not moving to its preferred
2314 	 * node and the best task is.
2315 	 */
2316 	if (env->best_task &&
2317 	    env->best_task->numa_preferred_nid == env->src_nid &&
2318 	    cur->numa_preferred_nid != env->src_nid) {
2319 		goto unlock;
2320 	}
2321 
2322 	/*
2323 	 * "imp" is the fault differential for the source task between the
2324 	 * source and destination node. Calculate the total differential for
2325 	 * the source task and potential destination task. The more negative
2326 	 * the value is, the more remote accesses that would be expected to
2327 	 * be incurred if the tasks were swapped.
2328 	 *
2329 	 * If dst and source tasks are in the same NUMA group, or not
2330 	 * in any group then look only at task weights.
2331 	 */
2332 	cur_ng = rcu_dereference(cur->numa_group);
2333 	if (cur_ng == p_ng) {
2334 		/*
2335 		 * Do not swap within a group or between tasks that have
2336 		 * no group if there is spare capacity. Swapping does
2337 		 * not address the load imbalance and helps one task at
2338 		 * the cost of punishing another.
2339 		 */
2340 		if (env->dst_stats.node_type == node_has_spare)
2341 			goto unlock;
2342 
2343 		imp = taskimp + task_weight(cur, env->src_nid, dist) -
2344 		      task_weight(cur, env->dst_nid, dist);
2345 		/*
2346 		 * Add some hysteresis to prevent swapping the
2347 		 * tasks within a group over tiny differences.
2348 		 */
2349 		if (cur_ng)
2350 			imp -= imp / 16;
2351 	} else {
2352 		/*
2353 		 * Compare the group weights. If a task is all by itself
2354 		 * (not part of a group), use the task weight instead.
2355 		 */
2356 		if (cur_ng && p_ng)
2357 			imp += group_weight(cur, env->src_nid, dist) -
2358 			       group_weight(cur, env->dst_nid, dist);
2359 		else
2360 			imp += task_weight(cur, env->src_nid, dist) -
2361 			       task_weight(cur, env->dst_nid, dist);
2362 	}
2363 
2364 	/* Discourage picking a task already on its preferred node */
2365 	if (cur->numa_preferred_nid == env->dst_nid)
2366 		imp -= imp / 16;
2367 
2368 	/*
2369 	 * Encourage picking a task that moves to its preferred node.
2370 	 * This potentially makes imp larger than it's maximum of
2371 	 * 1998 (see SMALLIMP and task_weight for why) but in this
2372 	 * case, it does not matter.
2373 	 */
2374 	if (cur->numa_preferred_nid == env->src_nid)
2375 		imp += imp / 8;
2376 
2377 	if (maymove && moveimp > imp && moveimp > env->best_imp) {
2378 		imp = moveimp;
2379 		cur = NULL;
2380 		goto assign;
2381 	}
2382 
2383 	/*
2384 	 * Prefer swapping with a task moving to its preferred node over a
2385 	 * task that is not.
2386 	 */
2387 	if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2388 	    env->best_task->numa_preferred_nid != env->src_nid) {
2389 		goto assign;
2390 	}
2391 
2392 	/*
2393 	 * If the NUMA importance is less than SMALLIMP,
2394 	 * task migration might only result in ping pong
2395 	 * of tasks and also hurt performance due to cache
2396 	 * misses.
2397 	 */
2398 	if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2399 		goto unlock;
2400 
2401 	/*
2402 	 * In the overloaded case, try and keep the load balanced.
2403 	 */
2404 	load = task_h_load(env->p) - task_h_load(cur);
2405 	if (!load)
2406 		goto assign;
2407 
2408 	dst_load = env->dst_stats.load + load;
2409 	src_load = env->src_stats.load - load;
2410 
2411 	if (load_too_imbalanced(src_load, dst_load, env))
2412 		goto unlock;
2413 
2414 assign:
2415 	/* Evaluate an idle CPU for a task numa move. */
2416 	if (!cur) {
2417 		int cpu = env->dst_stats.idle_cpu;
2418 
2419 		/* Nothing cached so current CPU went idle since the search. */
2420 		if (cpu < 0)
2421 			cpu = env->dst_cpu;
2422 
2423 		/*
2424 		 * If the CPU is no longer truly idle and the previous best CPU
2425 		 * is, keep using it.
2426 		 */
2427 		if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2428 		    idle_cpu(env->best_cpu)) {
2429 			cpu = env->best_cpu;
2430 		}
2431 
2432 		env->dst_cpu = cpu;
2433 	}
2434 
2435 	task_numa_assign(env, cur, imp);
2436 
2437 	/*
2438 	 * If a move to idle is allowed because there is capacity or load
2439 	 * balance improves then stop the search. While a better swap
2440 	 * candidate may exist, a search is not free.
2441 	 */
2442 	if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2443 		stopsearch = true;
2444 
2445 	/*
2446 	 * If a swap candidate must be identified and the current best task
2447 	 * moves its preferred node then stop the search.
2448 	 */
2449 	if (!maymove && env->best_task &&
2450 	    env->best_task->numa_preferred_nid == env->src_nid) {
2451 		stopsearch = true;
2452 	}
2453 unlock:
2454 	rcu_read_unlock();
2455 
2456 	return stopsearch;
2457 }
2458 
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2459 static void task_numa_find_cpu(struct task_numa_env *env,
2460 				long taskimp, long groupimp)
2461 {
2462 	bool maymove = false;
2463 	int cpu;
2464 
2465 	/*
2466 	 * If dst node has spare capacity, then check if there is an
2467 	 * imbalance that would be overruled by the load balancer.
2468 	 */
2469 	if (env->dst_stats.node_type == node_has_spare) {
2470 		unsigned int imbalance;
2471 		int src_running, dst_running;
2472 
2473 		/*
2474 		 * Would movement cause an imbalance? Note that if src has
2475 		 * more running tasks that the imbalance is ignored as the
2476 		 * move improves the imbalance from the perspective of the
2477 		 * CPU load balancer.
2478 		 * */
2479 		src_running = env->src_stats.nr_running - 1;
2480 		dst_running = env->dst_stats.nr_running + 1;
2481 		imbalance = max(0, dst_running - src_running);
2482 		imbalance = adjust_numa_imbalance(imbalance, dst_running,
2483 						  env->imb_numa_nr);
2484 
2485 		/* Use idle CPU if there is no imbalance */
2486 		if (!imbalance) {
2487 			maymove = true;
2488 			if (env->dst_stats.idle_cpu >= 0) {
2489 				env->dst_cpu = env->dst_stats.idle_cpu;
2490 				task_numa_assign(env, NULL, 0);
2491 				return;
2492 			}
2493 		}
2494 	} else {
2495 		long src_load, dst_load, load;
2496 		/*
2497 		 * If the improvement from just moving env->p direction is better
2498 		 * than swapping tasks around, check if a move is possible.
2499 		 */
2500 		load = task_h_load(env->p);
2501 		dst_load = env->dst_stats.load + load;
2502 		src_load = env->src_stats.load - load;
2503 		maymove = !load_too_imbalanced(src_load, dst_load, env);
2504 	}
2505 
2506 	for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2507 		/* Skip this CPU if the source task cannot migrate */
2508 		if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2509 			continue;
2510 
2511 		env->dst_cpu = cpu;
2512 		if (task_numa_compare(env, taskimp, groupimp, maymove))
2513 			break;
2514 	}
2515 }
2516 
task_numa_migrate(struct task_struct * p)2517 static int task_numa_migrate(struct task_struct *p)
2518 {
2519 	struct task_numa_env env = {
2520 		.p = p,
2521 
2522 		.src_cpu = task_cpu(p),
2523 		.src_nid = task_node(p),
2524 
2525 		.imbalance_pct = 112,
2526 
2527 		.best_task = NULL,
2528 		.best_imp = 0,
2529 		.best_cpu = -1,
2530 	};
2531 	unsigned long taskweight, groupweight;
2532 	struct sched_domain *sd;
2533 	long taskimp, groupimp;
2534 	struct numa_group *ng;
2535 	struct rq *best_rq;
2536 	int nid, ret, dist;
2537 
2538 	/*
2539 	 * Pick the lowest SD_NUMA domain, as that would have the smallest
2540 	 * imbalance and would be the first to start moving tasks about.
2541 	 *
2542 	 * And we want to avoid any moving of tasks about, as that would create
2543 	 * random movement of tasks -- counter the numa conditions we're trying
2544 	 * to satisfy here.
2545 	 */
2546 	rcu_read_lock();
2547 	sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2548 	if (sd) {
2549 		env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2550 		env.imb_numa_nr = sd->imb_numa_nr;
2551 	}
2552 	rcu_read_unlock();
2553 
2554 	/*
2555 	 * Cpusets can break the scheduler domain tree into smaller
2556 	 * balance domains, some of which do not cross NUMA boundaries.
2557 	 * Tasks that are "trapped" in such domains cannot be migrated
2558 	 * elsewhere, so there is no point in (re)trying.
2559 	 */
2560 	if (unlikely(!sd)) {
2561 		sched_setnuma(p, task_node(p));
2562 		return -EINVAL;
2563 	}
2564 
2565 	env.dst_nid = p->numa_preferred_nid;
2566 	dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2567 	taskweight = task_weight(p, env.src_nid, dist);
2568 	groupweight = group_weight(p, env.src_nid, dist);
2569 	update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2570 	taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2571 	groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2572 	update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2573 
2574 	/* Try to find a spot on the preferred nid. */
2575 	task_numa_find_cpu(&env, taskimp, groupimp);
2576 
2577 	/*
2578 	 * Look at other nodes in these cases:
2579 	 * - there is no space available on the preferred_nid
2580 	 * - the task is part of a numa_group that is interleaved across
2581 	 *   multiple NUMA nodes; in order to better consolidate the group,
2582 	 *   we need to check other locations.
2583 	 */
2584 	ng = deref_curr_numa_group(p);
2585 	if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2586 		for_each_node_state(nid, N_CPU) {
2587 			if (nid == env.src_nid || nid == p->numa_preferred_nid)
2588 				continue;
2589 
2590 			dist = node_distance(env.src_nid, env.dst_nid);
2591 			if (sched_numa_topology_type == NUMA_BACKPLANE &&
2592 						dist != env.dist) {
2593 				taskweight = task_weight(p, env.src_nid, dist);
2594 				groupweight = group_weight(p, env.src_nid, dist);
2595 			}
2596 
2597 			/* Only consider nodes where both task and groups benefit */
2598 			taskimp = task_weight(p, nid, dist) - taskweight;
2599 			groupimp = group_weight(p, nid, dist) - groupweight;
2600 			if (taskimp < 0 && groupimp < 0)
2601 				continue;
2602 
2603 			env.dist = dist;
2604 			env.dst_nid = nid;
2605 			update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2606 			task_numa_find_cpu(&env, taskimp, groupimp);
2607 		}
2608 	}
2609 
2610 	/*
2611 	 * If the task is part of a workload that spans multiple NUMA nodes,
2612 	 * and is migrating into one of the workload's active nodes, remember
2613 	 * this node as the task's preferred numa node, so the workload can
2614 	 * settle down.
2615 	 * A task that migrated to a second choice node will be better off
2616 	 * trying for a better one later. Do not set the preferred node here.
2617 	 */
2618 	if (ng) {
2619 		if (env.best_cpu == -1)
2620 			nid = env.src_nid;
2621 		else
2622 			nid = cpu_to_node(env.best_cpu);
2623 
2624 		if (nid != p->numa_preferred_nid)
2625 			sched_setnuma(p, nid);
2626 	}
2627 
2628 	/* No better CPU than the current one was found. */
2629 	if (env.best_cpu == -1) {
2630 		trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2631 		return -EAGAIN;
2632 	}
2633 
2634 	best_rq = cpu_rq(env.best_cpu);
2635 	if (env.best_task == NULL) {
2636 		ret = migrate_task_to(p, env.best_cpu);
2637 		WRITE_ONCE(best_rq->numa_migrate_on, 0);
2638 		if (ret != 0)
2639 			trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2640 		return ret;
2641 	}
2642 
2643 	ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2644 	WRITE_ONCE(best_rq->numa_migrate_on, 0);
2645 
2646 	if (ret != 0)
2647 		trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2648 	put_task_struct(env.best_task);
2649 	return ret;
2650 }
2651 
2652 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2653 static void numa_migrate_preferred(struct task_struct *p)
2654 {
2655 	unsigned long interval = HZ;
2656 
2657 	/* This task has no NUMA fault statistics yet */
2658 	if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2659 		return;
2660 
2661 	/* Periodically retry migrating the task to the preferred node */
2662 	interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2663 	p->numa_migrate_retry = jiffies + interval;
2664 
2665 	/* Success if task is already running on preferred CPU */
2666 	if (task_node(p) == p->numa_preferred_nid)
2667 		return;
2668 
2669 	/* Otherwise, try migrate to a CPU on the preferred node */
2670 	task_numa_migrate(p);
2671 }
2672 
2673 /*
2674  * Find out how many nodes the workload is actively running on. Do this by
2675  * tracking the nodes from which NUMA hinting faults are triggered. This can
2676  * be different from the set of nodes where the workload's memory is currently
2677  * located.
2678  */
numa_group_count_active_nodes(struct numa_group * numa_group)2679 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2680 {
2681 	unsigned long faults, max_faults = 0;
2682 	int nid, active_nodes = 0;
2683 
2684 	for_each_node_state(nid, N_CPU) {
2685 		faults = group_faults_cpu(numa_group, nid);
2686 		if (faults > max_faults)
2687 			max_faults = faults;
2688 	}
2689 
2690 	for_each_node_state(nid, N_CPU) {
2691 		faults = group_faults_cpu(numa_group, nid);
2692 		if (faults * ACTIVE_NODE_FRACTION > max_faults)
2693 			active_nodes++;
2694 	}
2695 
2696 	numa_group->max_faults_cpu = max_faults;
2697 	numa_group->active_nodes = active_nodes;
2698 }
2699 
2700 /*
2701  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2702  * increments. The more local the fault statistics are, the higher the scan
2703  * period will be for the next scan window. If local/(local+remote) ratio is
2704  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2705  * the scan period will decrease. Aim for 70% local accesses.
2706  */
2707 #define NUMA_PERIOD_SLOTS 10
2708 #define NUMA_PERIOD_THRESHOLD 7
2709 
2710 /*
2711  * Increase the scan period (slow down scanning) if the majority of
2712  * our memory is already on our local node, or if the majority of
2713  * the page accesses are shared with other processes.
2714  * Otherwise, decrease the scan period.
2715  */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2716 static void update_task_scan_period(struct task_struct *p,
2717 			unsigned long shared, unsigned long private)
2718 {
2719 	unsigned int period_slot;
2720 	int lr_ratio, ps_ratio;
2721 	int diff;
2722 
2723 	unsigned long remote = p->numa_faults_locality[0];
2724 	unsigned long local = p->numa_faults_locality[1];
2725 
2726 	/*
2727 	 * If there were no record hinting faults then either the task is
2728 	 * completely idle or all activity is in areas that are not of interest
2729 	 * to automatic numa balancing. Related to that, if there were failed
2730 	 * migration then it implies we are migrating too quickly or the local
2731 	 * node is overloaded. In either case, scan slower
2732 	 */
2733 	if (local + shared == 0 || p->numa_faults_locality[2]) {
2734 		p->numa_scan_period = min(p->numa_scan_period_max,
2735 			p->numa_scan_period << 1);
2736 
2737 		p->mm->numa_next_scan = jiffies +
2738 			msecs_to_jiffies(p->numa_scan_period);
2739 
2740 		return;
2741 	}
2742 
2743 	/*
2744 	 * Prepare to scale scan period relative to the current period.
2745 	 *	 == NUMA_PERIOD_THRESHOLD scan period stays the same
2746 	 *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2747 	 *	 >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2748 	 */
2749 	period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2750 	lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2751 	ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2752 
2753 	if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2754 		/*
2755 		 * Most memory accesses are local. There is no need to
2756 		 * do fast NUMA scanning, since memory is already local.
2757 		 */
2758 		int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2759 		if (!slot)
2760 			slot = 1;
2761 		diff = slot * period_slot;
2762 	} else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2763 		/*
2764 		 * Most memory accesses are shared with other tasks.
2765 		 * There is no point in continuing fast NUMA scanning,
2766 		 * since other tasks may just move the memory elsewhere.
2767 		 */
2768 		int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2769 		if (!slot)
2770 			slot = 1;
2771 		diff = slot * period_slot;
2772 	} else {
2773 		/*
2774 		 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2775 		 * yet they are not on the local NUMA node. Speed up
2776 		 * NUMA scanning to get the memory moved over.
2777 		 */
2778 		int ratio = max(lr_ratio, ps_ratio);
2779 		diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2780 	}
2781 
2782 	p->numa_scan_period = clamp(p->numa_scan_period + diff,
2783 			task_scan_min(p), task_scan_max(p));
2784 	memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2785 }
2786 
2787 /*
2788  * Get the fraction of time the task has been running since the last
2789  * NUMA placement cycle. The scheduler keeps similar statistics, but
2790  * decays those on a 32ms period, which is orders of magnitude off
2791  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2792  * stats only if the task is so new there are no NUMA statistics yet.
2793  */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2794 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2795 {
2796 	u64 runtime, delta, now;
2797 	/* Use the start of this time slice to avoid calculations. */
2798 	now = p->se.exec_start;
2799 	runtime = p->se.sum_exec_runtime;
2800 
2801 	if (p->last_task_numa_placement) {
2802 		delta = runtime - p->last_sum_exec_runtime;
2803 		*period = now - p->last_task_numa_placement;
2804 
2805 		/* Avoid time going backwards, prevent potential divide error: */
2806 		if (unlikely((s64)*period < 0))
2807 			*period = 0;
2808 	} else {
2809 		delta = p->se.avg.load_sum;
2810 		*period = LOAD_AVG_MAX;
2811 	}
2812 
2813 	p->last_sum_exec_runtime = runtime;
2814 	p->last_task_numa_placement = now;
2815 
2816 	return delta;
2817 }
2818 
2819 /*
2820  * Determine the preferred nid for a task in a numa_group. This needs to
2821  * be done in a way that produces consistent results with group_weight,
2822  * otherwise workloads might not converge.
2823  */
preferred_group_nid(struct task_struct * p,int nid)2824 static int preferred_group_nid(struct task_struct *p, int nid)
2825 {
2826 	nodemask_t nodes;
2827 	int dist;
2828 
2829 	/* Direct connections between all NUMA nodes. */
2830 	if (sched_numa_topology_type == NUMA_DIRECT)
2831 		return nid;
2832 
2833 	/*
2834 	 * On a system with glueless mesh NUMA topology, group_weight
2835 	 * scores nodes according to the number of NUMA hinting faults on
2836 	 * both the node itself, and on nearby nodes.
2837 	 */
2838 	if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2839 		unsigned long score, max_score = 0;
2840 		int node, max_node = nid;
2841 
2842 		dist = sched_max_numa_distance;
2843 
2844 		for_each_node_state(node, N_CPU) {
2845 			score = group_weight(p, node, dist);
2846 			if (score > max_score) {
2847 				max_score = score;
2848 				max_node = node;
2849 			}
2850 		}
2851 		return max_node;
2852 	}
2853 
2854 	/*
2855 	 * Finding the preferred nid in a system with NUMA backplane
2856 	 * interconnect topology is more involved. The goal is to locate
2857 	 * tasks from numa_groups near each other in the system, and
2858 	 * untangle workloads from different sides of the system. This requires
2859 	 * searching down the hierarchy of node groups, recursively searching
2860 	 * inside the highest scoring group of nodes. The nodemask tricks
2861 	 * keep the complexity of the search down.
2862 	 */
2863 	nodes = node_states[N_CPU];
2864 	for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2865 		unsigned long max_faults = 0;
2866 		nodemask_t max_group = NODE_MASK_NONE;
2867 		int a, b;
2868 
2869 		/* Are there nodes at this distance from each other? */
2870 		if (!find_numa_distance(dist))
2871 			continue;
2872 
2873 		for_each_node_mask(a, nodes) {
2874 			unsigned long faults = 0;
2875 			nodemask_t this_group;
2876 			nodes_clear(this_group);
2877 
2878 			/* Sum group's NUMA faults; includes a==b case. */
2879 			for_each_node_mask(b, nodes) {
2880 				if (node_distance(a, b) < dist) {
2881 					faults += group_faults(p, b);
2882 					node_set(b, this_group);
2883 					node_clear(b, nodes);
2884 				}
2885 			}
2886 
2887 			/* Remember the top group. */
2888 			if (faults > max_faults) {
2889 				max_faults = faults;
2890 				max_group = this_group;
2891 				/*
2892 				 * subtle: at the smallest distance there is
2893 				 * just one node left in each "group", the
2894 				 * winner is the preferred nid.
2895 				 */
2896 				nid = a;
2897 			}
2898 		}
2899 		/* Next round, evaluate the nodes within max_group. */
2900 		if (!max_faults)
2901 			break;
2902 		nodes = max_group;
2903 	}
2904 	return nid;
2905 }
2906 
task_numa_placement(struct task_struct * p)2907 static void task_numa_placement(struct task_struct *p)
2908 {
2909 	int seq, nid, max_nid = NUMA_NO_NODE;
2910 	unsigned long max_faults = 0;
2911 	unsigned long fault_types[2] = { 0, 0 };
2912 	unsigned long total_faults;
2913 	u64 runtime, period;
2914 	spinlock_t *group_lock = NULL;
2915 	struct numa_group *ng;
2916 
2917 	/*
2918 	 * The p->mm->numa_scan_seq field gets updated without
2919 	 * exclusive access. Use READ_ONCE() here to ensure
2920 	 * that the field is read in a single access:
2921 	 */
2922 	seq = READ_ONCE(p->mm->numa_scan_seq);
2923 	if (p->numa_scan_seq == seq)
2924 		return;
2925 	p->numa_scan_seq = seq;
2926 	p->numa_scan_period_max = task_scan_max(p);
2927 
2928 	total_faults = p->numa_faults_locality[0] +
2929 		       p->numa_faults_locality[1];
2930 	runtime = numa_get_avg_runtime(p, &period);
2931 
2932 	/* If the task is part of a group prevent parallel updates to group stats */
2933 	ng = deref_curr_numa_group(p);
2934 	if (ng) {
2935 		group_lock = &ng->lock;
2936 		spin_lock_irq(group_lock);
2937 	}
2938 
2939 	/* Find the node with the highest number of faults */
2940 	for_each_online_node(nid) {
2941 		/* Keep track of the offsets in numa_faults array */
2942 		int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2943 		unsigned long faults = 0, group_faults = 0;
2944 		int priv;
2945 
2946 		for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2947 			long diff, f_diff, f_weight;
2948 
2949 			mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2950 			membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2951 			cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2952 			cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2953 
2954 			/* Decay existing window, copy faults since last scan */
2955 			diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2956 			fault_types[priv] += p->numa_faults[membuf_idx];
2957 			p->numa_faults[membuf_idx] = 0;
2958 
2959 			/*
2960 			 * Normalize the faults_from, so all tasks in a group
2961 			 * count according to CPU use, instead of by the raw
2962 			 * number of faults. Tasks with little runtime have
2963 			 * little over-all impact on throughput, and thus their
2964 			 * faults are less important.
2965 			 */
2966 			f_weight = div64_u64(runtime << 16, period + 1);
2967 			f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2968 				   (total_faults + 1);
2969 			f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2970 			p->numa_faults[cpubuf_idx] = 0;
2971 
2972 			p->numa_faults[mem_idx] += diff;
2973 			p->numa_faults[cpu_idx] += f_diff;
2974 			faults += p->numa_faults[mem_idx];
2975 			p->total_numa_faults += diff;
2976 			if (ng) {
2977 				/*
2978 				 * safe because we can only change our own group
2979 				 *
2980 				 * mem_idx represents the offset for a given
2981 				 * nid and priv in a specific region because it
2982 				 * is at the beginning of the numa_faults array.
2983 				 */
2984 				ng->faults[mem_idx] += diff;
2985 				ng->faults[cpu_idx] += f_diff;
2986 				ng->total_faults += diff;
2987 				group_faults += ng->faults[mem_idx];
2988 			}
2989 		}
2990 
2991 		if (!ng) {
2992 			if (faults > max_faults) {
2993 				max_faults = faults;
2994 				max_nid = nid;
2995 			}
2996 		} else if (group_faults > max_faults) {
2997 			max_faults = group_faults;
2998 			max_nid = nid;
2999 		}
3000 	}
3001 
3002 	/* Cannot migrate task to CPU-less node */
3003 	if (max_nid != NUMA_NO_NODE && !node_state(max_nid, N_CPU)) {
3004 		int near_nid = max_nid;
3005 		int distance, near_distance = INT_MAX;
3006 
3007 		for_each_node_state(nid, N_CPU) {
3008 			distance = node_distance(max_nid, nid);
3009 			if (distance < near_distance) {
3010 				near_nid = nid;
3011 				near_distance = distance;
3012 			}
3013 		}
3014 		max_nid = near_nid;
3015 	}
3016 
3017 	if (ng) {
3018 		numa_group_count_active_nodes(ng);
3019 		spin_unlock_irq(group_lock);
3020 		max_nid = preferred_group_nid(p, max_nid);
3021 	}
3022 
3023 	if (max_faults) {
3024 		/* Set the new preferred node */
3025 		if (max_nid != p->numa_preferred_nid)
3026 			sched_setnuma(p, max_nid);
3027 	}
3028 
3029 	update_task_scan_period(p, fault_types[0], fault_types[1]);
3030 }
3031 
get_numa_group(struct numa_group * grp)3032 static inline int get_numa_group(struct numa_group *grp)
3033 {
3034 	return refcount_inc_not_zero(&grp->refcount);
3035 }
3036 
put_numa_group(struct numa_group * grp)3037 static inline void put_numa_group(struct numa_group *grp)
3038 {
3039 	if (refcount_dec_and_test(&grp->refcount))
3040 		kfree_rcu(grp, rcu);
3041 }
3042 
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)3043 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3044 			int *priv)
3045 {
3046 	struct numa_group *grp, *my_grp;
3047 	struct task_struct *tsk;
3048 	bool join = false;
3049 	int cpu = cpupid_to_cpu(cpupid);
3050 	int i;
3051 
3052 	if (unlikely(!deref_curr_numa_group(p))) {
3053 		unsigned int size = sizeof(struct numa_group) +
3054 				    NR_NUMA_HINT_FAULT_STATS *
3055 				    nr_node_ids * sizeof(unsigned long);
3056 
3057 		grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3058 		if (!grp)
3059 			return;
3060 
3061 		refcount_set(&grp->refcount, 1);
3062 		grp->active_nodes = 1;
3063 		grp->max_faults_cpu = 0;
3064 		spin_lock_init(&grp->lock);
3065 		grp->gid = p->pid;
3066 
3067 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3068 			grp->faults[i] = p->numa_faults[i];
3069 
3070 		grp->total_faults = p->total_numa_faults;
3071 
3072 		grp->nr_tasks++;
3073 		rcu_assign_pointer(p->numa_group, grp);
3074 	}
3075 
3076 	rcu_read_lock();
3077 	tsk = READ_ONCE(cpu_rq(cpu)->curr);
3078 
3079 	if (!cpupid_match_pid(tsk, cpupid))
3080 		goto no_join;
3081 
3082 	grp = rcu_dereference(tsk->numa_group);
3083 	if (!grp)
3084 		goto no_join;
3085 
3086 	my_grp = deref_curr_numa_group(p);
3087 	if (grp == my_grp)
3088 		goto no_join;
3089 
3090 	/*
3091 	 * Only join the other group if its bigger; if we're the bigger group,
3092 	 * the other task will join us.
3093 	 */
3094 	if (my_grp->nr_tasks > grp->nr_tasks)
3095 		goto no_join;
3096 
3097 	/*
3098 	 * Tie-break on the grp address.
3099 	 */
3100 	if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3101 		goto no_join;
3102 
3103 	/* Always join threads in the same process. */
3104 	if (tsk->mm == current->mm)
3105 		join = true;
3106 
3107 	/* Simple filter to avoid false positives due to PID collisions */
3108 	if (flags & TNF_SHARED)
3109 		join = true;
3110 
3111 	/* Update priv based on whether false sharing was detected */
3112 	*priv = !join;
3113 
3114 	if (join && !get_numa_group(grp))
3115 		goto no_join;
3116 
3117 	rcu_read_unlock();
3118 
3119 	if (!join)
3120 		return;
3121 
3122 	WARN_ON_ONCE(irqs_disabled());
3123 	double_lock_irq(&my_grp->lock, &grp->lock);
3124 
3125 	for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3126 		my_grp->faults[i] -= p->numa_faults[i];
3127 		grp->faults[i] += p->numa_faults[i];
3128 	}
3129 	my_grp->total_faults -= p->total_numa_faults;
3130 	grp->total_faults += p->total_numa_faults;
3131 
3132 	my_grp->nr_tasks--;
3133 	grp->nr_tasks++;
3134 
3135 	spin_unlock(&my_grp->lock);
3136 	spin_unlock_irq(&grp->lock);
3137 
3138 	rcu_assign_pointer(p->numa_group, grp);
3139 
3140 	put_numa_group(my_grp);
3141 	return;
3142 
3143 no_join:
3144 	rcu_read_unlock();
3145 	return;
3146 }
3147 
3148 /*
3149  * Get rid of NUMA statistics associated with a task (either current or dead).
3150  * If @final is set, the task is dead and has reached refcount zero, so we can
3151  * safely free all relevant data structures. Otherwise, there might be
3152  * concurrent reads from places like load balancing and procfs, and we should
3153  * reset the data back to default state without freeing ->numa_faults.
3154  */
task_numa_free(struct task_struct * p,bool final)3155 void task_numa_free(struct task_struct *p, bool final)
3156 {
3157 	/* safe: p either is current or is being freed by current */
3158 	struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3159 	unsigned long *numa_faults = p->numa_faults;
3160 	unsigned long flags;
3161 	int i;
3162 
3163 	if (!numa_faults)
3164 		return;
3165 
3166 	if (grp) {
3167 		spin_lock_irqsave(&grp->lock, flags);
3168 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3169 			grp->faults[i] -= p->numa_faults[i];
3170 		grp->total_faults -= p->total_numa_faults;
3171 
3172 		grp->nr_tasks--;
3173 		spin_unlock_irqrestore(&grp->lock, flags);
3174 		RCU_INIT_POINTER(p->numa_group, NULL);
3175 		put_numa_group(grp);
3176 	}
3177 
3178 	if (final) {
3179 		p->numa_faults = NULL;
3180 		kfree(numa_faults);
3181 	} else {
3182 		p->total_numa_faults = 0;
3183 		for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3184 			numa_faults[i] = 0;
3185 	}
3186 }
3187 
3188 /*
3189  * Got a PROT_NONE fault for a page on @node.
3190  */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3191 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3192 {
3193 	struct task_struct *p = current;
3194 	bool migrated = flags & TNF_MIGRATED;
3195 	int cpu_node = task_node(current);
3196 	int local = !!(flags & TNF_FAULT_LOCAL);
3197 	struct numa_group *ng;
3198 	int priv;
3199 
3200 	if (!static_branch_likely(&sched_numa_balancing))
3201 		return;
3202 
3203 	/* for example, ksmd faulting in a user's mm */
3204 	if (!p->mm)
3205 		return;
3206 
3207 	/*
3208 	 * NUMA faults statistics are unnecessary for the slow memory
3209 	 * node for memory tiering mode.
3210 	 */
3211 	if (!node_is_toptier(mem_node) &&
3212 	    (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3213 	     !cpupid_valid(last_cpupid)))
3214 		return;
3215 
3216 	/* Allocate buffer to track faults on a per-node basis */
3217 	if (unlikely(!p->numa_faults)) {
3218 		int size = sizeof(*p->numa_faults) *
3219 			   NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3220 
3221 		p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3222 		if (!p->numa_faults)
3223 			return;
3224 
3225 		p->total_numa_faults = 0;
3226 		memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3227 	}
3228 
3229 	/*
3230 	 * First accesses are treated as private, otherwise consider accesses
3231 	 * to be private if the accessing pid has not changed
3232 	 */
3233 	if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3234 		priv = 1;
3235 	} else {
3236 		priv = cpupid_match_pid(p, last_cpupid);
3237 		if (!priv && !(flags & TNF_NO_GROUP))
3238 			task_numa_group(p, last_cpupid, flags, &priv);
3239 	}
3240 
3241 	/*
3242 	 * If a workload spans multiple NUMA nodes, a shared fault that
3243 	 * occurs wholly within the set of nodes that the workload is
3244 	 * actively using should be counted as local. This allows the
3245 	 * scan rate to slow down when a workload has settled down.
3246 	 */
3247 	ng = deref_curr_numa_group(p);
3248 	if (!priv && !local && ng && ng->active_nodes > 1 &&
3249 				numa_is_active_node(cpu_node, ng) &&
3250 				numa_is_active_node(mem_node, ng))
3251 		local = 1;
3252 
3253 	/*
3254 	 * Retry to migrate task to preferred node periodically, in case it
3255 	 * previously failed, or the scheduler moved us.
3256 	 */
3257 	if (time_after(jiffies, p->numa_migrate_retry)) {
3258 		task_numa_placement(p);
3259 		numa_migrate_preferred(p);
3260 	}
3261 
3262 	if (migrated)
3263 		p->numa_pages_migrated += pages;
3264 	if (flags & TNF_MIGRATE_FAIL)
3265 		p->numa_faults_locality[2] += pages;
3266 
3267 	p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3268 	p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3269 	p->numa_faults_locality[local] += pages;
3270 }
3271 
reset_ptenuma_scan(struct task_struct * p)3272 static void reset_ptenuma_scan(struct task_struct *p)
3273 {
3274 	/*
3275 	 * We only did a read acquisition of the mmap sem, so
3276 	 * p->mm->numa_scan_seq is written to without exclusive access
3277 	 * and the update is not guaranteed to be atomic. That's not
3278 	 * much of an issue though, since this is just used for
3279 	 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3280 	 * expensive, to avoid any form of compiler optimizations:
3281 	 */
3282 	WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3283 	p->mm->numa_scan_offset = 0;
3284 }
3285 
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3286 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3287 {
3288 	unsigned long pids;
3289 	/*
3290 	 * Allow unconditional access first two times, so that all the (pages)
3291 	 * of VMAs get prot_none fault introduced irrespective of accesses.
3292 	 * This is also done to avoid any side effect of task scanning
3293 	 * amplifying the unfairness of disjoint set of VMAs' access.
3294 	 */
3295 	if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3296 		return true;
3297 
3298 	pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3299 	if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3300 		return true;
3301 
3302 	/*
3303 	 * Complete a scan that has already started regardless of PID access, or
3304 	 * some VMAs may never be scanned in multi-threaded applications:
3305 	 */
3306 	if (mm->numa_scan_offset > vma->vm_start) {
3307 		trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3308 		return true;
3309 	}
3310 
3311 	/*
3312 	 * This vma has not been accessed for a while, and if the number
3313 	 * the threads in the same process is low, which means no other
3314 	 * threads can help scan this vma, force a vma scan.
3315 	 */
3316 	if (READ_ONCE(mm->numa_scan_seq) >
3317 	   (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3318 		return true;
3319 
3320 	return false;
3321 }
3322 
3323 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3324 
3325 /*
3326  * The expensive part of numa migration is done from task_work context.
3327  * Triggered from task_tick_numa().
3328  */
task_numa_work(struct callback_head * work)3329 static void task_numa_work(struct callback_head *work)
3330 {
3331 	unsigned long migrate, next_scan, now = jiffies;
3332 	struct task_struct *p = current;
3333 	struct mm_struct *mm = p->mm;
3334 	u64 runtime = p->se.sum_exec_runtime;
3335 	struct vm_area_struct *vma;
3336 	unsigned long start, end;
3337 	unsigned long nr_pte_updates = 0;
3338 	long pages, virtpages;
3339 	struct vma_iterator vmi;
3340 	bool vma_pids_skipped;
3341 	bool vma_pids_forced = false;
3342 
3343 	SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3344 
3345 	work->next = work;
3346 	/*
3347 	 * Who cares about NUMA placement when they're dying.
3348 	 *
3349 	 * NOTE: make sure not to dereference p->mm before this check,
3350 	 * exit_task_work() happens _after_ exit_mm() so we could be called
3351 	 * without p->mm even though we still had it when we enqueued this
3352 	 * work.
3353 	 */
3354 	if (p->flags & PF_EXITING)
3355 		return;
3356 
3357 	if (!mm->numa_next_scan) {
3358 		mm->numa_next_scan = now +
3359 			msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3360 	}
3361 
3362 	/*
3363 	 * Enforce maximal scan/migration frequency..
3364 	 */
3365 	migrate = mm->numa_next_scan;
3366 	if (time_before(now, migrate))
3367 		return;
3368 
3369 	if (p->numa_scan_period == 0) {
3370 		p->numa_scan_period_max = task_scan_max(p);
3371 		p->numa_scan_period = task_scan_start(p);
3372 	}
3373 
3374 	next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3375 	if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3376 		return;
3377 
3378 	/*
3379 	 * Delay this task enough that another task of this mm will likely win
3380 	 * the next time around.
3381 	 */
3382 	p->node_stamp += 2 * TICK_NSEC;
3383 
3384 	pages = sysctl_numa_balancing_scan_size;
3385 	pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3386 	virtpages = pages * 8;	   /* Scan up to this much virtual space */
3387 	if (!pages)
3388 		return;
3389 
3390 
3391 	if (!mmap_read_trylock(mm))
3392 		return;
3393 
3394 	/*
3395 	 * VMAs are skipped if the current PID has not trapped a fault within
3396 	 * the VMA recently. Allow scanning to be forced if there is no
3397 	 * suitable VMA remaining.
3398 	 */
3399 	vma_pids_skipped = false;
3400 
3401 retry_pids:
3402 	start = mm->numa_scan_offset;
3403 	vma_iter_init(&vmi, mm, start);
3404 	vma = vma_next(&vmi);
3405 	if (!vma) {
3406 		reset_ptenuma_scan(p);
3407 		start = 0;
3408 		vma_iter_set(&vmi, start);
3409 		vma = vma_next(&vmi);
3410 	}
3411 
3412 	for (; vma; vma = vma_next(&vmi)) {
3413 		if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3414 			is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3415 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3416 			continue;
3417 		}
3418 
3419 		/*
3420 		 * Shared library pages mapped by multiple processes are not
3421 		 * migrated as it is expected they are cache replicated. Avoid
3422 		 * hinting faults in read-only file-backed mappings or the vdso
3423 		 * as migrating the pages will be of marginal benefit.
3424 		 */
3425 		if (!vma->vm_mm ||
3426 		    (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3427 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3428 			continue;
3429 		}
3430 
3431 		/*
3432 		 * Skip inaccessible VMAs to avoid any confusion between
3433 		 * PROT_NONE and NUMA hinting ptes
3434 		 */
3435 		if (!vma_is_accessible(vma)) {
3436 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3437 			continue;
3438 		}
3439 
3440 		/* Initialise new per-VMA NUMAB state. */
3441 		if (!vma->numab_state) {
3442 			struct vma_numab_state *ptr;
3443 
3444 			ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3445 			if (!ptr)
3446 				continue;
3447 
3448 			if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3449 				kfree(ptr);
3450 				continue;
3451 			}
3452 
3453 			vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3454 
3455 			vma->numab_state->next_scan = now +
3456 				msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3457 
3458 			/* Reset happens after 4 times scan delay of scan start */
3459 			vma->numab_state->pids_active_reset =  vma->numab_state->next_scan +
3460 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3461 
3462 			/*
3463 			 * Ensure prev_scan_seq does not match numa_scan_seq,
3464 			 * to prevent VMAs being skipped prematurely on the
3465 			 * first scan:
3466 			 */
3467 			 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3468 		}
3469 
3470 		/*
3471 		 * Scanning the VMA's of short lived tasks add more overhead. So
3472 		 * delay the scan for new VMAs.
3473 		 */
3474 		if (mm->numa_scan_seq && time_before(jiffies,
3475 						vma->numab_state->next_scan)) {
3476 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3477 			continue;
3478 		}
3479 
3480 		/* RESET access PIDs regularly for old VMAs. */
3481 		if (mm->numa_scan_seq &&
3482 				time_after(jiffies, vma->numab_state->pids_active_reset)) {
3483 			vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3484 				msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3485 			vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3486 			vma->numab_state->pids_active[1] = 0;
3487 		}
3488 
3489 		/* Do not rescan VMAs twice within the same sequence. */
3490 		if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3491 			mm->numa_scan_offset = vma->vm_end;
3492 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3493 			continue;
3494 		}
3495 
3496 		/*
3497 		 * Do not scan the VMA if task has not accessed it, unless no other
3498 		 * VMA candidate exists.
3499 		 */
3500 		if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3501 			vma_pids_skipped = true;
3502 			trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3503 			continue;
3504 		}
3505 
3506 		do {
3507 			start = max(start, vma->vm_start);
3508 			end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3509 			end = min(end, vma->vm_end);
3510 			nr_pte_updates = change_prot_numa(vma, start, end);
3511 
3512 			/*
3513 			 * Try to scan sysctl_numa_balancing_size worth of
3514 			 * hpages that have at least one present PTE that
3515 			 * is not already pte-numa. If the VMA contains
3516 			 * areas that are unused or already full of prot_numa
3517 			 * PTEs, scan up to virtpages, to skip through those
3518 			 * areas faster.
3519 			 */
3520 			if (nr_pte_updates)
3521 				pages -= (end - start) >> PAGE_SHIFT;
3522 			virtpages -= (end - start) >> PAGE_SHIFT;
3523 
3524 			start = end;
3525 			if (pages <= 0 || virtpages <= 0)
3526 				goto out;
3527 
3528 			cond_resched();
3529 		} while (end != vma->vm_end);
3530 
3531 		/* VMA scan is complete, do not scan until next sequence. */
3532 		vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3533 
3534 		/*
3535 		 * Only force scan within one VMA at a time, to limit the
3536 		 * cost of scanning a potentially uninteresting VMA.
3537 		 */
3538 		if (vma_pids_forced)
3539 			break;
3540 	}
3541 
3542 	/*
3543 	 * If no VMAs are remaining and VMAs were skipped due to the PID
3544 	 * not accessing the VMA previously, then force a scan to ensure
3545 	 * forward progress:
3546 	 */
3547 	if (!vma && !vma_pids_forced && vma_pids_skipped) {
3548 		vma_pids_forced = true;
3549 		goto retry_pids;
3550 	}
3551 
3552 out:
3553 	/*
3554 	 * It is possible to reach the end of the VMA list but the last few
3555 	 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3556 	 * would find the !migratable VMA on the next scan but not reset the
3557 	 * scanner to the start so check it now.
3558 	 */
3559 	if (vma)
3560 		mm->numa_scan_offset = start;
3561 	else
3562 		reset_ptenuma_scan(p);
3563 	mmap_read_unlock(mm);
3564 
3565 	/*
3566 	 * Make sure tasks use at least 32x as much time to run other code
3567 	 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3568 	 * Usually update_task_scan_period slows down scanning enough; on an
3569 	 * overloaded system we need to limit overhead on a per task basis.
3570 	 */
3571 	if (unlikely(p->se.sum_exec_runtime != runtime)) {
3572 		u64 diff = p->se.sum_exec_runtime - runtime;
3573 		p->node_stamp += 32 * diff;
3574 	}
3575 }
3576 
init_numa_balancing(unsigned long clone_flags,struct task_struct * p)3577 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3578 {
3579 	int mm_users = 0;
3580 	struct mm_struct *mm = p->mm;
3581 
3582 	if (mm) {
3583 		mm_users = atomic_read(&mm->mm_users);
3584 		if (mm_users == 1) {
3585 			mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3586 			mm->numa_scan_seq = 0;
3587 		}
3588 	}
3589 	p->node_stamp			= 0;
3590 	p->numa_scan_seq		= mm ? mm->numa_scan_seq : 0;
3591 	p->numa_scan_period		= sysctl_numa_balancing_scan_delay;
3592 	p->numa_migrate_retry		= 0;
3593 	/* Protect against double add, see task_tick_numa and task_numa_work */
3594 	p->numa_work.next		= &p->numa_work;
3595 	p->numa_faults			= NULL;
3596 	p->numa_pages_migrated		= 0;
3597 	p->total_numa_faults		= 0;
3598 	RCU_INIT_POINTER(p->numa_group, NULL);
3599 	p->last_task_numa_placement	= 0;
3600 	p->last_sum_exec_runtime	= 0;
3601 
3602 	init_task_work(&p->numa_work, task_numa_work);
3603 
3604 	/* New address space, reset the preferred nid */
3605 	if (!(clone_flags & CLONE_VM)) {
3606 		p->numa_preferred_nid = NUMA_NO_NODE;
3607 		return;
3608 	}
3609 
3610 	/*
3611 	 * New thread, keep existing numa_preferred_nid which should be copied
3612 	 * already by arch_dup_task_struct but stagger when scans start.
3613 	 */
3614 	if (mm) {
3615 		unsigned int delay;
3616 
3617 		delay = min_t(unsigned int, task_scan_max(current),
3618 			current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3619 		delay += 2 * TICK_NSEC;
3620 		p->node_stamp = delay;
3621 	}
3622 }
3623 
3624 /*
3625  * Drive the periodic memory faults..
3626  */
task_tick_numa(struct rq * rq,struct task_struct * curr)3627 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3628 {
3629 	struct callback_head *work = &curr->numa_work;
3630 	u64 period, now;
3631 
3632 	/*
3633 	 * We don't care about NUMA placement if we don't have memory.
3634 	 */
3635 	if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3636 		return;
3637 
3638 	/*
3639 	 * Using runtime rather than walltime has the dual advantage that
3640 	 * we (mostly) drive the selection from busy threads and that the
3641 	 * task needs to have done some actual work before we bother with
3642 	 * NUMA placement.
3643 	 */
3644 	now = curr->se.sum_exec_runtime;
3645 	period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3646 
3647 	if (now > curr->node_stamp + period) {
3648 		if (!curr->node_stamp)
3649 			curr->numa_scan_period = task_scan_start(curr);
3650 		curr->node_stamp += period;
3651 
3652 		if (!time_before(jiffies, curr->mm->numa_next_scan))
3653 			task_work_add(curr, work, TWA_RESUME);
3654 	}
3655 }
3656 
update_scan_period(struct task_struct * p,int new_cpu)3657 static void update_scan_period(struct task_struct *p, int new_cpu)
3658 {
3659 	int src_nid = cpu_to_node(task_cpu(p));
3660 	int dst_nid = cpu_to_node(new_cpu);
3661 
3662 	if (!static_branch_likely(&sched_numa_balancing))
3663 		return;
3664 
3665 	if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3666 		return;
3667 
3668 	if (src_nid == dst_nid)
3669 		return;
3670 
3671 	/*
3672 	 * Allow resets if faults have been trapped before one scan
3673 	 * has completed. This is most likely due to a new task that
3674 	 * is pulled cross-node due to wakeups or load balancing.
3675 	 */
3676 	if (p->numa_scan_seq) {
3677 		/*
3678 		 * Avoid scan adjustments if moving to the preferred
3679 		 * node or if the task was not previously running on
3680 		 * the preferred node.
3681 		 */
3682 		if (dst_nid == p->numa_preferred_nid ||
3683 		    (p->numa_preferred_nid != NUMA_NO_NODE &&
3684 			src_nid != p->numa_preferred_nid))
3685 			return;
3686 	}
3687 
3688 	p->numa_scan_period = task_scan_start(p);
3689 }
3690 
3691 #else
task_tick_numa(struct rq * rq,struct task_struct * curr)3692 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3693 {
3694 }
3695 
account_numa_enqueue(struct rq * rq,struct task_struct * p)3696 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3697 {
3698 }
3699 
account_numa_dequeue(struct rq * rq,struct task_struct * p)3700 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3701 {
3702 }
3703 
update_scan_period(struct task_struct * p,int new_cpu)3704 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3705 {
3706 }
3707 
3708 #endif /* CONFIG_NUMA_BALANCING */
3709 
3710 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3711 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3712 {
3713 	update_load_add(&cfs_rq->load, se->load.weight);
3714 #ifdef CONFIG_SMP
3715 	if (entity_is_task(se)) {
3716 		struct rq *rq = rq_of(cfs_rq);
3717 
3718 		account_numa_enqueue(rq, task_of(se));
3719 		list_add(&se->group_node, &rq->cfs_tasks);
3720 	}
3721 #endif
3722 	cfs_rq->nr_running++;
3723 	if (se_is_idle(se))
3724 		cfs_rq->idle_nr_running++;
3725 }
3726 
3727 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3728 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3729 {
3730 	update_load_sub(&cfs_rq->load, se->load.weight);
3731 #ifdef CONFIG_SMP
3732 	if (entity_is_task(se)) {
3733 		account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3734 		list_del_init(&se->group_node);
3735 	}
3736 #endif
3737 	cfs_rq->nr_running--;
3738 	if (se_is_idle(se))
3739 		cfs_rq->idle_nr_running--;
3740 }
3741 
3742 /*
3743  * Signed add and clamp on underflow.
3744  *
3745  * Explicitly do a load-store to ensure the intermediate value never hits
3746  * memory. This allows lockless observations without ever seeing the negative
3747  * values.
3748  */
3749 #define add_positive(_ptr, _val) do {                           \
3750 	typeof(_ptr) ptr = (_ptr);                              \
3751 	typeof(_val) val = (_val);                              \
3752 	typeof(*ptr) res, var = READ_ONCE(*ptr);                \
3753 								\
3754 	res = var + val;                                        \
3755 								\
3756 	if (val < 0 && res > var)                               \
3757 		res = 0;                                        \
3758 								\
3759 	WRITE_ONCE(*ptr, res);                                  \
3760 } while (0)
3761 
3762 /*
3763  * Unsigned subtract and clamp on underflow.
3764  *
3765  * Explicitly do a load-store to ensure the intermediate value never hits
3766  * memory. This allows lockless observations without ever seeing the negative
3767  * values.
3768  */
3769 #define sub_positive(_ptr, _val) do {				\
3770 	typeof(_ptr) ptr = (_ptr);				\
3771 	typeof(*ptr) val = (_val);				\
3772 	typeof(*ptr) res, var = READ_ONCE(*ptr);		\
3773 	res = var - val;					\
3774 	if (res > var)						\
3775 		res = 0;					\
3776 	WRITE_ONCE(*ptr, res);					\
3777 } while (0)
3778 
3779 /*
3780  * Remove and clamp on negative, from a local variable.
3781  *
3782  * A variant of sub_positive(), which does not use explicit load-store
3783  * and is thus optimized for local variable updates.
3784  */
3785 #define lsub_positive(_ptr, _val) do {				\
3786 	typeof(_ptr) ptr = (_ptr);				\
3787 	*ptr -= min_t(typeof(*ptr), *ptr, _val);		\
3788 } while (0)
3789 
3790 #ifdef CONFIG_SMP
3791 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3792 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3793 {
3794 	cfs_rq->avg.load_avg += se->avg.load_avg;
3795 	cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3796 }
3797 
3798 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3799 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3800 {
3801 	sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3802 	sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3803 	/* See update_cfs_rq_load_avg() */
3804 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3805 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3806 }
3807 #else
3808 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3809 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3810 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3811 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3812 #endif
3813 
reweight_eevdf(struct sched_entity * se,u64 avruntime,unsigned long weight)3814 static void reweight_eevdf(struct sched_entity *se, u64 avruntime,
3815 			   unsigned long weight)
3816 {
3817 	unsigned long old_weight = se->load.weight;
3818 	s64 vlag, vslice;
3819 
3820 	/*
3821 	 * VRUNTIME
3822 	 * ========
3823 	 *
3824 	 * COROLLARY #1: The virtual runtime of the entity needs to be
3825 	 * adjusted if re-weight at !0-lag point.
3826 	 *
3827 	 * Proof: For contradiction assume this is not true, so we can
3828 	 * re-weight without changing vruntime at !0-lag point.
3829 	 *
3830 	 *             Weight	VRuntime   Avg-VRuntime
3831 	 *     before    w          v            V
3832 	 *      after    w'         v'           V'
3833 	 *
3834 	 * Since lag needs to be preserved through re-weight:
3835 	 *
3836 	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
3837 	 *	==>	V' = (V - v)*w/w' + v		(1)
3838 	 *
3839 	 * Let W be the total weight of the entities before reweight,
3840 	 * since V' is the new weighted average of entities:
3841 	 *
3842 	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
3843 	 *
3844 	 * by using (1) & (2) we obtain:
3845 	 *
3846 	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
3847 	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
3848 	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
3849 	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
3850 	 *
3851 	 * Since we are doing at !0-lag point which means V != v, we
3852 	 * can simplify (3):
3853 	 *
3854 	 *	==>	W / (W + w' - w) = w / w'
3855 	 *	==>	Ww' = Ww + ww' - ww
3856 	 *	==>	W * (w' - w) = w * (w' - w)
3857 	 *	==>	W = w	(re-weight indicates w' != w)
3858 	 *
3859 	 * So the cfs_rq contains only one entity, hence vruntime of
3860 	 * the entity @v should always equal to the cfs_rq's weighted
3861 	 * average vruntime @V, which means we will always re-weight
3862 	 * at 0-lag point, thus breach assumption. Proof completed.
3863 	 *
3864 	 *
3865 	 * COROLLARY #2: Re-weight does NOT affect weighted average
3866 	 * vruntime of all the entities.
3867 	 *
3868 	 * Proof: According to corollary #1, Eq. (1) should be:
3869 	 *
3870 	 *	(V - v)*w = (V' - v')*w'
3871 	 *	==>    v' = V' - (V - v)*w/w'		(4)
3872 	 *
3873 	 * According to the weighted average formula, we have:
3874 	 *
3875 	 *	V' = (WV - wv + w'v') / (W - w + w')
3876 	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
3877 	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
3878 	 *	   = (WV + w'V' - Vw) / (W - w + w')
3879 	 *
3880 	 *	==>  V'*(W - w + w') = WV + w'V' - Vw
3881 	 *	==>	V' * (W - w) = (W - w) * V	(5)
3882 	 *
3883 	 * If the entity is the only one in the cfs_rq, then reweight
3884 	 * always occurs at 0-lag point, so V won't change. Or else
3885 	 * there are other entities, hence W != w, then Eq. (5) turns
3886 	 * into V' = V. So V won't change in either case, proof done.
3887 	 *
3888 	 *
3889 	 * So according to corollary #1 & #2, the effect of re-weight
3890 	 * on vruntime should be:
3891 	 *
3892 	 *	v' = V' - (V - v) * w / w'		(4)
3893 	 *	   = V  - (V - v) * w / w'
3894 	 *	   = V  - vl * w / w'
3895 	 *	   = V  - vl'
3896 	 */
3897 	if (avruntime != se->vruntime) {
3898 		vlag = entity_lag(avruntime, se);
3899 		vlag = div_s64(vlag * old_weight, weight);
3900 		se->vruntime = avruntime - vlag;
3901 	}
3902 
3903 	/*
3904 	 * DEADLINE
3905 	 * ========
3906 	 *
3907 	 * When the weight changes, the virtual time slope changes and
3908 	 * we should adjust the relative virtual deadline accordingly.
3909 	 *
3910 	 *	d' = v' + (d - v)*w/w'
3911 	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
3912 	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
3913 	 *	   = V  + (d - V)*w/w'
3914 	 */
3915 	vslice = (s64)(se->deadline - avruntime);
3916 	vslice = div_s64(vslice * old_weight, weight);
3917 	se->deadline = avruntime + vslice;
3918 }
3919 
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3920 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3921 			    unsigned long weight)
3922 {
3923 	bool curr = cfs_rq->curr == se;
3924 	u64 avruntime;
3925 
3926 	if (se->on_rq) {
3927 		/* commit outstanding execution time */
3928 		update_curr(cfs_rq);
3929 		avruntime = avg_vruntime(cfs_rq);
3930 		if (!curr)
3931 			__dequeue_entity(cfs_rq, se);
3932 		update_load_sub(&cfs_rq->load, se->load.weight);
3933 	}
3934 	dequeue_load_avg(cfs_rq, se);
3935 
3936 	if (se->on_rq) {
3937 		reweight_eevdf(se, avruntime, weight);
3938 	} else {
3939 		/*
3940 		 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3941 		 * we need to scale se->vlag when w_i changes.
3942 		 */
3943 		se->vlag = div_s64(se->vlag * se->load.weight, weight);
3944 	}
3945 
3946 	update_load_set(&se->load, weight);
3947 
3948 #ifdef CONFIG_SMP
3949 	do {
3950 		u32 divider = get_pelt_divider(&se->avg);
3951 
3952 		se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3953 	} while (0);
3954 #endif
3955 
3956 	enqueue_load_avg(cfs_rq, se);
3957 	if (se->on_rq) {
3958 		update_load_add(&cfs_rq->load, se->load.weight);
3959 		if (!curr)
3960 			__enqueue_entity(cfs_rq, se);
3961 
3962 		/*
3963 		 * The entity's vruntime has been adjusted, so let's check
3964 		 * whether the rq-wide min_vruntime needs updated too. Since
3965 		 * the calculations above require stable min_vruntime rather
3966 		 * than up-to-date one, we do the update at the end of the
3967 		 * reweight process.
3968 		 */
3969 		update_min_vruntime(cfs_rq);
3970 	}
3971 }
3972 
reweight_task(struct task_struct * p,const struct load_weight * lw)3973 void reweight_task(struct task_struct *p, const struct load_weight *lw)
3974 {
3975 	struct sched_entity *se = &p->se;
3976 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
3977 	struct load_weight *load = &se->load;
3978 
3979 	reweight_entity(cfs_rq, se, lw->weight);
3980 	load->inv_weight = lw->inv_weight;
3981 }
3982 
3983 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3984 
3985 #ifdef CONFIG_FAIR_GROUP_SCHED
3986 #ifdef CONFIG_SMP
3987 /*
3988  * All this does is approximate the hierarchical proportion which includes that
3989  * global sum we all love to hate.
3990  *
3991  * That is, the weight of a group entity, is the proportional share of the
3992  * group weight based on the group runqueue weights. That is:
3993  *
3994  *                     tg->weight * grq->load.weight
3995  *   ge->load.weight = -----------------------------               (1)
3996  *                       \Sum grq->load.weight
3997  *
3998  * Now, because computing that sum is prohibitively expensive to compute (been
3999  * there, done that) we approximate it with this average stuff. The average
4000  * moves slower and therefore the approximation is cheaper and more stable.
4001  *
4002  * So instead of the above, we substitute:
4003  *
4004  *   grq->load.weight -> grq->avg.load_avg                         (2)
4005  *
4006  * which yields the following:
4007  *
4008  *                     tg->weight * grq->avg.load_avg
4009  *   ge->load.weight = ------------------------------              (3)
4010  *                             tg->load_avg
4011  *
4012  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
4013  *
4014  * That is shares_avg, and it is right (given the approximation (2)).
4015  *
4016  * The problem with it is that because the average is slow -- it was designed
4017  * to be exactly that of course -- this leads to transients in boundary
4018  * conditions. In specific, the case where the group was idle and we start the
4019  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
4020  * yielding bad latency etc..
4021  *
4022  * Now, in that special case (1) reduces to:
4023  *
4024  *                     tg->weight * grq->load.weight
4025  *   ge->load.weight = ----------------------------- = tg->weight   (4)
4026  *                         grp->load.weight
4027  *
4028  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
4029  *
4030  * So what we do is modify our approximation (3) to approach (4) in the (near)
4031  * UP case, like:
4032  *
4033  *   ge->load.weight =
4034  *
4035  *              tg->weight * grq->load.weight
4036  *     ---------------------------------------------------         (5)
4037  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
4038  *
4039  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
4040  * we need to use grq->avg.load_avg as its lower bound, which then gives:
4041  *
4042  *
4043  *                     tg->weight * grq->load.weight
4044  *   ge->load.weight = -----------------------------		   (6)
4045  *                             tg_load_avg'
4046  *
4047  * Where:
4048  *
4049  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
4050  *                  max(grq->load.weight, grq->avg.load_avg)
4051  *
4052  * And that is shares_weight and is icky. In the (near) UP case it approaches
4053  * (4) while in the normal case it approaches (3). It consistently
4054  * overestimates the ge->load.weight and therefore:
4055  *
4056  *   \Sum ge->load.weight >= tg->weight
4057  *
4058  * hence icky!
4059  */
calc_group_shares(struct cfs_rq * cfs_rq)4060 static long calc_group_shares(struct cfs_rq *cfs_rq)
4061 {
4062 	long tg_weight, tg_shares, load, shares;
4063 	struct task_group *tg = cfs_rq->tg;
4064 
4065 	tg_shares = READ_ONCE(tg->shares);
4066 
4067 	load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
4068 
4069 	tg_weight = atomic_long_read(&tg->load_avg);
4070 
4071 	/* Ensure tg_weight >= load */
4072 	tg_weight -= cfs_rq->tg_load_avg_contrib;
4073 	tg_weight += load;
4074 
4075 	shares = (tg_shares * load);
4076 	if (tg_weight)
4077 		shares /= tg_weight;
4078 
4079 	/*
4080 	 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
4081 	 * of a group with small tg->shares value. It is a floor value which is
4082 	 * assigned as a minimum load.weight to the sched_entity representing
4083 	 * the group on a CPU.
4084 	 *
4085 	 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
4086 	 * on an 8-core system with 8 tasks each runnable on one CPU shares has
4087 	 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
4088 	 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
4089 	 * instead of 0.
4090 	 */
4091 	return clamp_t(long, shares, MIN_SHARES, tg_shares);
4092 }
4093 #endif /* CONFIG_SMP */
4094 
4095 /*
4096  * Recomputes the group entity based on the current state of its group
4097  * runqueue.
4098  */
update_cfs_group(struct sched_entity * se)4099 static void update_cfs_group(struct sched_entity *se)
4100 {
4101 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4102 	long shares;
4103 
4104 	if (!gcfs_rq)
4105 		return;
4106 
4107 	if (throttled_hierarchy(gcfs_rq))
4108 		return;
4109 
4110 #ifndef CONFIG_SMP
4111 	shares = READ_ONCE(gcfs_rq->tg->shares);
4112 #else
4113 	shares = calc_group_shares(gcfs_rq);
4114 #endif
4115 	if (unlikely(se->load.weight != shares))
4116 		reweight_entity(cfs_rq_of(se), se, shares);
4117 }
4118 
4119 #else /* CONFIG_FAIR_GROUP_SCHED */
update_cfs_group(struct sched_entity * se)4120 static inline void update_cfs_group(struct sched_entity *se)
4121 {
4122 }
4123 #endif /* CONFIG_FAIR_GROUP_SCHED */
4124 
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)4125 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
4126 {
4127 	struct rq *rq = rq_of(cfs_rq);
4128 
4129 	if (&rq->cfs == cfs_rq) {
4130 		/*
4131 		 * There are a few boundary cases this might miss but it should
4132 		 * get called often enough that that should (hopefully) not be
4133 		 * a real problem.
4134 		 *
4135 		 * It will not get called when we go idle, because the idle
4136 		 * thread is a different class (!fair), nor will the utilization
4137 		 * number include things like RT tasks.
4138 		 *
4139 		 * As is, the util number is not freq-invariant (we'd have to
4140 		 * implement arch_scale_freq_capacity() for that).
4141 		 *
4142 		 * See cpu_util_cfs().
4143 		 */
4144 		cpufreq_update_util(rq, flags);
4145 	}
4146 }
4147 
4148 #ifdef CONFIG_SMP
load_avg_is_decayed(struct sched_avg * sa)4149 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4150 {
4151 	if (sa->load_sum)
4152 		return false;
4153 
4154 	if (sa->util_sum)
4155 		return false;
4156 
4157 	if (sa->runnable_sum)
4158 		return false;
4159 
4160 	/*
4161 	 * _avg must be null when _sum are null because _avg = _sum / divider
4162 	 * Make sure that rounding and/or propagation of PELT values never
4163 	 * break this.
4164 	 */
4165 	SCHED_WARN_ON(sa->load_avg ||
4166 		      sa->util_avg ||
4167 		      sa->runnable_avg);
4168 
4169 	return true;
4170 }
4171 
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)4172 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4173 {
4174 	return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4175 				 cfs_rq->last_update_time_copy);
4176 }
4177 #ifdef CONFIG_FAIR_GROUP_SCHED
4178 /*
4179  * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4180  * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4181  * bottom-up, we only have to test whether the cfs_rq before us on the list
4182  * is our child.
4183  * If cfs_rq is not on the list, test whether a child needs its to be added to
4184  * connect a branch to the tree  * (see list_add_leaf_cfs_rq() for details).
4185  */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4186 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4187 {
4188 	struct cfs_rq *prev_cfs_rq;
4189 	struct list_head *prev;
4190 	struct rq *rq = rq_of(cfs_rq);
4191 
4192 	if (cfs_rq->on_list) {
4193 		prev = cfs_rq->leaf_cfs_rq_list.prev;
4194 	} else {
4195 		prev = rq->tmp_alone_branch;
4196 	}
4197 
4198 	if (prev == &rq->leaf_cfs_rq_list)
4199 		return false;
4200 
4201 	prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4202 
4203 	return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4204 }
4205 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4206 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4207 {
4208 	if (cfs_rq->load.weight)
4209 		return false;
4210 
4211 	if (!load_avg_is_decayed(&cfs_rq->avg))
4212 		return false;
4213 
4214 	if (child_cfs_rq_on_list(cfs_rq))
4215 		return false;
4216 
4217 	return true;
4218 }
4219 
4220 /**
4221  * update_tg_load_avg - update the tg's load avg
4222  * @cfs_rq: the cfs_rq whose avg changed
4223  *
4224  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4225  * However, because tg->load_avg is a global value there are performance
4226  * considerations.
4227  *
4228  * In order to avoid having to look at the other cfs_rq's, we use a
4229  * differential update where we store the last value we propagated. This in
4230  * turn allows skipping updates if the differential is 'small'.
4231  *
4232  * Updating tg's load_avg is necessary before update_cfs_share().
4233  */
update_tg_load_avg(struct cfs_rq * cfs_rq)4234 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4235 {
4236 	long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4237 
4238 	/*
4239 	 * No need to update load_avg for root_task_group as it is not used.
4240 	 */
4241 	if (cfs_rq->tg == &root_task_group)
4242 		return;
4243 
4244 	if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4245 		atomic_long_add(delta, &cfs_rq->tg->load_avg);
4246 		cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4247 	}
4248 }
4249 
4250 /*
4251  * Called within set_task_rq() right before setting a task's CPU. The
4252  * caller only guarantees p->pi_lock is held; no other assumptions,
4253  * including the state of rq->lock, should be made.
4254  */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4255 void set_task_rq_fair(struct sched_entity *se,
4256 		      struct cfs_rq *prev, struct cfs_rq *next)
4257 {
4258 	u64 p_last_update_time;
4259 	u64 n_last_update_time;
4260 
4261 	if (!sched_feat(ATTACH_AGE_LOAD))
4262 		return;
4263 
4264 	/*
4265 	 * We are supposed to update the task to "current" time, then its up to
4266 	 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4267 	 * getting what current time is, so simply throw away the out-of-date
4268 	 * time. This will result in the wakee task is less decayed, but giving
4269 	 * the wakee more load sounds not bad.
4270 	 */
4271 	if (!(se->avg.last_update_time && prev))
4272 		return;
4273 
4274 	p_last_update_time = cfs_rq_last_update_time(prev);
4275 	n_last_update_time = cfs_rq_last_update_time(next);
4276 
4277 	__update_load_avg_blocked_se(p_last_update_time, se);
4278 	se->avg.last_update_time = n_last_update_time;
4279 }
4280 
4281 /*
4282  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4283  * propagate its contribution. The key to this propagation is the invariant
4284  * that for each group:
4285  *
4286  *   ge->avg == grq->avg						(1)
4287  *
4288  * _IFF_ we look at the pure running and runnable sums. Because they
4289  * represent the very same entity, just at different points in the hierarchy.
4290  *
4291  * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4292  * and simply copies the running/runnable sum over (but still wrong, because
4293  * the group entity and group rq do not have their PELT windows aligned).
4294  *
4295  * However, update_tg_cfs_load() is more complex. So we have:
4296  *
4297  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg		(2)
4298  *
4299  * And since, like util, the runnable part should be directly transferable,
4300  * the following would _appear_ to be the straight forward approach:
4301  *
4302  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg	(3)
4303  *
4304  * And per (1) we have:
4305  *
4306  *   ge->avg.runnable_avg == grq->avg.runnable_avg
4307  *
4308  * Which gives:
4309  *
4310  *                      ge->load.weight * grq->avg.load_avg
4311  *   ge->avg.load_avg = -----------------------------------		(4)
4312  *                               grq->load.weight
4313  *
4314  * Except that is wrong!
4315  *
4316  * Because while for entities historical weight is not important and we
4317  * really only care about our future and therefore can consider a pure
4318  * runnable sum, runqueues can NOT do this.
4319  *
4320  * We specifically want runqueues to have a load_avg that includes
4321  * historical weights. Those represent the blocked load, the load we expect
4322  * to (shortly) return to us. This only works by keeping the weights as
4323  * integral part of the sum. We therefore cannot decompose as per (3).
4324  *
4325  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4326  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4327  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4328  * runnable section of these tasks overlap (or not). If they were to perfectly
4329  * align the rq as a whole would be runnable 2/3 of the time. If however we
4330  * always have at least 1 runnable task, the rq as a whole is always runnable.
4331  *
4332  * So we'll have to approximate.. :/
4333  *
4334  * Given the constraint:
4335  *
4336  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4337  *
4338  * We can construct a rule that adds runnable to a rq by assuming minimal
4339  * overlap.
4340  *
4341  * On removal, we'll assume each task is equally runnable; which yields:
4342  *
4343  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4344  *
4345  * XXX: only do this for the part of runnable > running ?
4346  *
4347  */
4348 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4349 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4350 {
4351 	long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4352 	u32 new_sum, divider;
4353 
4354 	/* Nothing to update */
4355 	if (!delta_avg)
4356 		return;
4357 
4358 	/*
4359 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4360 	 * See ___update_load_avg() for details.
4361 	 */
4362 	divider = get_pelt_divider(&cfs_rq->avg);
4363 
4364 
4365 	/* Set new sched_entity's utilization */
4366 	se->avg.util_avg = gcfs_rq->avg.util_avg;
4367 	new_sum = se->avg.util_avg * divider;
4368 	delta_sum = (long)new_sum - (long)se->avg.util_sum;
4369 	se->avg.util_sum = new_sum;
4370 
4371 	/* Update parent cfs_rq utilization */
4372 	add_positive(&cfs_rq->avg.util_avg, delta_avg);
4373 	add_positive(&cfs_rq->avg.util_sum, delta_sum);
4374 
4375 	/* See update_cfs_rq_load_avg() */
4376 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4377 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4378 }
4379 
4380 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4381 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4382 {
4383 	long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4384 	u32 new_sum, divider;
4385 
4386 	/* Nothing to update */
4387 	if (!delta_avg)
4388 		return;
4389 
4390 	/*
4391 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4392 	 * See ___update_load_avg() for details.
4393 	 */
4394 	divider = get_pelt_divider(&cfs_rq->avg);
4395 
4396 	/* Set new sched_entity's runnable */
4397 	se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4398 	new_sum = se->avg.runnable_avg * divider;
4399 	delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4400 	se->avg.runnable_sum = new_sum;
4401 
4402 	/* Update parent cfs_rq runnable */
4403 	add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4404 	add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4405 	/* See update_cfs_rq_load_avg() */
4406 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4407 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4408 }
4409 
4410 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4411 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4412 {
4413 	long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4414 	unsigned long load_avg;
4415 	u64 load_sum = 0;
4416 	s64 delta_sum;
4417 	u32 divider;
4418 
4419 	if (!runnable_sum)
4420 		return;
4421 
4422 	gcfs_rq->prop_runnable_sum = 0;
4423 
4424 	/*
4425 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4426 	 * See ___update_load_avg() for details.
4427 	 */
4428 	divider = get_pelt_divider(&cfs_rq->avg);
4429 
4430 	if (runnable_sum >= 0) {
4431 		/*
4432 		 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4433 		 * the CPU is saturated running == runnable.
4434 		 */
4435 		runnable_sum += se->avg.load_sum;
4436 		runnable_sum = min_t(long, runnable_sum, divider);
4437 	} else {
4438 		/*
4439 		 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4440 		 * assuming all tasks are equally runnable.
4441 		 */
4442 		if (scale_load_down(gcfs_rq->load.weight)) {
4443 			load_sum = div_u64(gcfs_rq->avg.load_sum,
4444 				scale_load_down(gcfs_rq->load.weight));
4445 		}
4446 
4447 		/* But make sure to not inflate se's runnable */
4448 		runnable_sum = min(se->avg.load_sum, load_sum);
4449 	}
4450 
4451 	/*
4452 	 * runnable_sum can't be lower than running_sum
4453 	 * Rescale running sum to be in the same range as runnable sum
4454 	 * running_sum is in [0 : LOAD_AVG_MAX <<  SCHED_CAPACITY_SHIFT]
4455 	 * runnable_sum is in [0 : LOAD_AVG_MAX]
4456 	 */
4457 	running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4458 	runnable_sum = max(runnable_sum, running_sum);
4459 
4460 	load_sum = se_weight(se) * runnable_sum;
4461 	load_avg = div_u64(load_sum, divider);
4462 
4463 	delta_avg = load_avg - se->avg.load_avg;
4464 	if (!delta_avg)
4465 		return;
4466 
4467 	delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4468 
4469 	se->avg.load_sum = runnable_sum;
4470 	se->avg.load_avg = load_avg;
4471 	add_positive(&cfs_rq->avg.load_avg, delta_avg);
4472 	add_positive(&cfs_rq->avg.load_sum, delta_sum);
4473 	/* See update_cfs_rq_load_avg() */
4474 	cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4475 					  cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4476 }
4477 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4478 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4479 {
4480 	cfs_rq->propagate = 1;
4481 	cfs_rq->prop_runnable_sum += runnable_sum;
4482 }
4483 
4484 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4485 static inline int propagate_entity_load_avg(struct sched_entity *se)
4486 {
4487 	struct cfs_rq *cfs_rq, *gcfs_rq;
4488 
4489 	if (entity_is_task(se))
4490 		return 0;
4491 
4492 	gcfs_rq = group_cfs_rq(se);
4493 	if (!gcfs_rq->propagate)
4494 		return 0;
4495 
4496 	gcfs_rq->propagate = 0;
4497 
4498 	cfs_rq = cfs_rq_of(se);
4499 
4500 	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4501 
4502 	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4503 	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4504 	update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4505 
4506 	trace_pelt_cfs_tp(cfs_rq);
4507 	trace_pelt_se_tp(se);
4508 
4509 	return 1;
4510 }
4511 
4512 /*
4513  * Check if we need to update the load and the utilization of a blocked
4514  * group_entity:
4515  */
skip_blocked_update(struct sched_entity * se)4516 static inline bool skip_blocked_update(struct sched_entity *se)
4517 {
4518 	struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4519 
4520 	/*
4521 	 * If sched_entity still have not zero load or utilization, we have to
4522 	 * decay it:
4523 	 */
4524 	if (se->avg.load_avg || se->avg.util_avg)
4525 		return false;
4526 
4527 	/*
4528 	 * If there is a pending propagation, we have to update the load and
4529 	 * the utilization of the sched_entity:
4530 	 */
4531 	if (gcfs_rq->propagate)
4532 		return false;
4533 
4534 	/*
4535 	 * Otherwise, the load and the utilization of the sched_entity is
4536 	 * already zero and there is no pending propagation, so it will be a
4537 	 * waste of time to try to decay it:
4538 	 */
4539 	return true;
4540 }
4541 
4542 #else /* CONFIG_FAIR_GROUP_SCHED */
4543 
update_tg_load_avg(struct cfs_rq * cfs_rq)4544 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4545 
propagate_entity_load_avg(struct sched_entity * se)4546 static inline int propagate_entity_load_avg(struct sched_entity *se)
4547 {
4548 	return 0;
4549 }
4550 
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4551 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4552 
4553 #endif /* CONFIG_FAIR_GROUP_SCHED */
4554 
4555 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4556 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4557 {
4558 	u64 throttled = 0, now, lut;
4559 	struct cfs_rq *cfs_rq;
4560 	struct rq *rq;
4561 	bool is_idle;
4562 
4563 	if (load_avg_is_decayed(&se->avg))
4564 		return;
4565 
4566 	cfs_rq = cfs_rq_of(se);
4567 	rq = rq_of(cfs_rq);
4568 
4569 	rcu_read_lock();
4570 	is_idle = is_idle_task(rcu_dereference(rq->curr));
4571 	rcu_read_unlock();
4572 
4573 	/*
4574 	 * The lag estimation comes with a cost we don't want to pay all the
4575 	 * time. Hence, limiting to the case where the source CPU is idle and
4576 	 * we know we are at the greatest risk to have an outdated clock.
4577 	 */
4578 	if (!is_idle)
4579 		return;
4580 
4581 	/*
4582 	 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4583 	 *
4584 	 *   last_update_time (the cfs_rq's last_update_time)
4585 	 *	= cfs_rq_clock_pelt()@cfs_rq_idle
4586 	 *      = rq_clock_pelt()@cfs_rq_idle
4587 	 *        - cfs->throttled_clock_pelt_time@cfs_rq_idle
4588 	 *
4589 	 *   cfs_idle_lag (delta between rq's update and cfs_rq's update)
4590 	 *      = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4591 	 *
4592 	 *   rq_idle_lag (delta between now and rq's update)
4593 	 *      = sched_clock_cpu() - rq_clock()@rq_idle
4594 	 *
4595 	 * We can then write:
4596 	 *
4597 	 *    now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4598 	 *          sched_clock_cpu() - rq_clock()@rq_idle
4599 	 * Where:
4600 	 *      rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4601 	 *      rq_clock()@rq_idle      is rq->clock_idle
4602 	 *      cfs->throttled_clock_pelt_time@cfs_rq_idle
4603 	 *                              is cfs_rq->throttled_pelt_idle
4604 	 */
4605 
4606 #ifdef CONFIG_CFS_BANDWIDTH
4607 	throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4608 	/* The clock has been stopped for throttling */
4609 	if (throttled == U64_MAX)
4610 		return;
4611 #endif
4612 	now = u64_u32_load(rq->clock_pelt_idle);
4613 	/*
4614 	 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4615 	 * is observed the old clock_pelt_idle value and the new clock_idle,
4616 	 * which lead to an underestimation. The opposite would lead to an
4617 	 * overestimation.
4618 	 */
4619 	smp_rmb();
4620 	lut = cfs_rq_last_update_time(cfs_rq);
4621 
4622 	now -= throttled;
4623 	if (now < lut)
4624 		/*
4625 		 * cfs_rq->avg.last_update_time is more recent than our
4626 		 * estimation, let's use it.
4627 		 */
4628 		now = lut;
4629 	else
4630 		now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4631 
4632 	__update_load_avg_blocked_se(now, se);
4633 }
4634 #else
migrate_se_pelt_lag(struct sched_entity * se)4635 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4636 #endif
4637 
4638 /**
4639  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4640  * @now: current time, as per cfs_rq_clock_pelt()
4641  * @cfs_rq: cfs_rq to update
4642  *
4643  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4644  * avg. The immediate corollary is that all (fair) tasks must be attached.
4645  *
4646  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4647  *
4648  * Return: true if the load decayed or we removed load.
4649  *
4650  * Since both these conditions indicate a changed cfs_rq->avg.load we should
4651  * call update_tg_load_avg() when this function returns true.
4652  */
4653 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4654 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4655 {
4656 	unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4657 	struct sched_avg *sa = &cfs_rq->avg;
4658 	int decayed = 0;
4659 
4660 	if (cfs_rq->removed.nr) {
4661 		unsigned long r;
4662 		u32 divider = get_pelt_divider(&cfs_rq->avg);
4663 
4664 		raw_spin_lock(&cfs_rq->removed.lock);
4665 		swap(cfs_rq->removed.util_avg, removed_util);
4666 		swap(cfs_rq->removed.load_avg, removed_load);
4667 		swap(cfs_rq->removed.runnable_avg, removed_runnable);
4668 		cfs_rq->removed.nr = 0;
4669 		raw_spin_unlock(&cfs_rq->removed.lock);
4670 
4671 		r = removed_load;
4672 		sub_positive(&sa->load_avg, r);
4673 		sub_positive(&sa->load_sum, r * divider);
4674 		/* See sa->util_sum below */
4675 		sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4676 
4677 		r = removed_util;
4678 		sub_positive(&sa->util_avg, r);
4679 		sub_positive(&sa->util_sum, r * divider);
4680 		/*
4681 		 * Because of rounding, se->util_sum might ends up being +1 more than
4682 		 * cfs->util_sum. Although this is not a problem by itself, detaching
4683 		 * a lot of tasks with the rounding problem between 2 updates of
4684 		 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4685 		 * cfs_util_avg is not.
4686 		 * Check that util_sum is still above its lower bound for the new
4687 		 * util_avg. Given that period_contrib might have moved since the last
4688 		 * sync, we are only sure that util_sum must be above or equal to
4689 		 *    util_avg * minimum possible divider
4690 		 */
4691 		sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4692 
4693 		r = removed_runnable;
4694 		sub_positive(&sa->runnable_avg, r);
4695 		sub_positive(&sa->runnable_sum, r * divider);
4696 		/* See sa->util_sum above */
4697 		sa->runnable_sum = max_t(u32, sa->runnable_sum,
4698 					      sa->runnable_avg * PELT_MIN_DIVIDER);
4699 
4700 		/*
4701 		 * removed_runnable is the unweighted version of removed_load so we
4702 		 * can use it to estimate removed_load_sum.
4703 		 */
4704 		add_tg_cfs_propagate(cfs_rq,
4705 			-(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4706 
4707 		decayed = 1;
4708 	}
4709 
4710 	decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4711 	u64_u32_store_copy(sa->last_update_time,
4712 			   cfs_rq->last_update_time_copy,
4713 			   sa->last_update_time);
4714 	return decayed;
4715 }
4716 
4717 /**
4718  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4719  * @cfs_rq: cfs_rq to attach to
4720  * @se: sched_entity to attach
4721  *
4722  * Must call update_cfs_rq_load_avg() before this, since we rely on
4723  * cfs_rq->avg.last_update_time being current.
4724  */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4725 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4726 {
4727 	/*
4728 	 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4729 	 * See ___update_load_avg() for details.
4730 	 */
4731 	u32 divider = get_pelt_divider(&cfs_rq->avg);
4732 
4733 	/*
4734 	 * When we attach the @se to the @cfs_rq, we must align the decay
4735 	 * window because without that, really weird and wonderful things can
4736 	 * happen.
4737 	 *
4738 	 * XXX illustrate
4739 	 */
4740 	se->avg.last_update_time = cfs_rq->avg.last_update_time;
4741 	se->avg.period_contrib = cfs_rq->avg.period_contrib;
4742 
4743 	/*
4744 	 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4745 	 * period_contrib. This isn't strictly correct, but since we're
4746 	 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4747 	 * _sum a little.
4748 	 */
4749 	se->avg.util_sum = se->avg.util_avg * divider;
4750 
4751 	se->avg.runnable_sum = se->avg.runnable_avg * divider;
4752 
4753 	se->avg.load_sum = se->avg.load_avg * divider;
4754 	if (se_weight(se) < se->avg.load_sum)
4755 		se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4756 	else
4757 		se->avg.load_sum = 1;
4758 
4759 	enqueue_load_avg(cfs_rq, se);
4760 	cfs_rq->avg.util_avg += se->avg.util_avg;
4761 	cfs_rq->avg.util_sum += se->avg.util_sum;
4762 	cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4763 	cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4764 
4765 	add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4766 
4767 	cfs_rq_util_change(cfs_rq, 0);
4768 
4769 	trace_pelt_cfs_tp(cfs_rq);
4770 }
4771 
4772 /**
4773  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4774  * @cfs_rq: cfs_rq to detach from
4775  * @se: sched_entity to detach
4776  *
4777  * Must call update_cfs_rq_load_avg() before this, since we rely on
4778  * cfs_rq->avg.last_update_time being current.
4779  */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4780 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4781 {
4782 	dequeue_load_avg(cfs_rq, se);
4783 	sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4784 	sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4785 	/* See update_cfs_rq_load_avg() */
4786 	cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4787 					  cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4788 
4789 	sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4790 	sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4791 	/* See update_cfs_rq_load_avg() */
4792 	cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4793 					      cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4794 
4795 	add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4796 
4797 	cfs_rq_util_change(cfs_rq, 0);
4798 
4799 	trace_pelt_cfs_tp(cfs_rq);
4800 }
4801 
4802 /*
4803  * Optional action to be done while updating the load average
4804  */
4805 #define UPDATE_TG	0x1
4806 #define SKIP_AGE_LOAD	0x2
4807 #define DO_ATTACH	0x4
4808 #define DO_DETACH	0x8
4809 
4810 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4811 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4812 {
4813 	u64 now = cfs_rq_clock_pelt(cfs_rq);
4814 	int decayed;
4815 
4816 	/*
4817 	 * Track task load average for carrying it to new CPU after migrated, and
4818 	 * track group sched_entity load average for task_h_load calc in migration
4819 	 */
4820 	if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4821 		__update_load_avg_se(now, cfs_rq, se);
4822 
4823 	decayed  = update_cfs_rq_load_avg(now, cfs_rq);
4824 	decayed |= propagate_entity_load_avg(se);
4825 
4826 	if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4827 
4828 		/*
4829 		 * DO_ATTACH means we're here from enqueue_entity().
4830 		 * !last_update_time means we've passed through
4831 		 * migrate_task_rq_fair() indicating we migrated.
4832 		 *
4833 		 * IOW we're enqueueing a task on a new CPU.
4834 		 */
4835 		attach_entity_load_avg(cfs_rq, se);
4836 		update_tg_load_avg(cfs_rq);
4837 
4838 	} else if (flags & DO_DETACH) {
4839 		/*
4840 		 * DO_DETACH means we're here from dequeue_entity()
4841 		 * and we are migrating task out of the CPU.
4842 		 */
4843 		detach_entity_load_avg(cfs_rq, se);
4844 		update_tg_load_avg(cfs_rq);
4845 	} else if (decayed) {
4846 		cfs_rq_util_change(cfs_rq, 0);
4847 
4848 		if (flags & UPDATE_TG)
4849 			update_tg_load_avg(cfs_rq);
4850 	}
4851 }
4852 
4853 /*
4854  * Synchronize entity load avg of dequeued entity without locking
4855  * the previous rq.
4856  */
sync_entity_load_avg(struct sched_entity * se)4857 static void sync_entity_load_avg(struct sched_entity *se)
4858 {
4859 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4860 	u64 last_update_time;
4861 
4862 	last_update_time = cfs_rq_last_update_time(cfs_rq);
4863 	__update_load_avg_blocked_se(last_update_time, se);
4864 }
4865 
4866 /*
4867  * Task first catches up with cfs_rq, and then subtract
4868  * itself from the cfs_rq (task must be off the queue now).
4869  */
remove_entity_load_avg(struct sched_entity * se)4870 static void remove_entity_load_avg(struct sched_entity *se)
4871 {
4872 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
4873 	unsigned long flags;
4874 
4875 	/*
4876 	 * tasks cannot exit without having gone through wake_up_new_task() ->
4877 	 * enqueue_task_fair() which will have added things to the cfs_rq,
4878 	 * so we can remove unconditionally.
4879 	 */
4880 
4881 	sync_entity_load_avg(se);
4882 
4883 	raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4884 	++cfs_rq->removed.nr;
4885 	cfs_rq->removed.util_avg	+= se->avg.util_avg;
4886 	cfs_rq->removed.load_avg	+= se->avg.load_avg;
4887 	cfs_rq->removed.runnable_avg	+= se->avg.runnable_avg;
4888 	raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4889 }
4890 
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4891 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4892 {
4893 	return cfs_rq->avg.runnable_avg;
4894 }
4895 
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4896 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4897 {
4898 	return cfs_rq->avg.load_avg;
4899 }
4900 
4901 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4902 
task_util(struct task_struct * p)4903 static inline unsigned long task_util(struct task_struct *p)
4904 {
4905 #ifdef CONFIG_SCHED_WALT
4906 	if (likely(!walt_disabled && sysctl_sched_use_walt_task_util))
4907 		return p->ravg.demand_scaled;
4908 #endif
4909 	return READ_ONCE(p->se.avg.util_avg);
4910 }
4911 
_task_util_est(struct task_struct * p)4912 static inline unsigned long _task_util_est(struct task_struct *p)
4913 {
4914 	struct util_est ue = READ_ONCE(p->se.avg.util_est);
4915 
4916 	return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4917 }
4918 
task_util_est(struct task_struct * p)4919 static inline unsigned long task_util_est(struct task_struct *p)
4920 {
4921 #ifdef CONFIG_SCHED_WALT
4922 	if (likely(!walt_disabled && sysctl_sched_use_walt_task_util))
4923 		return p->ravg.demand_scaled;
4924 #endif
4925 	return max(task_util(p), _task_util_est(p));
4926 }
4927 
4928 #ifdef CONFIG_UCLAMP_TASK
4929 #ifdef CONFIG_SCHED_RT_CAS
uclamp_task_util(struct task_struct * p,unsigned long uclamp_min,unsigned long uclamp_max)4930 unsigned long uclamp_task_util(struct task_struct *p,
4931 					     unsigned long uclamp_min,
4932 					     unsigned long uclamp_max)
4933 #else
4934 static inline unsigned long uclamp_task_util(struct task_struct *p,
4935 					     unsigned long uclamp_min,
4936 					     unsigned long uclamp_max)
4937 #endif
4938 {
4939 	return clamp(task_util_est(p), uclamp_min, uclamp_max);
4940 }
4941 #else
4942 #ifdef CONFIG_SCHED_RT_CAS
uclamp_task_util(struct task_struct * p,unsigned long uclamp_min,unsigned long uclamp_max)4943 unsigned long uclamp_task_util(struct task_struct *p,
4944 					     unsigned long uclamp_min,
4945 					     unsigned long uclamp_max)
4946 #else
4947 static inline unsigned long uclamp_task_util(struct task_struct *p,
4948 					     unsigned long uclamp_min,
4949 					     unsigned long uclamp_max)
4950 #endif
4951 {
4952 	return task_util_est(p);
4953 }
4954 #endif
4955 
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4956 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4957 				    struct task_struct *p)
4958 {
4959 	unsigned int enqueued;
4960 
4961 	if (!sched_feat(UTIL_EST))
4962 		return;
4963 
4964 	/* Update root cfs_rq's estimated utilization */
4965 	enqueued  = cfs_rq->avg.util_est.enqueued;
4966 	enqueued += _task_util_est(p);
4967 	WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4968 
4969 	trace_sched_util_est_cfs_tp(cfs_rq);
4970 }
4971 
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4972 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4973 				    struct task_struct *p)
4974 {
4975 	unsigned int enqueued;
4976 
4977 	if (!sched_feat(UTIL_EST))
4978 		return;
4979 
4980 	/* Update root cfs_rq's estimated utilization */
4981 	enqueued  = cfs_rq->avg.util_est.enqueued;
4982 	enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4983 	WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4984 
4985 	trace_sched_util_est_cfs_tp(cfs_rq);
4986 }
4987 
4988 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4989 
4990 /*
4991  * Check if a (signed) value is within a specified (unsigned) margin,
4992  * based on the observation that:
4993  *
4994  *     abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4995  *
4996  * NOTE: this only works when value + margin < INT_MAX.
4997  */
within_margin(int value,int margin)4998 static inline bool within_margin(int value, int margin)
4999 {
5000 	return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
5001 }
5002 
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5003 static inline void util_est_update(struct cfs_rq *cfs_rq,
5004 				   struct task_struct *p,
5005 				   bool task_sleep)
5006 {
5007 	long last_ewma_diff, last_enqueued_diff;
5008 	struct util_est ue;
5009 
5010 	if (!sched_feat(UTIL_EST))
5011 		return;
5012 
5013 	/*
5014 	 * Skip update of task's estimated utilization when the task has not
5015 	 * yet completed an activation, e.g. being migrated.
5016 	 */
5017 	if (!task_sleep)
5018 		return;
5019 
5020 	/*
5021 	 * If the PELT values haven't changed since enqueue time,
5022 	 * skip the util_est update.
5023 	 */
5024 	ue = p->se.avg.util_est;
5025 	if (ue.enqueued & UTIL_AVG_UNCHANGED)
5026 		return;
5027 
5028 	last_enqueued_diff = ue.enqueued;
5029 
5030 	/*
5031 	 * Reset EWMA on utilization increases, the moving average is used only
5032 	 * to smooth utilization decreases.
5033 	 */
5034 	ue.enqueued = task_util(p);
5035 	if (sched_feat(UTIL_EST_FASTUP)) {
5036 		if (ue.ewma < ue.enqueued) {
5037 			ue.ewma = ue.enqueued;
5038 			goto done;
5039 		}
5040 	}
5041 
5042 	/*
5043 	 * Skip update of task's estimated utilization when its members are
5044 	 * already ~1% close to its last activation value.
5045 	 */
5046 	last_ewma_diff = ue.enqueued - ue.ewma;
5047 	last_enqueued_diff -= ue.enqueued;
5048 	if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
5049 		if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
5050 			goto done;
5051 
5052 		return;
5053 	}
5054 
5055 	/*
5056 	 * To avoid overestimation of actual task utilization, skip updates if
5057 	 * we cannot grant there is idle time in this CPU.
5058 	 */
5059 	if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
5060 		return;
5061 
5062 	/*
5063 	 * Update Task's estimated utilization
5064 	 *
5065 	 * When *p completes an activation we can consolidate another sample
5066 	 * of the task size. This is done by storing the current PELT value
5067 	 * as ue.enqueued and by using this value to update the Exponential
5068 	 * Weighted Moving Average (EWMA):
5069 	 *
5070 	 *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
5071 	 *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
5072 	 *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
5073 	 *          = w * (      last_ewma_diff            ) +     ewma(t-1)
5074 	 *          = w * (last_ewma_diff  +  ewma(t-1) / w)
5075 	 *
5076 	 * Where 'w' is the weight of new samples, which is configured to be
5077 	 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5078 	 */
5079 	ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
5080 	ue.ewma  += last_ewma_diff;
5081 	ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
5082 done:
5083 	ue.enqueued |= UTIL_AVG_UNCHANGED;
5084 	WRITE_ONCE(p->se.avg.util_est, ue);
5085 
5086 	trace_sched_util_est_se_tp(&p->se);
5087 }
5088 
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)5089 static inline int util_fits_cpu(unsigned long util,
5090 				unsigned long uclamp_min,
5091 				unsigned long uclamp_max,
5092 				int cpu)
5093 {
5094 	unsigned long capacity_orig, capacity_orig_thermal;
5095 	unsigned long capacity = capacity_of(cpu);
5096 	bool fits, uclamp_max_fits;
5097 
5098 	/*
5099 	 * Check if the real util fits without any uclamp boost/cap applied.
5100 	 */
5101 	fits = fits_capacity(util, capacity);
5102 
5103 	if (!uclamp_is_used())
5104 		return fits;
5105 
5106 	/*
5107 	 * We must use capacity_orig_of() for comparing against uclamp_min and
5108 	 * uclamp_max. We only care about capacity pressure (by using
5109 	 * capacity_of()) for comparing against the real util.
5110 	 *
5111 	 * If a task is boosted to 1024 for example, we don't want a tiny
5112 	 * pressure to skew the check whether it fits a CPU or not.
5113 	 *
5114 	 * Similarly if a task is capped to capacity_orig_of(little_cpu), it
5115 	 * should fit a little cpu even if there's some pressure.
5116 	 *
5117 	 * Only exception is for thermal pressure since it has a direct impact
5118 	 * on available OPP of the system.
5119 	 *
5120 	 * We honour it for uclamp_min only as a drop in performance level
5121 	 * could result in not getting the requested minimum performance level.
5122 	 *
5123 	 * For uclamp_max, we can tolerate a drop in performance level as the
5124 	 * goal is to cap the task. So it's okay if it's getting less.
5125 	 */
5126 	capacity_orig = capacity_orig_of(cpu);
5127 	capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
5128 
5129 	/*
5130 	 * We want to force a task to fit a cpu as implied by uclamp_max.
5131 	 * But we do have some corner cases to cater for..
5132 	 *
5133 	 *
5134 	 *                                 C=z
5135 	 *   |                             ___
5136 	 *   |                  C=y       |   |
5137 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _  uclamp_max
5138 	 *   |      C=x        |   |      |   |
5139 	 *   |      ___        |   |      |   |
5140 	 *   |     |   |       |   |      |   |    (util somewhere in this region)
5141 	 *   |     |   |       |   |      |   |
5142 	 *   |     |   |       |   |      |   |
5143 	 *   +----------------------------------------
5144 	 *         cpu0        cpu1       cpu2
5145 	 *
5146 	 *   In the above example if a task is capped to a specific performance
5147 	 *   point, y, then when:
5148 	 *
5149 	 *   * util = 80% of x then it does not fit on cpu0 and should migrate
5150 	 *     to cpu1
5151 	 *   * util = 80% of y then it is forced to fit on cpu1 to honour
5152 	 *     uclamp_max request.
5153 	 *
5154 	 *   which is what we're enforcing here. A task always fits if
5155 	 *   uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
5156 	 *   the normal upmigration rules should withhold still.
5157 	 *
5158 	 *   Only exception is when we are on max capacity, then we need to be
5159 	 *   careful not to block overutilized state. This is so because:
5160 	 *
5161 	 *     1. There's no concept of capping at max_capacity! We can't go
5162 	 *        beyond this performance level anyway.
5163 	 *     2. The system is being saturated when we're operating near
5164 	 *        max capacity, it doesn't make sense to block overutilized.
5165 	 */
5166 	uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5167 	uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5168 	fits = fits || uclamp_max_fits;
5169 
5170 	/*
5171 	 *
5172 	 *                                 C=z
5173 	 *   |                             ___       (region a, capped, util >= uclamp_max)
5174 	 *   |                  C=y       |   |
5175 	 *   |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5176 	 *   |      C=x        |   |      |   |
5177 	 *   |      ___        |   |      |   |      (region b, uclamp_min <= util <= uclamp_max)
5178 	 *   |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5179 	 *   |     |   |       |   |      |   |
5180 	 *   |     |   |       |   |      |   |      (region c, boosted, util < uclamp_min)
5181 	 *   +----------------------------------------
5182 	 *         cpu0        cpu1       cpu2
5183 	 *
5184 	 * a) If util > uclamp_max, then we're capped, we don't care about
5185 	 *    actual fitness value here. We only care if uclamp_max fits
5186 	 *    capacity without taking margin/pressure into account.
5187 	 *    See comment above.
5188 	 *
5189 	 * b) If uclamp_min <= util <= uclamp_max, then the normal
5190 	 *    fits_capacity() rules apply. Except we need to ensure that we
5191 	 *    enforce we remain within uclamp_max, see comment above.
5192 	 *
5193 	 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5194 	 *    need to take into account the boosted value fits the CPU without
5195 	 *    taking margin/pressure into account.
5196 	 *
5197 	 * Cases (a) and (b) are handled in the 'fits' variable already. We
5198 	 * just need to consider an extra check for case (c) after ensuring we
5199 	 * handle the case uclamp_min > uclamp_max.
5200 	 */
5201 	uclamp_min = min(uclamp_min, uclamp_max);
5202 	if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
5203 		return -1;
5204 
5205 	return fits;
5206 }
5207 
task_fits_cpu(struct task_struct * p,int cpu)5208 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5209 {
5210 	unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5211 	unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5212 	unsigned long util = task_util_est(p);
5213 	/*
5214 	 * Return true only if the cpu fully fits the task requirements, which
5215 	 * include the utilization but also the performance hints.
5216 	 */
5217 	return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5218 }
5219 
5220 #ifdef CONFIG_SCHED_RTG
task_fits_max(struct task_struct * p,int cpu)5221 bool task_fits_max(struct task_struct *p, int cpu)
5222 {
5223 	unsigned long capacity = capacity_orig_of(cpu);
5224 	unsigned long max_capacity = cpu_rq(cpu)->rd->max_cpu_capacity;
5225 
5226 	if (capacity == max_capacity)
5227 		return true;
5228 
5229 	return task_fits_cpu(p, cpu);
5230 }
5231 #endif
5232 
update_misfit_status(struct task_struct * p,struct rq * rq)5233 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5234 {
5235 	bool task_fits = false;
5236 #ifdef CONFIG_SCHED_RTG
5237 	int cpu = cpu_of(rq);
5238 	struct cpumask *rtg_target = NULL;
5239 #endif
5240 	if (!sched_asym_cpucap_active())
5241 		return;
5242 
5243 	if (!p || p->nr_cpus_allowed == 1) {
5244 		rq->misfit_task_load = 0;
5245 		return;
5246 	}
5247 
5248 #ifdef CONFIG_SCHED_RTG
5249 	rtg_target = find_rtg_target(p);
5250 	if (rtg_target)
5251 		task_fits = capacity_orig_of(cpu) >=
5252 				capacity_orig_of(cpumask_first(rtg_target));
5253 	else
5254 		task_fits = task_fits_cpu(p, cpu_of(rq));
5255 #else
5256 	task_fits = task_fits_cpu(p, cpu_of(rq));
5257 #endif
5258 	if (task_fits) {
5259 		rq->misfit_task_load = 0;
5260 		return;
5261 	}
5262 
5263 	/*
5264 	 * Make sure that misfit_task_load will not be null even if
5265 	 * task_h_load() returns 0.
5266 	 */
5267 	rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5268 }
5269 
5270 #else /* CONFIG_SMP */
5271 
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)5272 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5273 {
5274 	return !cfs_rq->nr_running;
5275 }
5276 
5277 #define UPDATE_TG	0x0
5278 #define SKIP_AGE_LOAD	0x0
5279 #define DO_ATTACH	0x0
5280 #define DO_DETACH	0x0
5281 
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)5282 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
5283 {
5284 	cfs_rq_util_change(cfs_rq, 0);
5285 }
5286 
remove_entity_load_avg(struct sched_entity * se)5287 static inline void remove_entity_load_avg(struct sched_entity *se) {}
5288 
5289 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5290 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5291 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5292 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5293 
newidle_balance(struct rq * rq,struct rq_flags * rf)5294 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
5295 {
5296 	return 0;
5297 }
5298 
5299 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5300 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5301 
5302 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5303 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5304 
5305 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5306 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
5307 		bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)5308 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
5309 
5310 #endif /* CONFIG_SMP */
5311 
5312 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5313 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5314 {
5315 	u64 vslice, vruntime = avg_vruntime(cfs_rq);
5316 	s64 lag = 0;
5317 
5318 	se->slice = sysctl_sched_base_slice;
5319 	vslice = calc_delta_fair(se->slice, se);
5320 
5321 	/*
5322 	 * Due to how V is constructed as the weighted average of entities,
5323 	 * adding tasks with positive lag, or removing tasks with negative lag
5324 	 * will move 'time' backwards, this can screw around with the lag of
5325 	 * other tasks.
5326 	 *
5327 	 * EEVDF: placement strategy #1 / #2
5328 	 */
5329 	if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
5330 		struct sched_entity *curr = cfs_rq->curr;
5331 		unsigned long load;
5332 
5333 		lag = se->vlag;
5334 
5335 		/*
5336 		 * If we want to place a task and preserve lag, we have to
5337 		 * consider the effect of the new entity on the weighted
5338 		 * average and compensate for this, otherwise lag can quickly
5339 		 * evaporate.
5340 		 *
5341 		 * Lag is defined as:
5342 		 *
5343 		 *   lag_i = S - s_i = w_i * (V - v_i)
5344 		 *
5345 		 * To avoid the 'w_i' term all over the place, we only track
5346 		 * the virtual lag:
5347 		 *
5348 		 *   vl_i = V - v_i <=> v_i = V - vl_i
5349 		 *
5350 		 * And we take V to be the weighted average of all v:
5351 		 *
5352 		 *   V = (\Sum w_j*v_j) / W
5353 		 *
5354 		 * Where W is: \Sum w_j
5355 		 *
5356 		 * Then, the weighted average after adding an entity with lag
5357 		 * vl_i is given by:
5358 		 *
5359 		 *   V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5360 		 *      = (W*V + w_i*(V - vl_i)) / (W + w_i)
5361 		 *      = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5362 		 *      = (V*(W + w_i) - w_i*l) / (W + w_i)
5363 		 *      = V - w_i*vl_i / (W + w_i)
5364 		 *
5365 		 * And the actual lag after adding an entity with vl_i is:
5366 		 *
5367 		 *   vl'_i = V' - v_i
5368 		 *         = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5369 		 *         = vl_i - w_i*vl_i / (W + w_i)
5370 		 *
5371 		 * Which is strictly less than vl_i. So in order to preserve lag
5372 		 * we should inflate the lag before placement such that the
5373 		 * effective lag after placement comes out right.
5374 		 *
5375 		 * As such, invert the above relation for vl'_i to get the vl_i
5376 		 * we need to use such that the lag after placement is the lag
5377 		 * we computed before dequeue.
5378 		 *
5379 		 *   vl'_i = vl_i - w_i*vl_i / (W + w_i)
5380 		 *         = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5381 		 *
5382 		 *   (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5383 		 *                   = W*vl_i
5384 		 *
5385 		 *   vl_i = (W + w_i)*vl'_i / W
5386 		 */
5387 		load = cfs_rq->avg_load;
5388 		if (curr && curr->on_rq)
5389 			load += scale_load_down(curr->load.weight);
5390 
5391 		lag *= load + scale_load_down(se->load.weight);
5392 		if (WARN_ON_ONCE(!load))
5393 			load = 1;
5394 		lag = div_s64(lag, load);
5395 	}
5396 
5397 	se->vruntime = vruntime - lag;
5398 
5399 	/*
5400 	 * When joining the competition; the exisiting tasks will be,
5401 	 * on average, halfway through their slice, as such start tasks
5402 	 * off with half a slice to ease into the competition.
5403 	 */
5404 	if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5405 		vslice /= 2;
5406 
5407 	/*
5408 	 * EEVDF: vd_i = ve_i + r_i/w_i
5409 	 */
5410 	se->deadline = se->vruntime + vslice;
5411 }
5412 
5413 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5414 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5415 
5416 static inline bool cfs_bandwidth_used(void);
5417 
5418 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5419 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5420 {
5421 	bool curr = cfs_rq->curr == se;
5422 
5423 	/*
5424 	 * If we're the current task, we must renormalise before calling
5425 	 * update_curr().
5426 	 */
5427 	if (curr)
5428 		place_entity(cfs_rq, se, flags);
5429 
5430 	update_curr(cfs_rq);
5431 
5432 	/*
5433 	 * When enqueuing a sched_entity, we must:
5434 	 *   - Update loads to have both entity and cfs_rq synced with now.
5435 	 *   - For group_entity, update its runnable_weight to reflect the new
5436 	 *     h_nr_running of its group cfs_rq.
5437 	 *   - For group_entity, update its weight to reflect the new share of
5438 	 *     its group cfs_rq
5439 	 *   - Add its new weight to cfs_rq->load.weight
5440 	 */
5441 	update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5442 	se_update_runnable(se);
5443 	/*
5444 	 * XXX update_load_avg() above will have attached us to the pelt sum;
5445 	 * but update_cfs_group() here will re-adjust the weight and have to
5446 	 * undo/redo all that. Seems wasteful.
5447 	 */
5448 	update_cfs_group(se);
5449 
5450 	/*
5451 	 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5452 	 * we can place the entity.
5453 	 */
5454 	if (!curr)
5455 		place_entity(cfs_rq, se, flags);
5456 
5457 	account_entity_enqueue(cfs_rq, se);
5458 
5459 	/* Entity has migrated, no longer consider this task hot */
5460 	if (flags & ENQUEUE_MIGRATED)
5461 		se->exec_start = 0;
5462 
5463 	check_schedstat_required();
5464 	update_stats_enqueue_fair(cfs_rq, se, flags);
5465 	if (!curr)
5466 		__enqueue_entity(cfs_rq, se);
5467 	se->on_rq = 1;
5468 
5469 	if (cfs_rq->nr_running == 1) {
5470 		check_enqueue_throttle(cfs_rq);
5471 		if (!throttled_hierarchy(cfs_rq)) {
5472 			list_add_leaf_cfs_rq(cfs_rq);
5473 		} else {
5474 #ifdef CONFIG_CFS_BANDWIDTH
5475 			struct rq *rq = rq_of(cfs_rq);
5476 
5477 			if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5478 				cfs_rq->throttled_clock = rq_clock(rq);
5479 			if (!cfs_rq->throttled_clock_self)
5480 				cfs_rq->throttled_clock_self = rq_clock(rq);
5481 #endif
5482 		}
5483 	}
5484 }
5485 
__clear_buddies_next(struct sched_entity * se)5486 static void __clear_buddies_next(struct sched_entity *se)
5487 {
5488 	for_each_sched_entity(se) {
5489 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
5490 		if (cfs_rq->next != se)
5491 			break;
5492 
5493 		cfs_rq->next = NULL;
5494 	}
5495 }
5496 
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5497 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5498 {
5499 	if (cfs_rq->next == se)
5500 		__clear_buddies_next(se);
5501 }
5502 
5503 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5504 
5505 static void
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5506 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5507 {
5508 	int action = UPDATE_TG;
5509 
5510 	if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5511 		action |= DO_DETACH;
5512 
5513 	/*
5514 	 * Update run-time statistics of the 'current'.
5515 	 */
5516 	update_curr(cfs_rq);
5517 
5518 	/*
5519 	 * When dequeuing a sched_entity, we must:
5520 	 *   - Update loads to have both entity and cfs_rq synced with now.
5521 	 *   - For group_entity, update its runnable_weight to reflect the new
5522 	 *     h_nr_running of its group cfs_rq.
5523 	 *   - Subtract its previous weight from cfs_rq->load.weight.
5524 	 *   - For group entity, update its weight to reflect the new share
5525 	 *     of its group cfs_rq.
5526 	 */
5527 	update_load_avg(cfs_rq, se, action);
5528 	se_update_runnable(se);
5529 
5530 	update_stats_dequeue_fair(cfs_rq, se, flags);
5531 
5532 	clear_buddies(cfs_rq, se);
5533 
5534 	update_entity_lag(cfs_rq, se);
5535 	if (se != cfs_rq->curr)
5536 		__dequeue_entity(cfs_rq, se);
5537 	se->on_rq = 0;
5538 	account_entity_dequeue(cfs_rq, se);
5539 
5540 	/* return excess runtime on last dequeue */
5541 	return_cfs_rq_runtime(cfs_rq);
5542 
5543 	update_cfs_group(se);
5544 
5545 	/*
5546 	 * Now advance min_vruntime if @se was the entity holding it back,
5547 	 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5548 	 * put back on, and if we advance min_vruntime, we'll be placed back
5549 	 * further than we started -- ie. we'll be penalized.
5550 	 */
5551 	if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5552 		update_min_vruntime(cfs_rq);
5553 
5554 	if (cfs_rq->nr_running == 0)
5555 		update_idle_cfs_rq_clock_pelt(cfs_rq);
5556 }
5557 
5558 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5559 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5560 {
5561 	clear_buddies(cfs_rq, se);
5562 
5563 	/* 'current' is not kept within the tree. */
5564 	if (se->on_rq) {
5565 		/*
5566 		 * Any task has to be enqueued before it get to execute on
5567 		 * a CPU. So account for the time it spent waiting on the
5568 		 * runqueue.
5569 		 */
5570 		update_stats_wait_end_fair(cfs_rq, se);
5571 		__dequeue_entity(cfs_rq, se);
5572 		update_load_avg(cfs_rq, se, UPDATE_TG);
5573 		/*
5574 		 * HACK, stash a copy of deadline at the point of pick in vlag,
5575 		 * which isn't used until dequeue.
5576 		 */
5577 		se->vlag = se->deadline;
5578 	}
5579 
5580 	update_stats_curr_start(cfs_rq, se);
5581 	cfs_rq->curr = se;
5582 
5583 	/*
5584 	 * Track our maximum slice length, if the CPU's load is at
5585 	 * least twice that of our own weight (i.e. dont track it
5586 	 * when there are only lesser-weight tasks around):
5587 	 */
5588 	if (schedstat_enabled() &&
5589 	    rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5590 		struct sched_statistics *stats;
5591 
5592 		stats = __schedstats_from_se(se);
5593 		__schedstat_set(stats->slice_max,
5594 				max((u64)stats->slice_max,
5595 				    se->sum_exec_runtime - se->prev_sum_exec_runtime));
5596 	}
5597 
5598 	se->prev_sum_exec_runtime = se->sum_exec_runtime;
5599 }
5600 
5601 static int
5602 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
5603 
5604 /*
5605  * Pick the next process, keeping these things in mind, in this order:
5606  * 1) keep things fair between processes/task groups
5607  * 2) pick the "next" process, since someone really wants that to run
5608  * 3) pick the "last" process, for cache locality
5609  * 4) do not run the "skip" process, if something else is available
5610  */
5611 static struct sched_entity *
pick_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * curr)5612 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5613 {
5614 	/*
5615 	 * Enabling NEXT_BUDDY will affect latency but not fairness.
5616 	 */
5617 	if (sched_feat(NEXT_BUDDY) &&
5618 	    cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5619 		return cfs_rq->next;
5620 
5621 	return pick_eevdf(cfs_rq);
5622 }
5623 
5624 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5625 
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5626 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5627 {
5628 	/*
5629 	 * If still on the runqueue then deactivate_task()
5630 	 * was not called and update_curr() has to be done:
5631 	 */
5632 	if (prev->on_rq)
5633 		update_curr(cfs_rq);
5634 
5635 	/* throttle cfs_rqs exceeding runtime */
5636 	check_cfs_rq_runtime(cfs_rq);
5637 
5638 	if (prev->on_rq) {
5639 		update_stats_wait_start_fair(cfs_rq, prev);
5640 		/* Put 'current' back into the tree. */
5641 		__enqueue_entity(cfs_rq, prev);
5642 		/* in !on_rq case, update occurred at dequeue */
5643 		update_load_avg(cfs_rq, prev, 0);
5644 	}
5645 	cfs_rq->curr = NULL;
5646 }
5647 
5648 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5649 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5650 {
5651 	/*
5652 	 * Update run-time statistics of the 'current'.
5653 	 */
5654 	update_curr(cfs_rq);
5655 
5656 	/*
5657 	 * Ensure that runnable average is periodically updated.
5658 	 */
5659 	update_load_avg(cfs_rq, curr, UPDATE_TG);
5660 	update_cfs_group(curr);
5661 
5662 #ifdef CONFIG_SCHED_HRTICK
5663 	/*
5664 	 * queued ticks are scheduled to match the slice, so don't bother
5665 	 * validating it and just reschedule.
5666 	 */
5667 	if (queued) {
5668 		resched_curr(rq_of(cfs_rq));
5669 		return;
5670 	}
5671 	/*
5672 	 * don't let the period tick interfere with the hrtick preemption
5673 	 */
5674 	if (!sched_feat(DOUBLE_TICK) &&
5675 			hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5676 		return;
5677 #endif
5678 }
5679 
5680 
5681 /**************************************************
5682  * CFS bandwidth control machinery
5683  */
5684 
5685 #ifdef CONFIG_CFS_BANDWIDTH
5686 
5687 #ifdef CONFIG_JUMP_LABEL
5688 static struct static_key __cfs_bandwidth_used;
5689 
cfs_bandwidth_used(void)5690 static inline bool cfs_bandwidth_used(void)
5691 {
5692 	return static_key_false(&__cfs_bandwidth_used);
5693 }
5694 
cfs_bandwidth_usage_inc(void)5695 void cfs_bandwidth_usage_inc(void)
5696 {
5697 	static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5698 }
5699 
cfs_bandwidth_usage_dec(void)5700 void cfs_bandwidth_usage_dec(void)
5701 {
5702 	static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5703 }
5704 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)5705 static bool cfs_bandwidth_used(void)
5706 {
5707 	return true;
5708 }
5709 
cfs_bandwidth_usage_inc(void)5710 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5711 void cfs_bandwidth_usage_dec(void) {}
5712 #endif /* CONFIG_JUMP_LABEL */
5713 
5714 /*
5715  * default period for cfs group bandwidth.
5716  * default: 0.1s, units: nanoseconds
5717  */
default_cfs_period(void)5718 static inline u64 default_cfs_period(void)
5719 {
5720 	return 100000000ULL;
5721 }
5722 
sched_cfs_bandwidth_slice(void)5723 static inline u64 sched_cfs_bandwidth_slice(void)
5724 {
5725 	return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5726 }
5727 
5728 /*
5729  * Replenish runtime according to assigned quota. We use sched_clock_cpu
5730  * directly instead of rq->clock to avoid adding additional synchronization
5731  * around rq->lock.
5732  *
5733  * requires cfs_b->lock
5734  */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5735 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5736 {
5737 	s64 runtime;
5738 
5739 	if (unlikely(cfs_b->quota == RUNTIME_INF))
5740 		return;
5741 
5742 	cfs_b->runtime += cfs_b->quota;
5743 	runtime = cfs_b->runtime_snap - cfs_b->runtime;
5744 	if (runtime > 0) {
5745 		cfs_b->burst_time += runtime;
5746 		cfs_b->nr_burst++;
5747 	}
5748 
5749 	cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5750 	cfs_b->runtime_snap = cfs_b->runtime;
5751 }
5752 
tg_cfs_bandwidth(struct task_group * tg)5753 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5754 {
5755 	return &tg->cfs_bandwidth;
5756 }
5757 
5758 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5759 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5760 				   struct cfs_rq *cfs_rq, u64 target_runtime)
5761 {
5762 	u64 min_amount, amount = 0;
5763 
5764 	lockdep_assert_held(&cfs_b->lock);
5765 
5766 	/* note: this is a positive sum as runtime_remaining <= 0 */
5767 	min_amount = target_runtime - cfs_rq->runtime_remaining;
5768 
5769 	if (cfs_b->quota == RUNTIME_INF)
5770 		amount = min_amount;
5771 	else {
5772 		start_cfs_bandwidth(cfs_b);
5773 
5774 		if (cfs_b->runtime > 0) {
5775 			amount = min(cfs_b->runtime, min_amount);
5776 			cfs_b->runtime -= amount;
5777 			cfs_b->idle = 0;
5778 		}
5779 	}
5780 
5781 	cfs_rq->runtime_remaining += amount;
5782 
5783 	return cfs_rq->runtime_remaining > 0;
5784 }
5785 
5786 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5787 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5788 {
5789 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5790 	int ret;
5791 
5792 	raw_spin_lock(&cfs_b->lock);
5793 	ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5794 	raw_spin_unlock(&cfs_b->lock);
5795 
5796 	return ret;
5797 }
5798 
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5799 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5800 {
5801 	/* dock delta_exec before expiring quota (as it could span periods) */
5802 	cfs_rq->runtime_remaining -= delta_exec;
5803 
5804 	if (likely(cfs_rq->runtime_remaining > 0))
5805 		return;
5806 
5807 	if (cfs_rq->throttled)
5808 		return;
5809 	/*
5810 	 * if we're unable to extend our runtime we resched so that the active
5811 	 * hierarchy can be throttled
5812 	 */
5813 	if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5814 		resched_curr(rq_of(cfs_rq));
5815 }
5816 
5817 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5818 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5819 {
5820 	if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5821 		return;
5822 
5823 	__account_cfs_rq_runtime(cfs_rq, delta_exec);
5824 }
5825 
cfs_rq_throttled(struct cfs_rq * cfs_rq)5826 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5827 {
5828 	return cfs_bandwidth_used() && cfs_rq->throttled;
5829 }
5830 
5831 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5832 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5833 {
5834 	return cfs_bandwidth_used() && cfs_rq->throttle_count;
5835 }
5836 
5837 /*
5838  * Ensure that neither of the group entities corresponding to src_cpu or
5839  * dest_cpu are members of a throttled hierarchy when performing group
5840  * load-balance operations.
5841  */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)5842 static inline int throttled_lb_pair(struct task_group *tg,
5843 				    int src_cpu, int dest_cpu)
5844 {
5845 	struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5846 
5847 	src_cfs_rq = tg->cfs_rq[src_cpu];
5848 	dest_cfs_rq = tg->cfs_rq[dest_cpu];
5849 
5850 	return throttled_hierarchy(src_cfs_rq) ||
5851 	       throttled_hierarchy(dest_cfs_rq);
5852 }
5853 
tg_unthrottle_up(struct task_group * tg,void * data)5854 static int tg_unthrottle_up(struct task_group *tg, void *data)
5855 {
5856 	struct rq *rq = data;
5857 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5858 
5859 	cfs_rq->throttle_count--;
5860 	if (!cfs_rq->throttle_count) {
5861 		cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5862 					     cfs_rq->throttled_clock_pelt;
5863 
5864 		/* Add cfs_rq with load or one or more already running entities to the list */
5865 		if (!cfs_rq_is_decayed(cfs_rq))
5866 			list_add_leaf_cfs_rq(cfs_rq);
5867 
5868 		if (cfs_rq->throttled_clock_self) {
5869 			u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5870 
5871 			cfs_rq->throttled_clock_self = 0;
5872 
5873 			if (SCHED_WARN_ON((s64)delta < 0))
5874 				delta = 0;
5875 
5876 			cfs_rq->throttled_clock_self_time += delta;
5877 		}
5878 	}
5879 
5880 	return 0;
5881 }
5882 
tg_throttle_down(struct task_group * tg,void * data)5883 static int tg_throttle_down(struct task_group *tg, void *data)
5884 {
5885 	struct rq *rq = data;
5886 	struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5887 
5888 	/* group is entering throttled state, stop time */
5889 	if (!cfs_rq->throttle_count) {
5890 		cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5891 		list_del_leaf_cfs_rq(cfs_rq);
5892 
5893 		SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5894 		if (cfs_rq->nr_running)
5895 			cfs_rq->throttled_clock_self = rq_clock(rq);
5896 	}
5897 	cfs_rq->throttle_count++;
5898 
5899 	return 0;
5900 }
5901 
throttle_cfs_rq(struct cfs_rq * cfs_rq)5902 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5903 {
5904 	struct rq *rq = rq_of(cfs_rq);
5905 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5906 	struct sched_entity *se;
5907 	long task_delta, idle_task_delta, dequeue = 1;
5908 
5909 	raw_spin_lock(&cfs_b->lock);
5910 	/* This will start the period timer if necessary */
5911 	if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5912 		/*
5913 		 * We have raced with bandwidth becoming available, and if we
5914 		 * actually throttled the timer might not unthrottle us for an
5915 		 * entire period. We additionally needed to make sure that any
5916 		 * subsequent check_cfs_rq_runtime calls agree not to throttle
5917 		 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5918 		 * for 1ns of runtime rather than just check cfs_b.
5919 		 */
5920 		dequeue = 0;
5921 	} else {
5922 		list_add_tail_rcu(&cfs_rq->throttled_list,
5923 				  &cfs_b->throttled_cfs_rq);
5924 	}
5925 	raw_spin_unlock(&cfs_b->lock);
5926 
5927 	if (!dequeue)
5928 		return false;  /* Throttle no longer required. */
5929 
5930 	se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5931 
5932 	/* freeze hierarchy runnable averages while throttled */
5933 	rcu_read_lock();
5934 	walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5935 	rcu_read_unlock();
5936 
5937 	task_delta = cfs_rq->h_nr_running;
5938 	idle_task_delta = cfs_rq->idle_h_nr_running;
5939 	for_each_sched_entity(se) {
5940 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5941 		/* throttled entity or throttle-on-deactivate */
5942 		if (!se->on_rq)
5943 			goto done;
5944 
5945 		dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5946 
5947 		if (cfs_rq_is_idle(group_cfs_rq(se)))
5948 			idle_task_delta = cfs_rq->h_nr_running;
5949 
5950 		qcfs_rq->h_nr_running -= task_delta;
5951 		qcfs_rq->idle_h_nr_running -= idle_task_delta;
5952 
5953 		if (qcfs_rq->load.weight) {
5954 			/* Avoid re-evaluating load for this entity: */
5955 			se = parent_entity(se);
5956 			break;
5957 		}
5958 	}
5959 
5960 	for_each_sched_entity(se) {
5961 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5962 		/* throttled entity or throttle-on-deactivate */
5963 		if (!se->on_rq)
5964 			goto done;
5965 
5966 		update_load_avg(qcfs_rq, se, 0);
5967 		se_update_runnable(se);
5968 
5969 		if (cfs_rq_is_idle(group_cfs_rq(se)))
5970 			idle_task_delta = cfs_rq->h_nr_running;
5971 
5972 		qcfs_rq->h_nr_running -= task_delta;
5973 		qcfs_rq->idle_h_nr_running -= idle_task_delta;
5974 		walt_dec_throttled_cfs_rq_stats(&qcfs_rq->walt_stats, cfs_rq);
5975 	}
5976 
5977 	/* At this point se is NULL and we are at root level*/
5978 	sub_nr_running(rq, task_delta);
5979 		walt_dec_throttled_cfs_rq_stats(&rq->walt_stats, cfs_rq);
5980 
5981 done:
5982 	/*
5983 	 * Note: distribution will already see us throttled via the
5984 	 * throttled-list.  rq->lock protects completion.
5985 	 */
5986 	cfs_rq->throttled = 1;
5987 	SCHED_WARN_ON(cfs_rq->throttled_clock);
5988 	if (cfs_rq->nr_running)
5989 		cfs_rq->throttled_clock = rq_clock(rq);
5990 	return true;
5991 }
5992 
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5993 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5994 {
5995 	struct rq *rq = rq_of(cfs_rq);
5996 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5997 	struct sched_entity *se;
5998 	long task_delta, idle_task_delta;
5999 	struct cfs_rq *tcfs_rq __maybe_unused = cfs_rq;
6000 
6001 	se = cfs_rq->tg->se[cpu_of(rq)];
6002 
6003 	cfs_rq->throttled = 0;
6004 
6005 	update_rq_clock(rq);
6006 
6007 	raw_spin_lock(&cfs_b->lock);
6008 	if (cfs_rq->throttled_clock) {
6009 		cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6010 		cfs_rq->throttled_clock = 0;
6011 	}
6012 	list_del_rcu(&cfs_rq->throttled_list);
6013 	raw_spin_unlock(&cfs_b->lock);
6014 
6015 	/* update hierarchical throttle state */
6016 	walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6017 
6018 	if (!cfs_rq->load.weight) {
6019 		if (!cfs_rq->on_list)
6020 			return;
6021 		/*
6022 		 * Nothing to run but something to decay (on_list)?
6023 		 * Complete the branch.
6024 		 */
6025 		for_each_sched_entity(se) {
6026 			if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6027 				break;
6028 		}
6029 		goto unthrottle_throttle;
6030 	}
6031 
6032 	task_delta = cfs_rq->h_nr_running;
6033 	idle_task_delta = cfs_rq->idle_h_nr_running;
6034 	for_each_sched_entity(se) {
6035 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6036 
6037 		if (se->on_rq)
6038 			break;
6039 		enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
6040 
6041 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6042 			idle_task_delta = cfs_rq->h_nr_running;
6043 
6044 		qcfs_rq->h_nr_running += task_delta;
6045 		qcfs_rq->idle_h_nr_running += idle_task_delta;
6046 		walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
6047 
6048 		/* end evaluation on encountering a throttled cfs_rq */
6049 		if (cfs_rq_throttled(qcfs_rq))
6050 			goto unthrottle_throttle;
6051 	}
6052 
6053 	for_each_sched_entity(se) {
6054 		struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6055 
6056 		update_load_avg(qcfs_rq, se, UPDATE_TG);
6057 		se_update_runnable(se);
6058 
6059 		if (cfs_rq_is_idle(group_cfs_rq(se)))
6060 			idle_task_delta = cfs_rq->h_nr_running;
6061 
6062 		qcfs_rq->h_nr_running += task_delta;
6063 		qcfs_rq->idle_h_nr_running += idle_task_delta;
6064 		walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
6065 
6066 		/* end evaluation on encountering a throttled cfs_rq */
6067 		if (cfs_rq_throttled(qcfs_rq))
6068 			goto unthrottle_throttle;
6069 	}
6070 
6071 	/* At this point se is NULL and we are at root level*/
6072 	add_nr_running(rq, task_delta);
6073 	walt_inc_throttled_cfs_rq_stats(&rq->walt_stats, tcfs_rq);
6074 
6075 unthrottle_throttle:
6076 	assert_list_leaf_cfs_rq(rq);
6077 
6078 	/* Determine whether we need to wake up potentially idle CPU: */
6079 	if (rq->curr == rq->idle && rq->cfs.nr_running)
6080 		resched_curr(rq);
6081 }
6082 
6083 #ifdef CONFIG_SMP
__cfsb_csd_unthrottle(void * arg)6084 static void __cfsb_csd_unthrottle(void *arg)
6085 {
6086 	struct cfs_rq *cursor, *tmp;
6087 	struct rq *rq = arg;
6088 	struct rq_flags rf;
6089 
6090 	rq_lock(rq, &rf);
6091 
6092 	/*
6093 	 * Iterating over the list can trigger several call to
6094 	 * update_rq_clock() in unthrottle_cfs_rq().
6095 	 * Do it once and skip the potential next ones.
6096 	 */
6097 	update_rq_clock(rq);
6098 	rq_clock_start_loop_update(rq);
6099 
6100 	/*
6101 	 * Since we hold rq lock we're safe from concurrent manipulation of
6102 	 * the CSD list. However, this RCU critical section annotates the
6103 	 * fact that we pair with sched_free_group_rcu(), so that we cannot
6104 	 * race with group being freed in the window between removing it
6105 	 * from the list and advancing to the next entry in the list.
6106 	 */
6107 	rcu_read_lock();
6108 
6109 	list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6110 				 throttled_csd_list) {
6111 		list_del_init(&cursor->throttled_csd_list);
6112 
6113 		if (cfs_rq_throttled(cursor))
6114 			unthrottle_cfs_rq(cursor);
6115 	}
6116 
6117 	rcu_read_unlock();
6118 
6119 	rq_clock_stop_loop_update(rq);
6120 	rq_unlock(rq, &rf);
6121 }
6122 
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6123 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6124 {
6125 	struct rq *rq = rq_of(cfs_rq);
6126 	bool first;
6127 
6128 	if (rq == this_rq()) {
6129 		unthrottle_cfs_rq(cfs_rq);
6130 		return;
6131 	}
6132 
6133 	/* Already enqueued */
6134 	if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
6135 		return;
6136 
6137 	first = list_empty(&rq->cfsb_csd_list);
6138 	list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6139 	if (first)
6140 		smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6141 }
6142 #else
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6143 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6144 {
6145 	unthrottle_cfs_rq(cfs_rq);
6146 }
6147 #endif
6148 
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6149 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6150 {
6151 	lockdep_assert_rq_held(rq_of(cfs_rq));
6152 
6153 	if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
6154 	    cfs_rq->runtime_remaining <= 0))
6155 		return;
6156 
6157 	__unthrottle_cfs_rq_async(cfs_rq);
6158 }
6159 
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6160 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6161 {
6162 	struct cfs_rq *local_unthrottle = NULL;
6163 	int this_cpu = smp_processor_id();
6164 	u64 runtime, remaining = 1;
6165 	bool throttled = false;
6166 	struct cfs_rq *cfs_rq;
6167 	struct rq_flags rf;
6168 	struct rq *rq;
6169 
6170 	rcu_read_lock();
6171 	list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6172 				throttled_list) {
6173 		rq = rq_of(cfs_rq);
6174 
6175 		if (!remaining) {
6176 			throttled = true;
6177 			break;
6178 		}
6179 
6180 		rq_lock_irqsave(rq, &rf);
6181 		if (!cfs_rq_throttled(cfs_rq))
6182 			goto next;
6183 
6184 #ifdef CONFIG_SMP
6185 		/* Already queued for async unthrottle */
6186 		if (!list_empty(&cfs_rq->throttled_csd_list))
6187 			goto next;
6188 #endif
6189 
6190 		/* By the above checks, this should never be true */
6191 		SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
6192 
6193 		raw_spin_lock(&cfs_b->lock);
6194 		runtime = -cfs_rq->runtime_remaining + 1;
6195 		if (runtime > cfs_b->runtime)
6196 			runtime = cfs_b->runtime;
6197 		cfs_b->runtime -= runtime;
6198 		remaining = cfs_b->runtime;
6199 		raw_spin_unlock(&cfs_b->lock);
6200 
6201 		cfs_rq->runtime_remaining += runtime;
6202 
6203 		/* we check whether we're throttled above */
6204 		if (cfs_rq->runtime_remaining > 0) {
6205 			if (cpu_of(rq) != this_cpu ||
6206 			    SCHED_WARN_ON(local_unthrottle))
6207 				unthrottle_cfs_rq_async(cfs_rq);
6208 			else
6209 				local_unthrottle = cfs_rq;
6210 		} else {
6211 			throttled = true;
6212 		}
6213 
6214 next:
6215 		rq_unlock_irqrestore(rq, &rf);
6216 	}
6217 	rcu_read_unlock();
6218 
6219 	if (local_unthrottle) {
6220 		rq = cpu_rq(this_cpu);
6221 		rq_lock_irqsave(rq, &rf);
6222 		if (cfs_rq_throttled(local_unthrottle))
6223 			unthrottle_cfs_rq(local_unthrottle);
6224 		rq_unlock_irqrestore(rq, &rf);
6225 	}
6226 
6227 	return throttled;
6228 }
6229 
6230 /*
6231  * Responsible for refilling a task_group's bandwidth and unthrottling its
6232  * cfs_rqs as appropriate. If there has been no activity within the last
6233  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6234  * used to track this state.
6235  */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6236 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6237 {
6238 	int throttled;
6239 
6240 	/* no need to continue the timer with no bandwidth constraint */
6241 	if (cfs_b->quota == RUNTIME_INF)
6242 		goto out_deactivate;
6243 
6244 	throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6245 	cfs_b->nr_periods += overrun;
6246 
6247 	/* Refill extra burst quota even if cfs_b->idle */
6248 	__refill_cfs_bandwidth_runtime(cfs_b);
6249 
6250 	/*
6251 	 * idle depends on !throttled (for the case of a large deficit), and if
6252 	 * we're going inactive then everything else can be deferred
6253 	 */
6254 	if (cfs_b->idle && !throttled)
6255 		goto out_deactivate;
6256 
6257 	if (!throttled) {
6258 		/* mark as potentially idle for the upcoming period */
6259 		cfs_b->idle = 1;
6260 		return 0;
6261 	}
6262 
6263 	/* account preceding periods in which throttling occurred */
6264 	cfs_b->nr_throttled += overrun;
6265 
6266 	/*
6267 	 * This check is repeated as we release cfs_b->lock while we unthrottle.
6268 	 */
6269 	while (throttled && cfs_b->runtime > 0) {
6270 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6271 		/* we can't nest cfs_b->lock while distributing bandwidth */
6272 		throttled = distribute_cfs_runtime(cfs_b);
6273 		raw_spin_lock_irqsave(&cfs_b->lock, flags);
6274 	}
6275 
6276 	/*
6277 	 * While we are ensured activity in the period following an
6278 	 * unthrottle, this also covers the case in which the new bandwidth is
6279 	 * insufficient to cover the existing bandwidth deficit.  (Forcing the
6280 	 * timer to remain active while there are any throttled entities.)
6281 	 */
6282 	cfs_b->idle = 0;
6283 
6284 	return 0;
6285 
6286 out_deactivate:
6287 	return 1;
6288 }
6289 
6290 /* a cfs_rq won't donate quota below this amount */
6291 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6292 /* minimum remaining period time to redistribute slack quota */
6293 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6294 /* how long we wait to gather additional slack before distributing */
6295 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6296 
6297 /*
6298  * Are we near the end of the current quota period?
6299  *
6300  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6301  * hrtimer base being cleared by hrtimer_start. In the case of
6302  * migrate_hrtimers, base is never cleared, so we are fine.
6303  */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6304 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6305 {
6306 	struct hrtimer *refresh_timer = &cfs_b->period_timer;
6307 	s64 remaining;
6308 
6309 	/* if the call-back is running a quota refresh is already occurring */
6310 	if (hrtimer_callback_running(refresh_timer))
6311 		return 1;
6312 
6313 	/* is a quota refresh about to occur? */
6314 	remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6315 	if (remaining < (s64)min_expire)
6316 		return 1;
6317 
6318 	return 0;
6319 }
6320 
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6321 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6322 {
6323 	u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6324 
6325 	/* if there's a quota refresh soon don't bother with slack */
6326 	if (runtime_refresh_within(cfs_b, min_left))
6327 		return;
6328 
6329 	/* don't push forwards an existing deferred unthrottle */
6330 	if (cfs_b->slack_started)
6331 		return;
6332 	cfs_b->slack_started = true;
6333 
6334 	hrtimer_start(&cfs_b->slack_timer,
6335 			ns_to_ktime(cfs_bandwidth_slack_period),
6336 			HRTIMER_MODE_REL);
6337 }
6338 
6339 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6340 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6341 {
6342 	struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6343 	s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6344 
6345 	if (slack_runtime <= 0)
6346 		return;
6347 
6348 	raw_spin_lock(&cfs_b->lock);
6349 	if (cfs_b->quota != RUNTIME_INF) {
6350 		cfs_b->runtime += slack_runtime;
6351 
6352 		/* we are under rq->lock, defer unthrottling using a timer */
6353 		if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6354 		    !list_empty(&cfs_b->throttled_cfs_rq))
6355 			start_cfs_slack_bandwidth(cfs_b);
6356 	}
6357 	raw_spin_unlock(&cfs_b->lock);
6358 
6359 	/* even if it's not valid for return we don't want to try again */
6360 	cfs_rq->runtime_remaining -= slack_runtime;
6361 }
6362 
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6363 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6364 {
6365 	if (!cfs_bandwidth_used())
6366 		return;
6367 
6368 	if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6369 		return;
6370 
6371 	__return_cfs_rq_runtime(cfs_rq);
6372 }
6373 
6374 /*
6375  * This is done with a timer (instead of inline with bandwidth return) since
6376  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6377  */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6378 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6379 {
6380 	u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6381 	unsigned long flags;
6382 
6383 	/* confirm we're still not at a refresh boundary */
6384 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6385 	cfs_b->slack_started = false;
6386 
6387 	if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6388 		raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6389 		return;
6390 	}
6391 
6392 	if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6393 		runtime = cfs_b->runtime;
6394 
6395 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6396 
6397 	if (!runtime)
6398 		return;
6399 
6400 	distribute_cfs_runtime(cfs_b);
6401 }
6402 
6403 /*
6404  * When a group wakes up we want to make sure that its quota is not already
6405  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6406  * runtime as update_curr() throttling can not trigger until it's on-rq.
6407  */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6408 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6409 {
6410 	if (!cfs_bandwidth_used())
6411 		return;
6412 
6413 	/* an active group must be handled by the update_curr()->put() path */
6414 	if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6415 		return;
6416 
6417 	/* ensure the group is not already throttled */
6418 	if (cfs_rq_throttled(cfs_rq))
6419 		return;
6420 
6421 	/* update runtime allocation */
6422 	account_cfs_rq_runtime(cfs_rq, 0);
6423 	if (cfs_rq->runtime_remaining <= 0)
6424 		throttle_cfs_rq(cfs_rq);
6425 }
6426 
sync_throttle(struct task_group * tg,int cpu)6427 static void sync_throttle(struct task_group *tg, int cpu)
6428 {
6429 	struct cfs_rq *pcfs_rq, *cfs_rq;
6430 
6431 	if (!cfs_bandwidth_used())
6432 		return;
6433 
6434 	if (!tg->parent)
6435 		return;
6436 
6437 	cfs_rq = tg->cfs_rq[cpu];
6438 	pcfs_rq = tg->parent->cfs_rq[cpu];
6439 
6440 	cfs_rq->throttle_count = pcfs_rq->throttle_count;
6441 	cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6442 }
6443 
6444 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6445 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6446 {
6447 	if (!cfs_bandwidth_used())
6448 		return false;
6449 
6450 	if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6451 		return false;
6452 
6453 	/*
6454 	 * it's possible for a throttled entity to be forced into a running
6455 	 * state (e.g. set_curr_task), in this case we're finished.
6456 	 */
6457 	if (cfs_rq_throttled(cfs_rq))
6458 		return true;
6459 
6460 	return throttle_cfs_rq(cfs_rq);
6461 }
6462 
sched_cfs_slack_timer(struct hrtimer * timer)6463 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6464 {
6465 	struct cfs_bandwidth *cfs_b =
6466 		container_of(timer, struct cfs_bandwidth, slack_timer);
6467 
6468 	do_sched_cfs_slack_timer(cfs_b);
6469 
6470 	return HRTIMER_NORESTART;
6471 }
6472 
6473 extern const u64 max_cfs_quota_period;
6474 
sched_cfs_period_timer(struct hrtimer * timer)6475 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6476 {
6477 	struct cfs_bandwidth *cfs_b =
6478 		container_of(timer, struct cfs_bandwidth, period_timer);
6479 	unsigned long flags;
6480 	int overrun;
6481 	int idle = 0;
6482 	int count = 0;
6483 
6484 	raw_spin_lock_irqsave(&cfs_b->lock, flags);
6485 	for (;;) {
6486 		overrun = hrtimer_forward_now(timer, cfs_b->period);
6487 		if (!overrun)
6488 			break;
6489 
6490 		idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6491 
6492 		if (++count > 3) {
6493 			u64 new, old = ktime_to_ns(cfs_b->period);
6494 
6495 			/*
6496 			 * Grow period by a factor of 2 to avoid losing precision.
6497 			 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6498 			 * to fail.
6499 			 */
6500 			new = old * 2;
6501 			if (new < max_cfs_quota_period) {
6502 				cfs_b->period = ns_to_ktime(new);
6503 				cfs_b->quota *= 2;
6504 				cfs_b->burst *= 2;
6505 
6506 				pr_warn_ratelimited(
6507 	"cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6508 					smp_processor_id(),
6509 					div_u64(new, NSEC_PER_USEC),
6510 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6511 			} else {
6512 				pr_warn_ratelimited(
6513 	"cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6514 					smp_processor_id(),
6515 					div_u64(old, NSEC_PER_USEC),
6516 					div_u64(cfs_b->quota, NSEC_PER_USEC));
6517 			}
6518 
6519 			/* reset count so we don't come right back in here */
6520 			count = 0;
6521 		}
6522 	}
6523 	if (idle)
6524 		cfs_b->period_active = 0;
6525 	raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6526 
6527 	return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6528 }
6529 
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6530 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6531 {
6532 	raw_spin_lock_init(&cfs_b->lock);
6533 	cfs_b->runtime = 0;
6534 	cfs_b->quota = RUNTIME_INF;
6535 	cfs_b->period = ns_to_ktime(default_cfs_period());
6536 	cfs_b->burst = 0;
6537 	cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6538 
6539 	INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6540 	hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6541 	cfs_b->period_timer.function = sched_cfs_period_timer;
6542 
6543 	/* Add a random offset so that timers interleave */
6544 	hrtimer_set_expires(&cfs_b->period_timer,
6545 			    get_random_u32_below(cfs_b->period));
6546 	hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6547 	cfs_b->slack_timer.function = sched_cfs_slack_timer;
6548 	cfs_b->slack_started = false;
6549 }
6550 
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6551 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6552 {
6553 	cfs_rq->runtime_enabled = 0;
6554 	INIT_LIST_HEAD(&cfs_rq->throttled_list);
6555 #ifdef CONFIG_SMP
6556 	INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6557 #endif
6558 	walt_init_cfs_rq_stats(cfs_rq);
6559 }
6560 
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6561 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6562 {
6563 	lockdep_assert_held(&cfs_b->lock);
6564 
6565 	if (cfs_b->period_active)
6566 		return;
6567 
6568 	cfs_b->period_active = 1;
6569 	hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6570 	hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6571 }
6572 
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6573 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6574 {
6575 	int __maybe_unused i;
6576 
6577 	/* init_cfs_bandwidth() was not called */
6578 	if (!cfs_b->throttled_cfs_rq.next)
6579 		return;
6580 
6581 	hrtimer_cancel(&cfs_b->period_timer);
6582 	hrtimer_cancel(&cfs_b->slack_timer);
6583 
6584 	/*
6585 	 * It is possible that we still have some cfs_rq's pending on a CSD
6586 	 * list, though this race is very rare. In order for this to occur, we
6587 	 * must have raced with the last task leaving the group while there
6588 	 * exist throttled cfs_rq(s), and the period_timer must have queued the
6589 	 * CSD item but the remote cpu has not yet processed it. To handle this,
6590 	 * we can simply flush all pending CSD work inline here. We're
6591 	 * guaranteed at this point that no additional cfs_rq of this group can
6592 	 * join a CSD list.
6593 	 */
6594 #ifdef CONFIG_SMP
6595 	for_each_possible_cpu(i) {
6596 		struct rq *rq = cpu_rq(i);
6597 		unsigned long flags;
6598 
6599 		if (list_empty(&rq->cfsb_csd_list))
6600 			continue;
6601 
6602 		local_irq_save(flags);
6603 		__cfsb_csd_unthrottle(rq);
6604 		local_irq_restore(flags);
6605 	}
6606 #endif
6607 }
6608 
6609 /*
6610  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6611  *
6612  * The race is harmless, since modifying bandwidth settings of unhooked group
6613  * bits doesn't do much.
6614  */
6615 
6616 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6617 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6618 {
6619 	struct task_group *tg;
6620 
6621 	lockdep_assert_rq_held(rq);
6622 
6623 	rcu_read_lock();
6624 	list_for_each_entry_rcu(tg, &task_groups, list) {
6625 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6626 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6627 
6628 		raw_spin_lock(&cfs_b->lock);
6629 		cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6630 		raw_spin_unlock(&cfs_b->lock);
6631 	}
6632 	rcu_read_unlock();
6633 }
6634 
6635 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6636 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6637 {
6638 	struct task_group *tg;
6639 
6640 	lockdep_assert_rq_held(rq);
6641 
6642 	/*
6643 	 * The rq clock has already been updated in the
6644 	 * set_rq_offline(), so we should skip updating
6645 	 * the rq clock again in unthrottle_cfs_rq().
6646 	 */
6647 	rq_clock_start_loop_update(rq);
6648 
6649 	rcu_read_lock();
6650 	list_for_each_entry_rcu(tg, &task_groups, list) {
6651 		struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6652 
6653 		if (!cfs_rq->runtime_enabled)
6654 			continue;
6655 
6656 		/*
6657 		 * clock_task is not advancing so we just need to make sure
6658 		 * there's some valid quota amount
6659 		 */
6660 		cfs_rq->runtime_remaining = 1;
6661 		/*
6662 		 * Offline rq is schedulable till CPU is completely disabled
6663 		 * in take_cpu_down(), so we prevent new cfs throttling here.
6664 		 */
6665 		cfs_rq->runtime_enabled = 0;
6666 
6667 		if (cfs_rq_throttled(cfs_rq))
6668 			unthrottle_cfs_rq(cfs_rq);
6669 	}
6670 	rcu_read_unlock();
6671 
6672 	rq_clock_stop_loop_update(rq);
6673 }
6674 
cfs_task_bw_constrained(struct task_struct * p)6675 bool cfs_task_bw_constrained(struct task_struct *p)
6676 {
6677 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
6678 
6679 	if (!cfs_bandwidth_used())
6680 		return false;
6681 
6682 	if (cfs_rq->runtime_enabled ||
6683 	    tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6684 		return true;
6685 
6686 	return false;
6687 }
6688 
6689 #ifdef CONFIG_NO_HZ_FULL
6690 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6691 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6692 {
6693 	int cpu = cpu_of(rq);
6694 
6695 	if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6696 		return;
6697 
6698 	if (!tick_nohz_full_cpu(cpu))
6699 		return;
6700 
6701 	if (rq->nr_running != 1)
6702 		return;
6703 
6704 	/*
6705 	 *  We know there is only one task runnable and we've just picked it. The
6706 	 *  normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6707 	 *  be otherwise able to stop the tick. Just need to check if we are using
6708 	 *  bandwidth control.
6709 	 */
6710 	if (cfs_task_bw_constrained(p))
6711 		tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6712 }
6713 #endif
6714 
6715 #else /* CONFIG_CFS_BANDWIDTH */
6716 
cfs_bandwidth_used(void)6717 static inline bool cfs_bandwidth_used(void)
6718 {
6719 	return false;
6720 }
6721 
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6722 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6723 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6724 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6725 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6726 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6727 
cfs_rq_throttled(struct cfs_rq * cfs_rq)6728 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6729 {
6730 	return 0;
6731 }
6732 
throttled_hierarchy(struct cfs_rq * cfs_rq)6733 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6734 {
6735 	return 0;
6736 }
6737 
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)6738 static inline int throttled_lb_pair(struct task_group *tg,
6739 				    int src_cpu, int dest_cpu)
6740 {
6741 	return 0;
6742 }
6743 
6744 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6745 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6746 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6747 #endif
6748 
tg_cfs_bandwidth(struct task_group * tg)6749 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6750 {
6751 	return NULL;
6752 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6753 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6754 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6755 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6756 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6757 bool cfs_task_bw_constrained(struct task_struct *p)
6758 {
6759 	return false;
6760 }
6761 #endif
6762 #endif /* CONFIG_CFS_BANDWIDTH */
6763 
6764 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6765 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6766 #endif
6767 
6768 /**************************************************
6769  * CFS operations on tasks:
6770  */
6771 
6772 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6773 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6774 {
6775 	struct sched_entity *se = &p->se;
6776 
6777 	SCHED_WARN_ON(task_rq(p) != rq);
6778 
6779 	if (rq->cfs.h_nr_running > 1) {
6780 		u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6781 		u64 slice = se->slice;
6782 		s64 delta = slice - ran;
6783 
6784 		if (delta < 0) {
6785 			if (task_current(rq, p))
6786 				resched_curr(rq);
6787 			return;
6788 		}
6789 		hrtick_start(rq, delta);
6790 	}
6791 }
6792 
6793 /*
6794  * called from enqueue/dequeue and updates the hrtick when the
6795  * current task is from our class and nr_running is low enough
6796  * to matter.
6797  */
hrtick_update(struct rq * rq)6798 static void hrtick_update(struct rq *rq)
6799 {
6800 	struct task_struct *curr = rq->curr;
6801 
6802 	if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6803 		return;
6804 
6805 	hrtick_start_fair(rq, curr);
6806 }
6807 #else /* !CONFIG_SCHED_HRTICK */
6808 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6809 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6810 {
6811 }
6812 
hrtick_update(struct rq * rq)6813 static inline void hrtick_update(struct rq *rq)
6814 {
6815 }
6816 #endif
6817 
6818 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)6819 static inline bool cpu_overutilized(int cpu)
6820 {
6821 	unsigned long  rq_util_min, rq_util_max;
6822 
6823 	if (!sched_energy_enabled())
6824 		return false;
6825 
6826 	rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6827 	rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6828 
6829 	/* Return true only if the utilization doesn't fit CPU's capacity */
6830 	return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6831 }
6832 
set_rd_overutilized_status(struct root_domain * rd,unsigned int status)6833 static inline void set_rd_overutilized_status(struct root_domain *rd,
6834 					      unsigned int status)
6835 {
6836 	if (!sched_energy_enabled())
6837 		return;
6838 
6839 	WRITE_ONCE(rd->overutilized, status);
6840 	trace_sched_overutilized_tp(rd, !!status);
6841 }
6842 
check_update_overutilized_status(struct rq * rq)6843 static inline void check_update_overutilized_status(struct rq *rq)
6844 {
6845 	/*
6846 	 * overutilized field is used for load balancing decisions only
6847 	 * if energy aware scheduler is being used
6848 	 */
6849 	if (!sched_energy_enabled())
6850 		return;
6851 
6852 	if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu))
6853 		set_rd_overutilized_status(rq->rd, SG_OVERUTILIZED);
6854 }
6855 #else
check_update_overutilized_status(struct rq * rq)6856 static inline void check_update_overutilized_status(struct rq *rq) { }
6857 #endif
6858 
6859 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6860 static int sched_idle_rq(struct rq *rq)
6861 {
6862 	return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6863 			rq->nr_running);
6864 }
6865 
6866 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)6867 static int sched_idle_cpu(int cpu)
6868 {
6869 	return sched_idle_rq(cpu_rq(cpu));
6870 }
6871 #endif
6872 
6873 static void set_next_buddy(struct sched_entity *se);
6874 
6875 #ifdef CONFIG_SCHED_LATENCY_NICE
check_preempt_from_idle(struct cfs_rq * cfs,struct sched_entity * se)6876 static void check_preempt_from_idle(struct cfs_rq *cfs, struct sched_entity *se)
6877 {
6878 	struct sched_entity *next;
6879 
6880 	if (se->latency_weight <= 0)
6881 		return;
6882 
6883 	if (cfs->nr_running <= 1)
6884 		return;
6885 	/*
6886 	 * When waking from idle, we don't need to check to preempt at wakeup
6887 	 * the idle thread and don't set next buddy as a candidate for being
6888 	 * picked in priority.
6889 	 * In case of simultaneous wakeup from idle, the latency sensitive tasks
6890 	 * lost opportunity to preempt non sensitive tasks which woke up
6891 	 * simultaneously.
6892 	 */
6893 
6894 	if (cfs->next)
6895 		next = cfs->next;
6896 	else
6897 		next = __pick_first_entity(cfs);
6898 
6899 	if (next && wakeup_preempt_entity(next, se) == 1)
6900 		set_next_buddy(se);
6901 }
6902 #endif
6903 
6904 /*
6905  * The enqueue_task method is called before nr_running is
6906  * increased. Here we update the fair scheduling stats and
6907  * then put the task into the rbtree:
6908  */
6909 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6910 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6911 {
6912 	struct cfs_rq *cfs_rq;
6913 	struct sched_entity *se = &p->se;
6914 	int idle_h_nr_running = task_has_idle_policy(p);
6915 	int task_new = !(flags & ENQUEUE_WAKEUP);
6916 
6917 	/*
6918 	 * The code below (indirectly) updates schedutil which looks at
6919 	 * the cfs_rq utilization to select a frequency.
6920 	 * Let's add the task's estimated utilization to the cfs_rq's
6921 	 * estimated utilization, before we update schedutil.
6922 	 */
6923 	util_est_enqueue(&rq->cfs, p);
6924 
6925 	/*
6926 	 * If in_iowait is set, the code below may not trigger any cpufreq
6927 	 * utilization updates, so do it here explicitly with the IOWAIT flag
6928 	 * passed.
6929 	 */
6930 	if (p->in_iowait)
6931 		cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6932 
6933 	for_each_sched_entity(se) {
6934 		if (se->on_rq)
6935 			break;
6936 		cfs_rq = cfs_rq_of(se);
6937 		enqueue_entity(cfs_rq, se, flags);
6938 
6939 		cfs_rq->h_nr_running++;
6940 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
6941 		walt_inc_cfs_rq_stats(cfs_rq, p);
6942 		if (cfs_rq_is_idle(cfs_rq))
6943 			idle_h_nr_running = 1;
6944 
6945 		/* end evaluation on encountering a throttled cfs_rq */
6946 		if (cfs_rq_throttled(cfs_rq))
6947 			goto enqueue_throttle;
6948 
6949 		flags = ENQUEUE_WAKEUP;
6950 	}
6951 
6952 	for_each_sched_entity(se) {
6953 		cfs_rq = cfs_rq_of(se);
6954 
6955 		update_load_avg(cfs_rq, se, UPDATE_TG);
6956 		se_update_runnable(se);
6957 		update_cfs_group(se);
6958 
6959 		cfs_rq->h_nr_running++;
6960 		cfs_rq->idle_h_nr_running += idle_h_nr_running;
6961 		walt_inc_cfs_rq_stats(cfs_rq, p);
6962 		if (cfs_rq_is_idle(cfs_rq))
6963 			idle_h_nr_running = 1;
6964 
6965 		/* end evaluation on encountering a throttled cfs_rq */
6966 		if (cfs_rq_throttled(cfs_rq))
6967 			goto enqueue_throttle;
6968 	}
6969 
6970 	/* At this point se is NULL and we are at root level*/
6971 	add_nr_running(rq, 1);
6972 	inc_rq_walt_stats(rq, p);
6973 	/*
6974 	 * Since new tasks are assigned an initial util_avg equal to
6975 	 * half of the spare capacity of their CPU, tiny tasks have the
6976 	 * ability to cross the overutilized threshold, which will
6977 	 * result in the load balancer ruining all the task placement
6978 	 * done by EAS. As a way to mitigate that effect, do not account
6979 	 * for the first enqueue operation of new tasks during the
6980 	 * overutilized flag detection.
6981 	 *
6982 	 * A better way of solving this problem would be to wait for
6983 	 * the PELT signals of tasks to converge before taking them
6984 	 * into account, but that is not straightforward to implement,
6985 	 * and the following generally works well enough in practice.
6986 	 */
6987 	if (!task_new)
6988 		check_update_overutilized_status(rq);
6989 
6990 #ifdef CONFIG_SCHED_LATENCY_NICE
6991 	if (rq->curr == rq->idle)
6992 		check_preempt_from_idle(cfs_rq_of(&p->se), &p->se);
6993 #endif
6994 
6995 enqueue_throttle:
6996 	assert_list_leaf_cfs_rq(rq);
6997 
6998 	hrtick_update(rq);
6999 }
7000 
7001 static void set_next_buddy(struct sched_entity *se);
7002 
7003 /*
7004  * The dequeue_task method is called before nr_running is
7005  * decreased. We remove the task from the rbtree and
7006  * update the fair scheduling stats:
7007  */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7008 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7009 {
7010 	struct cfs_rq *cfs_rq;
7011 	struct sched_entity *se = &p->se;
7012 	int task_sleep = flags & DEQUEUE_SLEEP;
7013 	int idle_h_nr_running = task_has_idle_policy(p);
7014 	bool was_sched_idle = sched_idle_rq(rq);
7015 
7016 	util_est_dequeue(&rq->cfs, p);
7017 
7018 	for_each_sched_entity(se) {
7019 		cfs_rq = cfs_rq_of(se);
7020 		dequeue_entity(cfs_rq, se, flags);
7021 
7022 		cfs_rq->h_nr_running--;
7023 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
7024 		walt_dec_cfs_rq_stats(cfs_rq, p);
7025 		if (cfs_rq_is_idle(cfs_rq))
7026 			idle_h_nr_running = 1;
7027 
7028 		/* end evaluation on encountering a throttled cfs_rq */
7029 		if (cfs_rq_throttled(cfs_rq))
7030 			goto dequeue_throttle;
7031 
7032 		/* Don't dequeue parent if it has other entities besides us */
7033 		if (cfs_rq->load.weight) {
7034 			/* Avoid re-evaluating load for this entity: */
7035 			se = parent_entity(se);
7036 			/*
7037 			 * Bias pick_next to pick a task from this cfs_rq, as
7038 			 * p is sleeping when it is within its sched_slice.
7039 			 */
7040 			if (task_sleep && se && !throttled_hierarchy(cfs_rq))
7041 				set_next_buddy(se);
7042 			break;
7043 		}
7044 		flags |= DEQUEUE_SLEEP;
7045 	}
7046 
7047 	for_each_sched_entity(se) {
7048 		cfs_rq = cfs_rq_of(se);
7049 
7050 		update_load_avg(cfs_rq, se, UPDATE_TG);
7051 		se_update_runnable(se);
7052 		update_cfs_group(se);
7053 
7054 		cfs_rq->h_nr_running--;
7055 		cfs_rq->idle_h_nr_running -= idle_h_nr_running;
7056 		walt_dec_cfs_rq_stats(cfs_rq, p);
7057 		if (cfs_rq_is_idle(cfs_rq))
7058 			idle_h_nr_running = 1;
7059 
7060 		/* end evaluation on encountering a throttled cfs_rq */
7061 		if (cfs_rq_throttled(cfs_rq))
7062 			goto dequeue_throttle;
7063 
7064 	}
7065 
7066 	/* At this point se is NULL and we are at root level*/
7067 	sub_nr_running(rq, 1);
7068 	dec_rq_walt_stats(rq, p);
7069 
7070 	/* balance early to pull high priority tasks */
7071 	if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7072 		rq->next_balance = jiffies;
7073 
7074 dequeue_throttle:
7075 	util_est_update(&rq->cfs, p, task_sleep);
7076 	hrtick_update(rq);
7077 }
7078 
7079 #ifdef CONFIG_SMP
7080 
7081 /* Working cpumask for: load_balance, load_balance_newidle. */
7082 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7083 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7084 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7085 
7086 #ifdef CONFIG_NO_HZ_COMMON
7087 
7088 static struct {
7089 	cpumask_var_t idle_cpus_mask;
7090 	atomic_t nr_cpus;
7091 	int has_blocked;		/* Idle CPUS has blocked load */
7092 	int needs_update;		/* Newly idle CPUs need their next_balance collated */
7093 	unsigned long next_balance;     /* in jiffy units */
7094 	unsigned long next_blocked;	/* Next update of blocked load in jiffies */
7095 } nohz ____cacheline_aligned;
7096 
7097 #endif /* CONFIG_NO_HZ_COMMON */
7098 
cpu_load(struct rq * rq)7099 static unsigned long cpu_load(struct rq *rq)
7100 {
7101 	return cfs_rq_load_avg(&rq->cfs);
7102 }
7103 
7104 /*
7105  * cpu_load_without - compute CPU load without any contributions from *p
7106  * @cpu: the CPU which load is requested
7107  * @p: the task which load should be discounted
7108  *
7109  * The load of a CPU is defined by the load of tasks currently enqueued on that
7110  * CPU as well as tasks which are currently sleeping after an execution on that
7111  * CPU.
7112  *
7113  * This method returns the load of the specified CPU by discounting the load of
7114  * the specified task, whenever the task is currently contributing to the CPU
7115  * load.
7116  */
cpu_load_without(struct rq * rq,struct task_struct * p)7117 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7118 {
7119 	struct cfs_rq *cfs_rq;
7120 	unsigned int load;
7121 
7122 	/* Task has no contribution or is new */
7123 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7124 		return cpu_load(rq);
7125 
7126 	cfs_rq = &rq->cfs;
7127 	load = READ_ONCE(cfs_rq->avg.load_avg);
7128 
7129 	/* Discount task's util from CPU's util */
7130 	lsub_positive(&load, task_h_load(p));
7131 
7132 	return load;
7133 }
7134 
cpu_runnable(struct rq * rq)7135 static unsigned long cpu_runnable(struct rq *rq)
7136 {
7137 	return cfs_rq_runnable_avg(&rq->cfs);
7138 }
7139 
cpu_runnable_without(struct rq * rq,struct task_struct * p)7140 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7141 {
7142 	struct cfs_rq *cfs_rq;
7143 	unsigned int runnable;
7144 
7145 	/* Task has no contribution or is new */
7146 	if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7147 		return cpu_runnable(rq);
7148 
7149 	cfs_rq = &rq->cfs;
7150 	runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7151 
7152 	/* Discount task's runnable from CPU's runnable */
7153 	lsub_positive(&runnable, p->se.avg.runnable_avg);
7154 
7155 	return runnable;
7156 }
7157 
capacity_of(int cpu)7158 static unsigned long capacity_of(int cpu)
7159 {
7160 	return cpu_rq(cpu)->cpu_capacity;
7161 }
7162 
record_wakee(struct task_struct * p)7163 static void record_wakee(struct task_struct *p)
7164 {
7165 	/*
7166 	 * Only decay a single time; tasks that have less then 1 wakeup per
7167 	 * jiffy will not have built up many flips.
7168 	 */
7169 	if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7170 		current->wakee_flips >>= 1;
7171 		current->wakee_flip_decay_ts = jiffies;
7172 	}
7173 
7174 	if (current->last_wakee != p) {
7175 		current->last_wakee = p;
7176 		current->wakee_flips++;
7177 	}
7178 }
7179 
7180 /*
7181  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7182  *
7183  * A waker of many should wake a different task than the one last awakened
7184  * at a frequency roughly N times higher than one of its wakees.
7185  *
7186  * In order to determine whether we should let the load spread vs consolidating
7187  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7188  * partner, and a factor of lls_size higher frequency in the other.
7189  *
7190  * With both conditions met, we can be relatively sure that the relationship is
7191  * non-monogamous, with partner count exceeding socket size.
7192  *
7193  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7194  * whatever is irrelevant, spread criteria is apparent partner count exceeds
7195  * socket size.
7196  */
wake_wide(struct task_struct * p)7197 static int wake_wide(struct task_struct *p)
7198 {
7199 	unsigned int master = current->wakee_flips;
7200 	unsigned int slave = p->wakee_flips;
7201 	int factor = __this_cpu_read(sd_llc_size);
7202 
7203 	if (master < slave)
7204 		swap(master, slave);
7205 	if (slave < factor || master < slave * factor)
7206 		return 0;
7207 	return 1;
7208 }
7209 
7210 /*
7211  * The purpose of wake_affine() is to quickly determine on which CPU we can run
7212  * soonest. For the purpose of speed we only consider the waking and previous
7213  * CPU.
7214  *
7215  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7216  *			cache-affine and is (or	will be) idle.
7217  *
7218  * wake_affine_weight() - considers the weight to reflect the average
7219  *			  scheduling latency of the CPUs. This seems to work
7220  *			  for the overloaded case.
7221  */
7222 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7223 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7224 {
7225 	/*
7226 	 * If this_cpu is idle, it implies the wakeup is from interrupt
7227 	 * context. Only allow the move if cache is shared. Otherwise an
7228 	 * interrupt intensive workload could force all tasks onto one
7229 	 * node depending on the IO topology or IRQ affinity settings.
7230 	 *
7231 	 * If the prev_cpu is idle and cache affine then avoid a migration.
7232 	 * There is no guarantee that the cache hot data from an interrupt
7233 	 * is more important than cache hot data on the prev_cpu and from
7234 	 * a cpufreq perspective, it's better to have higher utilisation
7235 	 * on one CPU.
7236 	 */
7237 	if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7238 		return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7239 
7240 	if (sync && cpu_rq(this_cpu)->nr_running == 1)
7241 		return this_cpu;
7242 
7243 	if (available_idle_cpu(prev_cpu))
7244 		return prev_cpu;
7245 
7246 	return nr_cpumask_bits;
7247 }
7248 
7249 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7250 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7251 		   int this_cpu, int prev_cpu, int sync)
7252 {
7253 	s64 this_eff_load, prev_eff_load;
7254 	unsigned long task_load;
7255 
7256 	this_eff_load = cpu_load(cpu_rq(this_cpu));
7257 
7258 	if (sync) {
7259 		unsigned long current_load = task_h_load(current);
7260 
7261 		if (current_load > this_eff_load)
7262 			return this_cpu;
7263 
7264 		this_eff_load -= current_load;
7265 	}
7266 
7267 	task_load = task_h_load(p);
7268 
7269 	this_eff_load += task_load;
7270 	if (sched_feat(WA_BIAS))
7271 		this_eff_load *= 100;
7272 	this_eff_load *= capacity_of(prev_cpu);
7273 
7274 	prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7275 	prev_eff_load -= task_load;
7276 	if (sched_feat(WA_BIAS))
7277 		prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7278 	prev_eff_load *= capacity_of(this_cpu);
7279 
7280 	/*
7281 	 * If sync, adjust the weight of prev_eff_load such that if
7282 	 * prev_eff == this_eff that select_idle_sibling() will consider
7283 	 * stacking the wakee on top of the waker if no other CPU is
7284 	 * idle.
7285 	 */
7286 	if (sync)
7287 		prev_eff_load += 1;
7288 
7289 	return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7290 }
7291 
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7292 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7293 		       int this_cpu, int prev_cpu, int sync)
7294 {
7295 	int target = nr_cpumask_bits;
7296 
7297 	if (sched_feat(WA_IDLE))
7298 		target = wake_affine_idle(this_cpu, prev_cpu, sync);
7299 
7300 	if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7301 		target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7302 
7303 	schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7304 	if (target != this_cpu)
7305 		return prev_cpu;
7306 
7307 	schedstat_inc(sd->ttwu_move_affine);
7308 	schedstat_inc(p->stats.nr_wakeups_affine);
7309 	return target;
7310 }
7311 
7312 static struct sched_group *
7313 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7314 
7315 /*
7316  * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
7317  */
7318 static int
find_idlest_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7319 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7320 {
7321 	unsigned long load, min_load = ULONG_MAX;
7322 	unsigned int min_exit_latency = UINT_MAX;
7323 	u64 latest_idle_timestamp = 0;
7324 	int least_loaded_cpu = this_cpu;
7325 	int shallowest_idle_cpu = -1;
7326 	int i;
7327 
7328 	/* Check if we have any choice: */
7329 	if (group->group_weight == 1)
7330 		return cpumask_first(sched_group_span(group));
7331 
7332 	/* Traverse only the allowed CPUs */
7333 	for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7334 		struct rq *rq = cpu_rq(i);
7335 
7336 		if (cpu_isolated(i))
7337 			continue;
7338 
7339 		if (!sched_core_cookie_match(rq, p))
7340 			continue;
7341 
7342 		if (sched_idle_cpu(i))
7343 			return i;
7344 
7345 		if (available_idle_cpu(i)) {
7346 			struct cpuidle_state *idle = idle_get_state(rq);
7347 			if (idle && idle->exit_latency < min_exit_latency) {
7348 				/*
7349 				 * We give priority to a CPU whose idle state
7350 				 * has the smallest exit latency irrespective
7351 				 * of any idle timestamp.
7352 				 */
7353 				min_exit_latency = idle->exit_latency;
7354 				latest_idle_timestamp = rq->idle_stamp;
7355 				shallowest_idle_cpu = i;
7356 			} else if ((!idle || idle->exit_latency == min_exit_latency) &&
7357 				   rq->idle_stamp > latest_idle_timestamp) {
7358 				/*
7359 				 * If equal or no active idle state, then
7360 				 * the most recently idled CPU might have
7361 				 * a warmer cache.
7362 				 */
7363 				latest_idle_timestamp = rq->idle_stamp;
7364 				shallowest_idle_cpu = i;
7365 			}
7366 		} else if (shallowest_idle_cpu == -1) {
7367 			load = cpu_load(cpu_rq(i));
7368 			if (load < min_load) {
7369 				min_load = load;
7370 				least_loaded_cpu = i;
7371 			}
7372 		}
7373 	}
7374 
7375 	return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7376 }
7377 
find_idlest_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7378 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
7379 				  int cpu, int prev_cpu, int sd_flag)
7380 {
7381 	int new_cpu = cpu;
7382 
7383 	if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7384 		return prev_cpu;
7385 
7386 	/*
7387 	 * We need task's util for cpu_util_without, sync it up to
7388 	 * prev_cpu's last_update_time.
7389 	 */
7390 	if (!(sd_flag & SD_BALANCE_FORK))
7391 		sync_entity_load_avg(&p->se);
7392 
7393 	while (sd) {
7394 		struct sched_group *group;
7395 		struct sched_domain *tmp;
7396 		int weight;
7397 
7398 		if (!(sd->flags & sd_flag)) {
7399 			sd = sd->child;
7400 			continue;
7401 		}
7402 
7403 		group = find_idlest_group(sd, p, cpu);
7404 		if (!group) {
7405 			sd = sd->child;
7406 			continue;
7407 		}
7408 
7409 		new_cpu = find_idlest_group_cpu(group, p, cpu);
7410 		if (new_cpu == cpu) {
7411 			/* Now try balancing at a lower domain level of 'cpu': */
7412 			sd = sd->child;
7413 			continue;
7414 		}
7415 
7416 		/* Now try balancing at a lower domain level of 'new_cpu': */
7417 		cpu = new_cpu;
7418 		weight = sd->span_weight;
7419 		sd = NULL;
7420 		for_each_domain(cpu, tmp) {
7421 			if (weight <= tmp->span_weight)
7422 				break;
7423 			if (tmp->flags & sd_flag)
7424 				sd = tmp;
7425 		}
7426 	}
7427 
7428 	return new_cpu;
7429 }
7430 
__select_idle_cpu(int cpu,struct task_struct * p)7431 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7432 {
7433 	if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7434 	    sched_cpu_cookie_match(cpu_rq(cpu), p))
7435 		return cpu;
7436 
7437 	return -1;
7438 }
7439 
7440 #ifdef CONFIG_SCHED_SMT
7441 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7442 EXPORT_SYMBOL_GPL(sched_smt_present);
7443 
set_idle_cores(int cpu,int val)7444 static inline void set_idle_cores(int cpu, int val)
7445 {
7446 	struct sched_domain_shared *sds;
7447 
7448 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7449 	if (sds)
7450 		WRITE_ONCE(sds->has_idle_cores, val);
7451 }
7452 
test_idle_cores(int cpu)7453 static inline bool test_idle_cores(int cpu)
7454 {
7455 	struct sched_domain_shared *sds;
7456 
7457 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7458 	if (sds)
7459 		return READ_ONCE(sds->has_idle_cores);
7460 
7461 	return false;
7462 }
7463 
7464 /*
7465  * Scans the local SMT mask to see if the entire core is idle, and records this
7466  * information in sd_llc_shared->has_idle_cores.
7467  *
7468  * Since SMT siblings share all cache levels, inspecting this limited remote
7469  * state should be fairly cheap.
7470  */
__update_idle_core(struct rq * rq)7471 void __update_idle_core(struct rq *rq)
7472 {
7473 	int core = cpu_of(rq);
7474 	int cpu;
7475 
7476 	rcu_read_lock();
7477 	if (test_idle_cores(core))
7478 		goto unlock;
7479 
7480 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7481 		if (cpu == core)
7482 			continue;
7483 
7484 		if (!available_idle_cpu(cpu))
7485 			goto unlock;
7486 	}
7487 
7488 	set_idle_cores(core, 1);
7489 unlock:
7490 	rcu_read_unlock();
7491 }
7492 
7493 /*
7494  * Scan the entire LLC domain for idle cores; this dynamically switches off if
7495  * there are no idle cores left in the system; tracked through
7496  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7497  */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7498 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7499 {
7500 
7501 #ifdef CONFIG_CPU_ISOLATION_OPT
7502 	cpumask_andnot(cpus, cpus, cpu_isolated_mask);
7503 #endif
7504 	bool idle = true;
7505 	int cpu;
7506 
7507 	for_each_cpu(cpu, cpu_smt_mask(core)) {
7508 		if (!available_idle_cpu(cpu)) {
7509 			idle = false;
7510 			if (*idle_cpu == -1) {
7511 				if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7512 					*idle_cpu = cpu;
7513 					break;
7514 				}
7515 				continue;
7516 			}
7517 			break;
7518 		}
7519 		if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7520 			*idle_cpu = cpu;
7521 	}
7522 
7523 	if (idle)
7524 		return core;
7525 
7526 	cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7527 	return -1;
7528 }
7529 
7530 /*
7531  * Scan the local SMT mask for idle CPUs.
7532  */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7533 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7534 {
7535 	int cpu;
7536 
7537 	for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7538 		if (cpu == target)
7539 			continue;
7540 		/*
7541 		 * Check if the CPU is in the LLC scheduling domain of @target.
7542 		 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7543 		 */
7544 		if (cpu_isolated(cpu))
7545 			continue;
7546 		if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7547 			continue;
7548 		if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7549 			return cpu;
7550 	}
7551 
7552 	return -1;
7553 }
7554 
7555 #else /* CONFIG_SCHED_SMT */
7556 
set_idle_cores(int cpu,int val)7557 static inline void set_idle_cores(int cpu, int val)
7558 {
7559 }
7560 
test_idle_cores(int cpu)7561 static inline bool test_idle_cores(int cpu)
7562 {
7563 	return false;
7564 }
7565 
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7566 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7567 {
7568 	return __select_idle_cpu(core, p);
7569 }
7570 
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7571 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7572 {
7573 	return -1;
7574 }
7575 
7576 #endif /* CONFIG_SCHED_SMT */
7577 
7578 /*
7579  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7580  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7581  * average idle time for this rq (as found in rq->avg_idle).
7582  */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7583 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7584 {
7585 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7586 	int i, cpu, idle_cpu = -1, nr = INT_MAX;
7587 	struct sched_domain_shared *sd_share;
7588 	struct rq *this_rq = this_rq();
7589 	int this = smp_processor_id();
7590 	struct sched_domain *this_sd = NULL;
7591 	u64 time = 0;
7592 
7593 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7594 
7595 	if (sched_feat(SIS_PROP) && !has_idle_core) {
7596 		u64 avg_cost, avg_idle, span_avg;
7597 		unsigned long now = jiffies;
7598 
7599 		this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7600 		if (!this_sd)
7601 			return -1;
7602 
7603 		/*
7604 		 * If we're busy, the assumption that the last idle period
7605 		 * predicts the future is flawed; age away the remaining
7606 		 * predicted idle time.
7607 		 */
7608 		if (unlikely(this_rq->wake_stamp < now)) {
7609 			while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7610 				this_rq->wake_stamp++;
7611 				this_rq->wake_avg_idle >>= 1;
7612 			}
7613 		}
7614 
7615 		avg_idle = this_rq->wake_avg_idle;
7616 		avg_cost = this_sd->avg_scan_cost + 1;
7617 
7618 		span_avg = sd->span_weight * avg_idle;
7619 		if (span_avg > 4*avg_cost)
7620 			nr = div_u64(span_avg, avg_cost);
7621 		else
7622 			nr = 4;
7623 
7624 		time = cpu_clock(this);
7625 	}
7626 
7627 	if (sched_feat(SIS_UTIL)) {
7628 		sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7629 		if (sd_share) {
7630 			/* because !--nr is the condition to stop scan */
7631 			nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7632 			/* overloaded LLC is unlikely to have idle cpu/core */
7633 			if (nr == 1)
7634 				return -1;
7635 		}
7636 	}
7637 
7638 	for_each_cpu_wrap(cpu, cpus, target + 1) {
7639 		if (has_idle_core) {
7640 			i = select_idle_core(p, cpu, cpus, &idle_cpu);
7641 			if ((unsigned int)i < nr_cpumask_bits)
7642 				return i;
7643 
7644 		} else {
7645 			if (!--nr)
7646 				return -1;
7647 		if (cpu_isolated(cpu))
7648 			continue;
7649 			idle_cpu = __select_idle_cpu(cpu, p);
7650 			if ((unsigned int)idle_cpu < nr_cpumask_bits)
7651 				break;
7652 		}
7653 	}
7654 
7655 	if (has_idle_core)
7656 		set_idle_cores(target, false);
7657 
7658 	if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7659 		time = cpu_clock(this) - time;
7660 
7661 		/*
7662 		 * Account for the scan cost of wakeups against the average
7663 		 * idle time.
7664 		 */
7665 		this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7666 
7667 		update_avg(&this_sd->avg_scan_cost, time);
7668 	}
7669 
7670 	return idle_cpu;
7671 }
7672 
7673 /*
7674  * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7675  * the task fits. If no CPU is big enough, but there are idle ones, try to
7676  * maximize capacity.
7677  */
7678 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7679 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7680 {
7681 	unsigned long task_util, util_min, util_max, best_cap = 0;
7682 	int fits, best_fits = 0;
7683 	int cpu, best_cpu = -1;
7684 	struct cpumask *cpus;
7685 
7686 	cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7687 	cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7688 
7689 	task_util = task_util_est(p);
7690 	util_min = uclamp_eff_value(p, UCLAMP_MIN);
7691 	util_max = uclamp_eff_value(p, UCLAMP_MAX);
7692 
7693 	for_each_cpu_wrap(cpu, cpus, target) {
7694 		unsigned long cpu_cap = capacity_of(cpu);
7695 
7696 		if (cpu_isolated(cpu))
7697 			continue;
7698 
7699 		if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7700 			continue;
7701 
7702 		fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7703 
7704 		/* This CPU fits with all requirements */
7705 		if (fits > 0)
7706 			return cpu;
7707 		/*
7708 		 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7709 		 * Look for the CPU with best capacity.
7710 		 */
7711 		else if (fits < 0)
7712 			cpu_cap = capacity_orig_of(cpu) - thermal_load_avg(cpu_rq(cpu));
7713 
7714 		/*
7715 		 * First, select CPU which fits better (-1 being better than 0).
7716 		 * Then, select the one with best capacity at same level.
7717 		 */
7718 		if ((fits < best_fits) ||
7719 		    ((fits == best_fits) && (cpu_cap > best_cap))) {
7720 			best_cap = cpu_cap;
7721 			best_cpu = cpu;
7722 			best_fits = fits;
7723 		}
7724 	}
7725 
7726 	return best_cpu;
7727 }
7728 
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7729 static inline bool asym_fits_cpu(unsigned long util,
7730 				 unsigned long util_min,
7731 				 unsigned long util_max,
7732 				 int cpu)
7733 {
7734 	if (sched_asym_cpucap_active())
7735 		/*
7736 		 * Return true only if the cpu fully fits the task requirements
7737 		 * which include the utilization and the performance hints.
7738 		 */
7739 		return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7740 
7741 	return true;
7742 }
7743 
7744 /*
7745  * Try and locate an idle core/thread in the LLC cache domain.
7746  */
select_idle_sibling(struct task_struct * p,int prev,int target)7747 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7748 {
7749 	bool has_idle_core = false;
7750 	struct sched_domain *sd;
7751 	unsigned long task_util, util_min, util_max;
7752 	int i, recent_used_cpu;
7753 
7754 	/*
7755 	 * On asymmetric system, update task utilization because we will check
7756 	 * that the task fits with cpu's capacity.
7757 	 */
7758 	if (sched_asym_cpucap_active()) {
7759 		sync_entity_load_avg(&p->se);
7760 		task_util = task_util_est(p);
7761 		util_min = uclamp_eff_value(p, UCLAMP_MIN);
7762 		util_max = uclamp_eff_value(p, UCLAMP_MAX);
7763 	}
7764 
7765 	/*
7766 	 * per-cpu select_rq_mask usage
7767 	 */
7768 	lockdep_assert_irqs_disabled();
7769 
7770 	if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7771 	    !cpu_isolated(target) && asym_fits_cpu(task_util, util_min, util_max, target))
7772 		return target;
7773 
7774 	/*
7775 	 * If the previous CPU is cache affine and idle, don't be stupid:
7776 	 */
7777 	if (prev != target && cpus_share_cache(prev, target) &&
7778 	    ((available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7779 	    !cpu_isolated(target) && asym_fits_cpu(task_util, util_min, util_max, prev)))
7780 		return prev;
7781 
7782 	/*
7783 	 * Allow a per-cpu kthread to stack with the wakee if the
7784 	 * kworker thread and the tasks previous CPUs are the same.
7785 	 * The assumption is that the wakee queued work for the
7786 	 * per-cpu kthread that is now complete and the wakeup is
7787 	 * essentially a sync wakeup. An obvious example of this
7788 	 * pattern is IO completions.
7789 	 */
7790 	if (is_per_cpu_kthread(current) &&
7791 	    in_task() &&
7792 	    prev == smp_processor_id() &&
7793 	    this_rq()->nr_running <= 1 &&
7794 	    asym_fits_cpu(task_util, util_min, util_max, prev)) {
7795 		return prev;
7796 	}
7797 
7798 	/* Check a recently used CPU as a potential idle candidate: */
7799 	recent_used_cpu = p->recent_used_cpu;
7800 	p->recent_used_cpu = prev;
7801 	if (recent_used_cpu != prev &&
7802 	    recent_used_cpu != target &&
7803 	    cpus_share_cache(recent_used_cpu, target) &&
7804 	    (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7805 	    cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7806 	    asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7807 		return recent_used_cpu;
7808 	}
7809 
7810 	/*
7811 	 * For asymmetric CPU capacity systems, our domain of interest is
7812 	 * sd_asym_cpucapacity rather than sd_llc.
7813 	 */
7814 	if (sched_asym_cpucap_active()) {
7815 		sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7816 		/*
7817 		 * On an asymmetric CPU capacity system where an exclusive
7818 		 * cpuset defines a symmetric island (i.e. one unique
7819 		 * capacity_orig value through the cpuset), the key will be set
7820 		 * but the CPUs within that cpuset will not have a domain with
7821 		 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7822 		 * capacity path.
7823 		 */
7824 		if (sd) {
7825 			i = select_idle_capacity(p, sd, target);
7826 			return ((unsigned)i < nr_cpumask_bits) ? i : target;
7827 		}
7828 	}
7829 
7830 	sd = rcu_dereference(per_cpu(sd_llc, target));
7831 	if (!sd)
7832 		return target;
7833 
7834 	if (sched_smt_active()) {
7835 		has_idle_core = test_idle_cores(target);
7836 
7837 		if (!has_idle_core && cpus_share_cache(prev, target)) {
7838 			i = select_idle_smt(p, sd, prev);
7839 			if ((unsigned int)i < nr_cpumask_bits)
7840 				return i;
7841 		}
7842 	}
7843 
7844 	i = select_idle_cpu(p, sd, has_idle_core, target);
7845 	if ((unsigned)i < nr_cpumask_bits)
7846 		return i;
7847 
7848 	return target;
7849 }
7850 
7851 /**
7852  * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7853  * @cpu: the CPU to get the utilization for
7854  * @p: task for which the CPU utilization should be predicted or NULL
7855  * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7856  * @boost: 1 to enable boosting, otherwise 0
7857  *
7858  * The unit of the return value must be the same as the one of CPU capacity
7859  * so that CPU utilization can be compared with CPU capacity.
7860  *
7861  * CPU utilization is the sum of running time of runnable tasks plus the
7862  * recent utilization of currently non-runnable tasks on that CPU.
7863  * It represents the amount of CPU capacity currently used by CFS tasks in
7864  * the range [0..max CPU capacity] with max CPU capacity being the CPU
7865  * capacity at f_max.
7866  *
7867  * The estimated CPU utilization is defined as the maximum between CPU
7868  * utilization and sum of the estimated utilization of the currently
7869  * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7870  * previously-executed tasks, which helps better deduce how busy a CPU will
7871  * be when a long-sleeping task wakes up. The contribution to CPU utilization
7872  * of such a task would be significantly decayed at this point of time.
7873  *
7874  * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7875  * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7876  * utilization. Boosting is implemented in cpu_util() so that internal
7877  * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7878  * latter via cpu_util_cfs_boost().
7879  *
7880  * CPU utilization can be higher than the current CPU capacity
7881  * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7882  * of rounding errors as well as task migrations or wakeups of new tasks.
7883  * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7884  * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7885  * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7886  * capacity. CPU utilization is allowed to overshoot current CPU capacity
7887  * though since this is useful for predicting the CPU capacity required
7888  * after task migrations (scheduler-driven DVFS).
7889  *
7890  * Return: (Boosted) (estimated) utilization for the specified CPU.
7891  */
7892 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7893 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7894 {
7895 	struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7896 	unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7897 	unsigned long runnable;
7898 
7899 #ifdef CONFIG_SCHED_WALT
7900 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
7901 		u64 walt_cpu_util =
7902 			cpu_rq(cpu)->walt_stats.cumulative_runnable_avg_scaled;
7903 
7904 		return min_t(unsigned long, walt_cpu_util,
7905 				capacity_orig_of(cpu));
7906 	}
7907 #endif
7908 
7909 	if (boost) {
7910 		runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7911 		util = max(util, runnable);
7912 	}
7913 
7914 	/*
7915 	 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7916 	 * contribution. If @p migrates from another CPU to @cpu add its
7917 	 * contribution. In all the other cases @cpu is not impacted by the
7918 	 * migration so its util_avg is already correct.
7919 	 */
7920 	if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7921 		lsub_positive(&util, task_util(p));
7922 	else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7923 		util += task_util(p);
7924 
7925 	if (sched_feat(UTIL_EST)) {
7926 		unsigned long util_est;
7927 
7928 		util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7929 
7930 		/*
7931 		 * During wake-up @p isn't enqueued yet and doesn't contribute
7932 		 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7933 		 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7934 		 * has been enqueued.
7935 		 *
7936 		 * During exec (@dst_cpu = -1) @p is enqueued and does
7937 		 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7938 		 * Remove it to "simulate" cpu_util without @p's contribution.
7939 		 *
7940 		 * Despite the task_on_rq_queued(@p) check there is still a
7941 		 * small window for a possible race when an exec
7942 		 * select_task_rq_fair() races with LB's detach_task().
7943 		 *
7944 		 *   detach_task()
7945 		 *     deactivate_task()
7946 		 *       p->on_rq = TASK_ON_RQ_MIGRATING;
7947 		 *       -------------------------------- A
7948 		 *       dequeue_task()                    \
7949 		 *         dequeue_task_fair()              + Race Time
7950 		 *           util_est_dequeue()            /
7951 		 *       -------------------------------- B
7952 		 *
7953 		 * The additional check "current == p" is required to further
7954 		 * reduce the race window.
7955 		 */
7956 		if (dst_cpu == cpu)
7957 			util_est += _task_util_est(p);
7958 		else if (p && unlikely(task_on_rq_queued(p) || current == p))
7959 			lsub_positive(&util_est, _task_util_est(p));
7960 
7961 		util = max(util, util_est);
7962 	}
7963 
7964 	return min(util, capacity_orig_of(cpu));
7965 }
7966 
cpu_util_cfs(int cpu)7967 unsigned long cpu_util_cfs(int cpu)
7968 {
7969 	return cpu_util(cpu, NULL, -1, 0);
7970 }
7971 
cpu_util_cfs_boost(int cpu)7972 unsigned long cpu_util_cfs_boost(int cpu)
7973 {
7974 	return cpu_util(cpu, NULL, -1, 1);
7975 }
7976 
7977 /*
7978  * cpu_util_without: compute cpu utilization without any contributions from *p
7979  * @cpu: the CPU which utilization is requested
7980  * @p: the task which utilization should be discounted
7981  *
7982  * The utilization of a CPU is defined by the utilization of tasks currently
7983  * enqueued on that CPU as well as tasks which are currently sleeping after an
7984  * execution on that CPU.
7985  *
7986  * This method returns the utilization of the specified CPU by discounting the
7987  * utilization of the specified task, whenever the task is currently
7988  * contributing to the CPU utilization.
7989  */
cpu_util_without(int cpu,struct task_struct * p)7990 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7991 {
7992 	unsigned int util;
7993 #ifdef CONFIG_SCHED_WALT
7994 	/*
7995 	 * WALT does not decay idle tasks in the same manner
7996 	 * as PELT, so it makes little sense to subtract task
7997 	 * utilization from cpu utilization. Instead just use
7998 	 * cpu_util for this case.
7999 	 */
8000 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util) &&
8001 						p->__state == TASK_WAKING)
8002 		return cpu_util_cfs(cpu);
8003 #endif
8004 	/* Task has no contribution or is new */
8005 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8006 		p = NULL;
8007 
8008 	return cpu_util(cpu, p, -1, 0);
8009 #ifdef CONFIG_SCHED_WALT
8010 	if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
8011 		util = max_t(long, cpu_util_cfs(cpu) - task_util(p), 0);
8012 		return min_t(unsigned long, util, capacity_orig_of(cpu));
8013 	}
8014 #endif
8015 }
8016 
8017 /*
8018  * energy_env - Utilization landscape for energy estimation.
8019  * @task_busy_time: Utilization contribution by the task for which we test the
8020  *                  placement. Given by eenv_task_busy_time().
8021  * @pd_busy_time:   Utilization of the whole perf domain without the task
8022  *                  contribution. Given by eenv_pd_busy_time().
8023  * @cpu_cap:        Maximum CPU capacity for the perf domain.
8024  * @pd_cap:         Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8025  */
8026 struct energy_env {
8027 	unsigned long task_busy_time;
8028 	unsigned long pd_busy_time;
8029 	unsigned long cpu_cap;
8030 	unsigned long pd_cap;
8031 };
8032 
8033 /*
8034  * Compute the task busy time for compute_energy(). This time cannot be
8035  * injected directly into effective_cpu_util() because of the IRQ scaling.
8036  * The latter only makes sense with the most recent CPUs where the task has
8037  * run.
8038  */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8039 static inline void eenv_task_busy_time(struct energy_env *eenv,
8040 				       struct task_struct *p, int prev_cpu)
8041 {
8042 	unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8043 	unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8044 
8045 	if (unlikely(irq >= max_cap))
8046 		busy_time = max_cap;
8047 	else
8048 		busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8049 
8050 	eenv->task_busy_time = busy_time;
8051 }
8052 
8053 #ifdef CONFIG_SCHED_RTG
capacity_spare_without(int cpu,struct task_struct * p)8054 unsigned long capacity_spare_without(int cpu, struct task_struct *p)
8055 {
8056 	return max_t(long, capacity_of(cpu) - cpu_util_without(cpu, p), 0);
8057 }
8058 #endif
8059 
8060 /*
8061  * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8062  * utilization for each @pd_cpus, it however doesn't take into account
8063  * clamping since the ratio (utilization / cpu_capacity) is already enough to
8064  * scale the EM reported power consumption at the (eventually clamped)
8065  * cpu_capacity.
8066  *
8067  * The contribution of the task @p for which we want to estimate the
8068  * energy cost is removed (by cpu_util()) and must be calculated
8069  * separately (see eenv_task_busy_time). This ensures:
8070  *
8071  *   - A stable PD utilization, no matter which CPU of that PD we want to place
8072  *     the task on.
8073  *
8074  *   - A fair comparison between CPUs as the task contribution (task_util())
8075  *     will always be the same no matter which CPU utilization we rely on
8076  *     (util_avg or util_est).
8077  *
8078  * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8079  * exceed @eenv->pd_cap.
8080  */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8081 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8082 				     struct cpumask *pd_cpus,
8083 				     struct task_struct *p)
8084 {
8085 	unsigned long busy_time = 0;
8086 	int cpu;
8087 
8088 	for_each_cpu(cpu, pd_cpus) {
8089 		unsigned long util = cpu_util(cpu, p, -1, 0);
8090 
8091 		busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
8092 	}
8093 
8094 	eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8095 }
8096 
8097 /*
8098  * Returns the current capacity of cpu after applying both
8099  * cpu and freq scaling.
8100  */
capacity_curr_of(int cpu)8101 unsigned long capacity_curr_of(int cpu)
8102 {
8103 	unsigned long max_cap = cpu_rq(cpu)->cpu_capacity_orig;
8104 	unsigned long scale_freq = arch_scale_freq_capacity(cpu);
8105 
8106 	return cap_scale(max_cap, scale_freq);
8107 }
8108 
8109 /*
8110  * Compute the maximum utilization for compute_energy() when the task @p
8111  * is placed on the cpu @dst_cpu.
8112  *
8113  * Returns the maximum utilization among @eenv->cpus. This utilization can't
8114  * exceed @eenv->cpu_cap.
8115  */
8116 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8117 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8118 		 struct task_struct *p, int dst_cpu)
8119 {
8120 	unsigned long max_util = 0;
8121 	int cpu;
8122 
8123 	for_each_cpu(cpu, pd_cpus) {
8124 		struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8125 		unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8126 		unsigned long eff_util;
8127 
8128 		/*
8129 		 * Performance domain frequency: utilization clamping
8130 		 * must be considered since it affects the selection
8131 		 * of the performance domain frequency.
8132 		 * NOTE: in case RT tasks are running, by default the
8133 		 * FREQUENCY_UTIL's utilization can be max OPP.
8134 		 */
8135 		eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
8136 		max_util = max(max_util, eff_util);
8137 	}
8138 
8139 	return min(max_util, eenv->cpu_cap);
8140 }
8141 
8142 /*
8143  * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8144  * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8145  * contribution is ignored.
8146  */
8147 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)8148 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8149 	       struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8150 {
8151 	unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8152 	unsigned long busy_time = eenv->pd_busy_time;
8153 
8154 	if (dst_cpu >= 0)
8155 		busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8156 
8157 	return em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8158 }
8159 
8160 /*
8161  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8162  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8163  * spare capacity in each performance domain and uses it as a potential
8164  * candidate to execute the task. Then, it uses the Energy Model to figure
8165  * out which of the CPU candidates is the most energy-efficient.
8166  *
8167  * The rationale for this heuristic is as follows. In a performance domain,
8168  * all the most energy efficient CPU candidates (according to the Energy
8169  * Model) are those for which we'll request a low frequency. When there are
8170  * several CPUs for which the frequency request will be the same, we don't
8171  * have enough data to break the tie between them, because the Energy Model
8172  * only includes active power costs. With this model, if we assume that
8173  * frequency requests follow utilization (e.g. using schedutil), the CPU with
8174  * the maximum spare capacity in a performance domain is guaranteed to be among
8175  * the best candidates of the performance domain.
8176  *
8177  * In practice, it could be preferable from an energy standpoint to pack
8178  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8179  * but that could also hurt our chances to go cluster idle, and we have no
8180  * ways to tell with the current Energy Model if this is actually a good
8181  * idea or not. So, find_energy_efficient_cpu() basically favors
8182  * cluster-packing, and spreading inside a cluster. That should at least be
8183  * a good thing for latency, and this is consistent with the idea that most
8184  * of the energy savings of EAS come from the asymmetry of the system, and
8185  * not so much from breaking the tie between identical CPUs. That's also the
8186  * reason why EAS is enabled in the topology code only for systems where
8187  * SD_ASYM_CPUCAPACITY is set.
8188  *
8189  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8190  * they don't have any useful utilization data yet and it's not possible to
8191  * forecast their impact on energy consumption. Consequently, they will be
8192  * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
8193  * to be energy-inefficient in some use-cases. The alternative would be to
8194  * bias new tasks towards specific types of CPUs first, or to try to infer
8195  * their util_avg from the parent task, but those heuristics could hurt
8196  * other use-cases too. So, until someone finds a better way to solve this,
8197  * let's keep things simple by re-using the existing slow path.
8198  */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8199 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8200 {
8201 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8202 	unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8203 	unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8204 	unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8205 	struct root_domain *rd = this_rq()->rd;
8206 	int cpu, best_energy_cpu, target = -1;
8207 	int prev_fits = -1, best_fits = -1;
8208 	unsigned long best_thermal_cap = 0;
8209 	unsigned long prev_thermal_cap = 0;
8210 	struct sched_domain *sd;
8211 	struct perf_domain *pd;
8212 	struct energy_env eenv;
8213 
8214 	rcu_read_lock();
8215 	pd = rcu_dereference(rd->pd);
8216 	if (!pd || READ_ONCE(rd->overutilized))
8217 		goto unlock;
8218 
8219 	/*
8220 	 * Energy-aware wake-up happens on the lowest sched_domain starting
8221 	 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8222 	 */
8223 	sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8224 	while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8225 		sd = sd->parent;
8226 	if (!sd)
8227 		goto unlock;
8228 
8229 	target = prev_cpu;
8230 
8231 	sync_entity_load_avg(&p->se);
8232 	if (!task_util_est(p) && p_util_min == 0)
8233 		goto unlock;
8234 
8235 	eenv_task_busy_time(&eenv, p, prev_cpu);
8236 
8237 	for (; pd; pd = pd->next) {
8238 		unsigned long util_min = p_util_min, util_max = p_util_max;
8239 		unsigned long cpu_cap, cpu_thermal_cap, util;
8240 		long prev_spare_cap = -1, max_spare_cap = -1;
8241 		unsigned long rq_util_min, rq_util_max;
8242 		unsigned long cur_delta, base_energy;
8243 		int max_spare_cap_cpu = -1;
8244 		int fits, max_fits = -1;
8245 
8246 		cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8247 
8248 		if (cpumask_empty(cpus))
8249 			continue;
8250 
8251 		/* Account thermal pressure for the energy estimation */
8252 		cpu = cpumask_first(cpus);
8253 		cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
8254 		cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
8255 
8256 		eenv.cpu_cap = cpu_thermal_cap;
8257 		eenv.pd_cap = 0;
8258 
8259 		for_each_cpu(cpu, cpus) {
8260 			struct rq *rq = cpu_rq(cpu);
8261 
8262 			eenv.pd_cap += cpu_thermal_cap;
8263 
8264 			if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8265 				continue;
8266 
8267 			if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8268 				continue;
8269 
8270 			util = cpu_util(cpu, p, cpu, 0);
8271 			cpu_cap = capacity_of(cpu);
8272 
8273 			/*
8274 			 * Skip CPUs that cannot satisfy the capacity request.
8275 			 * IOW, placing the task there would make the CPU
8276 			 * overutilized. Take uclamp into account to see how
8277 			 * much capacity we can get out of the CPU; this is
8278 			 * aligned with sched_cpu_util().
8279 			 */
8280 			if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8281 				/*
8282 				 * Open code uclamp_rq_util_with() except for
8283 				 * the clamp() part. Ie: apply max aggregation
8284 				 * only. util_fits_cpu() logic requires to
8285 				 * operate on non clamped util but must use the
8286 				 * max-aggregated uclamp_{min, max}.
8287 				 */
8288 				rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8289 				rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8290 
8291 				util_min = max(rq_util_min, p_util_min);
8292 				util_max = max(rq_util_max, p_util_max);
8293 			}
8294 
8295 			fits = util_fits_cpu(util, util_min, util_max, cpu);
8296 			if (!fits)
8297 				continue;
8298 
8299 			lsub_positive(&cpu_cap, util);
8300 
8301 			if (cpu == prev_cpu) {
8302 				/* Always use prev_cpu as a candidate. */
8303 				prev_spare_cap = cpu_cap;
8304 				prev_fits = fits;
8305 			} else if ((fits > max_fits) ||
8306 				   ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8307 				/*
8308 				 * Find the CPU with the maximum spare capacity
8309 				 * among the remaining CPUs in the performance
8310 				 * domain.
8311 				 */
8312 				max_spare_cap = cpu_cap;
8313 				max_spare_cap_cpu = cpu;
8314 				max_fits = fits;
8315 			}
8316 		}
8317 
8318 		if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8319 			continue;
8320 
8321 		eenv_pd_busy_time(&eenv, cpus, p);
8322 		/* Compute the 'base' energy of the pd, without @p */
8323 		base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8324 
8325 		/* Evaluate the energy impact of using prev_cpu. */
8326 		if (prev_spare_cap > -1) {
8327 			prev_delta = compute_energy(&eenv, pd, cpus, p,
8328 						    prev_cpu);
8329 			/* CPU utilization has changed */
8330 			if (prev_delta < base_energy)
8331 				goto unlock;
8332 			prev_delta -= base_energy;
8333 			prev_thermal_cap = cpu_thermal_cap;
8334 			best_delta = min(best_delta, prev_delta);
8335 		}
8336 
8337 		/* Evaluate the energy impact of using max_spare_cap_cpu. */
8338 		if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8339 			/* Current best energy cpu fits better */
8340 			if (max_fits < best_fits)
8341 				continue;
8342 
8343 			/*
8344 			 * Both don't fit performance hint (i.e. uclamp_min)
8345 			 * but best energy cpu has better capacity.
8346 			 */
8347 			if ((max_fits < 0) &&
8348 			    (cpu_thermal_cap <= best_thermal_cap))
8349 				continue;
8350 
8351 			cur_delta = compute_energy(&eenv, pd, cpus, p,
8352 						   max_spare_cap_cpu);
8353 			/* CPU utilization has changed */
8354 			if (cur_delta < base_energy)
8355 				goto unlock;
8356 			cur_delta -= base_energy;
8357 
8358 			/*
8359 			 * Both fit for the task but best energy cpu has lower
8360 			 * energy impact.
8361 			 */
8362 			if ((max_fits > 0) && (best_fits > 0) &&
8363 			    (cur_delta >= best_delta))
8364 				continue;
8365 
8366 			best_delta = cur_delta;
8367 			best_energy_cpu = max_spare_cap_cpu;
8368 			best_fits = max_fits;
8369 			best_thermal_cap = cpu_thermal_cap;
8370 		}
8371 	}
8372 	rcu_read_unlock();
8373 
8374 	if ((best_fits > prev_fits) ||
8375 	    ((best_fits > 0) && (best_delta < prev_delta)) ||
8376 	    ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
8377 		target = best_energy_cpu;
8378 
8379 	return target;
8380 
8381 unlock:
8382 	rcu_read_unlock();
8383 
8384 	return target;
8385 }
8386 
8387 /*
8388  * select_task_rq_fair: Select target runqueue for the waking task in domains
8389  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8390  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8391  *
8392  * Balances load by selecting the idlest CPU in the idlest group, or under
8393  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8394  *
8395  * Returns the target CPU number.
8396  */
8397 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8398 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8399 {
8400 	int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8401 	struct sched_domain *tmp, *sd = NULL;
8402 	int cpu = smp_processor_id();
8403 	int new_cpu = prev_cpu;
8404 	int want_affine = 0;
8405 	/* SD_flags and WF_flags share the first nibble */
8406 	int sd_flag = wake_flags & 0xF;
8407 #ifdef CONFIG_SCHED_RTG
8408 	int target_cpu = -1;
8409 		target_cpu = find_rtg_cpu(p);
8410 		if (target_cpu >= 0)
8411 			return target_cpu;
8412 #endif
8413 
8414 	/*
8415 	 * required for stable ->cpus_allowed
8416 	 */
8417 	lockdep_assert_held(&p->pi_lock);
8418 	if (wake_flags & WF_TTWU) {
8419 		record_wakee(p);
8420 
8421 		if ((wake_flags & WF_CURRENT_CPU) &&
8422 		    cpumask_test_cpu(cpu, p->cpus_ptr))
8423 			return cpu;
8424 
8425 		if (sched_energy_enabled()) {
8426 			new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8427 			if (new_cpu >= 0)
8428 				return new_cpu;
8429 			new_cpu = prev_cpu;
8430 		}
8431 
8432 		want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8433 	}
8434 
8435 	rcu_read_lock();
8436 	for_each_domain(cpu, tmp) {
8437 		/*
8438 		 * If both 'cpu' and 'prev_cpu' are part of this domain,
8439 		 * cpu is a valid SD_WAKE_AFFINE target.
8440 		 */
8441 		if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8442 		    cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8443 			if (cpu != prev_cpu)
8444 				new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8445 
8446 			sd = NULL; /* Prefer wake_affine over balance flags */
8447 			break;
8448 		}
8449 
8450 		/*
8451 		 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8452 		 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8453 		 * will usually go to the fast path.
8454 		 */
8455 		if (tmp->flags & sd_flag)
8456 			sd = tmp;
8457 		else if (!want_affine)
8458 			break;
8459 	}
8460 
8461 	if (unlikely(sd)) {
8462 		/* Slow path */
8463 		new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
8464 	} else if (wake_flags & WF_TTWU) { /* XXX always ? */
8465 		/* Fast path */
8466 		new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8467 	}
8468 	rcu_read_unlock();
8469 
8470 	return new_cpu;
8471 }
8472 
8473 /*
8474  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8475  * cfs_rq_of(p) references at time of call are still valid and identify the
8476  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8477  */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8478 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8479 {
8480 	struct sched_entity *se = &p->se;
8481 
8482 	if (!task_on_rq_migrating(p)) {
8483 		remove_entity_load_avg(se);
8484 
8485 		/*
8486 		 * Here, the task's PELT values have been updated according to
8487 		 * the current rq's clock. But if that clock hasn't been
8488 		 * updated in a while, a substantial idle time will be missed,
8489 		 * leading to an inflation after wake-up on the new rq.
8490 		 *
8491 		 * Estimate the missing time from the cfs_rq last_update_time
8492 		 * and update sched_avg to improve the PELT continuity after
8493 		 * migration.
8494 		 */
8495 		migrate_se_pelt_lag(se);
8496 	}
8497 
8498 	/* Tell new CPU we are migrated */
8499 	se->avg.last_update_time = 0;
8500 
8501 	update_scan_period(p, new_cpu);
8502 }
8503 
task_dead_fair(struct task_struct * p)8504 static void task_dead_fair(struct task_struct *p)
8505 {
8506 	remove_entity_load_avg(&p->se);
8507 }
8508 
8509 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8510 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8511 {
8512 	if (rq->nr_running)
8513 		return 1;
8514 
8515 	return newidle_balance(rq, rf) != 0;
8516 }
8517 #endif /* CONFIG_SMP */
8518 
8519 #ifdef CONFIG_SCHED_LATENCY_NICE
wakeup_latency_gran(struct sched_entity * curr,struct sched_entity * se)8520 static long wakeup_latency_gran(struct sched_entity *curr, struct sched_entity *se)
8521 {
8522 	int latency_weight = se->latency_weight;
8523 	long thresh = sysctl_sched_latency;
8524 
8525 	/*
8526 	 * A positive latency weigth means that the sched_entity has latency
8527 	 * requirement that needs to be evaluated versus other entity.
8528 	 * Otherwise, use the latency weight to evaluate how much scheduling
8529 	 * delay is acceptable by se.
8530 	 */
8531 	if ((se->latency_weight > 0) || (curr->latency_weight > 0))
8532 		latency_weight -= curr->latency_weight;
8533 
8534 	if (!latency_weight)
8535 		return 0;
8536 
8537 	if (sched_feat(GENTLE_FAIR_SLEEPERS))
8538 		thresh >>= 1;
8539 
8540 	/*
8541 	 * Clamp the delta to stay in the scheduler period range
8542 	 * [-sysctl_sched_latency:sysctl_sched_latency]
8543 	 */
8544 	latency_weight = clamp_t(long, latency_weight,
8545 				-1 * NICE_LATENCY_WEIGHT_MAX,
8546 				NICE_LATENCY_WEIGHT_MAX);
8547 
8548 	return (thresh * latency_weight) >> NICE_LATENCY_SHIFT;
8549 }
8550 #endif
8551 
wakeup_gran(struct sched_entity * se)8552 static unsigned long wakeup_gran(struct sched_entity *se)
8553 {
8554 	unsigned long gran = sysctl_sched_wakeup_granularity;
8555 
8556 	/*
8557 	 * Since its curr running now, convert the gran from real-time
8558 	 * to virtual-time in his units.
8559 	 *
8560 	 * By using 'se' instead of 'curr' we penalize light tasks, so
8561 	 * they get preempted easier. That is, if 'se' < 'curr' then
8562 	 * the resulting gran will be larger, therefore penalizing the
8563 	 * lighter, if otoh 'se' > 'curr' then the resulting gran will
8564 	 * be smaller, again penalizing the lighter task.
8565 	 *
8566 	 * This is especially important for buddies when the leftmost
8567 	 * task is higher priority than the buddy.
8568 	 */
8569 	return calc_delta_fair(gran, se);
8570 }
8571 
8572 /*
8573  * Should 'se' preempt 'curr'.
8574  *
8575  *             |s1
8576  *        |s2
8577  *   |s3
8578  *         g
8579  *      |<--->|c
8580  *
8581  *  w(c, s1) = -1
8582  *  w(c, s2) =  0
8583  *  w(c, s3) =  1
8584  *
8585  */
8586 static int
wakeup_preempt_entity(struct sched_entity * curr,struct sched_entity * se)8587 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
8588 {
8589 	s64 gran, vdiff = curr->vruntime - se->vruntime;
8590 
8591 #ifdef CONFIG_SCHED_LATENCY_NICE
8592 	/* Take into account latency priority */
8593 	vdiff += wakeup_latency_gran(curr, se);
8594 #endif
8595 
8596 	if (vdiff <= 0)
8597 		return -1;
8598 
8599 	gran = wakeup_gran(se);
8600 	if (vdiff > gran)
8601 		return 1;
8602 
8603 	return 0;
8604 }
8605 
set_next_buddy(struct sched_entity * se)8606 static void set_next_buddy(struct sched_entity *se)
8607 {
8608 	for_each_sched_entity(se) {
8609 		if (SCHED_WARN_ON(!se->on_rq))
8610 			return;
8611 		if (se_is_idle(se))
8612 			return;
8613 		cfs_rq_of(se)->next = se;
8614 	}
8615 }
8616 
8617 /*
8618  * Preempt the current task with a newly woken task if needed:
8619  */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8620 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8621 {
8622 	struct task_struct *curr = rq->curr;
8623 	struct sched_entity *se = &curr->se, *pse = &p->se;
8624 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8625 	int next_buddy_marked = 0;
8626 	int cse_is_idle, pse_is_idle;
8627 
8628 	if (unlikely(se == pse))
8629 		return;
8630 
8631 	/*
8632 	 * This is possible from callers such as attach_tasks(), in which we
8633 	 * unconditionally wakeup_preempt() after an enqueue (which may have
8634 	 * lead to a throttle).  This both saves work and prevents false
8635 	 * next-buddy nomination below.
8636 	 */
8637 	if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8638 		return;
8639 
8640 	if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8641 		set_next_buddy(pse);
8642 		next_buddy_marked = 1;
8643 	}
8644 
8645 	/*
8646 	 * We can come here with TIF_NEED_RESCHED already set from new task
8647 	 * wake up path.
8648 	 *
8649 	 * Note: this also catches the edge-case of curr being in a throttled
8650 	 * group (e.g. via set_curr_task), since update_curr() (in the
8651 	 * enqueue of curr) will have resulted in resched being set.  This
8652 	 * prevents us from potentially nominating it as a false LAST_BUDDY
8653 	 * below.
8654 	 */
8655 	if (test_tsk_need_resched(curr))
8656 		return;
8657 
8658 	if (!sched_feat(WAKEUP_PREEMPTION))
8659 		return;
8660 
8661 	find_matching_se(&se, &pse);
8662 	WARN_ON_ONCE(!pse);
8663 
8664 	cse_is_idle = se_is_idle(se);
8665 	pse_is_idle = se_is_idle(pse);
8666 
8667 	/*
8668 	 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8669 	 * in the inverse case).
8670 	 */
8671 	if (cse_is_idle && !pse_is_idle)
8672 		goto preempt;
8673 	if (cse_is_idle != pse_is_idle)
8674 		return;
8675 
8676 	/*
8677 	 * BATCH and IDLE tasks do not preempt others.
8678 	 */
8679 	if (unlikely(p->policy != SCHED_NORMAL))
8680 		return;
8681 
8682 	cfs_rq = cfs_rq_of(se);
8683 	update_curr(cfs_rq);
8684 	/*
8685 	 * XXX pick_eevdf(cfs_rq) != se ?
8686 	 */
8687 	if (pick_eevdf(cfs_rq) == pse)
8688 		goto preempt;
8689 
8690 	return;
8691 
8692 preempt:
8693 	resched_curr(rq);
8694 }
8695 
8696 #ifdef CONFIG_SMP
pick_task_fair(struct rq * rq)8697 static struct task_struct *pick_task_fair(struct rq *rq)
8698 {
8699 	struct sched_entity *se;
8700 	struct cfs_rq *cfs_rq;
8701 
8702 again:
8703 	cfs_rq = &rq->cfs;
8704 	if (!cfs_rq->nr_running)
8705 		return NULL;
8706 
8707 	do {
8708 		struct sched_entity *curr = cfs_rq->curr;
8709 
8710 		/* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8711 		if (curr) {
8712 			if (curr->on_rq)
8713 				update_curr(cfs_rq);
8714 			else
8715 				curr = NULL;
8716 
8717 			if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8718 				goto again;
8719 		}
8720 
8721 		se = pick_next_entity(cfs_rq, curr);
8722 		cfs_rq = group_cfs_rq(se);
8723 	} while (cfs_rq);
8724 
8725 	return task_of(se);
8726 }
8727 #endif
8728 
8729 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8730 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8731 {
8732 	struct cfs_rq *cfs_rq = &rq->cfs;
8733 	struct sched_entity *se;
8734 	struct task_struct *p;
8735 	int new_tasks;
8736 
8737 again:
8738 	if (!sched_fair_runnable(rq))
8739 		goto idle;
8740 
8741 #ifdef CONFIG_FAIR_GROUP_SCHED
8742 	if (!prev || prev->sched_class != &fair_sched_class)
8743 		goto simple;
8744 
8745 	/*
8746 	 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8747 	 * likely that a next task is from the same cgroup as the current.
8748 	 *
8749 	 * Therefore attempt to avoid putting and setting the entire cgroup
8750 	 * hierarchy, only change the part that actually changes.
8751 	 */
8752 
8753 	do {
8754 		struct sched_entity *curr = cfs_rq->curr;
8755 
8756 		/*
8757 		 * Since we got here without doing put_prev_entity() we also
8758 		 * have to consider cfs_rq->curr. If it is still a runnable
8759 		 * entity, update_curr() will update its vruntime, otherwise
8760 		 * forget we've ever seen it.
8761 		 */
8762 		if (curr) {
8763 			if (curr->on_rq)
8764 				update_curr(cfs_rq);
8765 			else
8766 				curr = NULL;
8767 
8768 			/*
8769 			 * This call to check_cfs_rq_runtime() will do the
8770 			 * throttle and dequeue its entity in the parent(s).
8771 			 * Therefore the nr_running test will indeed
8772 			 * be correct.
8773 			 */
8774 			if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8775 				cfs_rq = &rq->cfs;
8776 
8777 				if (!cfs_rq->nr_running)
8778 					goto idle;
8779 
8780 				goto simple;
8781 			}
8782 		}
8783 
8784 		se = pick_next_entity(cfs_rq, curr);
8785 		cfs_rq = group_cfs_rq(se);
8786 	} while (cfs_rq);
8787 
8788 	p = task_of(se);
8789 
8790 	/*
8791 	 * Since we haven't yet done put_prev_entity and if the selected task
8792 	 * is a different task than we started out with, try and touch the
8793 	 * least amount of cfs_rqs.
8794 	 */
8795 	if (prev != p) {
8796 		struct sched_entity *pse = &prev->se;
8797 
8798 		while (!(cfs_rq = is_same_group(se, pse))) {
8799 			int se_depth = se->depth;
8800 			int pse_depth = pse->depth;
8801 
8802 			if (se_depth <= pse_depth) {
8803 				put_prev_entity(cfs_rq_of(pse), pse);
8804 				pse = parent_entity(pse);
8805 			}
8806 			if (se_depth >= pse_depth) {
8807 				set_next_entity(cfs_rq_of(se), se);
8808 				se = parent_entity(se);
8809 			}
8810 		}
8811 
8812 		put_prev_entity(cfs_rq, pse);
8813 		set_next_entity(cfs_rq, se);
8814 	}
8815 
8816 	goto done;
8817 simple:
8818 #endif
8819 	if (prev)
8820 		put_prev_task(rq, prev);
8821 
8822 	do {
8823 		se = pick_next_entity(cfs_rq, NULL);
8824 		set_next_entity(cfs_rq, se);
8825 		cfs_rq = group_cfs_rq(se);
8826 	} while (cfs_rq);
8827 
8828 	p = task_of(se);
8829 
8830 done: __maybe_unused;
8831 #ifdef CONFIG_SMP
8832 	/*
8833 	 * Move the next running task to the front of
8834 	 * the list, so our cfs_tasks list becomes MRU
8835 	 * one.
8836 	 */
8837 	list_move(&p->se.group_node, &rq->cfs_tasks);
8838 #endif
8839 
8840 	if (hrtick_enabled_fair(rq))
8841 		hrtick_start_fair(rq, p);
8842 
8843 	update_misfit_status(p, rq);
8844 	sched_fair_update_stop_tick(rq, p);
8845 
8846 	return p;
8847 
8848 idle:
8849 	if (!rf)
8850 		return NULL;
8851 
8852 	new_tasks = newidle_balance(rq, rf);
8853 
8854 	/*
8855 	 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8856 	 * possible for any higher priority task to appear. In that case we
8857 	 * must re-start the pick_next_entity() loop.
8858 	 */
8859 	if (new_tasks < 0)
8860 		return RETRY_TASK;
8861 
8862 	if (new_tasks > 0)
8863 		goto again;
8864 
8865 	/*
8866 	 * rq is about to be idle, check if we need to update the
8867 	 * lost_idle_time of clock_pelt
8868 	 */
8869 	update_idle_rq_clock_pelt(rq);
8870 
8871 	return NULL;
8872 }
8873 
__pick_next_task_fair(struct rq * rq)8874 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8875 {
8876 	return pick_next_task_fair(rq, NULL, NULL);
8877 }
8878 
8879 /*
8880  * Account for a descheduled task:
8881  */
put_prev_task_fair(struct rq * rq,struct task_struct * prev)8882 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8883 {
8884 	struct sched_entity *se = &prev->se;
8885 	struct cfs_rq *cfs_rq;
8886 
8887 	for_each_sched_entity(se) {
8888 		cfs_rq = cfs_rq_of(se);
8889 		put_prev_entity(cfs_rq, se);
8890 	}
8891 }
8892 
8893 /*
8894  * sched_yield() is very simple
8895  */
yield_task_fair(struct rq * rq)8896 static void yield_task_fair(struct rq *rq)
8897 {
8898 	struct task_struct *curr = rq->curr;
8899 	struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8900 	struct sched_entity *se = &curr->se;
8901 
8902 	/*
8903 	 * Are we the only task in the tree?
8904 	 */
8905 	if (unlikely(rq->nr_running == 1))
8906 		return;
8907 
8908 	clear_buddies(cfs_rq, se);
8909 
8910 	update_rq_clock(rq);
8911 	/*
8912 	 * Update run-time statistics of the 'current'.
8913 	 */
8914 	update_curr(cfs_rq);
8915 	/*
8916 	 * Tell update_rq_clock() that we've just updated,
8917 	 * so we don't do microscopic update in schedule()
8918 	 * and double the fastpath cost.
8919 	 */
8920 	rq_clock_skip_update(rq);
8921 
8922 	se->deadline += calc_delta_fair(se->slice, se);
8923 }
8924 
yield_to_task_fair(struct rq * rq,struct task_struct * p)8925 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8926 {
8927 	struct sched_entity *se = &p->se;
8928 
8929 	/* throttled hierarchies are not runnable */
8930 	if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8931 		return false;
8932 
8933 	/* Tell the scheduler that we'd really like pse to run next. */
8934 	set_next_buddy(se);
8935 
8936 	yield_task_fair(rq);
8937 
8938 	return true;
8939 }
8940 
8941 #ifdef CONFIG_SMP
8942 /**************************************************
8943  * Fair scheduling class load-balancing methods.
8944  *
8945  * BASICS
8946  *
8947  * The purpose of load-balancing is to achieve the same basic fairness the
8948  * per-CPU scheduler provides, namely provide a proportional amount of compute
8949  * time to each task. This is expressed in the following equation:
8950  *
8951  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
8952  *
8953  * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8954  * W_i,0 is defined as:
8955  *
8956  *   W_i,0 = \Sum_j w_i,j                                             (2)
8957  *
8958  * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8959  * is derived from the nice value as per sched_prio_to_weight[].
8960  *
8961  * The weight average is an exponential decay average of the instantaneous
8962  * weight:
8963  *
8964  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
8965  *
8966  * C_i is the compute capacity of CPU i, typically it is the
8967  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8968  * can also include other factors [XXX].
8969  *
8970  * To achieve this balance we define a measure of imbalance which follows
8971  * directly from (1):
8972  *
8973  *   imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j }    (4)
8974  *
8975  * We them move tasks around to minimize the imbalance. In the continuous
8976  * function space it is obvious this converges, in the discrete case we get
8977  * a few fun cases generally called infeasible weight scenarios.
8978  *
8979  * [XXX expand on:
8980  *     - infeasible weights;
8981  *     - local vs global optima in the discrete case. ]
8982  *
8983  *
8984  * SCHED DOMAINS
8985  *
8986  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8987  * for all i,j solution, we create a tree of CPUs that follows the hardware
8988  * topology where each level pairs two lower groups (or better). This results
8989  * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8990  * tree to only the first of the previous level and we decrease the frequency
8991  * of load-balance at each level inv. proportional to the number of CPUs in
8992  * the groups.
8993  *
8994  * This yields:
8995  *
8996  *     log_2 n     1     n
8997  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
8998  *     i = 0      2^i   2^i
8999  *                               `- size of each group
9000  *         |         |     `- number of CPUs doing load-balance
9001  *         |         `- freq
9002  *         `- sum over all levels
9003  *
9004  * Coupled with a limit on how many tasks we can migrate every balance pass,
9005  * this makes (5) the runtime complexity of the balancer.
9006  *
9007  * An important property here is that each CPU is still (indirectly) connected
9008  * to every other CPU in at most O(log n) steps:
9009  *
9010  * The adjacency matrix of the resulting graph is given by:
9011  *
9012  *             log_2 n
9013  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
9014  *             k = 0
9015  *
9016  * And you'll find that:
9017  *
9018  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
9019  *
9020  * Showing there's indeed a path between every CPU in at most O(log n) steps.
9021  * The task movement gives a factor of O(m), giving a convergence complexity
9022  * of:
9023  *
9024  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
9025  *
9026  *
9027  * WORK CONSERVING
9028  *
9029  * In order to avoid CPUs going idle while there's still work to do, new idle
9030  * balancing is more aggressive and has the newly idle CPU iterate up the domain
9031  * tree itself instead of relying on other CPUs to bring it work.
9032  *
9033  * This adds some complexity to both (5) and (8) but it reduces the total idle
9034  * time.
9035  *
9036  * [XXX more?]
9037  *
9038  *
9039  * CGROUPS
9040  *
9041  * Cgroups make a horror show out of (2), instead of a simple sum we get:
9042  *
9043  *                                s_k,i
9044  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
9045  *                                 S_k
9046  *
9047  * Where
9048  *
9049  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
9050  *
9051  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9052  *
9053  * The big problem is S_k, its a global sum needed to compute a local (W_i)
9054  * property.
9055  *
9056  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9057  *      rewrite all of this once again.]
9058  */
9059 
9060 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9061 
9062 enum fbq_type { regular, remote, all };
9063 
9064 /*
9065  * 'group_type' describes the group of CPUs at the moment of load balancing.
9066  *
9067  * The enum is ordered by pulling priority, with the group with lowest priority
9068  * first so the group_type can simply be compared when selecting the busiest
9069  * group. See update_sd_pick_busiest().
9070  */
9071 enum group_type {
9072 	/* The group has spare capacity that can be used to run more tasks.  */
9073 	group_has_spare = 0,
9074 	/*
9075 	 * The group is fully used and the tasks don't compete for more CPU
9076 	 * cycles. Nevertheless, some tasks might wait before running.
9077 	 */
9078 	group_fully_busy,
9079 	/*
9080 	 * One task doesn't fit with CPU's capacity and must be migrated to a
9081 	 * more powerful CPU.
9082 	 */
9083 	group_misfit_task,
9084 	/*
9085 	 * Balance SMT group that's fully busy. Can benefit from migration
9086 	 * a task on SMT with busy sibling to another CPU on idle core.
9087 	 */
9088 	group_smt_balance,
9089 	/*
9090 	 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9091 	 * and the task should be migrated to it instead of running on the
9092 	 * current CPU.
9093 	 */
9094 	group_asym_packing,
9095 	/*
9096 	 * The tasks' affinity constraints previously prevented the scheduler
9097 	 * from balancing the load across the system.
9098 	 */
9099 	group_imbalanced,
9100 	/*
9101 	 * The CPU is overloaded and can't provide expected CPU cycles to all
9102 	 * tasks.
9103 	 */
9104 	group_overloaded
9105 };
9106 
9107 enum migration_type {
9108 	migrate_load = 0,
9109 	migrate_util,
9110 	migrate_task,
9111 	migrate_misfit
9112 };
9113 
9114 #define LBF_ALL_PINNED	0x01
9115 #define LBF_NEED_BREAK	0x02
9116 #define LBF_DST_PINNED  0x04
9117 #define LBF_SOME_PINNED	0x08
9118 #define LBF_ACTIVE_LB	0x10
9119 #ifdef CONFIG_SCHED_RTG
9120 #define LBF_IGNORE_PREFERRED_CLUSTER_TASKS 0x200
9121 #endif
9122 struct lb_env {
9123 	struct sched_domain	*sd;
9124 
9125 	struct rq		*src_rq;
9126 	int			src_cpu;
9127 
9128 	int			dst_cpu;
9129 	struct rq		*dst_rq;
9130 
9131 	struct cpumask		*dst_grpmask;
9132 	int			new_dst_cpu;
9133 	enum cpu_idle_type	idle;
9134 	long			imbalance;
9135 	/* The set of CPUs under consideration for load-balancing */
9136 	struct cpumask		*cpus;
9137 
9138 	unsigned int		flags;
9139 
9140 	unsigned int		loop;
9141 	unsigned int		loop_break;
9142 	unsigned int		loop_max;
9143 
9144 	enum fbq_type		fbq_type;
9145 	enum migration_type	migration_type;
9146 	struct list_head	tasks;
9147 };
9148 
9149 /*
9150  * Is this task likely cache-hot:
9151  */
task_hot(struct task_struct * p,struct lb_env * env)9152 static int task_hot(struct task_struct *p, struct lb_env *env)
9153 {
9154 	s64 delta;
9155 
9156 	lockdep_assert_rq_held(env->src_rq);
9157 
9158 	if (p->sched_class != &fair_sched_class)
9159 		return 0;
9160 
9161 	if (unlikely(task_has_idle_policy(p)))
9162 		return 0;
9163 
9164 	/* SMT siblings share cache */
9165 	if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9166 		return 0;
9167 
9168 	/*
9169 	 * Buddy candidates are cache hot:
9170 	 */
9171 	if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9172 	    (&p->se == cfs_rq_of(&p->se)->next))
9173 		return 1;
9174 
9175 	if (sysctl_sched_migration_cost == -1)
9176 		return 1;
9177 
9178 	/*
9179 	 * Don't migrate task if the task's cookie does not match
9180 	 * with the destination CPU's core cookie.
9181 	 */
9182 	if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9183 		return 1;
9184 
9185 	if (sysctl_sched_migration_cost == 0)
9186 		return 0;
9187 
9188 	delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9189 
9190 	return delta < (s64)sysctl_sched_migration_cost;
9191 }
9192 
9193 #ifdef CONFIG_NUMA_BALANCING
9194 /*
9195  * Returns 1, if task migration degrades locality
9196  * Returns 0, if task migration improves locality i.e migration preferred.
9197  * Returns -1, if task migration is not affected by locality.
9198  */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9199 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9200 {
9201 	struct numa_group *numa_group = rcu_dereference(p->numa_group);
9202 	unsigned long src_weight, dst_weight;
9203 	int src_nid, dst_nid, dist;
9204 
9205 	if (!static_branch_likely(&sched_numa_balancing))
9206 		return -1;
9207 
9208 	if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9209 		return -1;
9210 
9211 	src_nid = cpu_to_node(env->src_cpu);
9212 	dst_nid = cpu_to_node(env->dst_cpu);
9213 
9214 	if (src_nid == dst_nid)
9215 		return -1;
9216 
9217 	/* Migrating away from the preferred node is always bad. */
9218 	if (src_nid == p->numa_preferred_nid) {
9219 		if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9220 			return 1;
9221 		else
9222 			return -1;
9223 	}
9224 
9225 	/* Encourage migration to the preferred node. */
9226 	if (dst_nid == p->numa_preferred_nid)
9227 		return 0;
9228 
9229 	/* Leaving a core idle is often worse than degrading locality. */
9230 	if (env->idle == CPU_IDLE)
9231 		return -1;
9232 
9233 	dist = node_distance(src_nid, dst_nid);
9234 	if (numa_group) {
9235 		src_weight = group_weight(p, src_nid, dist);
9236 		dst_weight = group_weight(p, dst_nid, dist);
9237 	} else {
9238 		src_weight = task_weight(p, src_nid, dist);
9239 		dst_weight = task_weight(p, dst_nid, dist);
9240 	}
9241 
9242 	return dst_weight < src_weight;
9243 }
9244 
9245 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9246 static inline int migrate_degrades_locality(struct task_struct *p,
9247 					     struct lb_env *env)
9248 {
9249 	return -1;
9250 }
9251 #endif
9252 
9253 /*
9254  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9255  */
9256 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9257 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9258 {
9259 	int tsk_cache_hot;
9260 
9261 	lockdep_assert_rq_held(env->src_rq);
9262 	if (p->sched_task_hot)
9263 		p->sched_task_hot = 0;
9264 
9265 	/*
9266 	 * We do not migrate tasks that are:
9267 	 * 1) throttled_lb_pair, or
9268 	 * 2) cannot be migrated to this CPU due to cpus_ptr, or
9269 	 * 3) running (obviously), or
9270 	 * 4) are cache-hot on their current CPU.
9271 	 */
9272 	if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
9273 		return 0;
9274 
9275 	/* Disregard pcpu kthreads; they are where they need to be. */
9276 	if (kthread_is_per_cpu(p))
9277 		return 0;
9278 
9279 	if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9280 		int cpu;
9281 
9282 		schedstat_inc(p->stats.nr_failed_migrations_affine);
9283 
9284 		env->flags |= LBF_SOME_PINNED;
9285 
9286 		/*
9287 		 * Remember if this task can be migrated to any other CPU in
9288 		 * our sched_group. We may want to revisit it if we couldn't
9289 		 * meet load balance goals by pulling other tasks on src_cpu.
9290 		 *
9291 		 * Avoid computing new_dst_cpu
9292 		 * - for NEWLY_IDLE
9293 		 * - if we have already computed one in current iteration
9294 		 * - if it's an active balance
9295 		 */
9296 		if (env->idle == CPU_NEWLY_IDLE ||
9297 		    env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9298 			return 0;
9299 
9300 		/* Prevent to re-select dst_cpu via env's CPUs: */
9301 		for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
9302 			if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
9303 				env->flags |= LBF_DST_PINNED;
9304 				env->new_dst_cpu = cpu;
9305 				break;
9306 			}
9307 		}
9308 
9309 		return 0;
9310 	}
9311 
9312 	/* Record that we found at least one task that could run on dst_cpu */
9313 	env->flags &= ~LBF_ALL_PINNED;
9314 
9315 
9316 #ifdef CONFIG_SCHED_RTG
9317 	if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS &&
9318 			 !preferred_cluster(cpu_rq(env->dst_cpu)->cluster, p))
9319 		return 0;
9320 #endif
9321 
9322 	if (task_on_cpu(env->src_rq, p)) {
9323 		schedstat_inc(p->stats.nr_failed_migrations_running);
9324 		return 0;
9325 	}
9326 
9327 	/*
9328 	 * Aggressive migration if:
9329 	 * 1) active balance
9330 	 * 2) destination numa is preferred
9331 	 * 3) task is cache cold, or
9332 	 * 4) too many balance attempts have failed.
9333 	 */
9334 	if (env->flags & LBF_ACTIVE_LB)
9335 		return 1;
9336 
9337 	tsk_cache_hot = migrate_degrades_locality(p, env);
9338 	if (tsk_cache_hot == -1)
9339 		tsk_cache_hot = task_hot(p, env);
9340 
9341 	if (tsk_cache_hot <= 0 ||
9342 	    env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9343 		if (tsk_cache_hot == 1)
9344 			p->sched_task_hot = 1;
9345 		return 1;
9346 	}
9347 
9348 	schedstat_inc(p->stats.nr_failed_migrations_hot);
9349 	return 0;
9350 }
9351 
9352 /*
9353  * detach_task() -- detach the task for the migration specified in env
9354  */
detach_task(struct task_struct * p,struct lb_env * env)9355 static void detach_task(struct task_struct *p, struct lb_env *env)
9356 {
9357 	lockdep_assert_rq_held(env->src_rq);
9358 
9359 	if (p->sched_task_hot) {
9360 		p->sched_task_hot = 0;
9361 		schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9362 		schedstat_inc(p->stats.nr_forced_migrations);
9363 	}
9364 
9365 	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9366 #ifdef CONFIG_SCHED_WALT
9367 	double_lock_balance(env->src_rq, env->dst_rq);
9368 	if (!(env->src_rq->clock_update_flags & RQCF_UPDATED))
9369 		update_rq_clock(env->src_rq);
9370 #endif
9371 	set_task_cpu(p, env->dst_cpu);
9372 #ifdef CONFIG_SCHED_WALT
9373 	double_unlock_balance(env->src_rq, env->dst_rq);
9374 #endif
9375 }
9376 
9377 /*
9378  * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9379  * part of active balancing operations within "domain".
9380  *
9381  * Returns a task if successful and NULL otherwise.
9382  */
detach_one_task(struct lb_env * env)9383 static struct task_struct *detach_one_task(struct lb_env *env)
9384 {
9385 	struct task_struct *p;
9386 
9387 	lockdep_assert_rq_held(env->src_rq);
9388 
9389 	list_for_each_entry_reverse(p,
9390 			&env->src_rq->cfs_tasks, se.group_node) {
9391 		if (!can_migrate_task(p, env))
9392 			continue;
9393 
9394 		detach_task(p, env);
9395 
9396 		/*
9397 		 * Right now, this is only the second place where
9398 		 * lb_gained[env->idle] is updated (other is detach_tasks)
9399 		 * so we can safely collect stats here rather than
9400 		 * inside detach_tasks().
9401 		 */
9402 		schedstat_inc(env->sd->lb_gained[env->idle]);
9403 		return p;
9404 	}
9405 	return NULL;
9406 }
9407 
9408 /*
9409  * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9410  * busiest_rq, as part of a balancing operation within domain "sd".
9411  *
9412  * Returns number of detached tasks if successful and 0 otherwise.
9413  */
detach_tasks(struct lb_env * env)9414 static int detach_tasks(struct lb_env *env)
9415 {
9416 	struct list_head *tasks = &env->src_rq->cfs_tasks;
9417 	unsigned long util, load;
9418 	struct task_struct *p;
9419 	int detached = 0;
9420 #ifdef CONFIG_SCHED_RTG
9421 	int orig_loop = env->loop;
9422 #endif
9423 
9424 	lockdep_assert_rq_held(env->src_rq);
9425 
9426 	/*
9427 	 * Source run queue has been emptied by another CPU, clear
9428 	 * LBF_ALL_PINNED flag as we will not test any task.
9429 	 */
9430 	if (env->src_rq->nr_running <= 1) {
9431 		env->flags &= ~LBF_ALL_PINNED;
9432 		return 0;
9433 	}
9434 
9435 	if (env->imbalance <= 0)
9436 		return 0;
9437 
9438 #ifdef CONFIG_SCHED_RTG
9439 	if (!same_cluster(env->dst_cpu, env->src_cpu))
9440 		env->flags |= LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
9441 
9442 redo:
9443 #endif
9444 	while (!list_empty(tasks)) {
9445 		/*
9446 		 * We don't want to steal all, otherwise we may be treated likewise,
9447 		 * which could at worst lead to a livelock crash.
9448 		 */
9449 		if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
9450 			break;
9451 
9452 		env->loop++;
9453 		/* We've more or less seen every task there is, call it quits */
9454 		if (env->loop > env->loop_max)
9455 			break;
9456 
9457 		/* take a breather every nr_migrate tasks */
9458 		if (env->loop > env->loop_break) {
9459 			env->loop_break += SCHED_NR_MIGRATE_BREAK;
9460 			env->flags |= LBF_NEED_BREAK;
9461 			break;
9462 		}
9463 
9464 		p = list_last_entry(tasks, struct task_struct, se.group_node);
9465 
9466 		if (!can_migrate_task(p, env))
9467 			goto next;
9468 
9469 		switch (env->migration_type) {
9470 		case migrate_load:
9471 			/*
9472 			 * Depending of the number of CPUs and tasks and the
9473 			 * cgroup hierarchy, task_h_load() can return a null
9474 			 * value. Make sure that env->imbalance decreases
9475 			 * otherwise detach_tasks() will stop only after
9476 			 * detaching up to loop_max tasks.
9477 			 */
9478 			load = max_t(unsigned long, task_h_load(p), 1);
9479 
9480 			if (sched_feat(LB_MIN) &&
9481 			    load < 16 && !env->sd->nr_balance_failed)
9482 				goto next;
9483 
9484 			/*
9485 			 * Make sure that we don't migrate too much load.
9486 			 * Nevertheless, let relax the constraint if
9487 			 * scheduler fails to find a good waiting task to
9488 			 * migrate.
9489 			 */
9490 			if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9491 				goto next;
9492 
9493 			env->imbalance -= load;
9494 			break;
9495 
9496 		case migrate_util:
9497 			util = task_util_est(p);
9498 
9499 			if (util > env->imbalance)
9500 				goto next;
9501 
9502 			env->imbalance -= util;
9503 			break;
9504 
9505 		case migrate_task:
9506 			env->imbalance--;
9507 			break;
9508 
9509 		case migrate_misfit:
9510 			/* This is not a misfit task */
9511 			if (task_fits_cpu(p, env->src_cpu))
9512 				goto next;
9513 
9514 			env->imbalance = 0;
9515 			break;
9516 		}
9517 
9518 		detach_task(p, env);
9519 		list_add(&p->se.group_node, &env->tasks);
9520 
9521 		detached++;
9522 
9523 #ifdef CONFIG_PREEMPTION
9524 		/*
9525 		 * NEWIDLE balancing is a source of latency, so preemptible
9526 		 * kernels will stop after the first task is detached to minimize
9527 		 * the critical section.
9528 		 */
9529 		if (env->idle == CPU_NEWLY_IDLE)
9530 			break;
9531 #endif
9532 
9533 		/*
9534 		 * We only want to steal up to the prescribed amount of
9535 		 * load/util/tasks.
9536 		 */
9537 		if (env->imbalance <= 0)
9538 			break;
9539 
9540 		continue;
9541 next:
9542 		if (p->sched_task_hot)
9543 			schedstat_inc(p->stats.nr_failed_migrations_hot);
9544 
9545 		list_move(&p->se.group_node, tasks);
9546 	}
9547 
9548 #ifdef CONFIG_SCHED_RTG
9549 	if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS && !detached) {
9550 		tasks = &env->src_rq->cfs_tasks;
9551 		env->flags &= ~LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
9552 		env->loop = orig_loop;
9553 		goto redo;
9554 	}
9555 #endif
9556 
9557 	/*
9558 	 * Right now, this is one of only two places we collect this stat
9559 	 * so we can safely collect detach_one_task() stats here rather
9560 	 * than inside detach_one_task().
9561 	 */
9562 	schedstat_add(env->sd->lb_gained[env->idle], detached);
9563 
9564 	return detached;
9565 }
9566 
9567 /*
9568  * attach_task() -- attach the task detached by detach_task() to its new rq.
9569  */
attach_task(struct rq * rq,struct task_struct * p)9570 static void attach_task(struct rq *rq, struct task_struct *p)
9571 {
9572 	lockdep_assert_rq_held(rq);
9573 
9574 	WARN_ON_ONCE(task_rq(p) != rq);
9575 	activate_task(rq, p, ENQUEUE_NOCLOCK);
9576 	wakeup_preempt(rq, p, 0);
9577 }
9578 
9579 /*
9580  * attach_one_task() -- attaches the task returned from detach_one_task() to
9581  * its new rq.
9582  */
attach_one_task(struct rq * rq,struct task_struct * p)9583 static void attach_one_task(struct rq *rq, struct task_struct *p)
9584 {
9585 	struct rq_flags rf;
9586 
9587 	rq_lock(rq, &rf);
9588 	update_rq_clock(rq);
9589 	attach_task(rq, p);
9590 	rq_unlock(rq, &rf);
9591 }
9592 
9593 /*
9594  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9595  * new rq.
9596  */
attach_tasks(struct lb_env * env)9597 static void attach_tasks(struct lb_env *env)
9598 {
9599 	struct list_head *tasks = &env->tasks;
9600 	struct task_struct *p;
9601 	struct rq_flags rf;
9602 
9603 	rq_lock(env->dst_rq, &rf);
9604 	update_rq_clock(env->dst_rq);
9605 
9606 	while (!list_empty(tasks)) {
9607 		p = list_first_entry(tasks, struct task_struct, se.group_node);
9608 		list_del_init(&p->se.group_node);
9609 
9610 		attach_task(env->dst_rq, p);
9611 	}
9612 
9613 	rq_unlock(env->dst_rq, &rf);
9614 }
9615 
9616 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9617 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9618 {
9619 	if (cfs_rq->avg.load_avg)
9620 		return true;
9621 
9622 	if (cfs_rq->avg.util_avg)
9623 		return true;
9624 
9625 	return false;
9626 }
9627 
others_have_blocked(struct rq * rq)9628 static inline bool others_have_blocked(struct rq *rq)
9629 {
9630 	if (READ_ONCE(rq->avg_rt.util_avg))
9631 		return true;
9632 
9633 	if (READ_ONCE(rq->avg_dl.util_avg))
9634 		return true;
9635 
9636 	if (thermal_load_avg(rq))
9637 		return true;
9638 
9639 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
9640 	if (READ_ONCE(rq->avg_irq.util_avg))
9641 		return true;
9642 #endif
9643 
9644 	return false;
9645 }
9646 
update_blocked_load_tick(struct rq * rq)9647 static inline void update_blocked_load_tick(struct rq *rq)
9648 {
9649 	WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9650 }
9651 
update_blocked_load_status(struct rq * rq,bool has_blocked)9652 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9653 {
9654 	if (!has_blocked)
9655 		rq->has_blocked_load = 0;
9656 }
9657 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9658 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9659 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9660 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9661 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9662 #endif
9663 
__update_blocked_others(struct rq * rq,bool * done)9664 static bool __update_blocked_others(struct rq *rq, bool *done)
9665 {
9666 	const struct sched_class *curr_class;
9667 	u64 now = rq_clock_pelt(rq);
9668 	unsigned long thermal_pressure;
9669 	bool decayed;
9670 
9671 	/*
9672 	 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9673 	 * DL and IRQ signals have been updated before updating CFS.
9674 	 */
9675 	curr_class = rq->curr->sched_class;
9676 
9677 	thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9678 
9679 	decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9680 		  update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9681 		  update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9682 		  update_irq_load_avg(rq, 0);
9683 
9684 	if (others_have_blocked(rq))
9685 		*done = false;
9686 
9687 	return decayed;
9688 }
9689 
9690 #ifdef CONFIG_FAIR_GROUP_SCHED
9691 
__update_blocked_fair(struct rq * rq,bool * done)9692 static bool __update_blocked_fair(struct rq *rq, bool *done)
9693 {
9694 	struct cfs_rq *cfs_rq, *pos;
9695 	bool decayed = false;
9696 	int cpu = cpu_of(rq);
9697 
9698 	/*
9699 	 * Iterates the task_group tree in a bottom up fashion, see
9700 	 * list_add_leaf_cfs_rq() for details.
9701 	 */
9702 	for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9703 		struct sched_entity *se;
9704 
9705 		if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9706 			update_tg_load_avg(cfs_rq);
9707 
9708 			if (cfs_rq->nr_running == 0)
9709 				update_idle_cfs_rq_clock_pelt(cfs_rq);
9710 
9711 			if (cfs_rq == &rq->cfs)
9712 				decayed = true;
9713 		}
9714 
9715 		/* Propagate pending load changes to the parent, if any: */
9716 		se = cfs_rq->tg->se[cpu];
9717 		if (se && !skip_blocked_update(se))
9718 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9719 
9720 		/*
9721 		 * There can be a lot of idle CPU cgroups.  Don't let fully
9722 		 * decayed cfs_rqs linger on the list.
9723 		 */
9724 		if (cfs_rq_is_decayed(cfs_rq))
9725 			list_del_leaf_cfs_rq(cfs_rq);
9726 
9727 		/* Don't need periodic decay once load/util_avg are null */
9728 		if (cfs_rq_has_blocked(cfs_rq))
9729 			*done = false;
9730 	}
9731 
9732 	return decayed;
9733 }
9734 
9735 /*
9736  * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9737  * This needs to be done in a top-down fashion because the load of a child
9738  * group is a fraction of its parents load.
9739  */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9740 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9741 {
9742 	struct rq *rq = rq_of(cfs_rq);
9743 	struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9744 	unsigned long now = jiffies;
9745 	unsigned long load;
9746 
9747 	if (cfs_rq->last_h_load_update == now)
9748 		return;
9749 
9750 	WRITE_ONCE(cfs_rq->h_load_next, NULL);
9751 	for_each_sched_entity(se) {
9752 		cfs_rq = cfs_rq_of(se);
9753 		WRITE_ONCE(cfs_rq->h_load_next, se);
9754 		if (cfs_rq->last_h_load_update == now)
9755 			break;
9756 	}
9757 
9758 	if (!se) {
9759 		cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9760 		cfs_rq->last_h_load_update = now;
9761 	}
9762 
9763 	while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9764 		load = cfs_rq->h_load;
9765 		load = div64_ul(load * se->avg.load_avg,
9766 			cfs_rq_load_avg(cfs_rq) + 1);
9767 		cfs_rq = group_cfs_rq(se);
9768 		cfs_rq->h_load = load;
9769 		cfs_rq->last_h_load_update = now;
9770 	}
9771 }
9772 
task_h_load(struct task_struct * p)9773 static unsigned long task_h_load(struct task_struct *p)
9774 {
9775 	struct cfs_rq *cfs_rq = task_cfs_rq(p);
9776 
9777 	update_cfs_rq_h_load(cfs_rq);
9778 	return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9779 			cfs_rq_load_avg(cfs_rq) + 1);
9780 }
9781 #else
__update_blocked_fair(struct rq * rq,bool * done)9782 static bool __update_blocked_fair(struct rq *rq, bool *done)
9783 {
9784 	struct cfs_rq *cfs_rq = &rq->cfs;
9785 	bool decayed;
9786 
9787 	decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9788 	if (cfs_rq_has_blocked(cfs_rq))
9789 		*done = false;
9790 
9791 	return decayed;
9792 }
9793 
task_h_load(struct task_struct * p)9794 static unsigned long task_h_load(struct task_struct *p)
9795 {
9796 	return p->se.avg.load_avg;
9797 }
9798 #endif
9799 
update_blocked_averages(int cpu)9800 static void update_blocked_averages(int cpu)
9801 {
9802 	bool decayed = false, done = true;
9803 	struct rq *rq = cpu_rq(cpu);
9804 	struct rq_flags rf;
9805 
9806 	rq_lock_irqsave(rq, &rf);
9807 	update_blocked_load_tick(rq);
9808 	update_rq_clock(rq);
9809 
9810 	decayed |= __update_blocked_others(rq, &done);
9811 	decayed |= __update_blocked_fair(rq, &done);
9812 
9813 	update_blocked_load_status(rq, !done);
9814 	if (decayed)
9815 		cpufreq_update_util(rq, 0);
9816 	rq_unlock_irqrestore(rq, &rf);
9817 }
9818 
9819 /********** Helpers for find_busiest_group ************************/
9820 
9821 /*
9822  * sg_lb_stats - stats of a sched_group required for load_balancing
9823  */
9824 struct sg_lb_stats {
9825 	unsigned long avg_load; /*Avg load across the CPUs of the group */
9826 	unsigned long group_load; /* Total load over the CPUs of the group */
9827 	unsigned long group_capacity;
9828 	unsigned long group_util; /* Total utilization over the CPUs of the group */
9829 	unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9830 	unsigned int sum_nr_running; /* Nr of tasks running in the group */
9831 	unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9832 	unsigned int idle_cpus;
9833 	unsigned int group_weight;
9834 	enum group_type group_type;
9835 	unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9836 	unsigned int group_smt_balance;  /* Task on busy SMT be moved */
9837 	unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9838 #ifdef CONFIG_NUMA_BALANCING
9839 	unsigned int nr_numa_running;
9840 	unsigned int nr_preferred_running;
9841 #endif
9842 };
9843 
9844 /*
9845  * sd_lb_stats - Structure to store the statistics of a sched_domain
9846  *		 during load balancing.
9847  */
9848 struct sd_lb_stats {
9849 	struct sched_group *busiest;	/* Busiest group in this sd */
9850 	struct sched_group *local;	/* Local group in this sd */
9851 	unsigned long total_load;	/* Total load of all groups in sd */
9852 	unsigned long total_capacity;	/* Total capacity of all groups in sd */
9853 	unsigned long avg_load;	/* Average load across all groups in sd */
9854 	unsigned int prefer_sibling; /* tasks should go to sibling first */
9855 
9856 	struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9857 	struct sg_lb_stats local_stat;	/* Statistics of the local group */
9858 };
9859 
init_sd_lb_stats(struct sd_lb_stats * sds)9860 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9861 {
9862 	/*
9863 	 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9864 	 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9865 	 * We must however set busiest_stat::group_type and
9866 	 * busiest_stat::idle_cpus to the worst busiest group because
9867 	 * update_sd_pick_busiest() reads these before assignment.
9868 	 */
9869 	*sds = (struct sd_lb_stats){
9870 		.busiest = NULL,
9871 		.local = NULL,
9872 		.total_load = 0UL,
9873 		.total_capacity = 0UL,
9874 		.busiest_stat = {
9875 			.idle_cpus = UINT_MAX,
9876 			.group_type = group_has_spare,
9877 		},
9878 	};
9879 }
9880 
scale_rt_capacity(int cpu)9881 static unsigned long scale_rt_capacity(int cpu)
9882 {
9883 	struct rq *rq = cpu_rq(cpu);
9884 	unsigned long max = arch_scale_cpu_capacity(cpu);
9885 	unsigned long used, free;
9886 	unsigned long irq;
9887 
9888 	irq = cpu_util_irq(rq);
9889 
9890 	if (unlikely(irq >= max))
9891 		return 1;
9892 
9893 	/*
9894 	 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9895 	 * (running and not running) with weights 0 and 1024 respectively.
9896 	 * avg_thermal.load_avg tracks thermal pressure and the weighted
9897 	 * average uses the actual delta max capacity(load).
9898 	 */
9899 	used = READ_ONCE(rq->avg_rt.util_avg);
9900 	used += READ_ONCE(rq->avg_dl.util_avg);
9901 	used += thermal_load_avg(rq);
9902 
9903 	if (unlikely(used >= max))
9904 		return 1;
9905 
9906 	free = max - used;
9907 
9908 	return scale_irq_capacity(free, irq, max);
9909 }
9910 
update_cpu_capacity(struct sched_domain * sd,int cpu)9911 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9912 {
9913 	unsigned long capacity = scale_rt_capacity(cpu);
9914 	struct sched_group *sdg = sd->groups;
9915 
9916 	cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
9917 
9918 	if (!capacity)
9919 		capacity = 1;
9920 
9921 	cpu_rq(cpu)->cpu_capacity = capacity;
9922 	trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9923 
9924 	sdg->sgc->capacity = capacity;
9925 	sdg->sgc->min_capacity = capacity;
9926 	sdg->sgc->max_capacity = capacity;
9927 }
9928 
update_group_capacity(struct sched_domain * sd,int cpu)9929 void update_group_capacity(struct sched_domain *sd, int cpu)
9930 {
9931 	struct sched_domain *child = sd->child;
9932 	struct sched_group *group, *sdg = sd->groups;
9933 	unsigned long capacity, min_capacity, max_capacity;
9934 	unsigned long interval;
9935 
9936 	interval = msecs_to_jiffies(sd->balance_interval);
9937 	interval = clamp(interval, 1UL, max_load_balance_interval);
9938 	sdg->sgc->next_update = jiffies + interval;
9939 
9940 	if (!child) {
9941 		update_cpu_capacity(sd, cpu);
9942 		return;
9943 	}
9944 
9945 	capacity = 0;
9946 	min_capacity = ULONG_MAX;
9947 	max_capacity = 0;
9948 
9949 	if (child->flags & SD_OVERLAP) {
9950 		/*
9951 		 * SD_OVERLAP domains cannot assume that child groups
9952 		 * span the current group.
9953 		 */
9954 
9955 		for_each_cpu(cpu, sched_group_span(sdg)) {
9956 			unsigned long cpu_cap = capacity_of(cpu);
9957 
9958 			if (cpu_isolated(cpu))
9959 				continue;
9960 
9961 			capacity += cpu_cap;
9962 			min_capacity = min(cpu_cap, min_capacity);
9963 			max_capacity = max(cpu_cap, max_capacity);
9964 		}
9965 	} else  {
9966 		/*
9967 		 * !SD_OVERLAP domains can assume that child groups
9968 		 * span the current group.
9969 		 */
9970 
9971 		group = child->groups;
9972 		do {
9973 			struct sched_group_capacity *sgc = group->sgc;
9974 			__maybe_unused cpumask_t *cpus =
9975 					sched_group_span(group);
9976 
9977 			if (!cpu_isolated(cpumask_first(cpus))) {
9978 				capacity += sgc->capacity;
9979 				min_capacity = min(sgc->min_capacity,
9980 							min_capacity);
9981 				max_capacity = max(sgc->max_capacity,
9982 							max_capacity);
9983 			}
9984 			group = group->next;
9985 		} while (group != child->groups);
9986 	}
9987 
9988 	sdg->sgc->capacity = capacity;
9989 	sdg->sgc->min_capacity = min_capacity;
9990 	sdg->sgc->max_capacity = max_capacity;
9991 }
9992 
9993 /*
9994  * Check whether the capacity of the rq has been noticeably reduced by side
9995  * activity. The imbalance_pct is used for the threshold.
9996  * Return true is the capacity is reduced
9997  */
9998 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)9999 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10000 {
10001 	return ((rq->cpu_capacity * sd->imbalance_pct) <
10002 				(rq->cpu_capacity_orig * 100));
10003 }
10004 
10005 /*
10006  * Check whether a rq has a misfit task and if it looks like we can actually
10007  * help that task: we can migrate the task to a CPU of higher capacity, or
10008  * the task's current CPU is heavily pressured.
10009  */
check_misfit_status(struct rq * rq,struct sched_domain * sd)10010 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
10011 {
10012 	return rq->misfit_task_load &&
10013 		(rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
10014 		 check_cpu_capacity(rq, sd));
10015 }
10016 
10017 /*
10018  * Group imbalance indicates (and tries to solve) the problem where balancing
10019  * groups is inadequate due to ->cpus_ptr constraints.
10020  *
10021  * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10022  * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10023  * Something like:
10024  *
10025  *	{ 0 1 2 3 } { 4 5 6 7 }
10026  *	        *     * * *
10027  *
10028  * If we were to balance group-wise we'd place two tasks in the first group and
10029  * two tasks in the second group. Clearly this is undesired as it will overload
10030  * cpu 3 and leave one of the CPUs in the second group unused.
10031  *
10032  * The current solution to this issue is detecting the skew in the first group
10033  * by noticing the lower domain failed to reach balance and had difficulty
10034  * moving tasks due to affinity constraints.
10035  *
10036  * When this is so detected; this group becomes a candidate for busiest; see
10037  * update_sd_pick_busiest(). And calculate_imbalance() and
10038  * find_busiest_group() avoid some of the usual balance conditions to allow it
10039  * to create an effective group imbalance.
10040  *
10041  * This is a somewhat tricky proposition since the next run might not find the
10042  * group imbalance and decide the groups need to be balanced again. A most
10043  * subtle and fragile situation.
10044  */
10045 
sg_imbalanced(struct sched_group * group)10046 static inline int sg_imbalanced(struct sched_group *group)
10047 {
10048 	return group->sgc->imbalance;
10049 }
10050 
10051 /*
10052  * group_has_capacity returns true if the group has spare capacity that could
10053  * be used by some tasks.
10054  * We consider that a group has spare capacity if the number of task is
10055  * smaller than the number of CPUs or if the utilization is lower than the
10056  * available capacity for CFS tasks.
10057  * For the latter, we use a threshold to stabilize the state, to take into
10058  * account the variance of the tasks' load and to return true if the available
10059  * capacity in meaningful for the load balancer.
10060  * As an example, an available capacity of 1% can appear but it doesn't make
10061  * any benefit for the load balance.
10062  */
10063 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10064 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10065 {
10066 	if (sgs->sum_nr_running < sgs->group_weight)
10067 		return true;
10068 
10069 	if ((sgs->group_capacity * imbalance_pct) <
10070 			(sgs->group_runnable * 100))
10071 		return false;
10072 
10073 	if ((sgs->group_capacity * 100) >
10074 			(sgs->group_util * imbalance_pct))
10075 		return true;
10076 
10077 	return false;
10078 }
10079 
10080 /*
10081  *  group_is_overloaded returns true if the group has more tasks than it can
10082  *  handle.
10083  *  group_is_overloaded is not equals to !group_has_capacity because a group
10084  *  with the exact right number of tasks, has no more spare capacity but is not
10085  *  overloaded so both group_has_capacity and group_is_overloaded return
10086  *  false.
10087  */
10088 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10089 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10090 {
10091 	if (sgs->sum_nr_running <= sgs->group_weight)
10092 		return false;
10093 
10094 	if ((sgs->group_capacity * 100) <
10095 			(sgs->group_util * imbalance_pct))
10096 		return true;
10097 
10098 	if ((sgs->group_capacity * imbalance_pct) <
10099 			(sgs->group_runnable * 100))
10100 		return true;
10101 
10102 	return false;
10103 }
10104 
10105 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10106 group_type group_classify(unsigned int imbalance_pct,
10107 			  struct sched_group *group,
10108 			  struct sg_lb_stats *sgs)
10109 {
10110 	if (group_is_overloaded(imbalance_pct, sgs))
10111 		return group_overloaded;
10112 
10113 	if (sg_imbalanced(group))
10114 		return group_imbalanced;
10115 
10116 	if (sgs->group_asym_packing)
10117 		return group_asym_packing;
10118 
10119 	if (sgs->group_smt_balance)
10120 		return group_smt_balance;
10121 
10122 	if (sgs->group_misfit_task_load)
10123 		return group_misfit_task;
10124 
10125 	if (!group_has_capacity(imbalance_pct, sgs))
10126 		return group_fully_busy;
10127 
10128 	return group_has_spare;
10129 }
10130 
10131 /**
10132  * sched_use_asym_prio - Check whether asym_packing priority must be used
10133  * @sd:		The scheduling domain of the load balancing
10134  * @cpu:	A CPU
10135  *
10136  * Always use CPU priority when balancing load between SMT siblings. When
10137  * balancing load between cores, it is not sufficient that @cpu is idle. Only
10138  * use CPU priority if the whole core is idle.
10139  *
10140  * Returns: True if the priority of @cpu must be followed. False otherwise.
10141  */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10142 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10143 {
10144 	if (!sched_smt_active())
10145 		return true;
10146 
10147 	return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10148 }
10149 
10150 /**
10151  * sched_asym - Check if the destination CPU can do asym_packing load balance
10152  * @env:	The load balancing environment
10153  * @sds:	Load-balancing data with statistics of the local group
10154  * @sgs:	Load-balancing statistics of the candidate busiest group
10155  * @group:	The candidate busiest group
10156  *
10157  * @env::dst_cpu can do asym_packing if it has higher priority than the
10158  * preferred CPU of @group.
10159  *
10160  * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
10161  * can do asym_packing balance only if all its SMT siblings are idle. Also, it
10162  * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
10163  * imbalances in the number of CPUS are dealt with in find_busiest_group().
10164  *
10165  * If we are balancing load within an SMT core, or at PKG domain level, always
10166  * proceed.
10167  *
10168  * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10169  * otherwise.
10170  */
10171 static inline bool
sched_asym(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * sgs,struct sched_group * group)10172 sched_asym(struct lb_env *env, struct sd_lb_stats *sds,  struct sg_lb_stats *sgs,
10173 	   struct sched_group *group)
10174 {
10175 	/* Ensure that the whole local core is idle, if applicable. */
10176 	if (!sched_use_asym_prio(env->sd, env->dst_cpu))
10177 		return false;
10178 
10179 	/*
10180 	 * CPU priorities does not make sense for SMT cores with more than one
10181 	 * busy sibling.
10182 	 */
10183 	if (group->flags & SD_SHARE_CPUCAPACITY) {
10184 		if (sgs->group_weight - sgs->idle_cpus != 1)
10185 			return false;
10186 	}
10187 
10188 	return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
10189 }
10190 
10191 /* 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)10192 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10193 				    struct sched_group *sg2)
10194 {
10195 	if (!sg1 || !sg2)
10196 		return false;
10197 
10198 	return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10199 		(sg2->flags & SD_SHARE_CPUCAPACITY);
10200 }
10201 
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10202 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10203 			       struct sched_group *group)
10204 {
10205 	if (env->idle == CPU_NOT_IDLE)
10206 		return false;
10207 
10208 	/*
10209 	 * For SMT source group, it is better to move a task
10210 	 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10211 	 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10212 	 * will not be on.
10213 	 */
10214 	if (group->flags & SD_SHARE_CPUCAPACITY &&
10215 	    sgs->sum_h_nr_running > 1)
10216 		return true;
10217 
10218 	return false;
10219 }
10220 
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10221 static inline long sibling_imbalance(struct lb_env *env,
10222 				    struct sd_lb_stats *sds,
10223 				    struct sg_lb_stats *busiest,
10224 				    struct sg_lb_stats *local)
10225 {
10226 	int ncores_busiest, ncores_local;
10227 	long imbalance;
10228 
10229 	if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
10230 		return 0;
10231 
10232 	ncores_busiest = sds->busiest->cores;
10233 	ncores_local = sds->local->cores;
10234 
10235 	if (ncores_busiest == ncores_local) {
10236 		imbalance = busiest->sum_nr_running;
10237 		lsub_positive(&imbalance, local->sum_nr_running);
10238 		return imbalance;
10239 	}
10240 
10241 	/* Balance such that nr_running/ncores ratio are same on both groups */
10242 	imbalance = ncores_local * busiest->sum_nr_running;
10243 	lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10244 	/* Normalize imbalance and do rounding on normalization */
10245 	imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10246 	imbalance /= ncores_local + ncores_busiest;
10247 
10248 	/* Take advantage of resource in an empty sched group */
10249 	if (imbalance <= 1 && local->sum_nr_running == 0 &&
10250 	    busiest->sum_nr_running > 1)
10251 		imbalance = 2;
10252 
10253 	return imbalance;
10254 }
10255 
10256 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10257 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10258 {
10259 	/*
10260 	 * When there is more than 1 task, the group_overloaded case already
10261 	 * takes care of cpu with reduced capacity
10262 	 */
10263 	if (rq->cfs.h_nr_running != 1)
10264 		return false;
10265 
10266 	return check_cpu_capacity(rq, sd);
10267 }
10268 
10269 /**
10270  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10271  * @env: The load balancing environment.
10272  * @sds: Load-balancing data with statistics of the local group.
10273  * @group: sched_group whose statistics are to be updated.
10274  * @sgs: variable to hold the statistics for this group.
10275  * @sg_status: Holds flag indicating the status of the sched_group
10276  */
update_sg_lb_stats(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * group,struct sg_lb_stats * sgs,int * sg_status)10277 static inline void update_sg_lb_stats(struct lb_env *env,
10278 				      struct sd_lb_stats *sds,
10279 				      struct sched_group *group,
10280 				      struct sg_lb_stats *sgs,
10281 				      int *sg_status)
10282 {
10283 	int i, nr_running, local_group;
10284 
10285 	memset(sgs, 0, sizeof(*sgs));
10286 
10287 	local_group = group == sds->local;
10288 
10289 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10290 		struct rq *rq = cpu_rq(i);
10291 		unsigned long load = cpu_load(rq);
10292 		if (cpu_isolated(i))
10293 			continue;
10294 
10295 		sgs->group_load += load;
10296 		sgs->group_util += cpu_util_cfs(i);
10297 		sgs->group_runnable += cpu_runnable(rq);
10298 		sgs->sum_h_nr_running += rq->cfs.h_nr_running;
10299 
10300 		nr_running = rq->nr_running;
10301 		sgs->sum_nr_running += nr_running;
10302 
10303 		if (nr_running > 1)
10304 			*sg_status |= SG_OVERLOAD;
10305 
10306 		if (cpu_overutilized(i))
10307 			*sg_status |= SG_OVERUTILIZED;
10308 
10309 #ifdef CONFIG_NUMA_BALANCING
10310 		sgs->nr_numa_running += rq->nr_numa_running;
10311 		sgs->nr_preferred_running += rq->nr_preferred_running;
10312 #endif
10313 		/*
10314 		 * No need to call idle_cpu() if nr_running is not 0
10315 		 */
10316 		if (!nr_running && idle_cpu(i)) {
10317 			sgs->idle_cpus++;
10318 			/* Idle cpu can't have misfit task */
10319 			continue;
10320 		}
10321 
10322 		if (local_group)
10323 			continue;
10324 
10325 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10326 			/* Check for a misfit task on the cpu */
10327 			if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10328 				sgs->group_misfit_task_load = rq->misfit_task_load;
10329 				*sg_status |= SG_OVERLOAD;
10330 			}
10331 		} else if ((env->idle != CPU_NOT_IDLE) &&
10332 			   sched_reduced_capacity(rq, env->sd)) {
10333 			/* Check for a task running on a CPU with reduced capacity */
10334 			if (sgs->group_misfit_task_load < load)
10335 				sgs->group_misfit_task_load = load;
10336 		}
10337 	}
10338 
10339 	sgs->group_capacity = group->sgc->capacity;
10340 
10341 	sgs->group_weight = group->group_weight;
10342 
10343 	/* Isolated CPU has no weight */
10344 	if (!group->group_weight) {
10345 		sgs->group_capacity = 0;
10346 		sgs->avg_load = 0;
10347 		sgs->group_type = group_has_spare;
10348 		sgs->group_weight = group->group_weight;
10349 		return;
10350 	}
10351 
10352 	/* Check if dst CPU is idle and preferred to this group */
10353 	if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
10354 	    env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
10355 	    sched_asym(env, sds, sgs, group)) {
10356 		sgs->group_asym_packing = 1;
10357 	}
10358 
10359 	/* Check for loaded SMT group to be balanced to dst CPU */
10360 	if (!local_group && smt_balance(env, sgs, group))
10361 		sgs->group_smt_balance = 1;
10362 
10363 	sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10364 
10365 	/* Computing avg_load makes sense only when group is overloaded */
10366 	if (sgs->group_type == group_overloaded)
10367 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10368 				sgs->group_capacity;
10369 }
10370 
10371 /**
10372  * update_sd_pick_busiest - return 1 on busiest group
10373  * @env: The load balancing environment.
10374  * @sds: sched_domain statistics
10375  * @sg: sched_group candidate to be checked for being the busiest
10376  * @sgs: sched_group statistics
10377  *
10378  * Determine if @sg is a busier group than the previously selected
10379  * busiest group.
10380  *
10381  * Return: %true if @sg is a busier group than the previously selected
10382  * busiest group. %false otherwise.
10383  */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10384 static bool update_sd_pick_busiest(struct lb_env *env,
10385 				   struct sd_lb_stats *sds,
10386 				   struct sched_group *sg,
10387 				   struct sg_lb_stats *sgs)
10388 {
10389 	struct sg_lb_stats *busiest = &sds->busiest_stat;
10390 
10391 	/* Make sure that there is at least one task to pull */
10392 	if (!sgs->sum_h_nr_running)
10393 		return false;
10394 
10395 	/*
10396 	 * Don't try to pull misfit tasks we can't help.
10397 	 * We can use max_capacity here as reduction in capacity on some
10398 	 * CPUs in the group should either be possible to resolve
10399 	 * internally or be covered by avg_load imbalance (eventually).
10400 	 */
10401 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10402 	    (sgs->group_type == group_misfit_task) &&
10403 	    (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10404 	     sds->local_stat.group_type != group_has_spare))
10405 		return false;
10406 
10407 	if (sgs->group_type > busiest->group_type)
10408 		return true;
10409 
10410 	if (sgs->group_type < busiest->group_type)
10411 		return false;
10412 
10413 	/*
10414 	 * The candidate and the current busiest group are the same type of
10415 	 * group. Let check which one is the busiest according to the type.
10416 	 */
10417 
10418 	switch (sgs->group_type) {
10419 	case group_overloaded:
10420 		/* Select the overloaded group with highest avg_load. */
10421 		if (sgs->avg_load <= busiest->avg_load)
10422 			return false;
10423 		break;
10424 
10425 	case group_imbalanced:
10426 		/*
10427 		 * Select the 1st imbalanced group as we don't have any way to
10428 		 * choose one more than another.
10429 		 */
10430 		return false;
10431 
10432 	case group_asym_packing:
10433 		/* Prefer to move from lowest priority CPU's work */
10434 		if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
10435 			return false;
10436 		break;
10437 
10438 	case group_misfit_task:
10439 		/*
10440 		 * If we have more than one misfit sg go with the biggest
10441 		 * misfit.
10442 		 */
10443 		if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
10444 			return false;
10445 		break;
10446 
10447 	case group_smt_balance:
10448 		/*
10449 		 * Check if we have spare CPUs on either SMT group to
10450 		 * choose has spare or fully busy handling.
10451 		 */
10452 		if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10453 			goto has_spare;
10454 
10455 		fallthrough;
10456 
10457 	case group_fully_busy:
10458 		/*
10459 		 * Select the fully busy group with highest avg_load. In
10460 		 * theory, there is no need to pull task from such kind of
10461 		 * group because tasks have all compute capacity that they need
10462 		 * but we can still improve the overall throughput by reducing
10463 		 * contention when accessing shared HW resources.
10464 		 *
10465 		 * XXX for now avg_load is not computed and always 0 so we
10466 		 * select the 1st one, except if @sg is composed of SMT
10467 		 * siblings.
10468 		 */
10469 
10470 		if (sgs->avg_load < busiest->avg_load)
10471 			return false;
10472 
10473 		if (sgs->avg_load == busiest->avg_load) {
10474 			/*
10475 			 * SMT sched groups need more help than non-SMT groups.
10476 			 * If @sg happens to also be SMT, either choice is good.
10477 			 */
10478 			if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10479 				return false;
10480 		}
10481 
10482 		break;
10483 
10484 	case group_has_spare:
10485 		/*
10486 		 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10487 		 * as we do not want to pull task off SMT core with one task
10488 		 * and make the core idle.
10489 		 */
10490 		if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10491 			if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10492 				return false;
10493 			else
10494 				return true;
10495 		}
10496 has_spare:
10497 
10498 		/*
10499 		 * Select not overloaded group with lowest number of idle cpus
10500 		 * and highest number of running tasks. We could also compare
10501 		 * the spare capacity which is more stable but it can end up
10502 		 * that the group has less spare capacity but finally more idle
10503 		 * CPUs which means less opportunity to pull tasks.
10504 		 */
10505 		if (sgs->idle_cpus > busiest->idle_cpus)
10506 			return false;
10507 		else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10508 			 (sgs->sum_nr_running <= busiest->sum_nr_running))
10509 			return false;
10510 
10511 		break;
10512 	}
10513 
10514 	/*
10515 	 * Candidate sg has no more than one task per CPU and has higher
10516 	 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10517 	 * throughput. Maximize throughput, power/energy consequences are not
10518 	 * considered.
10519 	 */
10520 	if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10521 	    (sgs->group_type <= group_fully_busy) &&
10522 	    (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10523 		return false;
10524 
10525 	return true;
10526 }
10527 
10528 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10529 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10530 {
10531 	if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10532 		return regular;
10533 	if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10534 		return remote;
10535 	return all;
10536 }
10537 
fbq_classify_rq(struct rq * rq)10538 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10539 {
10540 	if (rq->nr_running > rq->nr_numa_running)
10541 		return regular;
10542 	if (rq->nr_running > rq->nr_preferred_running)
10543 		return remote;
10544 	return all;
10545 }
10546 #else
fbq_classify_group(struct sg_lb_stats * sgs)10547 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10548 {
10549 	return all;
10550 }
10551 
fbq_classify_rq(struct rq * rq)10552 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10553 {
10554 	return regular;
10555 }
10556 #endif /* CONFIG_NUMA_BALANCING */
10557 
10558 
10559 struct sg_lb_stats;
10560 
10561 /*
10562  * task_running_on_cpu - return 1 if @p is running on @cpu.
10563  */
10564 
task_running_on_cpu(int cpu,struct task_struct * p)10565 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10566 {
10567 	/* Task has no contribution or is new */
10568 	if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10569 		return 0;
10570 
10571 	if (task_on_rq_queued(p))
10572 		return 1;
10573 
10574 	return 0;
10575 }
10576 
10577 /**
10578  * idle_cpu_without - would a given CPU be idle without p ?
10579  * @cpu: the processor on which idleness is tested.
10580  * @p: task which should be ignored.
10581  *
10582  * Return: 1 if the CPU would be idle. 0 otherwise.
10583  */
idle_cpu_without(int cpu,struct task_struct * p)10584 static int idle_cpu_without(int cpu, struct task_struct *p)
10585 {
10586 	struct rq *rq = cpu_rq(cpu);
10587 
10588 	if (rq->curr != rq->idle && rq->curr != p)
10589 		return 0;
10590 
10591 	/*
10592 	 * rq->nr_running can't be used but an updated version without the
10593 	 * impact of p on cpu must be used instead. The updated nr_running
10594 	 * be computed and tested before calling idle_cpu_without().
10595 	 */
10596 
10597 #ifdef CONFIG_SMP
10598 	if (rq->ttwu_pending)
10599 		return 0;
10600 #endif
10601 
10602 	return 1;
10603 }
10604 
10605 /*
10606  * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10607  * @sd: The sched_domain level to look for idlest group.
10608  * @group: sched_group whose statistics are to be updated.
10609  * @sgs: variable to hold the statistics for this group.
10610  * @p: The task for which we look for the idlest group/CPU.
10611  */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10612 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10613 					  struct sched_group *group,
10614 					  struct sg_lb_stats *sgs,
10615 					  struct task_struct *p)
10616 {
10617 	int i, nr_running;
10618 
10619 	memset(sgs, 0, sizeof(*sgs));
10620 
10621 	/* Assume that task can't fit any CPU of the group */
10622 	if (sd->flags & SD_ASYM_CPUCAPACITY)
10623 		sgs->group_misfit_task_load = 1;
10624 
10625 	for_each_cpu(i, sched_group_span(group)) {
10626 		struct rq *rq = cpu_rq(i);
10627 		unsigned int local;
10628 
10629 		sgs->group_load += cpu_load_without(rq, p);
10630 		sgs->group_util += cpu_util_without(i, p);
10631 		sgs->group_runnable += cpu_runnable_without(rq, p);
10632 		local = task_running_on_cpu(i, p);
10633 		sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10634 
10635 		nr_running = rq->nr_running - local;
10636 		sgs->sum_nr_running += nr_running;
10637 
10638 		/*
10639 		 * No need to call idle_cpu_without() if nr_running is not 0
10640 		 */
10641 		if (!nr_running && idle_cpu_without(i, p))
10642 			sgs->idle_cpus++;
10643 
10644 		/* Check if task fits in the CPU */
10645 		if (sd->flags & SD_ASYM_CPUCAPACITY &&
10646 		    sgs->group_misfit_task_load &&
10647 		    task_fits_cpu(p, i))
10648 			sgs->group_misfit_task_load = 0;
10649 
10650 	}
10651 
10652 	sgs->group_capacity = group->sgc->capacity;
10653 
10654 	sgs->group_weight = group->group_weight;
10655 
10656 	sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10657 
10658 	/*
10659 	 * Computing avg_load makes sense only when group is fully busy or
10660 	 * overloaded
10661 	 */
10662 	if (sgs->group_type == group_fully_busy ||
10663 		sgs->group_type == group_overloaded)
10664 		sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10665 				sgs->group_capacity;
10666 }
10667 
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10668 static bool update_pick_idlest(struct sched_group *idlest,
10669 			       struct sg_lb_stats *idlest_sgs,
10670 			       struct sched_group *group,
10671 			       struct sg_lb_stats *sgs)
10672 {
10673 	if (sgs->group_type < idlest_sgs->group_type)
10674 		return true;
10675 
10676 	if (sgs->group_type > idlest_sgs->group_type)
10677 		return false;
10678 
10679 	/*
10680 	 * The candidate and the current idlest group are the same type of
10681 	 * group. Let check which one is the idlest according to the type.
10682 	 */
10683 
10684 	switch (sgs->group_type) {
10685 	case group_overloaded:
10686 	case group_fully_busy:
10687 		/* Select the group with lowest avg_load. */
10688 		if (idlest_sgs->avg_load <= sgs->avg_load)
10689 			return false;
10690 		break;
10691 
10692 	case group_imbalanced:
10693 	case group_asym_packing:
10694 	case group_smt_balance:
10695 		/* Those types are not used in the slow wakeup path */
10696 		return false;
10697 
10698 	case group_misfit_task:
10699 		/* Select group with the highest max capacity */
10700 		if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10701 			return false;
10702 		break;
10703 
10704 	case group_has_spare:
10705 		/* Select group with most idle CPUs */
10706 		if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10707 			return false;
10708 
10709 		/* Select group with lowest group_util */
10710 		if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10711 			idlest_sgs->group_util <= sgs->group_util)
10712 			return false;
10713 
10714 		break;
10715 	}
10716 
10717 	return true;
10718 }
10719 
10720 /*
10721  * find_idlest_group() finds and returns the least busy CPU group within the
10722  * domain.
10723  *
10724  * Assumes p is allowed on at least one CPU in sd.
10725  */
10726 static struct sched_group *
find_idlest_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10727 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10728 {
10729 	struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10730 	struct sg_lb_stats local_sgs, tmp_sgs;
10731 	struct sg_lb_stats *sgs;
10732 	unsigned long imbalance;
10733 	struct sg_lb_stats idlest_sgs = {
10734 			.avg_load = UINT_MAX,
10735 			.group_type = group_overloaded,
10736 	};
10737 #ifdef CONFIG_CPU_ISOLATION_OPT
10738 	cpumask_t allowed_cpus;
10739 
10740 	cpumask_andnot(&allowed_cpus, p->cpus_ptr, cpu_isolated_mask);
10741 #endif
10742 	do {
10743 		int local_group;
10744 
10745 		/* Skip over this group if it has no CPUs allowed */
10746 #ifdef CONFIG_CPU_ISOLATION_OPT
10747 		if (!cpumask_intersects(sched_group_span(group),
10748 					&allowed_cpus))
10749 #else
10750 		if (!cpumask_intersects(sched_group_span(group),
10751 					p->cpus_ptr))
10752 #endif
10753 			continue;
10754 
10755 		/* Skip over this group if no cookie matched */
10756 		if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10757 			continue;
10758 
10759 		local_group = cpumask_test_cpu(this_cpu,
10760 					       sched_group_span(group));
10761 
10762 		if (local_group) {
10763 			sgs = &local_sgs;
10764 			local = group;
10765 		} else {
10766 			sgs = &tmp_sgs;
10767 		}
10768 
10769 		update_sg_wakeup_stats(sd, group, sgs, p);
10770 
10771 		if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10772 			idlest = group;
10773 			idlest_sgs = *sgs;
10774 		}
10775 
10776 	} while (group = group->next, group != sd->groups);
10777 
10778 
10779 	/* There is no idlest group to push tasks to */
10780 	if (!idlest)
10781 		return NULL;
10782 
10783 	/* The local group has been skipped because of CPU affinity */
10784 	if (!local)
10785 		return idlest;
10786 
10787 	/*
10788 	 * If the local group is idler than the selected idlest group
10789 	 * don't try and push the task.
10790 	 */
10791 	if (local_sgs.group_type < idlest_sgs.group_type)
10792 		return NULL;
10793 
10794 	/*
10795 	 * If the local group is busier than the selected idlest group
10796 	 * try and push the task.
10797 	 */
10798 	if (local_sgs.group_type > idlest_sgs.group_type)
10799 		return idlest;
10800 
10801 	switch (local_sgs.group_type) {
10802 	case group_overloaded:
10803 	case group_fully_busy:
10804 
10805 		/* Calculate allowed imbalance based on load */
10806 		imbalance = scale_load_down(NICE_0_LOAD) *
10807 				(sd->imbalance_pct-100) / 100;
10808 
10809 		/*
10810 		 * When comparing groups across NUMA domains, it's possible for
10811 		 * the local domain to be very lightly loaded relative to the
10812 		 * remote domains but "imbalance" skews the comparison making
10813 		 * remote CPUs look much more favourable. When considering
10814 		 * cross-domain, add imbalance to the load on the remote node
10815 		 * and consider staying local.
10816 		 */
10817 
10818 		if ((sd->flags & SD_NUMA) &&
10819 		    ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10820 			return NULL;
10821 
10822 		/*
10823 		 * If the local group is less loaded than the selected
10824 		 * idlest group don't try and push any tasks.
10825 		 */
10826 		if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10827 			return NULL;
10828 
10829 		if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10830 			return NULL;
10831 		break;
10832 
10833 	case group_imbalanced:
10834 	case group_asym_packing:
10835 	case group_smt_balance:
10836 		/* Those type are not used in the slow wakeup path */
10837 		return NULL;
10838 
10839 	case group_misfit_task:
10840 		/* Select group with the highest max capacity */
10841 		if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10842 			return NULL;
10843 		break;
10844 
10845 	case group_has_spare:
10846 #ifdef CONFIG_NUMA
10847 		if (sd->flags & SD_NUMA) {
10848 			int imb_numa_nr = sd->imb_numa_nr;
10849 #ifdef CONFIG_NUMA_BALANCING
10850 			int idlest_cpu;
10851 			/*
10852 			 * If there is spare capacity at NUMA, try to select
10853 			 * the preferred node
10854 			 */
10855 			if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10856 				return NULL;
10857 
10858 			idlest_cpu = cpumask_first(sched_group_span(idlest));
10859 			if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10860 				return idlest;
10861 #endif /* CONFIG_NUMA_BALANCING */
10862 			/*
10863 			 * Otherwise, keep the task close to the wakeup source
10864 			 * and improve locality if the number of running tasks
10865 			 * would remain below threshold where an imbalance is
10866 			 * allowed while accounting for the possibility the
10867 			 * task is pinned to a subset of CPUs. If there is a
10868 			 * real need of migration, periodic load balance will
10869 			 * take care of it.
10870 			 */
10871 			if (p->nr_cpus_allowed != NR_CPUS) {
10872 				struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10873 
10874 				cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10875 				imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10876 			}
10877 
10878 			imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10879 			if (!adjust_numa_imbalance(imbalance,
10880 						   local_sgs.sum_nr_running + 1,
10881 						   imb_numa_nr)) {
10882 				return NULL;
10883 			}
10884 		}
10885 #endif /* CONFIG_NUMA */
10886 
10887 		/*
10888 		 * Select group with highest number of idle CPUs. We could also
10889 		 * compare the utilization which is more stable but it can end
10890 		 * up that the group has less spare capacity but finally more
10891 		 * idle CPUs which means more opportunity to run task.
10892 		 */
10893 		if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10894 			return NULL;
10895 		break;
10896 	}
10897 
10898 	return idlest;
10899 }
10900 
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)10901 static void update_idle_cpu_scan(struct lb_env *env,
10902 				 unsigned long sum_util)
10903 {
10904 	struct sched_domain_shared *sd_share;
10905 	int llc_weight, pct;
10906 	u64 x, y, tmp;
10907 	/*
10908 	 * Update the number of CPUs to scan in LLC domain, which could
10909 	 * be used as a hint in select_idle_cpu(). The update of sd_share
10910 	 * could be expensive because it is within a shared cache line.
10911 	 * So the write of this hint only occurs during periodic load
10912 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10913 	 * can fire way more frequently than the former.
10914 	 */
10915 	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10916 		return;
10917 
10918 	llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10919 	if (env->sd->span_weight != llc_weight)
10920 		return;
10921 
10922 	sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10923 	if (!sd_share)
10924 		return;
10925 
10926 	/*
10927 	 * The number of CPUs to search drops as sum_util increases, when
10928 	 * sum_util hits 85% or above, the scan stops.
10929 	 * The reason to choose 85% as the threshold is because this is the
10930 	 * imbalance_pct(117) when a LLC sched group is overloaded.
10931 	 *
10932 	 * let y = SCHED_CAPACITY_SCALE - p * x^2                       [1]
10933 	 * and y'= y / SCHED_CAPACITY_SCALE
10934 	 *
10935 	 * x is the ratio of sum_util compared to the CPU capacity:
10936 	 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10937 	 * y' is the ratio of CPUs to be scanned in the LLC domain,
10938 	 * and the number of CPUs to scan is calculated by:
10939 	 *
10940 	 * nr_scan = llc_weight * y'                                    [2]
10941 	 *
10942 	 * When x hits the threshold of overloaded, AKA, when
10943 	 * x = 100 / pct, y drops to 0. According to [1],
10944 	 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10945 	 *
10946 	 * Scale x by SCHED_CAPACITY_SCALE:
10947 	 * x' = sum_util / llc_weight;                                  [3]
10948 	 *
10949 	 * and finally [1] becomes:
10950 	 * y = SCHED_CAPACITY_SCALE -
10951 	 *     x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE)            [4]
10952 	 *
10953 	 */
10954 	/* equation [3] */
10955 	x = sum_util;
10956 	do_div(x, llc_weight);
10957 
10958 	/* equation [4] */
10959 	pct = env->sd->imbalance_pct;
10960 	tmp = x * x * pct * pct;
10961 	do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10962 	tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10963 	y = SCHED_CAPACITY_SCALE - tmp;
10964 
10965 	/* equation [2] */
10966 	y *= llc_weight;
10967 	do_div(y, SCHED_CAPACITY_SCALE);
10968 	if ((int)y != sd_share->nr_idle_scan)
10969 		WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10970 }
10971 
10972 /**
10973  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10974  * @env: The load balancing environment.
10975  * @sds: variable to hold the statistics for this sched_domain.
10976  */
10977 
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)10978 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10979 {
10980 	struct sched_group *sg = env->sd->groups;
10981 	struct sg_lb_stats *local = &sds->local_stat;
10982 	struct sg_lb_stats tmp_sgs;
10983 	unsigned long sum_util = 0;
10984 	int sg_status = 0;
10985 
10986 	do {
10987 		struct sg_lb_stats *sgs = &tmp_sgs;
10988 		int local_group;
10989 
10990 		local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10991 		if (local_group) {
10992 			sds->local = sg;
10993 			sgs = local;
10994 
10995 			if (env->idle != CPU_NEWLY_IDLE ||
10996 			    time_after_eq(jiffies, sg->sgc->next_update))
10997 				update_group_capacity(env->sd, env->dst_cpu);
10998 		}
10999 
11000 		update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
11001 
11002 		if (local_group)
11003 			goto next_group;
11004 
11005 
11006 		if (update_sd_pick_busiest(env, sds, sg, sgs)) {
11007 			sds->busiest = sg;
11008 			sds->busiest_stat = *sgs;
11009 		}
11010 
11011 next_group:
11012 		/* Now, start updating sd_lb_stats */
11013 		sds->total_load += sgs->group_load;
11014 		sds->total_capacity += sgs->group_capacity;
11015 
11016 		sum_util += sgs->group_util;
11017 		sg = sg->next;
11018 	} while (sg != env->sd->groups);
11019 
11020 	/*
11021 	 * Indicate that the child domain of the busiest group prefers tasks
11022 	 * go to a child's sibling domains first. NB the flags of a sched group
11023 	 * are those of the child domain.
11024 	 */
11025 	if (sds->busiest)
11026 		sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11027 
11028 
11029 	if (env->sd->flags & SD_NUMA)
11030 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11031 
11032 	if (!env->sd->parent) {
11033 		/* update overload indicator if we are at root domain */
11034 		WRITE_ONCE(env->dst_rq->rd->overload, sg_status & SG_OVERLOAD);
11035 
11036 		/* Update over-utilization (tipping point, U >= 0) indicator */
11037 		set_rd_overutilized_status(env->dst_rq->rd,
11038 					   sg_status & SG_OVERUTILIZED);
11039 	} else if (sg_status & SG_OVERUTILIZED) {
11040 		set_rd_overutilized_status(env->dst_rq->rd, SG_OVERUTILIZED);
11041 	}
11042 
11043 	update_idle_cpu_scan(env, sum_util);
11044 }
11045 
11046 /**
11047  * calculate_imbalance - Calculate the amount of imbalance present within the
11048  *			 groups of a given sched_domain during load balance.
11049  * @env: load balance environment
11050  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11051  */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11052 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11053 {
11054 	struct sg_lb_stats *local, *busiest;
11055 
11056 	local = &sds->local_stat;
11057 	busiest = &sds->busiest_stat;
11058 
11059 	if (busiest->group_type == group_misfit_task) {
11060 		if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11061 			/* Set imbalance to allow misfit tasks to be balanced. */
11062 			env->migration_type = migrate_misfit;
11063 			env->imbalance = 1;
11064 		} else {
11065 			/*
11066 			 * Set load imbalance to allow moving task from cpu
11067 			 * with reduced capacity.
11068 			 */
11069 			env->migration_type = migrate_load;
11070 			env->imbalance = busiest->group_misfit_task_load;
11071 		}
11072 		return;
11073 	}
11074 
11075 	if (busiest->group_type == group_asym_packing) {
11076 		/*
11077 		 * In case of asym capacity, we will try to migrate all load to
11078 		 * the preferred CPU.
11079 		 */
11080 		env->migration_type = migrate_task;
11081 		env->imbalance = busiest->sum_h_nr_running;
11082 		return;
11083 	}
11084 
11085 	if (busiest->group_type == group_smt_balance) {
11086 		/* Reduce number of tasks sharing CPU capacity */
11087 		env->migration_type = migrate_task;
11088 		env->imbalance = 1;
11089 		return;
11090 	}
11091 
11092 	if (busiest->group_type == group_imbalanced) {
11093 		/*
11094 		 * In the group_imb case we cannot rely on group-wide averages
11095 		 * to ensure CPU-load equilibrium, try to move any task to fix
11096 		 * the imbalance. The next load balance will take care of
11097 		 * balancing back the system.
11098 		 */
11099 		env->migration_type = migrate_task;
11100 		env->imbalance = 1;
11101 		return;
11102 	}
11103 
11104 	/*
11105 	 * Try to use spare capacity of local group without overloading it or
11106 	 * emptying busiest.
11107 	 */
11108 	if (local->group_type == group_has_spare) {
11109 		if ((busiest->group_type > group_fully_busy) &&
11110 		    !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
11111 			/*
11112 			 * If busiest is overloaded, try to fill spare
11113 			 * capacity. This might end up creating spare capacity
11114 			 * in busiest or busiest still being overloaded but
11115 			 * there is no simple way to directly compute the
11116 			 * amount of load to migrate in order to balance the
11117 			 * system.
11118 			 */
11119 			env->migration_type = migrate_util;
11120 			env->imbalance = max(local->group_capacity, local->group_util) -
11121 					 local->group_util;
11122 
11123 			/*
11124 			 * In some cases, the group's utilization is max or even
11125 			 * higher than capacity because of migrations but the
11126 			 * local CPU is (newly) idle. There is at least one
11127 			 * waiting task in this overloaded busiest group. Let's
11128 			 * try to pull it.
11129 			 */
11130 			if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
11131 				env->migration_type = migrate_task;
11132 				env->imbalance = 1;
11133 			}
11134 
11135 			return;
11136 		}
11137 
11138 		if (busiest->group_weight == 1 || sds->prefer_sibling) {
11139 			/*
11140 			 * When prefer sibling, evenly spread running tasks on
11141 			 * groups.
11142 			 */
11143 			env->migration_type = migrate_task;
11144 			env->imbalance = sibling_imbalance(env, sds, busiest, local);
11145 		} else {
11146 
11147 			/*
11148 			 * If there is no overload, we just want to even the number of
11149 			 * idle cpus.
11150 			 */
11151 			env->migration_type = migrate_task;
11152 			env->imbalance = max_t(long, 0,
11153 					       (local->idle_cpus - busiest->idle_cpus));
11154 		}
11155 
11156 #ifdef CONFIG_NUMA
11157 		/* Consider allowing a small imbalance between NUMA groups */
11158 		if (env->sd->flags & SD_NUMA) {
11159 			env->imbalance = adjust_numa_imbalance(env->imbalance,
11160 							       local->sum_nr_running + 1,
11161 							       env->sd->imb_numa_nr);
11162 		}
11163 #endif
11164 
11165 		/* Number of tasks to move to restore balance */
11166 		env->imbalance >>= 1;
11167 
11168 		return;
11169 	}
11170 
11171 	/*
11172 	 * Local is fully busy but has to take more load to relieve the
11173 	 * busiest group
11174 	 */
11175 	if (local->group_type < group_overloaded) {
11176 		/*
11177 		 * Local will become overloaded so the avg_load metrics are
11178 		 * finally needed.
11179 		 */
11180 
11181 		local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11182 				  local->group_capacity;
11183 
11184 		/*
11185 		 * If the local group is more loaded than the selected
11186 		 * busiest group don't try to pull any tasks.
11187 		 */
11188 		if (local->avg_load >= busiest->avg_load) {
11189 			env->imbalance = 0;
11190 			return;
11191 		}
11192 
11193 		sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11194 				sds->total_capacity;
11195 
11196 		/*
11197 		 * If the local group is more loaded than the average system
11198 		 * load, don't try to pull any tasks.
11199 		 */
11200 		if (local->avg_load >= sds->avg_load) {
11201 			env->imbalance = 0;
11202 			return;
11203 		}
11204 
11205 	}
11206 
11207 	/*
11208 	 * Both group are or will become overloaded and we're trying to get all
11209 	 * the CPUs to the average_load, so we don't want to push ourselves
11210 	 * above the average load, nor do we wish to reduce the max loaded CPU
11211 	 * below the average load. At the same time, we also don't want to
11212 	 * reduce the group load below the group capacity. Thus we look for
11213 	 * the minimum possible imbalance.
11214 	 */
11215 	env->migration_type = migrate_load;
11216 	env->imbalance = min(
11217 		(busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11218 		(sds->avg_load - local->avg_load) * local->group_capacity
11219 	) / SCHED_CAPACITY_SCALE;
11220 }
11221 
11222 /******* find_busiest_group() helpers end here *********************/
11223 
11224 /*
11225  * Decision matrix according to the local and busiest group type:
11226  *
11227  * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11228  * has_spare        nr_idle   balanced   N/A    N/A  balanced   balanced
11229  * fully_busy       nr_idle   nr_idle    N/A    N/A  balanced   balanced
11230  * misfit_task      force     N/A        N/A    N/A  N/A        N/A
11231  * asym_packing     force     force      N/A    N/A  force      force
11232  * imbalanced       force     force      N/A    N/A  force      force
11233  * overloaded       force     force      N/A    N/A  force      avg_load
11234  *
11235  * N/A :      Not Applicable because already filtered while updating
11236  *            statistics.
11237  * balanced : The system is balanced for these 2 groups.
11238  * force :    Calculate the imbalance as load migration is probably needed.
11239  * avg_load : Only if imbalance is significant enough.
11240  * nr_idle :  dst_cpu is not busy and the number of idle CPUs is quite
11241  *            different in groups.
11242  */
11243 
11244 /**
11245  * find_busiest_group - Returns the busiest group within the sched_domain
11246  * if there is an imbalance.
11247  * @env: The load balancing environment.
11248  *
11249  * Also calculates the amount of runnable load which should be moved
11250  * to restore balance.
11251  *
11252  * Return:	- The busiest group if imbalance exists.
11253  */
find_busiest_group(struct lb_env * env)11254 static struct sched_group *find_busiest_group(struct lb_env *env)
11255 {
11256 	struct sg_lb_stats *local, *busiest;
11257 	struct sd_lb_stats sds;
11258 
11259 	init_sd_lb_stats(&sds);
11260 
11261 	/*
11262 	 * Compute the various statistics relevant for load balancing at
11263 	 * this level.
11264 	 */
11265 	update_sd_lb_stats(env, &sds);
11266 
11267 	/* There is no busy sibling group to pull tasks from */
11268 	if (!sds.busiest)
11269 		goto out_balanced;
11270 
11271 	busiest = &sds.busiest_stat;
11272 
11273 	/* Misfit tasks should be dealt with regardless of the avg load */
11274 	if (busiest->group_type == group_misfit_task)
11275 		goto force_balance;
11276 
11277 	if (sched_energy_enabled()) {
11278 		struct root_domain *rd = env->dst_rq->rd;
11279 
11280 		if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
11281 			goto out_balanced;
11282 	}
11283 
11284 	/* ASYM feature bypasses nice load balance check */
11285 	if (busiest->group_type == group_asym_packing)
11286 		goto force_balance;
11287 
11288 	/*
11289 	 * If the busiest group is imbalanced the below checks don't
11290 	 * work because they assume all things are equal, which typically
11291 	 * isn't true due to cpus_ptr constraints and the like.
11292 	 */
11293 	if (busiest->group_type == group_imbalanced)
11294 		goto force_balance;
11295 
11296 	local = &sds.local_stat;
11297 	/*
11298 	 * If the local group is busier than the selected busiest group
11299 	 * don't try and pull any tasks.
11300 	 */
11301 	if (local->group_type > busiest->group_type)
11302 		goto out_balanced;
11303 
11304 	/*
11305 	 * When groups are overloaded, use the avg_load to ensure fairness
11306 	 * between tasks.
11307 	 */
11308 	if (local->group_type == group_overloaded) {
11309 		/*
11310 		 * If the local group is more loaded than the selected
11311 		 * busiest group don't try to pull any tasks.
11312 		 */
11313 		if (local->avg_load >= busiest->avg_load)
11314 			goto out_balanced;
11315 
11316 		/* XXX broken for overlapping NUMA groups */
11317 		sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11318 				sds.total_capacity;
11319 
11320 		/*
11321 		 * Don't pull any tasks if this group is already above the
11322 		 * domain average load.
11323 		 */
11324 		if (local->avg_load >= sds.avg_load)
11325 			goto out_balanced;
11326 
11327 		/*
11328 		 * If the busiest group is more loaded, use imbalance_pct to be
11329 		 * conservative.
11330 		 */
11331 		if (100 * busiest->avg_load <=
11332 				env->sd->imbalance_pct * local->avg_load)
11333 			goto out_balanced;
11334 	}
11335 
11336 	/*
11337 	 * Try to move all excess tasks to a sibling domain of the busiest
11338 	 * group's child domain.
11339 	 */
11340 	if (sds.prefer_sibling && local->group_type == group_has_spare &&
11341 	    sibling_imbalance(env, &sds, busiest, local) > 1)
11342 		goto force_balance;
11343 
11344 	if (busiest->group_type != group_overloaded) {
11345 		if (env->idle == CPU_NOT_IDLE) {
11346 			/*
11347 			 * If the busiest group is not overloaded (and as a
11348 			 * result the local one too) but this CPU is already
11349 			 * busy, let another idle CPU try to pull task.
11350 			 */
11351 			goto out_balanced;
11352 		}
11353 
11354 		if (busiest->group_type == group_smt_balance &&
11355 		    smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11356 			/* Let non SMT CPU pull from SMT CPU sharing with sibling */
11357 			goto force_balance;
11358 		}
11359 
11360 		if (busiest->group_weight > 1 &&
11361 		    local->idle_cpus <= (busiest->idle_cpus + 1)) {
11362 			/*
11363 			 * If the busiest group is not overloaded
11364 			 * and there is no imbalance between this and busiest
11365 			 * group wrt idle CPUs, it is balanced. The imbalance
11366 			 * becomes significant if the diff is greater than 1
11367 			 * otherwise we might end up to just move the imbalance
11368 			 * on another group. Of course this applies only if
11369 			 * there is more than 1 CPU per group.
11370 			 */
11371 			goto out_balanced;
11372 		}
11373 
11374 		if (busiest->sum_h_nr_running == 1) {
11375 			/*
11376 			 * busiest doesn't have any tasks waiting to run
11377 			 */
11378 			goto out_balanced;
11379 		}
11380 	}
11381 
11382 force_balance:
11383 	/* Looks like there is an imbalance. Compute it */
11384 	calculate_imbalance(env, &sds);
11385 	return env->imbalance ? sds.busiest : NULL;
11386 
11387 out_balanced:
11388 	env->imbalance = 0;
11389 	return NULL;
11390 }
11391 
11392 /*
11393  * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
11394  */
find_busiest_queue(struct lb_env * env,struct sched_group * group)11395 static struct rq *find_busiest_queue(struct lb_env *env,
11396 				     struct sched_group *group)
11397 {
11398 	struct rq *busiest = NULL, *rq;
11399 	unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11400 	unsigned int busiest_nr = 0;
11401 	int i;
11402 
11403 	for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11404 		unsigned long capacity, load, util;
11405 		unsigned int nr_running;
11406 		enum fbq_type rt;
11407 
11408 		rq = cpu_rq(i);
11409 		rt = fbq_classify_rq(rq);
11410 
11411 		/*
11412 		 * We classify groups/runqueues into three groups:
11413 		 *  - regular: there are !numa tasks
11414 		 *  - remote:  there are numa tasks that run on the 'wrong' node
11415 		 *  - all:     there is no distinction
11416 		 *
11417 		 * In order to avoid migrating ideally placed numa tasks,
11418 		 * ignore those when there's better options.
11419 		 *
11420 		 * If we ignore the actual busiest queue to migrate another
11421 		 * task, the next balance pass can still reduce the busiest
11422 		 * queue by moving tasks around inside the node.
11423 		 *
11424 		 * If we cannot move enough load due to this classification
11425 		 * the next pass will adjust the group classification and
11426 		 * allow migration of more tasks.
11427 		 *
11428 		 * Both cases only affect the total convergence complexity.
11429 		 */
11430 		if (rt > env->fbq_type)
11431 			continue;
11432 
11433 		if (cpu_isolated(i))
11434 			continue;
11435 
11436 		nr_running = rq->cfs.h_nr_running;
11437 		if (!nr_running)
11438 			continue;
11439 
11440 		capacity = capacity_of(i);
11441 
11442 		/*
11443 		 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11444 		 * eventually lead to active_balancing high->low capacity.
11445 		 * Higher per-CPU capacity is considered better than balancing
11446 		 * average load.
11447 		 */
11448 		if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11449 		    !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11450 		    nr_running == 1)
11451 			continue;
11452 
11453 		/*
11454 		 * Make sure we only pull tasks from a CPU of lower priority
11455 		 * when balancing between SMT siblings.
11456 		 *
11457 		 * If balancing between cores, let lower priority CPUs help
11458 		 * SMT cores with more than one busy sibling.
11459 		 */
11460 		if ((env->sd->flags & SD_ASYM_PACKING) &&
11461 		    sched_use_asym_prio(env->sd, i) &&
11462 		    sched_asym_prefer(i, env->dst_cpu) &&
11463 		    nr_running == 1)
11464 			continue;
11465 
11466 		switch (env->migration_type) {
11467 		case migrate_load:
11468 			/*
11469 			 * When comparing with load imbalance, use cpu_load()
11470 			 * which is not scaled with the CPU capacity.
11471 			 */
11472 			load = cpu_load(rq);
11473 
11474 			if (nr_running == 1 && load > env->imbalance &&
11475 			    !check_cpu_capacity(rq, env->sd))
11476 				break;
11477 
11478 			/*
11479 			 * For the load comparisons with the other CPUs,
11480 			 * consider the cpu_load() scaled with the CPU
11481 			 * capacity, so that the load can be moved away
11482 			 * from the CPU that is potentially running at a
11483 			 * lower capacity.
11484 			 *
11485 			 * Thus we're looking for max(load_i / capacity_i),
11486 			 * crosswise multiplication to rid ourselves of the
11487 			 * division works out to:
11488 			 * load_i * capacity_j > load_j * capacity_i;
11489 			 * where j is our previous maximum.
11490 			 */
11491 			if (load * busiest_capacity > busiest_load * capacity) {
11492 				busiest_load = load;
11493 				busiest_capacity = capacity;
11494 				busiest = rq;
11495 			}
11496 			break;
11497 
11498 		case migrate_util:
11499 			util = cpu_util_cfs_boost(i);
11500 
11501 			/*
11502 			 * Don't try to pull utilization from a CPU with one
11503 			 * running task. Whatever its utilization, we will fail
11504 			 * detach the task.
11505 			 */
11506 			if (nr_running <= 1)
11507 				continue;
11508 
11509 			if (busiest_util < util) {
11510 				busiest_util = util;
11511 				busiest = rq;
11512 			}
11513 			break;
11514 
11515 		case migrate_task:
11516 			if (busiest_nr < nr_running) {
11517 				busiest_nr = nr_running;
11518 				busiest = rq;
11519 			}
11520 			break;
11521 
11522 		case migrate_misfit:
11523 			/*
11524 			 * For ASYM_CPUCAPACITY domains with misfit tasks we
11525 			 * simply seek the "biggest" misfit task.
11526 			 */
11527 			if (rq->misfit_task_load > busiest_load) {
11528 				busiest_load = rq->misfit_task_load;
11529 				busiest = rq;
11530 			}
11531 
11532 			break;
11533 
11534 		}
11535 	}
11536 
11537 	return busiest;
11538 }
11539 
11540 /*
11541  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11542  * so long as it is large enough.
11543  */
11544 #define MAX_PINNED_INTERVAL	512
11545 
11546 static inline bool
asym_active_balance(struct lb_env * env)11547 asym_active_balance(struct lb_env *env)
11548 {
11549 	/*
11550 	 * ASYM_PACKING needs to force migrate tasks from busy but lower
11551 	 * priority CPUs in order to pack all tasks in the highest priority
11552 	 * CPUs. When done between cores, do it only if the whole core if the
11553 	 * whole core is idle.
11554 	 *
11555 	 * If @env::src_cpu is an SMT core with busy siblings, let
11556 	 * the lower priority @env::dst_cpu help it. Do not follow
11557 	 * CPU priority.
11558 	 */
11559 	return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
11560 	       sched_use_asym_prio(env->sd, env->dst_cpu) &&
11561 	       (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11562 		!sched_use_asym_prio(env->sd, env->src_cpu));
11563 }
11564 
11565 static inline bool
imbalanced_active_balance(struct lb_env * env)11566 imbalanced_active_balance(struct lb_env *env)
11567 {
11568 	struct sched_domain *sd = env->sd;
11569 
11570 	/*
11571 	 * The imbalanced case includes the case of pinned tasks preventing a fair
11572 	 * distribution of the load on the system but also the even distribution of the
11573 	 * threads on a system with spare capacity
11574 	 */
11575 	if ((env->migration_type == migrate_task) &&
11576 	    (sd->nr_balance_failed > sd->cache_nice_tries+2))
11577 		return 1;
11578 
11579 	return 0;
11580 }
11581 
need_active_balance(struct lb_env * env)11582 static int need_active_balance(struct lb_env *env)
11583 {
11584 	struct sched_domain *sd = env->sd;
11585 
11586 	if (asym_active_balance(env))
11587 		return 1;
11588 
11589 	if (imbalanced_active_balance(env))
11590 		return 1;
11591 
11592 	/*
11593 	 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11594 	 * It's worth migrating the task if the src_cpu's capacity is reduced
11595 	 * because of other sched_class or IRQs if more capacity stays
11596 	 * available on dst_cpu.
11597 	 */
11598 	if ((env->idle != CPU_NOT_IDLE) &&
11599 	    (env->src_rq->cfs.h_nr_running == 1)) {
11600 		if ((check_cpu_capacity(env->src_rq, sd)) &&
11601 		    (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11602 			return 1;
11603 	}
11604 
11605 	if (env->migration_type == migrate_misfit)
11606 		return 1;
11607 
11608 	return 0;
11609 }
11610 
11611 #ifdef CONFIG_CPU_ISOLATION_OPT
group_balance_cpu_not_isolated(struct sched_group * sg)11612 int group_balance_cpu_not_isolated(struct sched_group *sg)
11613 {
11614 	cpumask_t cpus;
11615 
11616 	cpumask_and(&cpus, sched_group_span(sg), group_balance_mask(sg));
11617 	cpumask_andnot(&cpus, &cpus, cpu_isolated_mask);
11618 	return cpumask_first(&cpus);
11619 }
11620 #endif
11621 static int active_load_balance_cpu_stop(void *data);
11622 
should_we_balance(struct lb_env * env)11623 static int should_we_balance(struct lb_env *env)
11624 {
11625 	struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11626 	struct sched_group *sg = env->sd->groups;
11627 	int cpu, idle_smt = -1;
11628 
11629 	/*
11630 	 * Ensure the balancing environment is consistent; can happen
11631 	 * when the softirq triggers 'during' hotplug.
11632 	 */
11633 	if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11634 		return 0;
11635 
11636 	/*
11637 	 * In the newly idle case, we will allow all the CPUs
11638 	 * to do the newly idle load balance.
11639 	 *
11640 	 * However, we bail out if we already have tasks or a wakeup pending,
11641 	 * to optimize wakeup latency.
11642 	 */
11643 	if (env->idle == CPU_NEWLY_IDLE) {
11644 		if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11645 			return 0;
11646 		return 1;
11647 	}
11648 
11649 	cpumask_copy(swb_cpus, group_balance_mask(sg));
11650 	/* Try to find first idle CPU */
11651 	for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11652 		if (!idle_cpu(cpu) || cpu_isolated(cpu))
11653 			continue;
11654 
11655 		/*
11656 		 * Don't balance to idle SMT in busy core right away when
11657 		 * balancing cores, but remember the first idle SMT CPU for
11658 		 * later consideration.  Find CPU on an idle core first.
11659 		 */
11660 		if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11661 			if (idle_smt == -1)
11662 				idle_smt = cpu;
11663 			/*
11664 			 * If the core is not idle, and first SMT sibling which is
11665 			 * idle has been found, then its not needed to check other
11666 			 * SMT siblings for idleness:
11667 			 */
11668 #ifdef CONFIG_SCHED_SMT
11669 			cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11670 #endif
11671 			continue;
11672 		}
11673 
11674 		/*
11675 		 * Are we the first idle core in a non-SMT domain or higher,
11676 		 * or the first idle CPU in a SMT domain?
11677 		 */
11678 		return cpu == env->dst_cpu;
11679 	}
11680 
11681 	/* Are we the first idle CPU with busy siblings? */
11682 	if (idle_smt != -1)
11683 		return idle_smt == env->dst_cpu;
11684 
11685 	/* Are we the first CPU of this group ? */
11686 	return group_balance_cpu_not_isolated(sg) == env->dst_cpu;
11687 }
11688 
11689 /*
11690  * Check this_cpu to ensure it is balanced within domain. Attempt to move
11691  * tasks if there is an imbalance.
11692  */
load_balance(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11693 static int load_balance(int this_cpu, struct rq *this_rq,
11694 			struct sched_domain *sd, enum cpu_idle_type idle,
11695 			int *continue_balancing)
11696 {
11697 	int ld_moved, cur_ld_moved, active_balance = 0;
11698 	struct sched_domain *sd_parent = sd->parent;
11699 	struct sched_group *group;
11700 	struct rq *busiest;
11701 	struct rq_flags rf;
11702 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11703 	struct lb_env env = {
11704 		.sd		= sd,
11705 		.dst_cpu	= this_cpu,
11706 		.dst_rq		= this_rq,
11707 		.dst_grpmask    = group_balance_mask(sd->groups),
11708 		.idle		= idle,
11709 		.loop_break	= SCHED_NR_MIGRATE_BREAK,
11710 		.cpus		= cpus,
11711 		.fbq_type	= all,
11712 		.tasks		= LIST_HEAD_INIT(env.tasks),
11713 	};
11714 
11715 	cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11716 
11717 	schedstat_inc(sd->lb_count[idle]);
11718 
11719 redo:
11720 	if (!should_we_balance(&env)) {
11721 		*continue_balancing = 0;
11722 		goto out_balanced;
11723 	}
11724 
11725 	group = find_busiest_group(&env);
11726 	if (!group) {
11727 		schedstat_inc(sd->lb_nobusyg[idle]);
11728 		goto out_balanced;
11729 	}
11730 
11731 	busiest = find_busiest_queue(&env, group);
11732 	if (!busiest) {
11733 		schedstat_inc(sd->lb_nobusyq[idle]);
11734 		goto out_balanced;
11735 	}
11736 
11737 	WARN_ON_ONCE(busiest == env.dst_rq);
11738 
11739 	schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11740 
11741 	env.src_cpu = busiest->cpu;
11742 	env.src_rq = busiest;
11743 
11744 	ld_moved = 0;
11745 	/* Clear this flag as soon as we find a pullable task */
11746 	env.flags |= LBF_ALL_PINNED;
11747 	if (busiest->nr_running > 1) {
11748 		/*
11749 		 * Attempt to move tasks. If find_busiest_group has found
11750 		 * an imbalance but busiest->nr_running <= 1, the group is
11751 		 * still unbalanced. ld_moved simply stays zero, so it is
11752 		 * correctly treated as an imbalance.
11753 		 */
11754 		env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
11755 
11756 more_balance:
11757 		rq_lock_irqsave(busiest, &rf);
11758 		update_rq_clock(busiest);
11759 
11760 		/*
11761 		 * cur_ld_moved - load moved in current iteration
11762 		 * ld_moved     - cumulative load moved across iterations
11763 		 */
11764 		cur_ld_moved = detach_tasks(&env);
11765 
11766 		/*
11767 		 * We've detached some tasks from busiest_rq. Every
11768 		 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11769 		 * unlock busiest->lock, and we are able to be sure
11770 		 * that nobody can manipulate the tasks in parallel.
11771 		 * See task_rq_lock() family for the details.
11772 		 */
11773 
11774 		rq_unlock(busiest, &rf);
11775 
11776 		if (cur_ld_moved) {
11777 			attach_tasks(&env);
11778 			ld_moved += cur_ld_moved;
11779 		}
11780 
11781 		local_irq_restore(rf.flags);
11782 
11783 		if (env.flags & LBF_NEED_BREAK) {
11784 			env.flags &= ~LBF_NEED_BREAK;
11785 			goto more_balance;
11786 		}
11787 
11788 		/*
11789 		 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11790 		 * us and move them to an alternate dst_cpu in our sched_group
11791 		 * where they can run. The upper limit on how many times we
11792 		 * iterate on same src_cpu is dependent on number of CPUs in our
11793 		 * sched_group.
11794 		 *
11795 		 * This changes load balance semantics a bit on who can move
11796 		 * load to a given_cpu. In addition to the given_cpu itself
11797 		 * (or a ilb_cpu acting on its behalf where given_cpu is
11798 		 * nohz-idle), we now have balance_cpu in a position to move
11799 		 * load to given_cpu. In rare situations, this may cause
11800 		 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11801 		 * _independently_ and at _same_ time to move some load to
11802 		 * given_cpu) causing excess load to be moved to given_cpu.
11803 		 * This however should not happen so much in practice and
11804 		 * moreover subsequent load balance cycles should correct the
11805 		 * excess load moved.
11806 		 */
11807 		if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11808 
11809 			/* Prevent to re-select dst_cpu via env's CPUs */
11810 			__cpumask_clear_cpu(env.dst_cpu, env.cpus);
11811 
11812 			env.dst_rq	 = cpu_rq(env.new_dst_cpu);
11813 			env.dst_cpu	 = env.new_dst_cpu;
11814 			env.flags	&= ~LBF_DST_PINNED;
11815 			env.loop	 = 0;
11816 			env.loop_break	 = SCHED_NR_MIGRATE_BREAK;
11817 
11818 			/*
11819 			 * Go back to "more_balance" rather than "redo" since we
11820 			 * need to continue with same src_cpu.
11821 			 */
11822 			goto more_balance;
11823 		}
11824 
11825 		/*
11826 		 * We failed to reach balance because of affinity.
11827 		 */
11828 		if (sd_parent) {
11829 			int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11830 
11831 			if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11832 				*group_imbalance = 1;
11833 		}
11834 
11835 		/* All tasks on this runqueue were pinned by CPU affinity */
11836 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
11837 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
11838 			/*
11839 			 * Attempting to continue load balancing at the current
11840 			 * sched_domain level only makes sense if there are
11841 			 * active CPUs remaining as possible busiest CPUs to
11842 			 * pull load from which are not contained within the
11843 			 * destination group that is receiving any migrated
11844 			 * load.
11845 			 */
11846 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
11847 				env.loop = 0;
11848 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
11849 				goto redo;
11850 			}
11851 			goto out_all_pinned;
11852 		}
11853 	}
11854 
11855 	if (!ld_moved) {
11856 		schedstat_inc(sd->lb_failed[idle]);
11857 		/*
11858 		 * Increment the failure counter only on periodic balance.
11859 		 * We do not want newidle balance, which can be very
11860 		 * frequent, pollute the failure counter causing
11861 		 * excessive cache_hot migrations and active balances.
11862 		 */
11863 		if (idle != CPU_NEWLY_IDLE)
11864 			sd->nr_balance_failed++;
11865 
11866 		if (need_active_balance(&env)) {
11867 			unsigned long flags;
11868 
11869 			raw_spin_rq_lock_irqsave(busiest, flags);
11870 
11871 			/*
11872 			 * Don't kick the active_load_balance_cpu_stop,
11873 			 * if the curr task on busiest CPU can't be
11874 			 * moved to this_cpu:
11875 			 */
11876 			if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11877 				raw_spin_rq_unlock_irqrestore(busiest, flags);
11878 				goto out_one_pinned;
11879 			}
11880 
11881 			/* Record that we found at least one task that could run on this_cpu */
11882 			env.flags &= ~LBF_ALL_PINNED;
11883 
11884 			/*
11885 			 * ->active_balance synchronizes accesses to
11886 			 * ->active_balance_work.  Once set, it's cleared
11887 			 * only after active load balance is finished.
11888 			 */
11889 			if (!busiest->active_balance &&
11890 			    !cpu_isolated(cpu_of(busiest))) {
11891 				busiest->active_balance = 1;
11892 				busiest->push_cpu = this_cpu;
11893 				active_balance = 1;
11894 			}
11895 
11896 			preempt_disable();
11897 			raw_spin_rq_unlock_irqrestore(busiest, flags);
11898 			if (active_balance) {
11899 				stop_one_cpu_nowait(cpu_of(busiest),
11900 					active_load_balance_cpu_stop, busiest,
11901 					&busiest->active_balance_work);
11902 			}
11903 			preempt_enable();
11904 		}
11905 	} else {
11906 		sd->nr_balance_failed = 0;
11907 	}
11908 
11909 	if (likely(!active_balance) || need_active_balance(&env)) {
11910 		/* We were unbalanced, so reset the balancing interval */
11911 		sd->balance_interval = sd->min_interval;
11912 	}
11913 
11914 	goto out;
11915 
11916 out_balanced:
11917 	/*
11918 	 * We reach balance although we may have faced some affinity
11919 	 * constraints. Clear the imbalance flag only if other tasks got
11920 	 * a chance to move and fix the imbalance.
11921 	 */
11922 	if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11923 		int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11924 
11925 		if (*group_imbalance)
11926 			*group_imbalance = 0;
11927 	}
11928 
11929 out_all_pinned:
11930 	/*
11931 	 * We reach balance because all tasks are pinned at this level so
11932 	 * we can't migrate them. Let the imbalance flag set so parent level
11933 	 * can try to migrate them.
11934 	 */
11935 	schedstat_inc(sd->lb_balanced[idle]);
11936 
11937 	sd->nr_balance_failed = 0;
11938 
11939 out_one_pinned:
11940 	ld_moved = 0;
11941 
11942 	/*
11943 	 * newidle_balance() disregards balance intervals, so we could
11944 	 * repeatedly reach this code, which would lead to balance_interval
11945 	 * skyrocketing in a short amount of time. Skip the balance_interval
11946 	 * increase logic to avoid that.
11947 	 */
11948 	if (env.idle == CPU_NEWLY_IDLE)
11949 		goto out;
11950 
11951 	/* tune up the balancing interval */
11952 	if ((env.flags & LBF_ALL_PINNED &&
11953 	     sd->balance_interval < MAX_PINNED_INTERVAL) ||
11954 	    sd->balance_interval < sd->max_interval)
11955 		sd->balance_interval *= 2;
11956 out:
11957 	return ld_moved;
11958 }
11959 
11960 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)11961 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11962 {
11963 	unsigned long interval = sd->balance_interval;
11964 
11965 	if (cpu_busy)
11966 		interval *= sd->busy_factor;
11967 
11968 	/* scale ms to jiffies */
11969 	interval = msecs_to_jiffies(interval);
11970 
11971 	/*
11972 	 * Reduce likelihood of busy balancing at higher domains racing with
11973 	 * balancing at lower domains by preventing their balancing periods
11974 	 * from being multiples of each other.
11975 	 */
11976 	if (cpu_busy)
11977 		interval -= 1;
11978 
11979 	interval = clamp(interval, 1UL, max_load_balance_interval);
11980 
11981 	return interval;
11982 }
11983 
11984 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)11985 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11986 {
11987 	unsigned long interval, next;
11988 
11989 	/* used by idle balance, so cpu_busy = 0 */
11990 	interval = get_sd_balance_interval(sd, 0);
11991 	next = sd->last_balance + interval;
11992 
11993 	if (time_after(*next_balance, next))
11994 		*next_balance = next;
11995 }
11996 
11997 /*
11998  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11999  * running tasks off the busiest CPU onto idle CPUs. It requires at
12000  * least 1 task to be running on each physical CPU where possible, and
12001  * avoids physical / logical imbalances.
12002  */
active_load_balance_cpu_stop(void * data)12003 static int active_load_balance_cpu_stop(void *data)
12004 {
12005 	struct rq *busiest_rq = data;
12006 	int busiest_cpu = cpu_of(busiest_rq);
12007 	int target_cpu = busiest_rq->push_cpu;
12008 	struct rq *target_rq = cpu_rq(target_cpu);
12009 	struct sched_domain *sd = NULL;
12010 	struct task_struct *p = NULL;
12011 	struct rq_flags rf;
12012 #ifdef CONFIG_SCHED_EAS
12013 	struct task_struct *push_task;
12014 	int push_task_detached = 0;
12015 #endif
12016 
12017 	rq_lock_irq(busiest_rq, &rf);
12018 	/*
12019 	 * Between queueing the stop-work and running it is a hole in which
12020 	 * CPUs can become inactive. We should not move tasks from or to
12021 	 * inactive CPUs.
12022 	 */
12023 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12024 		goto out_unlock;
12025 
12026 	/* Make sure the requested CPU hasn't gone down in the meantime: */
12027 	if (unlikely(busiest_cpu != smp_processor_id() ||
12028 		     !busiest_rq->active_balance))
12029 		goto out_unlock;
12030 
12031 	/* Is there any task to move? */
12032 	if (busiest_rq->nr_running <= 1)
12033 		goto out_unlock;
12034 
12035 	/*
12036 	 * This condition is "impossible", if it occurs
12037 	 * we need to fix it. Originally reported by
12038 	 * Bjorn Helgaas on a 128-CPU setup.
12039 	 */
12040 	WARN_ON_ONCE(busiest_rq == target_rq);
12041 #ifdef CONFIG_SCHED_EAS
12042 	push_task = busiest_rq->push_task;
12043 	target_cpu = busiest_rq->push_cpu;
12044 	if (push_task) {
12045 		struct lb_env env = {
12046 			.sd		= sd,
12047 			.dst_cpu	= target_cpu,
12048 			.dst_rq		= target_rq,
12049 			.src_cpu	= busiest_rq->cpu,
12050 			.src_rq		= busiest_rq,
12051 			.idle		= CPU_IDLE,
12052 			.flags		= 0,
12053 			.loop		= 0,
12054 		};
12055 		if (task_on_rq_queued(push_task) &&
12056 		    push_task->__state ==  TASK_RUNNING &&
12057 		    task_cpu(push_task) == busiest_cpu &&
12058 		    cpu_online(target_cpu)) {
12059 			update_rq_clock(busiest_rq);
12060 			detach_task(push_task, &env);
12061 			push_task_detached = 1;
12062 		}
12063 		goto out_unlock;
12064 	}
12065 #endif
12066 
12067 	/* Search for an sd spanning us and the target CPU. */
12068 	rcu_read_lock();
12069 	for_each_domain(target_cpu, sd) {
12070 		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12071 			break;
12072 	}
12073 
12074 	if (likely(sd)) {
12075 		struct lb_env env = {
12076 			.sd		= sd,
12077 			.dst_cpu	= target_cpu,
12078 			.dst_rq		= target_rq,
12079 			.src_cpu	= busiest_rq->cpu,
12080 			.src_rq		= busiest_rq,
12081 			.idle		= CPU_IDLE,
12082 			.flags		= LBF_ACTIVE_LB,
12083 		};
12084 
12085 		schedstat_inc(sd->alb_count);
12086 		update_rq_clock(busiest_rq);
12087 
12088 		p = detach_one_task(&env);
12089 		if (p) {
12090 			schedstat_inc(sd->alb_pushed);
12091 			/* Active balancing done, reset the failure counter. */
12092 			sd->nr_balance_failed = 0;
12093 		} else {
12094 			schedstat_inc(sd->alb_failed);
12095 		}
12096 	}
12097 	rcu_read_unlock();
12098 out_unlock:
12099 	busiest_rq->active_balance = 0;
12100 
12101 #ifdef CONFIG_SCHED_EAS
12102 	push_task = busiest_rq->push_task;
12103 	if (push_task)
12104 		busiest_rq->push_task = NULL;
12105 #endif
12106 	rq_unlock(busiest_rq, &rf);
12107 
12108 #ifdef CONFIG_SCHED_EAS
12109 	if (push_task) {
12110 		if (push_task_detached)
12111 			attach_one_task(target_rq, push_task);
12112 
12113 		put_task_struct(push_task);
12114 	}
12115 #endif
12116 
12117 	if (p)
12118 		attach_one_task(target_rq, p);
12119 
12120 	local_irq_enable();
12121 
12122 	return 0;
12123 }
12124 
12125 static DEFINE_SPINLOCK(balancing);
12126 
12127 /*
12128  * Scale the max load_balance interval with the number of CPUs in the system.
12129  * This trades load-balance latency on larger machines for less cross talk.
12130  */
update_max_interval(void)12131 void update_max_interval(void)
12132 {
12133 	unsigned int available_cpus;
12134 #ifdef CONFIG_CPU_ISOLATION_OPT
12135 	cpumask_t avail_mask;
12136 
12137 	cpumask_andnot(&avail_mask, cpu_online_mask, cpu_isolated_mask);
12138 	available_cpus = cpumask_weight(&avail_mask);
12139 #else
12140 	available_cpus = num_online_cpus();
12141 #endif
12142 
12143 	max_load_balance_interval = HZ*available_cpus/10;
12144 }
12145 
update_newidle_cost(struct sched_domain * sd,u64 cost)12146 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
12147 {
12148 	if (cost > sd->max_newidle_lb_cost) {
12149 		/*
12150 		 * Track max cost of a domain to make sure to not delay the
12151 		 * next wakeup on the CPU.
12152 		 */
12153 		sd->max_newidle_lb_cost = cost;
12154 		sd->last_decay_max_lb_cost = jiffies;
12155 	} else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
12156 		/*
12157 		 * Decay the newidle max times by ~1% per second to ensure that
12158 		 * it is not outdated and the current max cost is actually
12159 		 * shorter.
12160 		 */
12161 		sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12162 		sd->last_decay_max_lb_cost = jiffies;
12163 
12164 		return true;
12165 	}
12166 
12167 	return false;
12168 }
12169 
12170 /*
12171  * It checks each scheduling domain to see if it is due to be balanced,
12172  * and initiates a balancing operation if so.
12173  *
12174  * Balancing parameters are set up in init_sched_domains.
12175  */
rebalance_domains(struct rq * rq,enum cpu_idle_type idle)12176 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
12177 {
12178 	int continue_balancing = 1;
12179 	int cpu = rq->cpu;
12180 	int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12181 	unsigned long interval;
12182 	struct sched_domain *sd;
12183 	/* Earliest time when we have to do rebalance again */
12184 	unsigned long next_balance = jiffies + 60*HZ;
12185 	int update_next_balance = 0;
12186 	int need_serialize, need_decay = 0;
12187 	u64 max_cost = 0;
12188 
12189 	rcu_read_lock();
12190 	for_each_domain(cpu, sd) {
12191 		/*
12192 		 * Decay the newidle max times here because this is a regular
12193 		 * visit to all the domains.
12194 		 */
12195 		need_decay = update_newidle_cost(sd, 0);
12196 		max_cost += sd->max_newidle_lb_cost;
12197 
12198 		/*
12199 		 * Stop the load balance at this level. There is another
12200 		 * CPU in our sched group which is doing load balancing more
12201 		 * actively.
12202 		 */
12203 		if (!continue_balancing) {
12204 			if (need_decay)
12205 				continue;
12206 			break;
12207 		}
12208 
12209 		interval = get_sd_balance_interval(sd, busy);
12210 
12211 		need_serialize = sd->flags & SD_SERIALIZE;
12212 		if (need_serialize) {
12213 			if (!spin_trylock(&balancing))
12214 				goto out;
12215 		}
12216 
12217 		if (time_after_eq(jiffies, sd->last_balance + interval)) {
12218 			if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
12219 				/*
12220 				 * The LBF_DST_PINNED logic could have changed
12221 				 * env->dst_cpu, so we can't know our idle
12222 				 * state even if we migrated tasks. Update it.
12223 				 */
12224 				idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
12225 				busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12226 			}
12227 			sd->last_balance = jiffies;
12228 			interval = get_sd_balance_interval(sd, busy);
12229 		}
12230 		if (need_serialize)
12231 			spin_unlock(&balancing);
12232 out:
12233 		if (time_after(next_balance, sd->last_balance + interval)) {
12234 			next_balance = sd->last_balance + interval;
12235 			update_next_balance = 1;
12236 		}
12237 	}
12238 	if (need_decay) {
12239 		/*
12240 		 * Ensure the rq-wide value also decays but keep it at a
12241 		 * reasonable floor to avoid funnies with rq->avg_idle.
12242 		 */
12243 		rq->max_idle_balance_cost =
12244 			max((u64)sysctl_sched_migration_cost, max_cost);
12245 	}
12246 	rcu_read_unlock();
12247 
12248 	/*
12249 	 * next_balance will be updated only when there is a need.
12250 	 * When the cpu is attached to null domain for ex, it will not be
12251 	 * updated.
12252 	 */
12253 	if (likely(update_next_balance))
12254 		rq->next_balance = next_balance;
12255 
12256 }
12257 
on_null_domain(struct rq * rq)12258 static inline int on_null_domain(struct rq *rq)
12259 {
12260 	return unlikely(!rcu_dereference_sched(rq->sd));
12261 }
12262 
12263 #ifdef CONFIG_NO_HZ_COMMON
12264 /*
12265  * idle load balancing details
12266  * - When one of the busy CPUs notice that there may be an idle rebalancing
12267  *   needed, they will kick the idle load balancer, which then does idle
12268  *   load balancing for all the idle CPUs.
12269  * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED not set
12270  *   anywhere yet.
12271  */
12272 
find_new_ilb(void)12273 static inline int find_new_ilb(void)
12274 {
12275 	int ilb;
12276 	const struct cpumask *hk_mask;
12277 
12278 	hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
12279 
12280 	for_each_cpu_and(ilb, nohz.idle_cpus_mask, hk_mask) {
12281 
12282 		if (cpu_isolated(ilb))
12283 			continue;
12284 
12285 		if (ilb == smp_processor_id())
12286 			continue;
12287 
12288 		if (idle_cpu(ilb))
12289 			return ilb;
12290 	}
12291 
12292 	return nr_cpu_ids;
12293 }
12294 
12295 /*
12296  * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
12297  * idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
12298  */
kick_ilb(unsigned int flags)12299 static void kick_ilb(unsigned int flags)
12300 {
12301 	int ilb_cpu;
12302 
12303 	/*
12304 	 * Increase nohz.next_balance only when if full ilb is triggered but
12305 	 * not if we only update stats.
12306 	 */
12307 	if (flags & NOHZ_BALANCE_KICK)
12308 		nohz.next_balance = jiffies+1;
12309 
12310 	ilb_cpu = find_new_ilb();
12311 
12312 	if (ilb_cpu >= nr_cpu_ids)
12313 		return;
12314 
12315 	/*
12316 	 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12317 	 * the first flag owns it; cleared by nohz_csd_func().
12318 	 */
12319 	flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12320 	if (flags & NOHZ_KICK_MASK)
12321 		return;
12322 
12323 	/*
12324 	 * This way we generate an IPI on the target CPU which
12325 	 * is idle. And the softirq performing nohz idle load balance
12326 	 * will be run before returning from the IPI.
12327 	 */
12328 	smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12329 }
12330 
12331 /*
12332  * Current decision point for kicking the idle load balancer in the presence
12333  * of idle CPUs in the system.
12334  */
nohz_balancer_kick(struct rq * rq)12335 static void nohz_balancer_kick(struct rq *rq)
12336 {
12337 	unsigned long now = jiffies;
12338 	struct sched_domain_shared *sds;
12339 	struct sched_domain *sd;
12340 	int nr_busy, i, cpu = rq->cpu;
12341 	unsigned int flags = 0;
12342 	cpumask_t cpumask;
12343 
12344 	if (unlikely(rq->idle_balance))
12345 		return;
12346 
12347 	/*
12348 	 * We may be recently in ticked or tickless idle mode. At the first
12349 	 * busy tick after returning from idle, we will update the busy stats.
12350 	 */
12351 	nohz_balance_exit_idle(rq);
12352 
12353 	/*
12354 	 * None are in tickless mode and hence no need for NOHZ idle load
12355 	 * balancing.
12356 	 */
12357 #ifdef CONFIG_CPU_ISOLATION_OPT
12358 	cpumask_andnot(&cpumask, nohz.idle_cpus_mask, cpu_isolated_mask);
12359 	if (cpumask_empty(&cpumask))
12360 		return;
12361 #else
12362 	cpumask_copy(&cpumask, nohz.idle_cpus_mask);
12363 	if (likely(!atomic_read(&nohz.nr_cpus)))
12364 		return;
12365 #endif
12366 
12367 	if (READ_ONCE(nohz.has_blocked) &&
12368 	    time_after(now, READ_ONCE(nohz.next_blocked)))
12369 		flags = NOHZ_STATS_KICK;
12370 
12371 	if (time_before(now, nohz.next_balance))
12372 		goto out;
12373 
12374 	if (rq->nr_running >= 2) {
12375 		flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12376 		goto out;
12377 	}
12378 
12379 	rcu_read_lock();
12380 
12381 	sd = rcu_dereference(rq->sd);
12382 	if (sd) {
12383 		/*
12384 		 * If there's a CFS task and the current CPU has reduced
12385 		 * capacity; kick the ILB to see if there's a better CPU to run
12386 		 * on.
12387 		 */
12388 		if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
12389 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12390 			goto unlock;
12391 		}
12392 	}
12393 
12394 	sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12395 	if (sd) {
12396 		/*
12397 		 * When ASYM_PACKING; see if there's a more preferred CPU
12398 		 * currently idle; in which case, kick the ILB to move tasks
12399 		 * around.
12400 		 *
12401 		 * When balancing betwen cores, all the SMT siblings of the
12402 		 * preferred CPU must be idle.
12403 		 */
12404 		for_each_cpu_and(i, sched_domain_span(sd), &cpumask) {
12405 			if (sched_use_asym_prio(sd, i) &&
12406 			    sched_asym_prefer(i, cpu)) {
12407 				flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12408 				goto unlock;
12409 			}
12410 		}
12411 	}
12412 
12413 	sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12414 	if (sd) {
12415 		/*
12416 		 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12417 		 * to run the misfit task on.
12418 		 */
12419 		if (check_misfit_status(rq, sd)) {
12420 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12421 			goto unlock;
12422 		}
12423 
12424 		/*
12425 		 * For asymmetric systems, we do not want to nicely balance
12426 		 * cache use, instead we want to embrace asymmetry and only
12427 		 * ensure tasks have enough CPU capacity.
12428 		 *
12429 		 * Skip the LLC logic because it's not relevant in that case.
12430 		 */
12431 		goto unlock;
12432 	}
12433 
12434 	sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12435 	if (sds) {
12436 		/*
12437 		 * If there is an imbalance between LLC domains (IOW we could
12438 		 * increase the overall cache use), we need some less-loaded LLC
12439 		 * domain to pull some load. Likewise, we may need to spread
12440 		 * load within the current LLC domain (e.g. packed SMT cores but
12441 		 * other CPUs are idle). We can't really know from here how busy
12442 		 * the others are - so just get a nohz balance going if it looks
12443 		 * like this LLC domain has tasks we could move.
12444 		 */
12445 		nr_busy = atomic_read(&sds->nr_busy_cpus);
12446 		if (nr_busy > 1) {
12447 			flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12448 			goto unlock;
12449 		}
12450 	}
12451 unlock:
12452 	rcu_read_unlock();
12453 out:
12454 	if (READ_ONCE(nohz.needs_update))
12455 		flags |= NOHZ_NEXT_KICK;
12456 
12457 	if (flags)
12458 		kick_ilb(flags);
12459 }
12460 
set_cpu_sd_state_busy(int cpu)12461 static void set_cpu_sd_state_busy(int cpu)
12462 {
12463 	struct sched_domain *sd;
12464 
12465 	rcu_read_lock();
12466 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12467 
12468 	if (!sd || !sd->nohz_idle)
12469 		goto unlock;
12470 	sd->nohz_idle = 0;
12471 
12472 	atomic_inc(&sd->shared->nr_busy_cpus);
12473 unlock:
12474 	rcu_read_unlock();
12475 }
12476 
nohz_balance_exit_idle(struct rq * rq)12477 void nohz_balance_exit_idle(struct rq *rq)
12478 {
12479 	SCHED_WARN_ON(rq != this_rq());
12480 
12481 	if (likely(!rq->nohz_tick_stopped))
12482 		return;
12483 
12484 	rq->nohz_tick_stopped = 0;
12485 	cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12486 	atomic_dec(&nohz.nr_cpus);
12487 
12488 	set_cpu_sd_state_busy(rq->cpu);
12489 }
12490 
set_cpu_sd_state_idle(int cpu)12491 static void set_cpu_sd_state_idle(int cpu)
12492 {
12493 	struct sched_domain *sd;
12494 
12495 	rcu_read_lock();
12496 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
12497 
12498 	if (!sd || sd->nohz_idle)
12499 		goto unlock;
12500 	sd->nohz_idle = 1;
12501 
12502 	atomic_dec(&sd->shared->nr_busy_cpus);
12503 unlock:
12504 	rcu_read_unlock();
12505 }
12506 
12507 /*
12508  * This routine will record that the CPU is going idle with tick stopped.
12509  * This info will be used in performing idle load balancing in the future.
12510  */
nohz_balance_enter_idle(int cpu)12511 void nohz_balance_enter_idle(int cpu)
12512 {
12513 	struct rq *rq = cpu_rq(cpu);
12514 
12515 	SCHED_WARN_ON(cpu != smp_processor_id());
12516 
12517 	/* If this CPU is going down, then nothing needs to be done: */
12518 	if (!cpu_active(cpu))
12519 		return;
12520 
12521 	/* Spare idle load balancing on CPUs that don't want to be disturbed: */
12522 	if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
12523 		return;
12524 
12525 	/*
12526 	 * Can be set safely without rq->lock held
12527 	 * If a clear happens, it will have evaluated last additions because
12528 	 * rq->lock is held during the check and the clear
12529 	 */
12530 	rq->has_blocked_load = 1;
12531 
12532 	/*
12533 	 * The tick is still stopped but load could have been added in the
12534 	 * meantime. We set the nohz.has_blocked flag to trig a check of the
12535 	 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12536 	 * of nohz.has_blocked can only happen after checking the new load
12537 	 */
12538 	if (rq->nohz_tick_stopped)
12539 		goto out;
12540 
12541 	/* If we're a completely isolated CPU, we don't play: */
12542 	if (on_null_domain(rq))
12543 		return;
12544 
12545 	rq->nohz_tick_stopped = 1;
12546 
12547 	cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12548 	atomic_inc(&nohz.nr_cpus);
12549 
12550 	/*
12551 	 * Ensures that if nohz_idle_balance() fails to observe our
12552 	 * @idle_cpus_mask store, it must observe the @has_blocked
12553 	 * and @needs_update stores.
12554 	 */
12555 	smp_mb__after_atomic();
12556 
12557 	set_cpu_sd_state_idle(cpu);
12558 
12559 	WRITE_ONCE(nohz.needs_update, 1);
12560 out:
12561 	/*
12562 	 * Each time a cpu enter idle, we assume that it has blocked load and
12563 	 * enable the periodic update of the load of idle cpus
12564 	 */
12565 	WRITE_ONCE(nohz.has_blocked, 1);
12566 }
12567 
update_nohz_stats(struct rq * rq)12568 static bool update_nohz_stats(struct rq *rq)
12569 {
12570 	unsigned int cpu = rq->cpu;
12571 
12572 	if (!rq->has_blocked_load)
12573 		return false;
12574 
12575 	if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12576 		return false;
12577 
12578 	if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12579 		return true;
12580 
12581 	update_blocked_averages(cpu);
12582 
12583 	return rq->has_blocked_load;
12584 }
12585 
12586 /*
12587  * Internal function that runs load balance for all idle cpus. The load balance
12588  * can be a simple update of blocked load or a complete load balance with
12589  * tasks movement depending of flags.
12590  */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12591 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12592 {
12593 	/* Earliest time when we have to do rebalance again */
12594 	unsigned long now = jiffies;
12595 	unsigned long next_balance = now + 60*HZ;
12596 	bool has_blocked_load = false;
12597 	int update_next_balance = 0;
12598 	int this_cpu = this_rq->cpu;
12599 	int balance_cpu;
12600 	struct rq *rq;
12601 	cpumask_t cpus;
12602 
12603 	SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12604 
12605 	/*
12606 	 * We assume there will be no idle load after this update and clear
12607 	 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12608 	 * set the has_blocked flag and trigger another update of idle load.
12609 	 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12610 	 * setting the flag, we are sure to not clear the state and not
12611 	 * check the load of an idle cpu.
12612 	 *
12613 	 * Same applies to idle_cpus_mask vs needs_update.
12614 	 */
12615 	if (flags & NOHZ_STATS_KICK)
12616 		WRITE_ONCE(nohz.has_blocked, 0);
12617 	if (flags & NOHZ_NEXT_KICK)
12618 		WRITE_ONCE(nohz.needs_update, 0);
12619 
12620 	/*
12621 	 * Ensures that if we miss the CPU, we must see the has_blocked
12622 	 * store from nohz_balance_enter_idle().
12623 	 */
12624 	smp_mb();
12625 
12626 #ifdef CONFIG_CPU_ISOLATION_OPT
12627 	cpumask_andnot(&cpus, nohz.idle_cpus_mask, cpu_isolated_mask);
12628 #else
12629 	cpumask_copy(&cpus, nohz.idle_cpus_mask);
12630 #endif
12631 
12632 	/*
12633 	 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12634 	 * chance for other idle cpu to pull load.
12635 	 */
12636 	for_each_cpu_wrap(balance_cpu,  &cpus, this_cpu+1) {
12637 		if (!idle_cpu(balance_cpu))
12638 			continue;
12639 
12640 		/*
12641 		 * If this CPU gets work to do, stop the load balancing
12642 		 * work being done for other CPUs. Next load
12643 		 * balancing owner will pick it up.
12644 		 */
12645 		if (!idle_cpu(this_cpu) && need_resched()) {
12646 			if (flags & NOHZ_STATS_KICK)
12647 				has_blocked_load = true;
12648 			if (flags & NOHZ_NEXT_KICK)
12649 				WRITE_ONCE(nohz.needs_update, 1);
12650 			goto abort;
12651 		}
12652 
12653 		rq = cpu_rq(balance_cpu);
12654 
12655 		if (flags & NOHZ_STATS_KICK)
12656 			has_blocked_load |= update_nohz_stats(rq);
12657 
12658 		/*
12659 		 * If time for next balance is due,
12660 		 * do the balance.
12661 		 */
12662 		if (time_after_eq(jiffies, rq->next_balance)) {
12663 			struct rq_flags rf;
12664 
12665 			rq_lock_irqsave(rq, &rf);
12666 			update_rq_clock(rq);
12667 			rq_unlock_irqrestore(rq, &rf);
12668 
12669 			if (flags & NOHZ_BALANCE_KICK)
12670 				rebalance_domains(rq, CPU_IDLE);
12671 		}
12672 
12673 		if (time_after(next_balance, rq->next_balance)) {
12674 			next_balance = rq->next_balance;
12675 			update_next_balance = 1;
12676 		}
12677 	}
12678 
12679 	/*
12680 	 * next_balance will be updated only when there is a need.
12681 	 * When the CPU is attached to null domain for ex, it will not be
12682 	 * updated.
12683 	 */
12684 	if (likely(update_next_balance))
12685 		nohz.next_balance = next_balance;
12686 
12687 	if (flags & NOHZ_STATS_KICK)
12688 		WRITE_ONCE(nohz.next_blocked,
12689 			   now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12690 
12691 abort:
12692 	/* There is still blocked load, enable periodic update */
12693 	if (has_blocked_load)
12694 		WRITE_ONCE(nohz.has_blocked, 1);
12695 }
12696 
12697 /*
12698  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12699  * rebalancing for all the cpus for whom scheduler ticks are stopped.
12700  */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12701 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12702 {
12703 	unsigned int flags = this_rq->nohz_idle_balance;
12704 
12705 	if (!flags)
12706 		return false;
12707 
12708 	this_rq->nohz_idle_balance = 0;
12709 
12710 	if (idle != CPU_IDLE)
12711 		return false;
12712 
12713 	_nohz_idle_balance(this_rq, flags);
12714 
12715 	return true;
12716 }
12717 
12718 /*
12719  * Check if we need to run the ILB for updating blocked load before entering
12720  * idle state.
12721  */
nohz_run_idle_balance(int cpu)12722 void nohz_run_idle_balance(int cpu)
12723 {
12724 	unsigned int flags;
12725 
12726 	flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12727 
12728 	/*
12729 	 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12730 	 * (ie NOHZ_STATS_KICK set) and will do the same.
12731 	 */
12732 	if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12733 		_nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12734 }
12735 
nohz_newidle_balance(struct rq * this_rq)12736 static void nohz_newidle_balance(struct rq *this_rq)
12737 {
12738 	int this_cpu = this_rq->cpu;
12739 
12740 	/*
12741 	 * This CPU doesn't want to be disturbed by scheduler
12742 	 * housekeeping
12743 	 */
12744 	if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
12745 		return;
12746 
12747 	/* Will wake up very soon. No time for doing anything else*/
12748 	if (this_rq->avg_idle < sysctl_sched_migration_cost)
12749 		return;
12750 
12751 	/* Don't need to update blocked load of idle CPUs*/
12752 	if (!READ_ONCE(nohz.has_blocked) ||
12753 	    time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12754 		return;
12755 
12756 	/*
12757 	 * Set the need to trigger ILB in order to update blocked load
12758 	 * before entering idle state.
12759 	 */
12760 	atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12761 }
12762 
12763 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)12764 static inline void nohz_balancer_kick(struct rq *rq) { }
12765 
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12766 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12767 {
12768 	return false;
12769 }
12770 
nohz_newidle_balance(struct rq * this_rq)12771 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12772 #endif /* CONFIG_NO_HZ_COMMON */
12773 
12774 /*
12775  * newidle_balance is called by schedule() if this_cpu is about to become
12776  * idle. Attempts to pull tasks from other CPUs.
12777  *
12778  * Returns:
12779  *   < 0 - we released the lock and there are !fair tasks present
12780  *     0 - failed, no new tasks
12781  *   > 0 - success, new (fair) tasks present
12782  */
newidle_balance(struct rq * this_rq,struct rq_flags * rf)12783 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12784 {
12785 	unsigned long next_balance = jiffies + HZ;
12786 	int this_cpu = this_rq->cpu;
12787 	u64 t0, t1, curr_cost = 0;
12788 	struct sched_domain *sd;
12789 	int pulled_task = 0;
12790 
12791 	if (cpu_isolated(this_cpu))
12792 		return 0;
12793 
12794 	update_misfit_status(NULL, this_rq);
12795 
12796 	/*
12797 	 * There is a task waiting to run. No need to search for one.
12798 	 * Return 0; the task will be enqueued when switching to idle.
12799 	 */
12800 	if (this_rq->ttwu_pending)
12801 		return 0;
12802 
12803 	/*
12804 	 * We must set idle_stamp _before_ calling idle_balance(), such that we
12805 	 * measure the duration of idle_balance() as idle time.
12806 	 */
12807 	this_rq->idle_stamp = rq_clock(this_rq);
12808 
12809 	/*
12810 	 * Do not pull tasks towards !active CPUs...
12811 	 */
12812 	if (!cpu_active(this_cpu))
12813 		return 0;
12814 
12815 	/*
12816 	 * This is OK, because current is on_cpu, which avoids it being picked
12817 	 * for load-balance and preemption/IRQs are still disabled avoiding
12818 	 * further scheduler activity on it and we're being very careful to
12819 	 * re-start the picking loop.
12820 	 */
12821 	rq_unpin_lock(this_rq, rf);
12822 
12823 	rcu_read_lock();
12824 	sd = rcu_dereference_check_sched_domain(this_rq->sd);
12825 
12826 	if (!READ_ONCE(this_rq->rd->overload) ||
12827 	    (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12828 
12829 		if (sd)
12830 			update_next_balance(sd, &next_balance);
12831 		rcu_read_unlock();
12832 
12833 		goto out;
12834 	}
12835 	rcu_read_unlock();
12836 
12837 	raw_spin_rq_unlock(this_rq);
12838 
12839 	t0 = sched_clock_cpu(this_cpu);
12840 	update_blocked_averages(this_cpu);
12841 
12842 	rcu_read_lock();
12843 	for_each_domain(this_cpu, sd) {
12844 		int continue_balancing = 1;
12845 		u64 domain_cost;
12846 
12847 		update_next_balance(sd, &next_balance);
12848 
12849 		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12850 			break;
12851 
12852 		if (sd->flags & SD_BALANCE_NEWIDLE) {
12853 
12854 			pulled_task = load_balance(this_cpu, this_rq,
12855 						   sd, CPU_NEWLY_IDLE,
12856 						   &continue_balancing);
12857 
12858 			t1 = sched_clock_cpu(this_cpu);
12859 			domain_cost = t1 - t0;
12860 			update_newidle_cost(sd, domain_cost);
12861 
12862 			curr_cost += domain_cost;
12863 			t0 = t1;
12864 		}
12865 
12866 		/*
12867 		 * Stop searching for tasks to pull if there are
12868 		 * now runnable tasks on this rq.
12869 		 */
12870 		if (pulled_task || this_rq->nr_running > 0 ||
12871 		    this_rq->ttwu_pending)
12872 			break;
12873 	}
12874 	rcu_read_unlock();
12875 
12876 	raw_spin_rq_lock(this_rq);
12877 
12878 	if (curr_cost > this_rq->max_idle_balance_cost)
12879 		this_rq->max_idle_balance_cost = curr_cost;
12880 
12881 	/*
12882 	 * While browsing the domains, we released the rq lock, a task could
12883 	 * have been enqueued in the meantime. Since we're not going idle,
12884 	 * pretend we pulled a task.
12885 	 */
12886 	if (this_rq->cfs.h_nr_running && !pulled_task)
12887 		pulled_task = 1;
12888 
12889 	/* Is there a task of a high priority class? */
12890 	if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12891 		pulled_task = -1;
12892 
12893 out:
12894 	/* Move the next balance forward */
12895 	if (time_after(this_rq->next_balance, next_balance))
12896 		this_rq->next_balance = next_balance;
12897 
12898 	if (pulled_task)
12899 		this_rq->idle_stamp = 0;
12900 	else
12901 		nohz_newidle_balance(this_rq);
12902 
12903 	rq_repin_lock(this_rq, rf);
12904 
12905 	return pulled_task;
12906 }
12907 
12908 /*
12909  * run_rebalance_domains is triggered when needed from the scheduler tick.
12910  * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12911  */
run_rebalance_domains(struct softirq_action * h)12912 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12913 {
12914 	struct rq *this_rq = this_rq();
12915 	enum cpu_idle_type idle = this_rq->idle_balance ?
12916 						CPU_IDLE : CPU_NOT_IDLE;
12917 
12918 	/*
12919 	 * Since core isolation doesn't update nohz.idle_cpus_mask, there
12920 	 * is a possibility this nohz kicked cpu could be isolated. Hence
12921 	 * return if the cpu is isolated.
12922 	 */
12923 	if (cpu_isolated(this_rq->cpu))
12924 		return;
12925 
12926 	/*
12927 	 * If this CPU has a pending nohz_balance_kick, then do the
12928 	 * balancing on behalf of the other idle CPUs whose ticks are
12929 	 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12930 	 * give the idle CPUs a chance to load balance. Else we may
12931 	 * load balance only within the local sched_domain hierarchy
12932 	 * and abort nohz_idle_balance altogether if we pull some load.
12933 	 */
12934 	if (nohz_idle_balance(this_rq, idle))
12935 		return;
12936 
12937 	/* normal load balance */
12938 	update_blocked_averages(this_rq->cpu);
12939 	rebalance_domains(this_rq, idle);
12940 }
12941 
12942 /*
12943  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12944  */
trigger_load_balance(struct rq * rq)12945 void trigger_load_balance(struct rq *rq)
12946 {
12947 	/*
12948 	 * Don't need to rebalance while attached to NULL domain or
12949 	 * runqueue CPU is not active
12950 	 */
12951 	if (unlikely(on_null_domain(rq)) || cpu_isolated(cpu_of(rq)) || !cpu_active(cpu_of(rq)))
12952 		return;
12953 
12954 	if (time_after_eq(jiffies, rq->next_balance))
12955 		raise_softirq(SCHED_SOFTIRQ);
12956 
12957 	nohz_balancer_kick(rq);
12958 }
12959 
rq_online_fair(struct rq * rq)12960 static void rq_online_fair(struct rq *rq)
12961 {
12962 	update_sysctl();
12963 
12964 	update_runtime_enabled(rq);
12965 }
12966 
rq_offline_fair(struct rq * rq)12967 static void rq_offline_fair(struct rq *rq)
12968 {
12969 	update_sysctl();
12970 
12971 	/* Ensure any throttled groups are reachable by pick_next_task */
12972 	unthrottle_offline_cfs_rqs(rq);
12973 }
12974 
12975 #ifdef CONFIG_SCHED_EAS
12976 static inline int
kick_active_balance(struct rq * rq,struct task_struct * p,int new_cpu)12977 kick_active_balance(struct rq *rq, struct task_struct *p, int new_cpu)
12978 {
12979 	unsigned long flags;
12980 	int rc = 0;
12981 
12982 	if (cpu_of(rq) == new_cpu)
12983 		return rc;
12984 
12985 	/* Invoke active balance to force migrate currently running task */
12986 	raw_spin_lock_irqsave(&rq->__lock, flags);
12987 	if (!rq->active_balance) {
12988 		rq->active_balance = 1;
12989 		rq->push_cpu = new_cpu;
12990 		get_task_struct(p);
12991 		rq->push_task = p;
12992 		rc = 1;
12993 	}
12994 	raw_spin_unlock_irqrestore(&rq->__lock, flags);
12995 	return rc;
12996 }
12997 
12998 DEFINE_RAW_SPINLOCK(migration_lock);
check_for_migration_fair(struct rq * rq,struct task_struct * p)12999 static void check_for_migration_fair(struct rq *rq, struct task_struct *p)
13000 {
13001 	int active_balance;
13002 	int new_cpu = -1;
13003 	int prev_cpu = task_cpu(p);
13004 	int ret;
13005 
13006 #ifdef CONFIG_SCHED_RTG
13007 	bool need_down_migrate = false;
13008 	struct cpumask *rtg_target = find_rtg_target(p);
13009 
13010 	if (rtg_target &&
13011 	    (capacity_orig_of(prev_cpu) >
13012 	     capacity_orig_of(cpumask_first(rtg_target))))
13013 		need_down_migrate = true;
13014 #endif
13015 
13016 	if (rq->misfit_task_load) {
13017 		if (rq->curr->__state != TASK_RUNNING ||
13018 		    rq->curr->nr_cpus_allowed == 1)
13019 			return;
13020 
13021 		raw_spin_lock(&migration_lock);
13022 #ifdef CONFIG_SCHED_RTG
13023 		if (rtg_target) {
13024 			new_cpu = find_rtg_cpu(p);
13025 
13026 			if (new_cpu != -1 && need_down_migrate &&
13027 			    cpumask_test_cpu(new_cpu, rtg_target) &&
13028 			    idle_cpu(new_cpu))
13029 				goto do_active_balance;
13030 
13031 			if (new_cpu != -1 &&
13032 			    capacity_orig_of(new_cpu) > capacity_orig_of(prev_cpu))
13033 				goto do_active_balance;
13034 
13035 			goto out_unlock;
13036 		}
13037 #endif
13038 		rcu_read_lock();
13039 		new_cpu = find_energy_efficient_cpu(p, prev_cpu);
13040 		rcu_read_unlock();
13041 
13042 		if (new_cpu == -1 ||
13043 		    capacity_orig_of(new_cpu) <= capacity_orig_of(prev_cpu))
13044 			goto out_unlock;
13045 #ifdef CONFIG_SCHED_RTG
13046 do_active_balance:
13047 #endif
13048 		active_balance = kick_active_balance(rq, p, new_cpu);
13049 		if (active_balance) {
13050 			mark_reserved(new_cpu);
13051 			raw_spin_unlock(&migration_lock);
13052 			ret = stop_one_cpu_nowait(prev_cpu,
13053 				active_load_balance_cpu_stop, rq,
13054 				&rq->active_balance_work);
13055 			if (!ret)
13056 				clear_reserved(new_cpu);
13057 			else
13058 				wake_up_if_idle(new_cpu);
13059 			return;
13060 		}
13061 out_unlock:
13062 		raw_spin_unlock(&migration_lock);
13063 	}
13064 }
13065 #endif /* CONFIG_SCHED_EAS */
13066 
13067 #endif /* CONFIG_SMP */
13068 
13069 #ifdef CONFIG_SCHED_CORE
13070 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13071 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13072 {
13073 	u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13074 	u64 slice = se->slice;
13075 
13076 	return (rtime * min_nr_tasks > slice);
13077 }
13078 
13079 #define MIN_NR_TASKS_DURING_FORCEIDLE	2
task_tick_core(struct rq * rq,struct task_struct * curr)13080 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13081 {
13082 	if (!sched_core_enabled(rq))
13083 		return;
13084 
13085 	/*
13086 	 * If runqueue has only one task which used up its slice and
13087 	 * if the sibling is forced idle, then trigger schedule to
13088 	 * give forced idle task a chance.
13089 	 *
13090 	 * sched_slice() considers only this active rq and it gets the
13091 	 * whole slice. But during force idle, we have siblings acting
13092 	 * like a single runqueue and hence we need to consider runnable
13093 	 * tasks on this CPU and the forced idle CPU. Ideally, we should
13094 	 * go through the forced idle rq, but that would be a perf hit.
13095 	 * We can assume that the forced idle CPU has at least
13096 	 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13097 	 * if we need to give up the CPU.
13098 	 */
13099 	if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
13100 	    __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13101 		resched_curr(rq);
13102 }
13103 
13104 /*
13105  * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
13106  */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13107 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13108 			 bool forceidle)
13109 {
13110 	for_each_sched_entity(se) {
13111 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13112 
13113 		if (forceidle) {
13114 			if (cfs_rq->forceidle_seq == fi_seq)
13115 				break;
13116 			cfs_rq->forceidle_seq = fi_seq;
13117 		}
13118 
13119 		cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
13120 	}
13121 }
13122 
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13123 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13124 {
13125 	struct sched_entity *se = &p->se;
13126 
13127 	if (p->sched_class != &fair_sched_class)
13128 		return;
13129 
13130 	se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13131 }
13132 
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13133 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13134 			bool in_fi)
13135 {
13136 	struct rq *rq = task_rq(a);
13137 	const struct sched_entity *sea = &a->se;
13138 	const struct sched_entity *seb = &b->se;
13139 	struct cfs_rq *cfs_rqa;
13140 	struct cfs_rq *cfs_rqb;
13141 	s64 delta;
13142 
13143 	SCHED_WARN_ON(task_rq(b)->core != rq->core);
13144 
13145 #ifdef CONFIG_FAIR_GROUP_SCHED
13146 	/*
13147 	 * Find an se in the hierarchy for tasks a and b, such that the se's
13148 	 * are immediate siblings.
13149 	 */
13150 	while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13151 		int sea_depth = sea->depth;
13152 		int seb_depth = seb->depth;
13153 
13154 		if (sea_depth >= seb_depth)
13155 			sea = parent_entity(sea);
13156 		if (sea_depth <= seb_depth)
13157 			seb = parent_entity(seb);
13158 	}
13159 
13160 	se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13161 	se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13162 
13163 	cfs_rqa = sea->cfs_rq;
13164 	cfs_rqb = seb->cfs_rq;
13165 #else
13166 	cfs_rqa = &task_rq(a)->cfs;
13167 	cfs_rqb = &task_rq(b)->cfs;
13168 #endif
13169 
13170 	/*
13171 	 * Find delta after normalizing se's vruntime with its cfs_rq's
13172 	 * min_vruntime_fi, which would have been updated in prior calls
13173 	 * to se_fi_update().
13174 	 */
13175 	delta = (s64)(sea->vruntime - seb->vruntime) +
13176 		(s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
13177 
13178 	return delta > 0;
13179 }
13180 
task_is_throttled_fair(struct task_struct * p,int cpu)13181 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13182 {
13183 	struct cfs_rq *cfs_rq;
13184 
13185 #ifdef CONFIG_FAIR_GROUP_SCHED
13186 	cfs_rq = task_group(p)->cfs_rq[cpu];
13187 #else
13188 	cfs_rq = &cpu_rq(cpu)->cfs;
13189 #endif
13190 	return throttled_hierarchy(cfs_rq);
13191 }
13192 #else
task_tick_core(struct rq * rq,struct task_struct * curr)13193 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13194 #endif
13195 
13196 /*
13197  * scheduler tick hitting a task of our scheduling class.
13198  *
13199  * NOTE: This function can be called remotely by the tick offload that
13200  * goes along full dynticks. Therefore no local assumption can be made
13201  * and everything must be accessed through the @rq and @curr passed in
13202  * parameters.
13203  */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13204 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13205 {
13206 	struct cfs_rq *cfs_rq;
13207 	struct sched_entity *se = &curr->se;
13208 
13209 	for_each_sched_entity(se) {
13210 		cfs_rq = cfs_rq_of(se);
13211 		entity_tick(cfs_rq, se, queued);
13212 	}
13213 
13214 	if (static_branch_unlikely(&sched_numa_balancing))
13215 		task_tick_numa(rq, curr);
13216 
13217 	update_misfit_status(curr, rq);
13218 	check_update_overutilized_status(task_rq(curr));
13219 
13220 	task_tick_core(rq, curr);
13221 }
13222 
13223 /*
13224  * called on fork with the child task as argument from the parent's context
13225  *  - child not yet on the tasklist
13226  *  - preemption disabled
13227  */
task_fork_fair(struct task_struct * p)13228 static void task_fork_fair(struct task_struct *p)
13229 {
13230 	struct sched_entity *se = &p->se, *curr;
13231 	struct cfs_rq *cfs_rq;
13232 	struct rq *rq = this_rq();
13233 	struct rq_flags rf;
13234 
13235 	rq_lock(rq, &rf);
13236 	update_rq_clock(rq);
13237 
13238 	cfs_rq = task_cfs_rq(current);
13239 	curr = cfs_rq->curr;
13240 	if (curr)
13241 		update_curr(cfs_rq);
13242 	place_entity(cfs_rq, se, ENQUEUE_INITIAL);
13243 	rq_unlock(rq, &rf);
13244 }
13245 
13246 /*
13247  * Priority of the task has changed. Check to see if we preempt
13248  * the current task.
13249  */
13250 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)13251 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
13252 {
13253 	if (!task_on_rq_queued(p))
13254 		return;
13255 
13256 	if (rq->cfs.nr_running == 1)
13257 		return;
13258 
13259 	/*
13260 	 * Reschedule if we are currently running on this runqueue and
13261 	 * our priority decreased, or if we are not currently running on
13262 	 * this runqueue and our priority is higher than the current's
13263 	 */
13264 	if (task_current(rq, p)) {
13265 		if (p->prio > oldprio)
13266 			resched_curr(rq);
13267 	} else
13268 		wakeup_preempt(rq, p, 0);
13269 }
13270 
13271 #ifdef CONFIG_FAIR_GROUP_SCHED
13272 /*
13273  * Propagate the changes of the sched_entity across the tg tree to make it
13274  * visible to the root
13275  */
propagate_entity_cfs_rq(struct sched_entity * se)13276 static void propagate_entity_cfs_rq(struct sched_entity *se)
13277 {
13278 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13279 
13280 	if (cfs_rq_throttled(cfs_rq))
13281 		return;
13282 
13283 	if (!throttled_hierarchy(cfs_rq))
13284 		list_add_leaf_cfs_rq(cfs_rq);
13285 
13286 	/* Start to propagate at parent */
13287 	se = se->parent;
13288 
13289 	for_each_sched_entity(se) {
13290 		cfs_rq = cfs_rq_of(se);
13291 
13292 		update_load_avg(cfs_rq, se, UPDATE_TG);
13293 
13294 		if (cfs_rq_throttled(cfs_rq))
13295 			break;
13296 
13297 		if (!throttled_hierarchy(cfs_rq))
13298 			list_add_leaf_cfs_rq(cfs_rq);
13299 	}
13300 }
13301 #else
propagate_entity_cfs_rq(struct sched_entity * se)13302 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13303 #endif
13304 
detach_entity_cfs_rq(struct sched_entity * se)13305 static void detach_entity_cfs_rq(struct sched_entity *se)
13306 {
13307 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13308 
13309 #ifdef CONFIG_SMP
13310 	/*
13311 	 * In case the task sched_avg hasn't been attached:
13312 	 * - A forked task which hasn't been woken up by wake_up_new_task().
13313 	 * - A task which has been woken up by try_to_wake_up() but is
13314 	 *   waiting for actually being woken up by sched_ttwu_pending().
13315 	 */
13316 	if (!se->avg.last_update_time)
13317 		return;
13318 #endif
13319 
13320 	/* Catch up with the cfs_rq and remove our load when we leave */
13321 	update_load_avg(cfs_rq, se, 0);
13322 	detach_entity_load_avg(cfs_rq, se);
13323 	update_tg_load_avg(cfs_rq);
13324 	propagate_entity_cfs_rq(se);
13325 }
13326 
attach_entity_cfs_rq(struct sched_entity * se)13327 static void attach_entity_cfs_rq(struct sched_entity *se)
13328 {
13329 	struct cfs_rq *cfs_rq = cfs_rq_of(se);
13330 
13331 	/* Synchronize entity with its cfs_rq */
13332 	update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13333 	attach_entity_load_avg(cfs_rq, se);
13334 	update_tg_load_avg(cfs_rq);
13335 	propagate_entity_cfs_rq(se);
13336 }
13337 
detach_task_cfs_rq(struct task_struct * p)13338 static void detach_task_cfs_rq(struct task_struct *p)
13339 {
13340 	struct sched_entity *se = &p->se;
13341 
13342 	detach_entity_cfs_rq(se);
13343 }
13344 
attach_task_cfs_rq(struct task_struct * p)13345 static void attach_task_cfs_rq(struct task_struct *p)
13346 {
13347 	struct sched_entity *se = &p->se;
13348 
13349 	attach_entity_cfs_rq(se);
13350 }
13351 
switched_from_fair(struct rq * rq,struct task_struct * p)13352 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13353 {
13354 	detach_task_cfs_rq(p);
13355 }
13356 
switched_to_fair(struct rq * rq,struct task_struct * p)13357 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13358 {
13359 	attach_task_cfs_rq(p);
13360 
13361 	if (task_on_rq_queued(p)) {
13362 		/*
13363 		 * We were most likely switched from sched_rt, so
13364 		 * kick off the schedule if running, otherwise just see
13365 		 * if we can still preempt the current task.
13366 		 */
13367 		if (task_current(rq, p))
13368 			resched_curr(rq);
13369 		else
13370 			wakeup_preempt(rq, p, 0);
13371 	}
13372 }
13373 
13374 /* Account for a task changing its policy or group.
13375  *
13376  * This routine is mostly called to set cfs_rq->curr field when a task
13377  * migrates between groups/classes.
13378  */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13379 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13380 {
13381 	struct sched_entity *se = &p->se;
13382 
13383 #ifdef CONFIG_SMP
13384 	if (task_on_rq_queued(p)) {
13385 		/*
13386 		 * Move the next running task to the front of the list, so our
13387 		 * cfs_tasks list becomes MRU one.
13388 		 */
13389 		list_move(&se->group_node, &rq->cfs_tasks);
13390 	}
13391 #endif
13392 
13393 	for_each_sched_entity(se) {
13394 		struct cfs_rq *cfs_rq = cfs_rq_of(se);
13395 
13396 		set_next_entity(cfs_rq, se);
13397 		/* ensure bandwidth has been allocated on our new cfs_rq */
13398 		account_cfs_rq_runtime(cfs_rq, 0);
13399 	}
13400 }
13401 
init_cfs_rq(struct cfs_rq * cfs_rq)13402 void init_cfs_rq(struct cfs_rq *cfs_rq)
13403 {
13404 	cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13405 	u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
13406 #ifdef CONFIG_SMP
13407 	raw_spin_lock_init(&cfs_rq->removed.lock);
13408 #endif
13409 }
13410 
13411 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13412 static void task_change_group_fair(struct task_struct *p)
13413 {
13414 	/*
13415 	 * We couldn't detach or attach a forked task which
13416 	 * hasn't been woken up by wake_up_new_task().
13417 	 */
13418 	if (READ_ONCE(p->__state) == TASK_NEW)
13419 		return;
13420 
13421 	detach_task_cfs_rq(p);
13422 
13423 #ifdef CONFIG_SMP
13424 	/* Tell se's cfs_rq has been changed -- migrated */
13425 	p->se.avg.last_update_time = 0;
13426 #endif
13427 	set_task_rq(p, task_cpu(p));
13428 	attach_task_cfs_rq(p);
13429 }
13430 
free_fair_sched_group(struct task_group * tg)13431 void free_fair_sched_group(struct task_group *tg)
13432 {
13433 	int i;
13434 
13435 	for_each_possible_cpu(i) {
13436 		if (tg->cfs_rq)
13437 			kfree(tg->cfs_rq[i]);
13438 		if (tg->se)
13439 			kfree(tg->se[i]);
13440 	}
13441 
13442 	kfree(tg->cfs_rq);
13443 	kfree(tg->se);
13444 }
13445 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13446 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13447 {
13448 	struct sched_entity *se;
13449 	struct cfs_rq *cfs_rq;
13450 	int i;
13451 
13452 	tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13453 	if (!tg->cfs_rq)
13454 		goto err;
13455 	tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13456 	if (!tg->se)
13457 		goto err;
13458 
13459 	tg->shares = NICE_0_LOAD;
13460 
13461 	init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13462 
13463 	for_each_possible_cpu(i) {
13464 		cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13465 				      GFP_KERNEL, cpu_to_node(i));
13466 		if (!cfs_rq)
13467 			goto err;
13468 
13469 		se = kzalloc_node(sizeof(struct sched_entity_stats),
13470 				  GFP_KERNEL, cpu_to_node(i));
13471 		if (!se)
13472 			goto err_free_rq;
13473 
13474 		init_cfs_rq(cfs_rq);
13475 		init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13476 		init_entity_runnable_average(se);
13477 	}
13478 
13479 	return 1;
13480 
13481 err_free_rq:
13482 	kfree(cfs_rq);
13483 err:
13484 	return 0;
13485 }
13486 
online_fair_sched_group(struct task_group * tg)13487 void online_fair_sched_group(struct task_group *tg)
13488 {
13489 	struct sched_entity *se;
13490 	struct rq_flags rf;
13491 	struct rq *rq;
13492 	int i;
13493 
13494 	for_each_possible_cpu(i) {
13495 		rq = cpu_rq(i);
13496 		se = tg->se[i];
13497 		rq_lock_irq(rq, &rf);
13498 		update_rq_clock(rq);
13499 		attach_entity_cfs_rq(se);
13500 		sync_throttle(tg, i);
13501 		rq_unlock_irq(rq, &rf);
13502 	}
13503 }
13504 
unregister_fair_sched_group(struct task_group * tg)13505 void unregister_fair_sched_group(struct task_group *tg)
13506 {
13507 	unsigned long flags;
13508 	struct rq *rq;
13509 	int cpu;
13510 
13511 	destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13512 
13513 	for_each_possible_cpu(cpu) {
13514 		if (tg->se[cpu])
13515 			remove_entity_load_avg(tg->se[cpu]);
13516 
13517 		/*
13518 		 * Only empty task groups can be destroyed; so we can speculatively
13519 		 * check on_list without danger of it being re-added.
13520 		 */
13521 		if (!tg->cfs_rq[cpu]->on_list)
13522 			continue;
13523 
13524 		rq = cpu_rq(cpu);
13525 
13526 		raw_spin_rq_lock_irqsave(rq, flags);
13527 		list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
13528 		raw_spin_rq_unlock_irqrestore(rq, flags);
13529 	}
13530 }
13531 
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13532 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13533 			struct sched_entity *se, int cpu,
13534 			struct sched_entity *parent)
13535 {
13536 	struct rq *rq = cpu_rq(cpu);
13537 
13538 	cfs_rq->tg = tg;
13539 	cfs_rq->rq = rq;
13540 	init_cfs_rq_runtime(cfs_rq);
13541 
13542 	tg->cfs_rq[cpu] = cfs_rq;
13543 	tg->se[cpu] = se;
13544 
13545 	/* se could be NULL for root_task_group */
13546 	if (!se)
13547 		return;
13548 
13549 	if (!parent) {
13550 		se->cfs_rq = &rq->cfs;
13551 		se->depth = 0;
13552 	} else {
13553 		se->cfs_rq = parent->my_q;
13554 		se->depth = parent->depth + 1;
13555 	}
13556 
13557 	se->my_q = cfs_rq;
13558 	/* guarantee group entities always have weight */
13559 	update_load_set(&se->load, NICE_0_LOAD);
13560 	se->parent = parent;
13561 }
13562 
13563 static DEFINE_MUTEX(shares_mutex);
13564 
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13565 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13566 {
13567 	int i;
13568 
13569 	lockdep_assert_held(&shares_mutex);
13570 
13571 	/*
13572 	 * We can't change the weight of the root cgroup.
13573 	 */
13574 	if (!tg->se[0])
13575 		return -EINVAL;
13576 
13577 	shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13578 
13579 	if (tg->shares == shares)
13580 		return 0;
13581 
13582 	tg->shares = shares;
13583 	for_each_possible_cpu(i) {
13584 		struct rq *rq = cpu_rq(i);
13585 		struct sched_entity *se = tg->se[i];
13586 		struct rq_flags rf;
13587 
13588 		/* Propagate contribution to hierarchy */
13589 		rq_lock_irqsave(rq, &rf);
13590 		update_rq_clock(rq);
13591 		for_each_sched_entity(se) {
13592 			update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13593 			update_cfs_group(se);
13594 		}
13595 		rq_unlock_irqrestore(rq, &rf);
13596 	}
13597 
13598 	return 0;
13599 }
13600 
sched_group_set_shares(struct task_group * tg,unsigned long shares)13601 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13602 {
13603 	int ret;
13604 
13605 	mutex_lock(&shares_mutex);
13606 	if (tg_is_idle(tg))
13607 		ret = -EINVAL;
13608 	else
13609 		ret = __sched_group_set_shares(tg, shares);
13610 	mutex_unlock(&shares_mutex);
13611 
13612 	return ret;
13613 }
13614 
sched_group_set_idle(struct task_group * tg,long idle)13615 int sched_group_set_idle(struct task_group *tg, long idle)
13616 {
13617 	int i;
13618 
13619 	if (tg == &root_task_group)
13620 		return -EINVAL;
13621 
13622 	if (idle < 0 || idle > 1)
13623 		return -EINVAL;
13624 
13625 	mutex_lock(&shares_mutex);
13626 
13627 	if (tg->idle == idle) {
13628 		mutex_unlock(&shares_mutex);
13629 		return 0;
13630 	}
13631 
13632 	tg->idle = idle;
13633 
13634 	for_each_possible_cpu(i) {
13635 		struct rq *rq = cpu_rq(i);
13636 		struct sched_entity *se = tg->se[i];
13637 		struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
13638 		bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13639 		long idle_task_delta;
13640 		struct rq_flags rf;
13641 
13642 		rq_lock_irqsave(rq, &rf);
13643 
13644 		grp_cfs_rq->idle = idle;
13645 		if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13646 			goto next_cpu;
13647 
13648 		if (se->on_rq) {
13649 			parent_cfs_rq = cfs_rq_of(se);
13650 			if (cfs_rq_is_idle(grp_cfs_rq))
13651 				parent_cfs_rq->idle_nr_running++;
13652 			else
13653 				parent_cfs_rq->idle_nr_running--;
13654 		}
13655 
13656 		idle_task_delta = grp_cfs_rq->h_nr_running -
13657 				  grp_cfs_rq->idle_h_nr_running;
13658 		if (!cfs_rq_is_idle(grp_cfs_rq))
13659 			idle_task_delta *= -1;
13660 
13661 		for_each_sched_entity(se) {
13662 			struct cfs_rq *cfs_rq = cfs_rq_of(se);
13663 
13664 			if (!se->on_rq)
13665 				break;
13666 
13667 			cfs_rq->idle_h_nr_running += idle_task_delta;
13668 
13669 			/* Already accounted at parent level and above. */
13670 			if (cfs_rq_is_idle(cfs_rq))
13671 				break;
13672 		}
13673 
13674 next_cpu:
13675 		rq_unlock_irqrestore(rq, &rf);
13676 	}
13677 
13678 	/* Idle groups have minimum weight. */
13679 	if (tg_is_idle(tg))
13680 		__sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13681 	else
13682 		__sched_group_set_shares(tg, NICE_0_LOAD);
13683 
13684 	mutex_unlock(&shares_mutex);
13685 	return 0;
13686 }
13687 
13688 #else /* CONFIG_FAIR_GROUP_SCHED */
13689 
free_fair_sched_group(struct task_group * tg)13690 void free_fair_sched_group(struct task_group *tg) { }
13691 
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13692 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13693 {
13694 	return 1;
13695 }
13696 
online_fair_sched_group(struct task_group * tg)13697 void online_fair_sched_group(struct task_group *tg) { }
13698 
unregister_fair_sched_group(struct task_group * tg)13699 void unregister_fair_sched_group(struct task_group *tg) { }
13700 
13701 #endif /* CONFIG_FAIR_GROUP_SCHED */
13702 
13703 
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13704 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13705 {
13706 	struct sched_entity *se = &task->se;
13707 	unsigned int rr_interval = 0;
13708 
13709 	/*
13710 	 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13711 	 * idle runqueue:
13712 	 */
13713 	if (rq->cfs.load.weight)
13714 		rr_interval = NS_TO_JIFFIES(se->slice);
13715 
13716 	return rr_interval;
13717 }
13718 
13719 /*
13720  * All the scheduling class methods:
13721  */
13722 DEFINE_SCHED_CLASS(fair) = {
13723 
13724 	.enqueue_task		= enqueue_task_fair,
13725 	.dequeue_task		= dequeue_task_fair,
13726 	.yield_task		= yield_task_fair,
13727 	.yield_to_task		= yield_to_task_fair,
13728 
13729 	.wakeup_preempt		= check_preempt_wakeup_fair,
13730 
13731 	.pick_next_task		= __pick_next_task_fair,
13732 	.put_prev_task		= put_prev_task_fair,
13733 	.set_next_task          = set_next_task_fair,
13734 
13735 #ifdef CONFIG_SMP
13736 	.balance		= balance_fair,
13737 	.pick_task		= pick_task_fair,
13738 	.select_task_rq		= select_task_rq_fair,
13739 	.migrate_task_rq	= migrate_task_rq_fair,
13740 
13741 	.rq_online		= rq_online_fair,
13742 	.rq_offline		= rq_offline_fair,
13743 
13744 	.task_dead		= task_dead_fair,
13745 	.set_cpus_allowed	= set_cpus_allowed_common,
13746 #endif
13747 
13748 	.task_tick		= task_tick_fair,
13749 	.task_fork		= task_fork_fair,
13750 
13751 	.prio_changed		= prio_changed_fair,
13752 	.switched_from		= switched_from_fair,
13753 	.switched_to		= switched_to_fair,
13754 
13755 	.get_rr_interval	= get_rr_interval_fair,
13756 
13757 	.update_curr		= update_curr_fair,
13758 
13759 #ifdef CONFIG_FAIR_GROUP_SCHED
13760 	.task_change_group	= task_change_group_fair,
13761 #endif
13762 
13763 #ifdef CONFIG_SCHED_CORE
13764 	.task_is_throttled	= task_is_throttled_fair,
13765 #endif
13766 
13767 #ifdef CONFIG_UCLAMP_TASK
13768 	.uclamp_enabled		= 1,
13769 #endif
13770 #ifdef CONFIG_SCHED_WALT
13771 	.fixup_walt_sched_stats	= walt_fixup_sched_stats_fair,
13772 #endif
13773 #ifdef CONFIG_SCHED_EAS
13774 	.check_for_migration	= check_for_migration_fair,
13775 #endif
13776 };
13777 
13778 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)13779 void print_cfs_stats(struct seq_file *m, int cpu)
13780 {
13781 	struct cfs_rq *cfs_rq, *pos;
13782 
13783 	rcu_read_lock();
13784 	for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13785 		print_cfs_rq(m, cpu, cfs_rq);
13786 	rcu_read_unlock();
13787 }
13788 
13789 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13790 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13791 {
13792 	int node;
13793 	unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13794 	struct numa_group *ng;
13795 
13796 	rcu_read_lock();
13797 	ng = rcu_dereference(p->numa_group);
13798 	for_each_online_node(node) {
13799 		if (p->numa_faults) {
13800 			tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13801 			tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13802 		}
13803 		if (ng) {
13804 			gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13805 			gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13806 		}
13807 		print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13808 	}
13809 	rcu_read_unlock();
13810 }
13811 #endif /* CONFIG_NUMA_BALANCING */
13812 #endif /* CONFIG_SCHED_DEBUG */
13813 
init_sched_fair_class(void)13814 __init void init_sched_fair_class(void)
13815 {
13816 #ifdef CONFIG_SMP
13817 	int i;
13818 
13819 	for_each_possible_cpu(i) {
13820 		zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13821 		zalloc_cpumask_var_node(&per_cpu(select_rq_mask,    i), GFP_KERNEL, cpu_to_node(i));
13822 		zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13823 					GFP_KERNEL, cpu_to_node(i));
13824 
13825 #ifdef CONFIG_CFS_BANDWIDTH
13826 		INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13827 		INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13828 #endif
13829 	}
13830 
13831 	open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
13832 
13833 #ifdef CONFIG_NO_HZ_COMMON
13834 	nohz.next_balance = jiffies;
13835 	nohz.next_blocked = jiffies;
13836 	zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13837 #endif
13838 #endif /* SMP */
13839 
13840 }
13841 
13842 /* WALT sched implementation begins here */
13843 #ifdef CONFIG_SCHED_WALT
13844 
13845 #ifdef CONFIG_CFS_BANDWIDTH
13846 
walt_init_cfs_rq_stats(struct cfs_rq * cfs_rq)13847 static void walt_init_cfs_rq_stats(struct cfs_rq *cfs_rq)
13848 {
13849 	cfs_rq->walt_stats.cumulative_runnable_avg_scaled = 0;
13850 }
13851 
walt_inc_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)13852 static void walt_inc_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
13853 {
13854 	fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
13855 				      p->ravg.demand_scaled);
13856 }
13857 
walt_dec_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)13858 static void walt_dec_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
13859 {
13860 	fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
13861 				      -(s64)p->ravg.demand_scaled);
13862 }
13863 
walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)13864 static void walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
13865 					    struct cfs_rq *tcfs_rq)
13866 {
13867 	struct rq *rq = rq_of(tcfs_rq);
13868 
13869 	fixup_cumulative_runnable_avg(stats,
13870 			tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
13871 
13872 	if (stats == &rq->walt_stats)
13873 		walt_fixup_cum_window_demand(rq,
13874 			tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
13875 
13876 }
13877 
walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)13878 static void walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
13879 					    struct cfs_rq *tcfs_rq)
13880 {
13881 	struct rq *rq = rq_of(tcfs_rq);
13882 
13883 	fixup_cumulative_runnable_avg(stats,
13884 			-tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
13885 
13886 	/*
13887 	 * We remove the throttled cfs_rq's tasks's contribution from the
13888 	 * cumulative window demand so that the same can be added
13889 	 * unconditionally when the cfs_rq is unthrottled.
13890 	 */
13891 	if (stats == &rq->walt_stats)
13892 		walt_fixup_cum_window_demand(rq,
13893 			-tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
13894 }
13895 
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)13896 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
13897 					u16 updated_demand_scaled)
13898 {
13899 	struct cfs_rq *cfs_rq;
13900 	struct sched_entity *se = &p->se;
13901 	s64 task_load_delta = (s64)updated_demand_scaled -
13902 			      p->ravg.demand_scaled;
13903 
13904 	for_each_sched_entity(se) {
13905 		cfs_rq = cfs_rq_of(se);
13906 
13907 		fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
13908 					      task_load_delta);
13909 		if (cfs_rq_throttled(cfs_rq))
13910 			break;
13911 	}
13912 
13913 	/* Fix up rq->walt_stats only if we didn't find any throttled cfs_rq */
13914 	if (!se) {
13915 		fixup_cumulative_runnable_avg(&rq->walt_stats,
13916 					      task_load_delta);
13917 		walt_fixup_cum_window_demand(rq, task_load_delta);
13918 	}
13919 }
13920 
13921 #else /* CONFIG_CFS_BANDWIDTH */
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)13922 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
13923 					u16 updated_demand_scaled)
13924 {
13925 	fixup_walt_sched_stats_common(rq, p, updated_demand_scaled);
13926 }
13927 #endif /* CONFIG_CFS_BANDWIDTH */
13928 #endif /* CONFIG_SCHED_WALT */
13929