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