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