OSDN Git Service

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