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