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