OSDN Git Service

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