OSDN Git Service

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