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