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