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