]> git.karo-electronics.de Git - karo-tx-linux.git/blob - kernel/sched/fair.c
ab2f11be7e969b982828daf0afbf13adc2344e6e
[karo-tx-linux.git] / kernel / sched / fair.c
1 /*
2  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
3  *
4  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
5  *
6  *  Interactivity improvements by Mike Galbraith
7  *  (C) 2007 Mike Galbraith <efault@gmx.de>
8  *
9  *  Various enhancements by Dmitry Adamushko.
10  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
11  *
12  *  Group scheduling enhancements by Srivatsa Vaddagiri
13  *  Copyright IBM Corporation, 2007
14  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
15  *
16  *  Scaled math optimizations by Thomas Gleixner
17  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
18  *
19  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
21  */
22
23 #include <linux/latencytop.h>
24 #include <linux/sched.h>
25 #include <linux/cpumask.h>
26 #include <linux/slab.h>
27 #include <linux/profile.h>
28 #include <linux/interrupt.h>
29 #include <linux/random.h>
30 #include <linux/mempolicy.h>
31 #include <linux/task_work.h>
32
33 #include <trace/events/sched.h>
34
35 #include "sched.h"
36
37 /*
38  * Targeted preemption latency for CPU-bound tasks:
39  * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
40  *
41  * NOTE: this latency value is not the same as the concept of
42  * 'timeslice length' - timeslices in CFS are of variable length
43  * and have no persistent notion like in traditional, time-slice
44  * based scheduling concepts.
45  *
46  * (to see the precise effective timeslice length of your workload,
47  *  run vmstat and monitor the context-switches (cs) field)
48  */
49 unsigned int sysctl_sched_latency = 6000000ULL;
50 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
51
52 /*
53  * The initial- and re-scaling of tunables is configurable
54  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
55  *
56  * Options are:
57  * SCHED_TUNABLESCALING_NONE - unscaled, always *1
58  * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
59  * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
60  */
61 enum sched_tunable_scaling sysctl_sched_tunable_scaling
62         = SCHED_TUNABLESCALING_LOG;
63
64 /*
65  * Minimal preemption granularity for CPU-bound tasks:
66  * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
67  */
68 unsigned int sysctl_sched_min_granularity = 750000ULL;
69 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
70
71 /*
72  * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
73  */
74 static unsigned int sched_nr_latency = 8;
75
76 /*
77  * After fork, child runs first. If set to 0 (default) then
78  * parent will (try to) run first.
79  */
80 unsigned int sysctl_sched_child_runs_first __read_mostly;
81
82 /*
83  * SCHED_OTHER wake-up granularity.
84  * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
85  *
86  * This option delays the preemption effects of decoupled workloads
87  * and reduces their over-scheduling. Synchronous workloads will still
88  * have immediate wakeup/sleep latencies.
89  */
90 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
91 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
92
93 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
94
95 /*
96  * The exponential sliding  window over which load is averaged for shares
97  * distribution.
98  * (default: 10msec)
99  */
100 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
101
102 #ifdef CONFIG_CFS_BANDWIDTH
103 /*
104  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
105  * each time a cfs_rq requests quota.
106  *
107  * Note: in the case that the slice exceeds the runtime remaining (either due
108  * to consumption or the quota being specified to be smaller than the slice)
109  * we will always only issue the remaining available time.
110  *
111  * default: 5 msec, units: microseconds
112   */
113 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
114 #endif
115
116 /*
117  * Increase the granularity value when there are more CPUs,
118  * because with more CPUs the 'effective latency' as visible
119  * to users decreases. But the relationship is not linear,
120  * so pick a second-best guess by going with the log2 of the
121  * number of CPUs.
122  *
123  * This idea comes from the SD scheduler of Con Kolivas:
124  */
125 static int get_update_sysctl_factor(void)
126 {
127         unsigned int cpus = min_t(int, num_online_cpus(), 8);
128         unsigned int factor;
129
130         switch (sysctl_sched_tunable_scaling) {
131         case SCHED_TUNABLESCALING_NONE:
132                 factor = 1;
133                 break;
134         case SCHED_TUNABLESCALING_LINEAR:
135                 factor = cpus;
136                 break;
137         case SCHED_TUNABLESCALING_LOG:
138         default:
139                 factor = 1 + ilog2(cpus);
140                 break;
141         }
142
143         return factor;
144 }
145
146 static void update_sysctl(void)
147 {
148         unsigned int factor = get_update_sysctl_factor();
149
150 #define SET_SYSCTL(name) \
151         (sysctl_##name = (factor) * normalized_sysctl_##name)
152         SET_SYSCTL(sched_min_granularity);
153         SET_SYSCTL(sched_latency);
154         SET_SYSCTL(sched_wakeup_granularity);
155 #undef SET_SYSCTL
156 }
157
158 void sched_init_granularity(void)
159 {
160         update_sysctl();
161 }
162
163 #if BITS_PER_LONG == 32
164 # define WMULT_CONST    (~0UL)
165 #else
166 # define WMULT_CONST    (1UL << 32)
167 #endif
168
169 #define WMULT_SHIFT     32
170
171 /*
172  * Shift right and round:
173  */
174 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
175
176 /*
177  * delta *= weight / lw
178  */
179 static unsigned long
180 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
181                 struct load_weight *lw)
182 {
183         u64 tmp;
184
185         /*
186          * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
187          * entities since MIN_SHARES = 2. Treat weight as 1 if less than
188          * 2^SCHED_LOAD_RESOLUTION.
189          */
190         if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
191                 tmp = (u64)delta_exec * scale_load_down(weight);
192         else
193                 tmp = (u64)delta_exec;
194
195         if (!lw->inv_weight) {
196                 unsigned long 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          * Check whether we'd overflow the 64-bit multiplication:
208          */
209         if (unlikely(tmp > WMULT_CONST))
210                 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
211                         WMULT_SHIFT/2);
212         else
213                 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
214
215         return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
216 }
217
218
219 const struct sched_class fair_sched_class;
220
221 /**************************************************************
222  * CFS operations on generic schedulable entities:
223  */
224
225 #ifdef CONFIG_FAIR_GROUP_SCHED
226
227 /* cpu runqueue to which this cfs_rq is attached */
228 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
229 {
230         return cfs_rq->rq;
231 }
232
233 /* An entity is a task if it doesn't "own" a runqueue */
234 #define entity_is_task(se)      (!se->my_q)
235
236 static inline struct task_struct *task_of(struct sched_entity *se)
237 {
238 #ifdef CONFIG_SCHED_DEBUG
239         WARN_ON_ONCE(!entity_is_task(se));
240 #endif
241         return container_of(se, struct task_struct, se);
242 }
243
244 /* Walk up scheduling entities hierarchy */
245 #define for_each_sched_entity(se) \
246                 for (; se; se = se->parent)
247
248 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
249 {
250         return p->se.cfs_rq;
251 }
252
253 /* runqueue on which this entity is (to be) queued */
254 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
255 {
256         return se->cfs_rq;
257 }
258
259 /* runqueue "owned" by this group */
260 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
261 {
262         return grp->my_q;
263 }
264
265 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
266 {
267         if (!cfs_rq->on_list) {
268                 /*
269                  * Ensure we either appear before our parent (if already
270                  * enqueued) or force our parent to appear after us when it is
271                  * enqueued.  The fact that we always enqueue bottom-up
272                  * reduces this to two cases.
273                  */
274                 if (cfs_rq->tg->parent &&
275                     cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
276                         list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
277                                 &rq_of(cfs_rq)->leaf_cfs_rq_list);
278                 } else {
279                         list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
280                                 &rq_of(cfs_rq)->leaf_cfs_rq_list);
281                 }
282
283                 cfs_rq->on_list = 1;
284         }
285 }
286
287 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
288 {
289         if (cfs_rq->on_list) {
290                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
291                 cfs_rq->on_list = 0;
292         }
293 }
294
295 /* Iterate thr' all leaf cfs_rq's on a runqueue */
296 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
297         list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
298
299 /* Do the two (enqueued) entities belong to the same group ? */
300 static inline int
301 is_same_group(struct sched_entity *se, struct sched_entity *pse)
302 {
303         if (se->cfs_rq == pse->cfs_rq)
304                 return 1;
305
306         return 0;
307 }
308
309 static inline struct sched_entity *parent_entity(struct sched_entity *se)
310 {
311         return se->parent;
312 }
313
314 /* return depth at which a sched entity is present in the hierarchy */
315 static inline int depth_se(struct sched_entity *se)
316 {
317         int depth = 0;
318
319         for_each_sched_entity(se)
320                 depth++;
321
322         return depth;
323 }
324
325 static void
326 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
327 {
328         int se_depth, pse_depth;
329
330         /*
331          * preemption test can be made between sibling entities who are in the
332          * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
333          * both tasks until we find their ancestors who are siblings of common
334          * parent.
335          */
336
337         /* First walk up until both entities are at same depth */
338         se_depth = depth_se(*se);
339         pse_depth = depth_se(*pse);
340
341         while (se_depth > pse_depth) {
342                 se_depth--;
343                 *se = parent_entity(*se);
344         }
345
346         while (pse_depth > se_depth) {
347                 pse_depth--;
348                 *pse = parent_entity(*pse);
349         }
350
351         while (!is_same_group(*se, *pse)) {
352                 *se = parent_entity(*se);
353                 *pse = parent_entity(*pse);
354         }
355 }
356
357 #else   /* !CONFIG_FAIR_GROUP_SCHED */
358
359 static inline struct task_struct *task_of(struct sched_entity *se)
360 {
361         return container_of(se, struct task_struct, se);
362 }
363
364 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
365 {
366         return container_of(cfs_rq, struct rq, cfs);
367 }
368
369 #define entity_is_task(se)      1
370
371 #define for_each_sched_entity(se) \
372                 for (; se; se = NULL)
373
374 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
375 {
376         return &task_rq(p)->cfs;
377 }
378
379 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
380 {
381         struct task_struct *p = task_of(se);
382         struct rq *rq = task_rq(p);
383
384         return &rq->cfs;
385 }
386
387 /* runqueue "owned" by this group */
388 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
389 {
390         return NULL;
391 }
392
393 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
394 {
395 }
396
397 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
398 {
399 }
400
401 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
402                 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
403
404 static inline int
405 is_same_group(struct sched_entity *se, struct sched_entity *pse)
406 {
407         return 1;
408 }
409
410 static inline struct sched_entity *parent_entity(struct sched_entity *se)
411 {
412         return NULL;
413 }
414
415 static inline void
416 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
417 {
418 }
419
420 #endif  /* CONFIG_FAIR_GROUP_SCHED */
421
422 static __always_inline
423 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
424
425 /**************************************************************
426  * Scheduling class tree data structure manipulation methods:
427  */
428
429 static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
430 {
431         s64 delta = (s64)(vruntime - min_vruntime);
432         if (delta > 0)
433                 min_vruntime = vruntime;
434
435         return min_vruntime;
436 }
437
438 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
439 {
440         s64 delta = (s64)(vruntime - min_vruntime);
441         if (delta < 0)
442                 min_vruntime = vruntime;
443
444         return min_vruntime;
445 }
446
447 static inline int entity_before(struct sched_entity *a,
448                                 struct sched_entity *b)
449 {
450         return (s64)(a->vruntime - b->vruntime) < 0;
451 }
452
453 static void update_min_vruntime(struct cfs_rq *cfs_rq)
454 {
455         u64 vruntime = cfs_rq->min_vruntime;
456
457         if (cfs_rq->curr)
458                 vruntime = cfs_rq->curr->vruntime;
459
460         if (cfs_rq->rb_leftmost) {
461                 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
462                                                    struct sched_entity,
463                                                    run_node);
464
465                 if (!cfs_rq->curr)
466                         vruntime = se->vruntime;
467                 else
468                         vruntime = min_vruntime(vruntime, se->vruntime);
469         }
470
471         cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
472 #ifndef CONFIG_64BIT
473         smp_wmb();
474         cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
475 #endif
476 }
477
478 /*
479  * Enqueue an entity into the rb-tree:
480  */
481 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
482 {
483         struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
484         struct rb_node *parent = NULL;
485         struct sched_entity *entry;
486         int leftmost = 1;
487
488         /*
489          * Find the right place in the rbtree:
490          */
491         while (*link) {
492                 parent = *link;
493                 entry = rb_entry(parent, struct sched_entity, run_node);
494                 /*
495                  * We dont care about collisions. Nodes with
496                  * the same key stay together.
497                  */
498                 if (entity_before(se, entry)) {
499                         link = &parent->rb_left;
500                 } else {
501                         link = &parent->rb_right;
502                         leftmost = 0;
503                 }
504         }
505
506         /*
507          * Maintain a cache of leftmost tree entries (it is frequently
508          * used):
509          */
510         if (leftmost)
511                 cfs_rq->rb_leftmost = &se->run_node;
512
513         rb_link_node(&se->run_node, parent, link);
514         rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
515 }
516
517 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
518 {
519         if (cfs_rq->rb_leftmost == &se->run_node) {
520                 struct rb_node *next_node;
521
522                 next_node = rb_next(&se->run_node);
523                 cfs_rq->rb_leftmost = next_node;
524         }
525
526         rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
527 }
528
529 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
530 {
531         struct rb_node *left = cfs_rq->rb_leftmost;
532
533         if (!left)
534                 return NULL;
535
536         return rb_entry(left, struct sched_entity, run_node);
537 }
538
539 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
540 {
541         struct rb_node *next = rb_next(&se->run_node);
542
543         if (!next)
544                 return NULL;
545
546         return rb_entry(next, struct sched_entity, run_node);
547 }
548
549 #ifdef CONFIG_SCHED_DEBUG
550 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
551 {
552         struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
553
554         if (!last)
555                 return NULL;
556
557         return rb_entry(last, struct sched_entity, run_node);
558 }
559
560 /**************************************************************
561  * Scheduling class statistics methods:
562  */
563
564 int sched_proc_update_handler(struct ctl_table *table, int write,
565                 void __user *buffer, size_t *lenp,
566                 loff_t *ppos)
567 {
568         int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
569         int factor = get_update_sysctl_factor();
570
571         if (ret || !write)
572                 return ret;
573
574         sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
575                                         sysctl_sched_min_granularity);
576
577 #define WRT_SYSCTL(name) \
578         (normalized_sysctl_##name = sysctl_##name / (factor))
579         WRT_SYSCTL(sched_min_granularity);
580         WRT_SYSCTL(sched_latency);
581         WRT_SYSCTL(sched_wakeup_granularity);
582 #undef WRT_SYSCTL
583
584         return 0;
585 }
586 #endif
587
588 /*
589  * delta /= w
590  */
591 static inline unsigned long
592 calc_delta_fair(unsigned long delta, struct sched_entity *se)
593 {
594         if (unlikely(se->load.weight != NICE_0_LOAD))
595                 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
596
597         return delta;
598 }
599
600 /*
601  * The idea is to set a period in which each task runs once.
602  *
603  * When there are too many tasks (sched_nr_latency) we have to stretch
604  * this period because otherwise the slices get too small.
605  *
606  * p = (nr <= nl) ? l : l*nr/nl
607  */
608 static u64 __sched_period(unsigned long nr_running)
609 {
610         u64 period = sysctl_sched_latency;
611         unsigned long nr_latency = sched_nr_latency;
612
613         if (unlikely(nr_running > nr_latency)) {
614                 period = sysctl_sched_min_granularity;
615                 period *= nr_running;
616         }
617
618         return period;
619 }
620
621 /*
622  * We calculate the wall-time slice from the period by taking a part
623  * proportional to the weight.
624  *
625  * s = p*P[w/rw]
626  */
627 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
628 {
629         u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
630
631         for_each_sched_entity(se) {
632                 struct load_weight *load;
633                 struct load_weight lw;
634
635                 cfs_rq = cfs_rq_of(se);
636                 load = &cfs_rq->load;
637
638                 if (unlikely(!se->on_rq)) {
639                         lw = cfs_rq->load;
640
641                         update_load_add(&lw, se->load.weight);
642                         load = &lw;
643                 }
644                 slice = calc_delta_mine(slice, se->load.weight, load);
645         }
646         return slice;
647 }
648
649 /*
650  * We calculate the vruntime slice of a to be inserted task
651  *
652  * vs = s/w
653  */
654 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
655 {
656         return calc_delta_fair(sched_slice(cfs_rq, se), se);
657 }
658
659 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
660 static void update_cfs_shares(struct cfs_rq *cfs_rq);
661
662 /*
663  * Update the current task's runtime statistics. Skip current tasks that
664  * are not in our scheduling class.
665  */
666 static inline void
667 __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
668               unsigned long delta_exec)
669 {
670         unsigned long delta_exec_weighted;
671
672         schedstat_set(curr->statistics.exec_max,
673                       max((u64)delta_exec, curr->statistics.exec_max));
674
675         curr->sum_exec_runtime += delta_exec;
676         schedstat_add(cfs_rq, exec_clock, delta_exec);
677         delta_exec_weighted = calc_delta_fair(delta_exec, curr);
678
679         curr->vruntime += delta_exec_weighted;
680         update_min_vruntime(cfs_rq);
681
682 #if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
683         cfs_rq->load_unacc_exec_time += delta_exec;
684 #endif
685 }
686
687 static void update_curr(struct cfs_rq *cfs_rq)
688 {
689         struct sched_entity *curr = cfs_rq->curr;
690         u64 now = rq_of(cfs_rq)->clock_task;
691         unsigned long delta_exec;
692
693         if (unlikely(!curr))
694                 return;
695
696         /*
697          * Get the amount of time the current task was running
698          * since the last time we changed load (this cannot
699          * overflow on 32 bits):
700          */
701         delta_exec = (unsigned long)(now - curr->exec_start);
702         if (!delta_exec)
703                 return;
704
705         __update_curr(cfs_rq, curr, delta_exec);
706         curr->exec_start = now;
707
708         if (entity_is_task(curr)) {
709                 struct task_struct *curtask = task_of(curr);
710
711                 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
712                 cpuacct_charge(curtask, delta_exec);
713                 account_group_exec_runtime(curtask, delta_exec);
714         }
715
716         account_cfs_rq_runtime(cfs_rq, delta_exec);
717 }
718
719 static inline void
720 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
721 {
722         schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
723 }
724
725 /*
726  * Task is being enqueued - update stats:
727  */
728 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
729 {
730         /*
731          * Are we enqueueing a waiting task? (for current tasks
732          * a dequeue/enqueue event is a NOP)
733          */
734         if (se != cfs_rq->curr)
735                 update_stats_wait_start(cfs_rq, se);
736 }
737
738 static void
739 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
740 {
741         schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
742                         rq_of(cfs_rq)->clock - se->statistics.wait_start));
743         schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
744         schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
745                         rq_of(cfs_rq)->clock - se->statistics.wait_start);
746 #ifdef CONFIG_SCHEDSTATS
747         if (entity_is_task(se)) {
748                 trace_sched_stat_wait(task_of(se),
749                         rq_of(cfs_rq)->clock - se->statistics.wait_start);
750         }
751 #endif
752         schedstat_set(se->statistics.wait_start, 0);
753 }
754
755 static inline void
756 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
757 {
758         /*
759          * Mark the end of the wait period if dequeueing a
760          * waiting task:
761          */
762         if (se != cfs_rq->curr)
763                 update_stats_wait_end(cfs_rq, se);
764 }
765
766 /*
767  * We are picking a new current task - update its stats:
768  */
769 static inline void
770 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
771 {
772         /*
773          * We are starting a new run period:
774          */
775         se->exec_start = rq_of(cfs_rq)->clock_task;
776 }
777
778 /**************************************************
779  * Scheduling class numa methods.
780  *
781  * The purpose of the NUMA bits are to maintain compute (task) and data
782  * (memory) locality. We try and achieve this by making tasks stick to
783  * a particular node (their home node) but if fairness mandates they run
784  * elsewhere for long enough, we let the memory follow them.
785  *
786  * Tasks start out with their home-node unset (-1) this effectively means
787  * they act !NUMA until we've established the task is busy enough to bother
788  * with placement.
789  *
790  * We keep a home-node per task and use periodic fault scans to try and
791  * estalish a task<->page relation. This assumes the task<->page relation is a
792  * compute<->data relation, this is false for things like virt. and n:m
793  * threading solutions but its the best we can do given the information we
794  * have.
795  */
796
797 static unsigned long task_h_load(struct task_struct *p);
798
799 #ifdef CONFIG_SCHED_NUMA
800 static void account_offnode_enqueue(struct rq *rq, struct task_struct *p)
801 {
802         p->numa_contrib = task_h_load(p);
803         rq->offnode_weight += p->numa_contrib;
804         rq->offnode_running++;
805 }
806
807 static void account_offnode_dequeue(struct rq *rq, struct task_struct *p)
808 {
809         rq->offnode_weight -= p->numa_contrib;
810         rq->offnode_running--;
811 }
812
813 /*
814  * numa task sample period in ms: 5s
815  */
816 unsigned int sysctl_sched_numa_task_period_min = 5000;
817 unsigned int sysctl_sched_numa_task_period_max = 5000*16;
818
819 /*
820  * Wait for the 2-sample stuff to settle before migrating again
821  */
822 unsigned int sysctl_sched_numa_settle_count = 2;
823
824 /*
825  * Got a PROT_NONE fault for a page on @node.
826  */
827 void task_numa_fault(int node)
828 {
829         struct task_struct *p = current;
830
831         if (unlikely(!p->numa_faults)) {
832                 p->numa_faults = kzalloc(sizeof(unsigned long) * nr_node_ids,
833                                          GFP_KERNEL);
834                 if (!p->numa_faults)
835                         return;
836         }
837
838         p->numa_faults[node]++;
839 }
840
841 void task_numa_placement(void)
842 {
843         unsigned long faults, max_faults = 0;
844         struct task_struct *p = current;
845         int node, max_node = -1;
846         int seq = ACCESS_ONCE(p->mm->numa_scan_seq);
847
848         if (p->numa_scan_seq == seq)
849                 return;
850
851         p->numa_scan_seq = seq;
852
853         if (unlikely(!p->numa_faults))
854                 return;
855
856         for (node = 0; node < nr_node_ids; node++) {
857                 faults = p->numa_faults[node];
858
859                 if (faults > max_faults) {
860                         max_faults = faults;
861                         max_node = node;
862                 }
863
864                 p->numa_faults[node] /= 2;
865         }
866
867         if (max_node == -1)
868                 return;
869
870         if (p->node != max_node) {
871                 p->numa_task_period = sysctl_sched_numa_task_period_min;
872                 if (sched_feat(NUMA_SETTLE) &&
873                     (seq - p->numa_migrate_seq) <= (int)sysctl_sched_numa_settle_count)
874                         return;
875                 p->numa_migrate_seq = seq;
876                 sched_setnode(p, max_node);
877         } else {
878                 p->numa_task_period = min(sysctl_sched_numa_task_period_max,
879                                 p->numa_task_period * 2);
880         }
881 }
882
883 /*
884  * The expensive part of numa migration is done from task_work context.
885  * Triggered from task_tick_numa().
886  */
887 void task_numa_work(struct callback_head *work)
888 {
889         unsigned long migrate, next_scan, now = jiffies;
890         struct task_struct *p = current;
891         struct mm_struct *mm = p->mm;
892
893         WARN_ON_ONCE(p != container_of(work, struct task_struct, rcu));
894
895         /*
896          * Who cares about NUMA placement when they're dying.
897          *
898          * NOTE: make sure not to dereference p->mm before this check,
899          * exit_task_work() happens _after_ exit_mm() so we could be called
900          * without p->mm even though we still had it when we enqueued this
901          * work.
902          */
903         if (p->flags & PF_EXITING)
904                 return;
905
906         /*
907          * Enforce maximal scan/migration frequency..
908          */
909         migrate = mm->numa_next_scan;
910         if (time_before(now, migrate))
911                 return;
912
913         next_scan = now + 2*msecs_to_jiffies(sysctl_sched_numa_task_period_min);
914         if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
915                 return;
916
917         ACCESS_ONCE(mm->numa_scan_seq)++;
918         lazy_migrate_process(mm);
919 }
920
921 /*
922  * Drive the periodic memory faults..
923  */
924 void task_tick_numa(struct rq *rq, struct task_struct *curr)
925 {
926         u64 period, now;
927
928         /*
929          * We don't care about NUMA placement if we don't have memory.
930          */
931         if (!curr->mm)
932                 return;
933
934         /*
935          * Using runtime rather than walltime has the dual advantage that
936          * we (mostly) drive the selection from busy threads and that the
937          * task needs to have done some actual work before we bother with
938          * NUMA placement.
939          */
940         now = curr->se.sum_exec_runtime;
941         period = (u64)curr->numa_task_period * NSEC_PER_MSEC;
942
943         if (now - curr->node_stamp > period) {
944                 curr->node_stamp = now;
945
946                 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
947                         /*
948                          * We can re-use curr->rcu because we checked curr->mm
949                          * != NULL so release_task()->call_rcu() was not called
950                          * yet and exit_task_work() is called before
951                          * exit_notify().
952                          */
953                         init_task_work(&curr->rcu, task_numa_work);
954                         task_work_add(curr, &curr->rcu, true);
955                 }
956         }
957 }
958 #else
959 static void account_offnode_enqueue(struct rq *rq, struct task_struct *p)
960 {
961 }
962
963 static void account_offnode_dequeue(struct rq *rq, struct task_struct *p)
964 {
965 }
966
967 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
968 {
969 }
970 #endif /* CONFIG_SCHED_NUMA */
971
972 /**************************************************
973  * Scheduling class queueing methods:
974  */
975
976 static void
977 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
978 {
979         update_load_add(&cfs_rq->load, se->load.weight);
980         if (!parent_entity(se))
981                 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
982 #ifdef CONFIG_SMP
983         if (entity_is_task(se)) {
984                 struct rq *rq = rq_of(cfs_rq);
985                 struct task_struct *p = task_of(se);
986                 struct list_head *tasks = &rq->cfs_tasks;
987
988                 if (offnode_task(p)) {
989                         account_offnode_enqueue(rq, p);
990                         tasks = offnode_tasks(rq);
991                 }
992
993                 list_add(&se->group_node, tasks);
994         }
995 #endif /* CONFIG_SMP */
996         cfs_rq->nr_running++;
997 }
998
999 static void
1000 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1001 {
1002         update_load_sub(&cfs_rq->load, se->load.weight);
1003         if (!parent_entity(se))
1004                 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
1005         if (entity_is_task(se)) {
1006                 struct task_struct *p = task_of(se);
1007
1008                 list_del_init(&se->group_node);
1009
1010                 if (offnode_task(p))
1011                         account_offnode_dequeue(rq_of(cfs_rq), p);
1012         }
1013         cfs_rq->nr_running--;
1014 }
1015
1016 #ifdef CONFIG_FAIR_GROUP_SCHED
1017 /* we need this in update_cfs_load and load-balance functions below */
1018 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
1019 # ifdef CONFIG_SMP
1020 static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
1021                                             int global_update)
1022 {
1023         struct task_group *tg = cfs_rq->tg;
1024         long load_avg;
1025
1026         load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
1027         load_avg -= cfs_rq->load_contribution;
1028
1029         if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
1030                 atomic_add(load_avg, &tg->load_weight);
1031                 cfs_rq->load_contribution += load_avg;
1032         }
1033 }
1034
1035 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1036 {
1037         u64 period = sysctl_sched_shares_window;
1038         u64 now, delta;
1039         unsigned long load = cfs_rq->load.weight;
1040
1041         if (cfs_rq->tg == &root_task_group || throttled_hierarchy(cfs_rq))
1042                 return;
1043
1044         now = rq_of(cfs_rq)->clock_task;
1045         delta = now - cfs_rq->load_stamp;
1046
1047         /* truncate load history at 4 idle periods */
1048         if (cfs_rq->load_stamp > cfs_rq->load_last &&
1049             now - cfs_rq->load_last > 4 * period) {
1050                 cfs_rq->load_period = 0;
1051                 cfs_rq->load_avg = 0;
1052                 delta = period - 1;
1053         }
1054
1055         cfs_rq->load_stamp = now;
1056         cfs_rq->load_unacc_exec_time = 0;
1057         cfs_rq->load_period += delta;
1058         if (load) {
1059                 cfs_rq->load_last = now;
1060                 cfs_rq->load_avg += delta * load;
1061         }
1062
1063         /* consider updating load contribution on each fold or truncate */
1064         if (global_update || cfs_rq->load_period > period
1065             || !cfs_rq->load_period)
1066                 update_cfs_rq_load_contribution(cfs_rq, global_update);
1067
1068         while (cfs_rq->load_period > period) {
1069                 /*
1070                  * Inline assembly required to prevent the compiler
1071                  * optimising this loop into a divmod call.
1072                  * See __iter_div_u64_rem() for another example of this.
1073                  */
1074                 asm("" : "+rm" (cfs_rq->load_period));
1075                 cfs_rq->load_period /= 2;
1076                 cfs_rq->load_avg /= 2;
1077         }
1078
1079         if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
1080                 list_del_leaf_cfs_rq(cfs_rq);
1081 }
1082
1083 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
1084 {
1085         long tg_weight;
1086
1087         /*
1088          * Use this CPU's actual weight instead of the last load_contribution
1089          * to gain a more accurate current total weight. See
1090          * update_cfs_rq_load_contribution().
1091          */
1092         tg_weight = atomic_read(&tg->load_weight);
1093         tg_weight -= cfs_rq->load_contribution;
1094         tg_weight += cfs_rq->load.weight;
1095
1096         return tg_weight;
1097 }
1098
1099 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1100 {
1101         long tg_weight, load, shares;
1102
1103         tg_weight = calc_tg_weight(tg, cfs_rq);
1104         load = cfs_rq->load.weight;
1105
1106         shares = (tg->shares * load);
1107         if (tg_weight)
1108                 shares /= tg_weight;
1109
1110         if (shares < MIN_SHARES)
1111                 shares = MIN_SHARES;
1112         if (shares > tg->shares)
1113                 shares = tg->shares;
1114
1115         return shares;
1116 }
1117
1118 static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1119 {
1120         if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
1121                 update_cfs_load(cfs_rq, 0);
1122                 update_cfs_shares(cfs_rq);
1123         }
1124 }
1125 # else /* CONFIG_SMP */
1126 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1127 {
1128 }
1129
1130 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1131 {
1132         return tg->shares;
1133 }
1134
1135 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1136 {
1137 }
1138 # endif /* CONFIG_SMP */
1139 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
1140                             unsigned long weight)
1141 {
1142         if (se->on_rq) {
1143                 /* commit outstanding execution time */
1144                 if (cfs_rq->curr == se)
1145                         update_curr(cfs_rq);
1146                 account_entity_dequeue(cfs_rq, se);
1147         }
1148
1149         update_load_set(&se->load, weight);
1150
1151         if (se->on_rq)
1152                 account_entity_enqueue(cfs_rq, se);
1153 }
1154
1155 static void update_cfs_shares(struct cfs_rq *cfs_rq)
1156 {
1157         struct task_group *tg;
1158         struct sched_entity *se;
1159         long shares;
1160
1161         tg = cfs_rq->tg;
1162         se = tg->se[cpu_of(rq_of(cfs_rq))];
1163         if (!se || throttled_hierarchy(cfs_rq))
1164                 return;
1165 #ifndef CONFIG_SMP
1166         if (likely(se->load.weight == tg->shares))
1167                 return;
1168 #endif
1169         shares = calc_cfs_shares(cfs_rq, tg);
1170
1171         reweight_entity(cfs_rq_of(se), se, shares);
1172 }
1173 #else /* CONFIG_FAIR_GROUP_SCHED */
1174 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1175 {
1176 }
1177
1178 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
1179 {
1180 }
1181
1182 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1183 {
1184 }
1185 #endif /* CONFIG_FAIR_GROUP_SCHED */
1186
1187 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
1188 {
1189 #ifdef CONFIG_SCHEDSTATS
1190         struct task_struct *tsk = NULL;
1191
1192         if (entity_is_task(se))
1193                 tsk = task_of(se);
1194
1195         if (se->statistics.sleep_start) {
1196                 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
1197
1198                 if ((s64)delta < 0)
1199                         delta = 0;
1200
1201                 if (unlikely(delta > se->statistics.sleep_max))
1202                         se->statistics.sleep_max = delta;
1203
1204                 se->statistics.sleep_start = 0;
1205                 se->statistics.sum_sleep_runtime += delta;
1206
1207                 if (tsk) {
1208                         account_scheduler_latency(tsk, delta >> 10, 1);
1209                         trace_sched_stat_sleep(tsk, delta);
1210                 }
1211         }
1212         if (se->statistics.block_start) {
1213                 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
1214
1215                 if ((s64)delta < 0)
1216                         delta = 0;
1217
1218                 if (unlikely(delta > se->statistics.block_max))
1219                         se->statistics.block_max = delta;
1220
1221                 se->statistics.block_start = 0;
1222                 se->statistics.sum_sleep_runtime += delta;
1223
1224                 if (tsk) {
1225                         if (tsk->in_iowait) {
1226                                 se->statistics.iowait_sum += delta;
1227                                 se->statistics.iowait_count++;
1228                                 trace_sched_stat_iowait(tsk, delta);
1229                         }
1230
1231                         trace_sched_stat_blocked(tsk, delta);
1232
1233                         /*
1234                          * Blocking time is in units of nanosecs, so shift by
1235                          * 20 to get a milliseconds-range estimation of the
1236                          * amount of time that the task spent sleeping:
1237                          */
1238                         if (unlikely(prof_on == SLEEP_PROFILING)) {
1239                                 profile_hits(SLEEP_PROFILING,
1240                                                 (void *)get_wchan(tsk),
1241                                                 delta >> 20);
1242                         }
1243                         account_scheduler_latency(tsk, delta >> 10, 0);
1244                 }
1245         }
1246 #endif
1247 }
1248
1249 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1250 {
1251 #ifdef CONFIG_SCHED_DEBUG
1252         s64 d = se->vruntime - cfs_rq->min_vruntime;
1253
1254         if (d < 0)
1255                 d = -d;
1256
1257         if (d > 3*sysctl_sched_latency)
1258                 schedstat_inc(cfs_rq, nr_spread_over);
1259 #endif
1260 }
1261
1262 static void
1263 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1264 {
1265         u64 vruntime = cfs_rq->min_vruntime;
1266
1267         /*
1268          * The 'current' period is already promised to the current tasks,
1269          * however the extra weight of the new task will slow them down a
1270          * little, place the new task so that it fits in the slot that
1271          * stays open at the end.
1272          */
1273         if (initial && sched_feat(START_DEBIT))
1274                 vruntime += sched_vslice(cfs_rq, se);
1275
1276         /* sleeps up to a single latency don't count. */
1277         if (!initial) {
1278                 unsigned long thresh = sysctl_sched_latency;
1279
1280                 /*
1281                  * Halve their sleep time's effect, to allow
1282                  * for a gentler effect of sleepers:
1283                  */
1284                 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1285                         thresh >>= 1;
1286
1287                 vruntime -= thresh;
1288         }
1289
1290         /* ensure we never gain time by being placed backwards. */
1291         vruntime = max_vruntime(se->vruntime, vruntime);
1292
1293         se->vruntime = vruntime;
1294 }
1295
1296 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1297
1298 static void
1299 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1300 {
1301         /*
1302          * Update the normalized vruntime before updating min_vruntime
1303          * through callig update_curr().
1304          */
1305         if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
1306                 se->vruntime += cfs_rq->min_vruntime;
1307
1308         /*
1309          * Update run-time statistics of the 'current'.
1310          */
1311         update_curr(cfs_rq);
1312         update_cfs_load(cfs_rq, 0);
1313         account_entity_enqueue(cfs_rq, se);
1314         update_cfs_shares(cfs_rq);
1315
1316         if (flags & ENQUEUE_WAKEUP) {
1317                 place_entity(cfs_rq, se, 0);
1318                 enqueue_sleeper(cfs_rq, se);
1319         }
1320
1321         update_stats_enqueue(cfs_rq, se);
1322         check_spread(cfs_rq, se);
1323         if (se != cfs_rq->curr)
1324                 __enqueue_entity(cfs_rq, se);
1325         se->on_rq = 1;
1326
1327         if (cfs_rq->nr_running == 1) {
1328                 list_add_leaf_cfs_rq(cfs_rq);
1329                 check_enqueue_throttle(cfs_rq);
1330         }
1331 }
1332
1333 static void __clear_buddies_last(struct sched_entity *se)
1334 {
1335         for_each_sched_entity(se) {
1336                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1337                 if (cfs_rq->last == se)
1338                         cfs_rq->last = NULL;
1339                 else
1340                         break;
1341         }
1342 }
1343
1344 static void __clear_buddies_next(struct sched_entity *se)
1345 {
1346         for_each_sched_entity(se) {
1347                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1348                 if (cfs_rq->next == se)
1349                         cfs_rq->next = NULL;
1350                 else
1351                         break;
1352         }
1353 }
1354
1355 static void __clear_buddies_skip(struct sched_entity *se)
1356 {
1357         for_each_sched_entity(se) {
1358                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1359                 if (cfs_rq->skip == se)
1360                         cfs_rq->skip = NULL;
1361                 else
1362                         break;
1363         }
1364 }
1365
1366 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1367 {
1368         if (cfs_rq->last == se)
1369                 __clear_buddies_last(se);
1370
1371         if (cfs_rq->next == se)
1372                 __clear_buddies_next(se);
1373
1374         if (cfs_rq->skip == se)
1375                 __clear_buddies_skip(se);
1376 }
1377
1378 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1379
1380 static void
1381 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1382 {
1383         /*
1384          * Update run-time statistics of the 'current'.
1385          */
1386         update_curr(cfs_rq);
1387
1388         update_stats_dequeue(cfs_rq, se);
1389         if (flags & DEQUEUE_SLEEP) {
1390 #ifdef CONFIG_SCHEDSTATS
1391                 if (entity_is_task(se)) {
1392                         struct task_struct *tsk = task_of(se);
1393
1394                         if (tsk->state & TASK_INTERRUPTIBLE)
1395                                 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
1396                         if (tsk->state & TASK_UNINTERRUPTIBLE)
1397                                 se->statistics.block_start = rq_of(cfs_rq)->clock;
1398                 }
1399 #endif
1400         }
1401
1402         clear_buddies(cfs_rq, se);
1403
1404         if (se != cfs_rq->curr)
1405                 __dequeue_entity(cfs_rq, se);
1406         se->on_rq = 0;
1407         update_cfs_load(cfs_rq, 0);
1408         account_entity_dequeue(cfs_rq, se);
1409
1410         /*
1411          * Normalize the entity after updating the min_vruntime because the
1412          * update can refer to the ->curr item and we need to reflect this
1413          * movement in our normalized position.
1414          */
1415         if (!(flags & DEQUEUE_SLEEP))
1416                 se->vruntime -= cfs_rq->min_vruntime;
1417
1418         /* return excess runtime on last dequeue */
1419         return_cfs_rq_runtime(cfs_rq);
1420
1421         update_min_vruntime(cfs_rq);
1422         update_cfs_shares(cfs_rq);
1423 }
1424
1425 /*
1426  * Preempt the current task with a newly woken task if needed:
1427  */
1428 static void
1429 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1430 {
1431         unsigned long ideal_runtime, delta_exec;
1432         struct sched_entity *se;
1433         s64 delta;
1434
1435         ideal_runtime = sched_slice(cfs_rq, curr);
1436         delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
1437         if (delta_exec > ideal_runtime) {
1438                 resched_task(rq_of(cfs_rq)->curr);
1439                 /*
1440                  * The current task ran long enough, ensure it doesn't get
1441                  * re-elected due to buddy favours.
1442                  */
1443                 clear_buddies(cfs_rq, curr);
1444                 return;
1445         }
1446
1447         /*
1448          * Ensure that a task that missed wakeup preemption by a
1449          * narrow margin doesn't have to wait for a full slice.
1450          * This also mitigates buddy induced latencies under load.
1451          */
1452         if (delta_exec < sysctl_sched_min_granularity)
1453                 return;
1454
1455         se = __pick_first_entity(cfs_rq);
1456         delta = curr->vruntime - se->vruntime;
1457
1458         if (delta < 0)
1459                 return;
1460
1461         if (delta > ideal_runtime)
1462                 resched_task(rq_of(cfs_rq)->curr);
1463 }
1464
1465 static void
1466 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1467 {
1468         /* 'current' is not kept within the tree. */
1469         if (se->on_rq) {
1470                 /*
1471                  * Any task has to be enqueued before it get to execute on
1472                  * a CPU. So account for the time it spent waiting on the
1473                  * runqueue.
1474                  */
1475                 update_stats_wait_end(cfs_rq, se);
1476                 __dequeue_entity(cfs_rq, se);
1477         }
1478
1479         update_stats_curr_start(cfs_rq, se);
1480         cfs_rq->curr = se;
1481 #ifdef CONFIG_SCHEDSTATS
1482         /*
1483          * Track our maximum slice length, if the CPU's load is at
1484          * least twice that of our own weight (i.e. dont track it
1485          * when there are only lesser-weight tasks around):
1486          */
1487         if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
1488                 se->statistics.slice_max = max(se->statistics.slice_max,
1489                         se->sum_exec_runtime - se->prev_sum_exec_runtime);
1490         }
1491 #endif
1492         se->prev_sum_exec_runtime = se->sum_exec_runtime;
1493 }
1494
1495 static int
1496 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
1497
1498 /*
1499  * Pick the next process, keeping these things in mind, in this order:
1500  * 1) keep things fair between processes/task groups
1501  * 2) pick the "next" process, since someone really wants that to run
1502  * 3) pick the "last" process, for cache locality
1503  * 4) do not run the "skip" process, if something else is available
1504  */
1505 static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
1506 {
1507         struct sched_entity *se = __pick_first_entity(cfs_rq);
1508         struct sched_entity *left = se;
1509
1510         /*
1511          * Avoid running the skip buddy, if running something else can
1512          * be done without getting too unfair.
1513          */
1514         if (cfs_rq->skip == se) {
1515                 struct sched_entity *second = __pick_next_entity(se);
1516                 if (second && wakeup_preempt_entity(second, left) < 1)
1517                         se = second;
1518         }
1519
1520         /*
1521          * Prefer last buddy, try to return the CPU to a preempted task.
1522          */
1523         if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
1524                 se = cfs_rq->last;
1525
1526         /*
1527          * Someone really wants this to run. If it's not unfair, run it.
1528          */
1529         if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
1530                 se = cfs_rq->next;
1531
1532         clear_buddies(cfs_rq, se);
1533
1534         return se;
1535 }
1536
1537 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1538
1539 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
1540 {
1541         /*
1542          * If still on the runqueue then deactivate_task()
1543          * was not called and update_curr() has to be done:
1544          */
1545         if (prev->on_rq)
1546                 update_curr(cfs_rq);
1547
1548         /* throttle cfs_rqs exceeding runtime */
1549         check_cfs_rq_runtime(cfs_rq);
1550
1551         check_spread(cfs_rq, prev);
1552         if (prev->on_rq) {
1553                 update_stats_wait_start(cfs_rq, prev);
1554                 /* Put 'current' back into the tree. */
1555                 __enqueue_entity(cfs_rq, prev);
1556         }
1557         cfs_rq->curr = NULL;
1558 }
1559
1560 static void
1561 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
1562 {
1563         /*
1564          * Update run-time statistics of the 'current'.
1565          */
1566         update_curr(cfs_rq);
1567
1568         /*
1569          * Update share accounting for long-running entities.
1570          */
1571         update_entity_shares_tick(cfs_rq);
1572
1573 #ifdef CONFIG_SCHED_HRTICK
1574         /*
1575          * queued ticks are scheduled to match the slice, so don't bother
1576          * validating it and just reschedule.
1577          */
1578         if (queued) {
1579                 resched_task(rq_of(cfs_rq)->curr);
1580                 return;
1581         }
1582         /*
1583          * don't let the period tick interfere with the hrtick preemption
1584          */
1585         if (!sched_feat(DOUBLE_TICK) &&
1586                         hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
1587                 return;
1588 #endif
1589
1590         if (cfs_rq->nr_running > 1)
1591                 check_preempt_tick(cfs_rq, curr);
1592 }
1593
1594
1595 /**************************************************
1596  * CFS bandwidth control machinery
1597  */
1598
1599 #ifdef CONFIG_CFS_BANDWIDTH
1600
1601 #ifdef HAVE_JUMP_LABEL
1602 static struct static_key __cfs_bandwidth_used;
1603
1604 static inline bool cfs_bandwidth_used(void)
1605 {
1606         return static_key_false(&__cfs_bandwidth_used);
1607 }
1608
1609 void account_cfs_bandwidth_used(int enabled, int was_enabled)
1610 {
1611         /* only need to count groups transitioning between enabled/!enabled */
1612         if (enabled && !was_enabled)
1613                 static_key_slow_inc(&__cfs_bandwidth_used);
1614         else if (!enabled && was_enabled)
1615                 static_key_slow_dec(&__cfs_bandwidth_used);
1616 }
1617 #else /* HAVE_JUMP_LABEL */
1618 static bool cfs_bandwidth_used(void)
1619 {
1620         return true;
1621 }
1622
1623 void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
1624 #endif /* HAVE_JUMP_LABEL */
1625
1626 /*
1627  * default period for cfs group bandwidth.
1628  * default: 0.1s, units: nanoseconds
1629  */
1630 static inline u64 default_cfs_period(void)
1631 {
1632         return 100000000ULL;
1633 }
1634
1635 static inline u64 sched_cfs_bandwidth_slice(void)
1636 {
1637         return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
1638 }
1639
1640 /*
1641  * Replenish runtime according to assigned quota and update expiration time.
1642  * We use sched_clock_cpu directly instead of rq->clock to avoid adding
1643  * additional synchronization around rq->lock.
1644  *
1645  * requires cfs_b->lock
1646  */
1647 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
1648 {
1649         u64 now;
1650
1651         if (cfs_b->quota == RUNTIME_INF)
1652                 return;
1653
1654         now = sched_clock_cpu(smp_processor_id());
1655         cfs_b->runtime = cfs_b->quota;
1656         cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
1657 }
1658
1659 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
1660 {
1661         return &tg->cfs_bandwidth;
1662 }
1663
1664 /* returns 0 on failure to allocate runtime */
1665 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1666 {
1667         struct task_group *tg = cfs_rq->tg;
1668         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
1669         u64 amount = 0, min_amount, expires;
1670
1671         /* note: this is a positive sum as runtime_remaining <= 0 */
1672         min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
1673
1674         raw_spin_lock(&cfs_b->lock);
1675         if (cfs_b->quota == RUNTIME_INF)
1676                 amount = min_amount;
1677         else {
1678                 /*
1679                  * If the bandwidth pool has become inactive, then at least one
1680                  * period must have elapsed since the last consumption.
1681                  * Refresh the global state and ensure bandwidth timer becomes
1682                  * active.
1683                  */
1684                 if (!cfs_b->timer_active) {
1685                         __refill_cfs_bandwidth_runtime(cfs_b);
1686                         __start_cfs_bandwidth(cfs_b);
1687                 }
1688
1689                 if (cfs_b->runtime > 0) {
1690                         amount = min(cfs_b->runtime, min_amount);
1691                         cfs_b->runtime -= amount;
1692                         cfs_b->idle = 0;
1693                 }
1694         }
1695         expires = cfs_b->runtime_expires;
1696         raw_spin_unlock(&cfs_b->lock);
1697
1698         cfs_rq->runtime_remaining += amount;
1699         /*
1700          * we may have advanced our local expiration to account for allowed
1701          * spread between our sched_clock and the one on which runtime was
1702          * issued.
1703          */
1704         if ((s64)(expires - cfs_rq->runtime_expires) > 0)
1705                 cfs_rq->runtime_expires = expires;
1706
1707         return cfs_rq->runtime_remaining > 0;
1708 }
1709
1710 /*
1711  * Note: This depends on the synchronization provided by sched_clock and the
1712  * fact that rq->clock snapshots this value.
1713  */
1714 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1715 {
1716         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1717         struct rq *rq = rq_of(cfs_rq);
1718
1719         /* if the deadline is ahead of our clock, nothing to do */
1720         if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
1721                 return;
1722
1723         if (cfs_rq->runtime_remaining < 0)
1724                 return;
1725
1726         /*
1727          * If the local deadline has passed we have to consider the
1728          * possibility that our sched_clock is 'fast' and the global deadline
1729          * has not truly expired.
1730          *
1731          * Fortunately we can check determine whether this the case by checking
1732          * whether the global deadline has advanced.
1733          */
1734
1735         if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
1736                 /* extend local deadline, drift is bounded above by 2 ticks */
1737                 cfs_rq->runtime_expires += TICK_NSEC;
1738         } else {
1739                 /* global deadline is ahead, expiration has passed */
1740                 cfs_rq->runtime_remaining = 0;
1741         }
1742 }
1743
1744 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
1745                                      unsigned long delta_exec)
1746 {
1747         /* dock delta_exec before expiring quota (as it could span periods) */
1748         cfs_rq->runtime_remaining -= delta_exec;
1749         expire_cfs_rq_runtime(cfs_rq);
1750
1751         if (likely(cfs_rq->runtime_remaining > 0))
1752                 return;
1753
1754         /*
1755          * if we're unable to extend our runtime we resched so that the active
1756          * hierarchy can be throttled
1757          */
1758         if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
1759                 resched_task(rq_of(cfs_rq)->curr);
1760 }
1761
1762 static __always_inline
1763 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
1764 {
1765         if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
1766                 return;
1767
1768         __account_cfs_rq_runtime(cfs_rq, delta_exec);
1769 }
1770
1771 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
1772 {
1773         return cfs_bandwidth_used() && cfs_rq->throttled;
1774 }
1775
1776 /* check whether cfs_rq, or any parent, is throttled */
1777 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
1778 {
1779         return cfs_bandwidth_used() && cfs_rq->throttle_count;
1780 }
1781
1782 /*
1783  * Ensure that neither of the group entities corresponding to src_cpu or
1784  * dest_cpu are members of a throttled hierarchy when performing group
1785  * load-balance operations.
1786  */
1787 static inline int throttled_lb_pair(struct task_group *tg,
1788                                     int src_cpu, int dest_cpu)
1789 {
1790         struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
1791
1792         src_cfs_rq = tg->cfs_rq[src_cpu];
1793         dest_cfs_rq = tg->cfs_rq[dest_cpu];
1794
1795         return throttled_hierarchy(src_cfs_rq) ||
1796                throttled_hierarchy(dest_cfs_rq);
1797 }
1798
1799 /* updated child weight may affect parent so we have to do this bottom up */
1800 static int tg_unthrottle_up(struct task_group *tg, void *data)
1801 {
1802         struct rq *rq = data;
1803         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1804
1805         cfs_rq->throttle_count--;
1806 #ifdef CONFIG_SMP
1807         if (!cfs_rq->throttle_count) {
1808                 u64 delta = rq->clock_task - cfs_rq->load_stamp;
1809
1810                 /* leaving throttled state, advance shares averaging windows */
1811                 cfs_rq->load_stamp += delta;
1812                 cfs_rq->load_last += delta;
1813
1814                 /* update entity weight now that we are on_rq again */
1815                 update_cfs_shares(cfs_rq);
1816         }
1817 #endif
1818
1819         return 0;
1820 }
1821
1822 static int tg_throttle_down(struct task_group *tg, void *data)
1823 {
1824         struct rq *rq = data;
1825         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1826
1827         /* group is entering throttled state, record last load */
1828         if (!cfs_rq->throttle_count)
1829                 update_cfs_load(cfs_rq, 0);
1830         cfs_rq->throttle_count++;
1831
1832         return 0;
1833 }
1834
1835 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
1836 {
1837         struct rq *rq = rq_of(cfs_rq);
1838         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1839         struct sched_entity *se;
1840         long task_delta, dequeue = 1;
1841
1842         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1843
1844         /* account load preceding throttle */
1845         rcu_read_lock();
1846         walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
1847         rcu_read_unlock();
1848
1849         task_delta = cfs_rq->h_nr_running;
1850         for_each_sched_entity(se) {
1851                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
1852                 /* throttled entity or throttle-on-deactivate */
1853                 if (!se->on_rq)
1854                         break;
1855
1856                 if (dequeue)
1857                         dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
1858                 qcfs_rq->h_nr_running -= task_delta;
1859
1860                 if (qcfs_rq->load.weight)
1861                         dequeue = 0;
1862         }
1863
1864         if (!se)
1865                 rq->nr_running -= task_delta;
1866
1867         cfs_rq->throttled = 1;
1868         cfs_rq->throttled_timestamp = rq->clock;
1869         raw_spin_lock(&cfs_b->lock);
1870         list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
1871         raw_spin_unlock(&cfs_b->lock);
1872 }
1873
1874 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
1875 {
1876         struct rq *rq = rq_of(cfs_rq);
1877         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1878         struct sched_entity *se;
1879         int enqueue = 1;
1880         long task_delta;
1881
1882         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1883
1884         cfs_rq->throttled = 0;
1885         raw_spin_lock(&cfs_b->lock);
1886         cfs_b->throttled_time += rq->clock - cfs_rq->throttled_timestamp;
1887         list_del_rcu(&cfs_rq->throttled_list);
1888         raw_spin_unlock(&cfs_b->lock);
1889         cfs_rq->throttled_timestamp = 0;
1890
1891         update_rq_clock(rq);
1892         /* update hierarchical throttle state */
1893         walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
1894
1895         if (!cfs_rq->load.weight)
1896                 return;
1897
1898         task_delta = cfs_rq->h_nr_running;
1899         for_each_sched_entity(se) {
1900                 if (se->on_rq)
1901                         enqueue = 0;
1902
1903                 cfs_rq = cfs_rq_of(se);
1904                 if (enqueue)
1905                         enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
1906                 cfs_rq->h_nr_running += task_delta;
1907
1908                 if (cfs_rq_throttled(cfs_rq))
1909                         break;
1910         }
1911
1912         if (!se)
1913                 rq->nr_running += task_delta;
1914
1915         /* determine whether we need to wake up potentially idle cpu */
1916         if (rq->curr == rq->idle && rq->cfs.nr_running)
1917                 resched_task(rq->curr);
1918 }
1919
1920 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
1921                 u64 remaining, u64 expires)
1922 {
1923         struct cfs_rq *cfs_rq;
1924         u64 runtime = remaining;
1925
1926         rcu_read_lock();
1927         list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
1928                                 throttled_list) {
1929                 struct rq *rq = rq_of(cfs_rq);
1930
1931                 raw_spin_lock(&rq->lock);
1932                 if (!cfs_rq_throttled(cfs_rq))
1933                         goto next;
1934
1935                 runtime = -cfs_rq->runtime_remaining + 1;
1936                 if (runtime > remaining)
1937                         runtime = remaining;
1938                 remaining -= runtime;
1939
1940                 cfs_rq->runtime_remaining += runtime;
1941                 cfs_rq->runtime_expires = expires;
1942
1943                 /* we check whether we're throttled above */
1944                 if (cfs_rq->runtime_remaining > 0)
1945                         unthrottle_cfs_rq(cfs_rq);
1946
1947 next:
1948                 raw_spin_unlock(&rq->lock);
1949
1950                 if (!remaining)
1951                         break;
1952         }
1953         rcu_read_unlock();
1954
1955         return remaining;
1956 }
1957
1958 /*
1959  * Responsible for refilling a task_group's bandwidth and unthrottling its
1960  * cfs_rqs as appropriate. If there has been no activity within the last
1961  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
1962  * used to track this state.
1963  */
1964 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
1965 {
1966         u64 runtime, runtime_expires;
1967         int idle = 1, throttled;
1968
1969         raw_spin_lock(&cfs_b->lock);
1970         /* no need to continue the timer with no bandwidth constraint */
1971         if (cfs_b->quota == RUNTIME_INF)
1972                 goto out_unlock;
1973
1974         throttled = !list_empty(&cfs_b->throttled_cfs_rq);
1975         /* idle depends on !throttled (for the case of a large deficit) */
1976         idle = cfs_b->idle && !throttled;
1977         cfs_b->nr_periods += overrun;
1978
1979         /* if we're going inactive then everything else can be deferred */
1980         if (idle)
1981                 goto out_unlock;
1982
1983         __refill_cfs_bandwidth_runtime(cfs_b);
1984
1985         if (!throttled) {
1986                 /* mark as potentially idle for the upcoming period */
1987                 cfs_b->idle = 1;
1988                 goto out_unlock;
1989         }
1990
1991         /* account preceding periods in which throttling occurred */
1992         cfs_b->nr_throttled += overrun;
1993
1994         /*
1995          * There are throttled entities so we must first use the new bandwidth
1996          * to unthrottle them before making it generally available.  This
1997          * ensures that all existing debts will be paid before a new cfs_rq is
1998          * allowed to run.
1999          */
2000         runtime = cfs_b->runtime;
2001         runtime_expires = cfs_b->runtime_expires;
2002         cfs_b->runtime = 0;
2003
2004         /*
2005          * This check is repeated as we are holding onto the new bandwidth
2006          * while we unthrottle.  This can potentially race with an unthrottled
2007          * group trying to acquire new bandwidth from the global pool.
2008          */
2009         while (throttled && runtime > 0) {
2010                 raw_spin_unlock(&cfs_b->lock);
2011                 /* we can't nest cfs_b->lock while distributing bandwidth */
2012                 runtime = distribute_cfs_runtime(cfs_b, runtime,
2013                                                  runtime_expires);
2014                 raw_spin_lock(&cfs_b->lock);
2015
2016                 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2017         }
2018
2019         /* return (any) remaining runtime */
2020         cfs_b->runtime = runtime;
2021         /*
2022          * While we are ensured activity in the period following an
2023          * unthrottle, this also covers the case in which the new bandwidth is
2024          * insufficient to cover the existing bandwidth deficit.  (Forcing the
2025          * timer to remain active while there are any throttled entities.)
2026          */
2027         cfs_b->idle = 0;
2028 out_unlock:
2029         if (idle)
2030                 cfs_b->timer_active = 0;
2031         raw_spin_unlock(&cfs_b->lock);
2032
2033         return idle;
2034 }
2035
2036 /* a cfs_rq won't donate quota below this amount */
2037 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2038 /* minimum remaining period time to redistribute slack quota */
2039 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2040 /* how long we wait to gather additional slack before distributing */
2041 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2042
2043 /* are we near the end of the current quota period? */
2044 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2045 {
2046         struct hrtimer *refresh_timer = &cfs_b->period_timer;
2047         u64 remaining;
2048
2049         /* if the call-back is running a quota refresh is already occurring */
2050         if (hrtimer_callback_running(refresh_timer))
2051                 return 1;
2052
2053         /* is a quota refresh about to occur? */
2054         remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2055         if (remaining < min_expire)
2056                 return 1;
2057
2058         return 0;
2059 }
2060
2061 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2062 {
2063         u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2064
2065         /* if there's a quota refresh soon don't bother with slack */
2066         if (runtime_refresh_within(cfs_b, min_left))
2067                 return;
2068
2069         start_bandwidth_timer(&cfs_b->slack_timer,
2070                                 ns_to_ktime(cfs_bandwidth_slack_period));
2071 }
2072
2073 /* we know any runtime found here is valid as update_curr() precedes return */
2074 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2075 {
2076         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2077         s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2078
2079         if (slack_runtime <= 0)
2080                 return;
2081
2082         raw_spin_lock(&cfs_b->lock);
2083         if (cfs_b->quota != RUNTIME_INF &&
2084             cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2085                 cfs_b->runtime += slack_runtime;
2086
2087                 /* we are under rq->lock, defer unthrottling using a timer */
2088                 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2089                     !list_empty(&cfs_b->throttled_cfs_rq))
2090                         start_cfs_slack_bandwidth(cfs_b);
2091         }
2092         raw_spin_unlock(&cfs_b->lock);
2093
2094         /* even if it's not valid for return we don't want to try again */
2095         cfs_rq->runtime_remaining -= slack_runtime;
2096 }
2097
2098 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2099 {
2100         if (!cfs_bandwidth_used())
2101                 return;
2102
2103         if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
2104                 return;
2105
2106         __return_cfs_rq_runtime(cfs_rq);
2107 }
2108
2109 /*
2110  * This is done with a timer (instead of inline with bandwidth return) since
2111  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2112  */
2113 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2114 {
2115         u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2116         u64 expires;
2117
2118         /* confirm we're still not at a refresh boundary */
2119         if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2120                 return;
2121
2122         raw_spin_lock(&cfs_b->lock);
2123         if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2124                 runtime = cfs_b->runtime;
2125                 cfs_b->runtime = 0;
2126         }
2127         expires = cfs_b->runtime_expires;
2128         raw_spin_unlock(&cfs_b->lock);
2129
2130         if (!runtime)
2131                 return;
2132
2133         runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2134
2135         raw_spin_lock(&cfs_b->lock);
2136         if (expires == cfs_b->runtime_expires)
2137                 cfs_b->runtime = runtime;
2138         raw_spin_unlock(&cfs_b->lock);
2139 }
2140
2141 /*
2142  * When a group wakes up we want to make sure that its quota is not already
2143  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2144  * runtime as update_curr() throttling can not not trigger until it's on-rq.
2145  */
2146 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2147 {
2148         if (!cfs_bandwidth_used())
2149                 return;
2150
2151         /* an active group must be handled by the update_curr()->put() path */
2152         if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2153                 return;
2154
2155         /* ensure the group is not already throttled */
2156         if (cfs_rq_throttled(cfs_rq))
2157                 return;
2158
2159         /* update runtime allocation */
2160         account_cfs_rq_runtime(cfs_rq, 0);
2161         if (cfs_rq->runtime_remaining <= 0)
2162                 throttle_cfs_rq(cfs_rq);
2163 }
2164
2165 /* conditionally throttle active cfs_rq's from put_prev_entity() */
2166 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2167 {
2168         if (!cfs_bandwidth_used())
2169                 return;
2170
2171         if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2172                 return;
2173
2174         /*
2175          * it's possible for a throttled entity to be forced into a running
2176          * state (e.g. set_curr_task), in this case we're finished.
2177          */
2178         if (cfs_rq_throttled(cfs_rq))
2179                 return;
2180
2181         throttle_cfs_rq(cfs_rq);
2182 }
2183
2184 static inline u64 default_cfs_period(void);
2185 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2186 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2187
2188 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2189 {
2190         struct cfs_bandwidth *cfs_b =
2191                 container_of(timer, struct cfs_bandwidth, slack_timer);
2192         do_sched_cfs_slack_timer(cfs_b);
2193
2194         return HRTIMER_NORESTART;
2195 }
2196
2197 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2198 {
2199         struct cfs_bandwidth *cfs_b =
2200                 container_of(timer, struct cfs_bandwidth, period_timer);
2201         ktime_t now;
2202         int overrun;
2203         int idle = 0;
2204
2205         for (;;) {
2206                 now = hrtimer_cb_get_time(timer);
2207                 overrun = hrtimer_forward(timer, now, cfs_b->period);
2208
2209                 if (!overrun)
2210                         break;
2211
2212                 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2213         }
2214
2215         return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2216 }
2217
2218 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2219 {
2220         raw_spin_lock_init(&cfs_b->lock);
2221         cfs_b->runtime = 0;
2222         cfs_b->quota = RUNTIME_INF;
2223         cfs_b->period = ns_to_ktime(default_cfs_period());
2224
2225         INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2226         hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2227         cfs_b->period_timer.function = sched_cfs_period_timer;
2228         hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2229         cfs_b->slack_timer.function = sched_cfs_slack_timer;
2230 }
2231
2232 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2233 {
2234         cfs_rq->runtime_enabled = 0;
2235         INIT_LIST_HEAD(&cfs_rq->throttled_list);
2236 }
2237
2238 /* requires cfs_b->lock, may release to reprogram timer */
2239 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2240 {
2241         /*
2242          * The timer may be active because we're trying to set a new bandwidth
2243          * period or because we're racing with the tear-down path
2244          * (timer_active==0 becomes visible before the hrtimer call-back
2245          * terminates).  In either case we ensure that it's re-programmed
2246          */
2247         while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2248                 raw_spin_unlock(&cfs_b->lock);
2249                 /* ensure cfs_b->lock is available while we wait */
2250                 hrtimer_cancel(&cfs_b->period_timer);
2251
2252                 raw_spin_lock(&cfs_b->lock);
2253                 /* if someone else restarted the timer then we're done */
2254                 if (cfs_b->timer_active)
2255                         return;
2256         }
2257
2258         cfs_b->timer_active = 1;
2259         start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2260 }
2261
2262 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2263 {
2264         hrtimer_cancel(&cfs_b->period_timer);
2265         hrtimer_cancel(&cfs_b->slack_timer);
2266 }
2267
2268 static void unthrottle_offline_cfs_rqs(struct rq *rq)
2269 {
2270         struct cfs_rq *cfs_rq;
2271
2272         for_each_leaf_cfs_rq(rq, cfs_rq) {
2273                 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2274
2275                 if (!cfs_rq->runtime_enabled)
2276                         continue;
2277
2278                 /*
2279                  * clock_task is not advancing so we just need to make sure
2280                  * there's some valid quota amount
2281                  */
2282                 cfs_rq->runtime_remaining = cfs_b->quota;
2283                 if (cfs_rq_throttled(cfs_rq))
2284                         unthrottle_cfs_rq(cfs_rq);
2285         }
2286 }
2287
2288 #else /* CONFIG_CFS_BANDWIDTH */
2289 static __always_inline
2290 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec) {}
2291 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2292 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
2293 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2294
2295 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2296 {
2297         return 0;
2298 }
2299
2300 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2301 {
2302         return 0;
2303 }
2304
2305 static inline int throttled_lb_pair(struct task_group *tg,
2306                                     int src_cpu, int dest_cpu)
2307 {
2308         return 0;
2309 }
2310
2311 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2312
2313 #ifdef CONFIG_FAIR_GROUP_SCHED
2314 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2315 #endif
2316
2317 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2318 {
2319         return NULL;
2320 }
2321 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2322 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
2323
2324 #endif /* CONFIG_CFS_BANDWIDTH */
2325
2326 /**************************************************
2327  * CFS operations on tasks:
2328  */
2329
2330 #ifdef CONFIG_SCHED_HRTICK
2331 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2332 {
2333         struct sched_entity *se = &p->se;
2334         struct cfs_rq *cfs_rq = cfs_rq_of(se);
2335
2336         WARN_ON(task_rq(p) != rq);
2337
2338         if (cfs_rq->nr_running > 1) {
2339                 u64 slice = sched_slice(cfs_rq, se);
2340                 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2341                 s64 delta = slice - ran;
2342
2343                 if (delta < 0) {
2344                         if (rq->curr == p)
2345                                 resched_task(p);
2346                         return;
2347                 }
2348
2349                 /*
2350                  * Don't schedule slices shorter than 10000ns, that just
2351                  * doesn't make sense. Rely on vruntime for fairness.
2352                  */
2353                 if (rq->curr != p)
2354                         delta = max_t(s64, 10000LL, delta);
2355
2356                 hrtick_start(rq, delta);
2357         }
2358 }
2359
2360 /*
2361  * called from enqueue/dequeue and updates the hrtick when the
2362  * current task is from our class and nr_running is low enough
2363  * to matter.
2364  */
2365 static void hrtick_update(struct rq *rq)
2366 {
2367         struct task_struct *curr = rq->curr;
2368
2369         if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
2370                 return;
2371
2372         if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2373                 hrtick_start_fair(rq, curr);
2374 }
2375 #else /* !CONFIG_SCHED_HRTICK */
2376 static inline void
2377 hrtick_start_fair(struct rq *rq, struct task_struct *p)
2378 {
2379 }
2380
2381 static inline void hrtick_update(struct rq *rq)
2382 {
2383 }
2384 #endif
2385
2386 /*
2387  * The enqueue_task method is called before nr_running is
2388  * increased. Here we update the fair scheduling stats and
2389  * then put the task into the rbtree:
2390  */
2391 static void
2392 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2393 {
2394         struct cfs_rq *cfs_rq;
2395         struct sched_entity *se = &p->se;
2396
2397         for_each_sched_entity(se) {
2398                 if (se->on_rq)
2399                         break;
2400                 cfs_rq = cfs_rq_of(se);
2401                 enqueue_entity(cfs_rq, se, flags);
2402
2403                 /*
2404                  * end evaluation on encountering a throttled cfs_rq
2405                  *
2406                  * note: in the case of encountering a throttled cfs_rq we will
2407                  * post the final h_nr_running increment below.
2408                 */
2409                 if (cfs_rq_throttled(cfs_rq))
2410                         break;
2411                 cfs_rq->h_nr_running++;
2412
2413                 flags = ENQUEUE_WAKEUP;
2414         }
2415
2416         for_each_sched_entity(se) {
2417                 cfs_rq = cfs_rq_of(se);
2418                 cfs_rq->h_nr_running++;
2419
2420                 if (cfs_rq_throttled(cfs_rq))
2421                         break;
2422
2423                 update_cfs_load(cfs_rq, 0);
2424                 update_cfs_shares(cfs_rq);
2425         }
2426
2427         if (!se)
2428                 inc_nr_running(rq);
2429         hrtick_update(rq);
2430 }
2431
2432 static void set_next_buddy(struct sched_entity *se);
2433
2434 /*
2435  * The dequeue_task method is called before nr_running is
2436  * decreased. We remove the task from the rbtree and
2437  * update the fair scheduling stats:
2438  */
2439 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2440 {
2441         struct cfs_rq *cfs_rq;
2442         struct sched_entity *se = &p->se;
2443         int task_sleep = flags & DEQUEUE_SLEEP;
2444
2445         for_each_sched_entity(se) {
2446                 cfs_rq = cfs_rq_of(se);
2447                 dequeue_entity(cfs_rq, se, flags);
2448
2449                 /*
2450                  * end evaluation on encountering a throttled cfs_rq
2451                  *
2452                  * note: in the case of encountering a throttled cfs_rq we will
2453                  * post the final h_nr_running decrement below.
2454                 */
2455                 if (cfs_rq_throttled(cfs_rq))
2456                         break;
2457                 cfs_rq->h_nr_running--;
2458
2459                 /* Don't dequeue parent if it has other entities besides us */
2460                 if (cfs_rq->load.weight) {
2461                         /*
2462                          * Bias pick_next to pick a task from this cfs_rq, as
2463                          * p is sleeping when it is within its sched_slice.
2464                          */
2465                         if (task_sleep && parent_entity(se))
2466                                 set_next_buddy(parent_entity(se));
2467
2468                         /* avoid re-evaluating load for this entity */
2469                         se = parent_entity(se);
2470                         break;
2471                 }
2472                 flags |= DEQUEUE_SLEEP;
2473         }
2474
2475         for_each_sched_entity(se) {
2476                 cfs_rq = cfs_rq_of(se);
2477                 cfs_rq->h_nr_running--;
2478
2479                 if (cfs_rq_throttled(cfs_rq))
2480                         break;
2481
2482                 update_cfs_load(cfs_rq, 0);
2483                 update_cfs_shares(cfs_rq);
2484         }
2485
2486         if (!se)
2487                 dec_nr_running(rq);
2488         hrtick_update(rq);
2489 }
2490
2491 #ifdef CONFIG_SMP
2492 /* Used instead of source_load when we know the type == 0 */
2493 static unsigned long weighted_cpuload(const int cpu)
2494 {
2495         return cpu_rq(cpu)->load.weight;
2496 }
2497
2498 /*
2499  * Return a low guess at the load of a migration-source cpu weighted
2500  * according to the scheduling class and "nice" value.
2501  *
2502  * We want to under-estimate the load of migration sources, to
2503  * balance conservatively.
2504  */
2505 static unsigned long source_load(int cpu, int type)
2506 {
2507         struct rq *rq = cpu_rq(cpu);
2508         unsigned long total = weighted_cpuload(cpu);
2509
2510         if (type == 0 || !sched_feat(LB_BIAS))
2511                 return total;
2512
2513         return min(rq->cpu_load[type-1], total);
2514 }
2515
2516 /*
2517  * Return a high guess at the load of a migration-target cpu weighted
2518  * according to the scheduling class and "nice" value.
2519  */
2520 static unsigned long target_load(int cpu, int type)
2521 {
2522         struct rq *rq = cpu_rq(cpu);
2523         unsigned long total = weighted_cpuload(cpu);
2524
2525         if (type == 0 || !sched_feat(LB_BIAS))
2526                 return total;
2527
2528         return max(rq->cpu_load[type-1], total);
2529 }
2530
2531 static unsigned long power_of(int cpu)
2532 {
2533         return cpu_rq(cpu)->cpu_power;
2534 }
2535
2536 static unsigned long cpu_avg_load_per_task(int cpu)
2537 {
2538         struct rq *rq = cpu_rq(cpu);
2539         unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
2540
2541         if (nr_running)
2542                 return rq->load.weight / nr_running;
2543
2544         return 0;
2545 }
2546
2547
2548 static void task_waking_fair(struct task_struct *p)
2549 {
2550         struct sched_entity *se = &p->se;
2551         struct cfs_rq *cfs_rq = cfs_rq_of(se);
2552         u64 min_vruntime;
2553
2554 #ifndef CONFIG_64BIT
2555         u64 min_vruntime_copy;
2556
2557         do {
2558                 min_vruntime_copy = cfs_rq->min_vruntime_copy;
2559                 smp_rmb();
2560                 min_vruntime = cfs_rq->min_vruntime;
2561         } while (min_vruntime != min_vruntime_copy);
2562 #else
2563         min_vruntime = cfs_rq->min_vruntime;
2564 #endif
2565
2566         se->vruntime -= min_vruntime;
2567 }
2568
2569 #ifdef CONFIG_FAIR_GROUP_SCHED
2570 /*
2571  * effective_load() calculates the load change as seen from the root_task_group
2572  *
2573  * Adding load to a group doesn't make a group heavier, but can cause movement
2574  * of group shares between cpus. Assuming the shares were perfectly aligned one
2575  * can calculate the shift in shares.
2576  *
2577  * Calculate the effective load difference if @wl is added (subtracted) to @tg
2578  * on this @cpu and results in a total addition (subtraction) of @wg to the
2579  * total group weight.
2580  *
2581  * Given a runqueue weight distribution (rw_i) we can compute a shares
2582  * distribution (s_i) using:
2583  *
2584  *   s_i = rw_i / \Sum rw_j                                             (1)
2585  *
2586  * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
2587  * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
2588  * shares distribution (s_i):
2589  *
2590  *   rw_i = {   2,   4,   1,   0 }
2591  *   s_i  = { 2/7, 4/7, 1/7,   0 }
2592  *
2593  * As per wake_affine() we're interested in the load of two CPUs (the CPU the
2594  * task used to run on and the CPU the waker is running on), we need to
2595  * compute the effect of waking a task on either CPU and, in case of a sync
2596  * wakeup, compute the effect of the current task going to sleep.
2597  *
2598  * So for a change of @wl to the local @cpu with an overall group weight change
2599  * of @wl we can compute the new shares distribution (s'_i) using:
2600  *
2601  *   s'_i = (rw_i + @wl) / (@wg + \Sum rw_j)                            (2)
2602  *
2603  * Suppose we're interested in CPUs 0 and 1, and want to compute the load
2604  * differences in waking a task to CPU 0. The additional task changes the
2605  * weight and shares distributions like:
2606  *
2607  *   rw'_i = {   3,   4,   1,   0 }
2608  *   s'_i  = { 3/8, 4/8, 1/8,   0 }
2609  *
2610  * We can then compute the difference in effective weight by using:
2611  *
2612  *   dw_i = S * (s'_i - s_i)                                            (3)
2613  *
2614  * Where 'S' is the group weight as seen by its parent.
2615  *
2616  * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
2617  * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
2618  * 4/7) times the weight of the group.
2619  */
2620 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
2621 {
2622         struct sched_entity *se = tg->se[cpu];
2623
2624         if (!tg->parent)        /* the trivial, non-cgroup case */
2625                 return wl;
2626
2627         for_each_sched_entity(se) {
2628                 long w, W;
2629
2630                 tg = se->my_q->tg;
2631
2632                 /*
2633                  * W = @wg + \Sum rw_j
2634                  */
2635                 W = wg + calc_tg_weight(tg, se->my_q);
2636
2637                 /*
2638                  * w = rw_i + @wl
2639                  */
2640                 w = se->my_q->load.weight + wl;
2641
2642                 /*
2643                  * wl = S * s'_i; see (2)
2644                  */
2645                 if (W > 0 && w < W)
2646                         wl = (w * tg->shares) / W;
2647                 else
2648                         wl = tg->shares;
2649
2650                 /*
2651                  * Per the above, wl is the new se->load.weight value; since
2652                  * those are clipped to [MIN_SHARES, ...) do so now. See
2653                  * calc_cfs_shares().
2654                  */
2655                 if (wl < MIN_SHARES)
2656                         wl = MIN_SHARES;
2657
2658                 /*
2659                  * wl = dw_i = S * (s'_i - s_i); see (3)
2660                  */
2661                 wl -= se->load.weight;
2662
2663                 /*
2664                  * Recursively apply this logic to all parent groups to compute
2665                  * the final effective load change on the root group. Since
2666                  * only the @tg group gets extra weight, all parent groups can
2667                  * only redistribute existing shares. @wl is the shift in shares
2668                  * resulting from this level per the above.
2669                  */
2670                 wg = 0;
2671         }
2672
2673         return wl;
2674 }
2675 #else
2676
2677 static inline unsigned long effective_load(struct task_group *tg, int cpu,
2678                 unsigned long wl, unsigned long wg)
2679 {
2680         return wl;
2681 }
2682
2683 #endif
2684
2685 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
2686 {
2687         s64 this_load, load;
2688         int idx, this_cpu, prev_cpu;
2689         unsigned long tl_per_task;
2690         struct task_group *tg;
2691         unsigned long weight;
2692         int balanced;
2693
2694         idx       = sd->wake_idx;
2695         this_cpu  = smp_processor_id();
2696         prev_cpu  = task_cpu(p);
2697         load      = source_load(prev_cpu, idx);
2698         this_load = target_load(this_cpu, idx);
2699
2700         /*
2701          * If sync wakeup then subtract the (maximum possible)
2702          * effect of the currently running task from the load
2703          * of the current CPU:
2704          */
2705         if (sync) {
2706                 tg = task_group(current);
2707                 weight = current->se.load.weight;
2708
2709                 this_load += effective_load(tg, this_cpu, -weight, -weight);
2710                 load += effective_load(tg, prev_cpu, 0, -weight);
2711         }
2712
2713         tg = task_group(p);
2714         weight = p->se.load.weight;
2715
2716         /*
2717          * In low-load situations, where prev_cpu is idle and this_cpu is idle
2718          * due to the sync cause above having dropped this_load to 0, we'll
2719          * always have an imbalance, but there's really nothing you can do
2720          * about that, so that's good too.
2721          *
2722          * Otherwise check if either cpus are near enough in load to allow this
2723          * task to be woken on this_cpu.
2724          */
2725         if (this_load > 0) {
2726                 s64 this_eff_load, prev_eff_load;
2727
2728                 this_eff_load = 100;
2729                 this_eff_load *= power_of(prev_cpu);
2730                 this_eff_load *= this_load +
2731                         effective_load(tg, this_cpu, weight, weight);
2732
2733                 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
2734                 prev_eff_load *= power_of(this_cpu);
2735                 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
2736
2737                 balanced = this_eff_load <= prev_eff_load;
2738         } else
2739                 balanced = true;
2740
2741         /*
2742          * If the currently running task will sleep within
2743          * a reasonable amount of time then attract this newly
2744          * woken task:
2745          */
2746         if (sync && balanced)
2747                 return 1;
2748
2749         schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
2750         tl_per_task = cpu_avg_load_per_task(this_cpu);
2751
2752         if (balanced ||
2753             (this_load <= load &&
2754              this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
2755                 /*
2756                  * This domain has SD_WAKE_AFFINE and
2757                  * p is cache cold in this domain, and
2758                  * there is no bad imbalance.
2759                  */
2760                 schedstat_inc(sd, ttwu_move_affine);
2761                 schedstat_inc(p, se.statistics.nr_wakeups_affine);
2762
2763                 return 1;
2764         }
2765         return 0;
2766 }
2767
2768 /*
2769  * find_idlest_group finds and returns the least busy CPU group within the
2770  * domain.
2771  */
2772 static struct sched_group *
2773 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
2774                   int this_cpu, int load_idx)
2775 {
2776         struct sched_group *idlest = NULL, *group = sd->groups;
2777         unsigned long min_load = ULONG_MAX, this_load = 0;
2778         int imbalance = 100 + (sd->imbalance_pct-100)/2;
2779
2780         do {
2781                 unsigned long load, avg_load;
2782                 int local_group;
2783                 int i;
2784
2785                 /* Skip over this group if it has no CPUs allowed */
2786                 if (!cpumask_intersects(sched_group_cpus(group),
2787                                         tsk_cpus_allowed(p)))
2788                         continue;
2789
2790                 local_group = cpumask_test_cpu(this_cpu,
2791                                                sched_group_cpus(group));
2792
2793                 /* Tally up the load of all CPUs in the group */
2794                 avg_load = 0;
2795
2796                 for_each_cpu(i, sched_group_cpus(group)) {
2797                         /* Bias balancing toward cpus of our domain */
2798                         if (local_group)
2799                                 load = source_load(i, load_idx);
2800                         else
2801                                 load = target_load(i, load_idx);
2802
2803                         avg_load += load;
2804                 }
2805
2806                 /* Adjust by relative CPU power of the group */
2807                 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
2808
2809                 if (local_group) {
2810                         this_load = avg_load;
2811                 } else if (avg_load < min_load) {
2812                         min_load = avg_load;
2813                         idlest = group;
2814                 }
2815         } while (group = group->next, group != sd->groups);
2816
2817         if (!idlest || 100*this_load < imbalance*min_load)
2818                 return NULL;
2819         return idlest;
2820 }
2821
2822 /*
2823  * find_idlest_cpu - find the idlest cpu among the cpus in group.
2824  */
2825 static int
2826 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2827 {
2828         unsigned long load, min_load = ULONG_MAX;
2829         int idlest = -1;
2830         int i;
2831
2832         /* Traverse only the allowed CPUs */
2833         for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
2834                 load = weighted_cpuload(i);
2835
2836                 if (load < min_load || (load == min_load && i == this_cpu)) {
2837                         min_load = load;
2838                         idlest = i;
2839                 }
2840         }
2841
2842         return idlest;
2843 }
2844
2845 /*
2846  * Try and locate an idle CPU in the sched_domain.
2847  */
2848 static int select_idle_sibling(struct task_struct *p, int target)
2849 {
2850         int cpu = smp_processor_id();
2851         int prev_cpu = task_cpu(p);
2852         struct sched_domain *sd;
2853         struct sched_group *sg;
2854         int i;
2855
2856         /*
2857          * If the task is going to be woken-up on this cpu and if it is
2858          * already idle, then it is the right target.
2859          */
2860         if (target == cpu && idle_cpu(cpu))
2861                 return cpu;
2862
2863         /*
2864          * If the task is going to be woken-up on the cpu where it previously
2865          * ran and if it is currently idle, then it the right target.
2866          */
2867         if (target == prev_cpu && idle_cpu(prev_cpu))
2868                 return prev_cpu;
2869
2870         /*
2871          * Otherwise, iterate the domains and find an elegible idle cpu.
2872          */
2873         sd = rcu_dereference(per_cpu(sd_llc, target));
2874         for_each_lower_domain(sd) {
2875                 sg = sd->groups;
2876                 do {
2877                         if (!cpumask_intersects(sched_group_cpus(sg),
2878                                                 tsk_cpus_allowed(p)))
2879                                 goto next;
2880
2881                         for_each_cpu(i, sched_group_cpus(sg)) {
2882                                 if (!idle_cpu(i))
2883                                         goto next;
2884                         }
2885
2886                         target = cpumask_first_and(sched_group_cpus(sg),
2887                                         tsk_cpus_allowed(p));
2888                         goto done;
2889 next:
2890                         sg = sg->next;
2891                 } while (sg != sd->groups);
2892         }
2893 done:
2894         return target;
2895 }
2896
2897 #ifdef CONFIG_SCHED_NUMA
2898 static inline bool pick_numa_rand(int n)
2899 {
2900         return !(get_random_int() % n);
2901 }
2902
2903 /*
2904  * Pick a random elegible CPU in the target node, hopefully faster
2905  * than doing a least-loaded scan.
2906  */
2907 static int numa_select_node_cpu(struct task_struct *p, int node)
2908 {
2909         int weight = cpumask_weight(cpumask_of_node(node));
2910         int i, cpu = -1;
2911
2912         for_each_cpu_and(i, cpumask_of_node(node), tsk_cpus_allowed(p)) {
2913                 if (cpu < 0 || pick_numa_rand(weight))
2914                         cpu = i;
2915         }
2916
2917         return cpu;
2918 }
2919 #else
2920 static int numa_select_node_cpu(struct task_struct *p, int node)
2921 {
2922         return -1;
2923 }
2924 #endif /* CONFIG_SCHED_NUMA */
2925
2926 /*
2927  * sched_balance_self: balance the current task (running on cpu) in domains
2928  * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2929  * SD_BALANCE_EXEC.
2930  *
2931  * Balance, ie. select the least loaded group.
2932  *
2933  * Returns the target CPU number, or the same CPU if no balancing is needed.
2934  *
2935  * preempt must be disabled.
2936  */
2937 static int
2938 select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
2939 {
2940         struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
2941         int cpu = smp_processor_id();
2942         int prev_cpu = task_cpu(p);
2943         int new_cpu = cpu;
2944         int want_affine = 0;
2945         int sync = wake_flags & WF_SYNC;
2946         int node = tsk_home_node(p);
2947
2948         if (p->nr_cpus_allowed == 1)
2949                 return prev_cpu;
2950
2951         if (sd_flag & SD_BALANCE_WAKE) {
2952                 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
2953                         want_affine = 1;
2954                 new_cpu = prev_cpu;
2955         }
2956
2957         rcu_read_lock();
2958         if (sched_feat_numa(NUMA_TTWU_BIAS) && node != -1) {
2959                 /*
2960                  * For fork,exec find the idlest cpu in the home-node.
2961                  */
2962                 if (sd_flag & (SD_BALANCE_FORK|SD_BALANCE_EXEC)) {
2963                         int node_cpu = numa_select_node_cpu(p, node);
2964                         if (node_cpu < 0)
2965                                 goto find_sd;
2966
2967                         new_cpu = cpu = node_cpu;
2968                         sd = per_cpu(sd_node, cpu);
2969                         goto pick_idlest;
2970                 }
2971
2972                 /*
2973                  * For wake, pretend we were running in the home-node.
2974                  */
2975                 if (cpu_to_node(prev_cpu) != node) {
2976                         int node_cpu = numa_select_node_cpu(p, node);
2977                         if (node_cpu < 0)
2978                                 goto find_sd;
2979
2980                         if (sched_feat_numa(NUMA_TTWU_TO))
2981                                 cpu = node_cpu;
2982                         else
2983                                 prev_cpu = node_cpu;
2984                 }
2985         }
2986
2987 find_sd:
2988         for_each_domain(cpu, tmp) {
2989                 if (!(tmp->flags & SD_LOAD_BALANCE))
2990                         continue;
2991
2992                 /*
2993                  * If both cpu and prev_cpu are part of this domain,
2994                  * cpu is a valid SD_WAKE_AFFINE target.
2995                  */
2996                 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
2997                     cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
2998                         affine_sd = tmp;
2999                         break;
3000                 }
3001
3002                 if (tmp->flags & sd_flag)
3003                         sd = tmp;
3004         }
3005
3006         if (affine_sd) {
3007                 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
3008                         prev_cpu = cpu;
3009
3010                 new_cpu = select_idle_sibling(p, prev_cpu);
3011                 goto unlock;
3012         }
3013
3014 pick_idlest:
3015         while (sd) {
3016                 int load_idx = sd->forkexec_idx;
3017                 struct sched_group *group;
3018                 int weight;
3019
3020                 if (!(sd->flags & sd_flag)) {
3021                         sd = sd->child;
3022                         continue;
3023                 }
3024
3025                 if (sd_flag & SD_BALANCE_WAKE)
3026                         load_idx = sd->wake_idx;
3027
3028                 group = find_idlest_group(sd, p, cpu, load_idx);
3029                 if (!group) {
3030                         sd = sd->child;
3031                         continue;
3032                 }
3033
3034                 new_cpu = find_idlest_cpu(group, p, cpu);
3035                 if (new_cpu == -1 || new_cpu == cpu) {
3036                         /* Now try balancing at a lower domain level of cpu */
3037                         sd = sd->child;
3038                         continue;
3039                 }
3040
3041                 /* Now try balancing at a lower domain level of new_cpu */
3042                 cpu = new_cpu;
3043                 weight = sd->span_weight;
3044                 sd = NULL;
3045                 for_each_domain(cpu, tmp) {
3046                         if (weight <= tmp->span_weight)
3047                                 break;
3048                         if (tmp->flags & sd_flag)
3049                                 sd = tmp;
3050                 }
3051                 /* while loop will break here if sd == NULL */
3052         }
3053 unlock:
3054         rcu_read_unlock();
3055
3056         return new_cpu;
3057 }
3058 #endif /* CONFIG_SMP */
3059
3060 static unsigned long
3061 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
3062 {
3063         unsigned long gran = sysctl_sched_wakeup_granularity;
3064
3065         /*
3066          * Since its curr running now, convert the gran from real-time
3067          * to virtual-time in his units.
3068          *
3069          * By using 'se' instead of 'curr' we penalize light tasks, so
3070          * they get preempted easier. That is, if 'se' < 'curr' then
3071          * the resulting gran will be larger, therefore penalizing the
3072          * lighter, if otoh 'se' > 'curr' then the resulting gran will
3073          * be smaller, again penalizing the lighter task.
3074          *
3075          * This is especially important for buddies when the leftmost
3076          * task is higher priority than the buddy.
3077          */
3078         return calc_delta_fair(gran, se);
3079 }
3080
3081 /*
3082  * Should 'se' preempt 'curr'.
3083  *
3084  *             |s1
3085  *        |s2
3086  *   |s3
3087  *         g
3088  *      |<--->|c
3089  *
3090  *  w(c, s1) = -1
3091  *  w(c, s2) =  0
3092  *  w(c, s3) =  1
3093  *
3094  */
3095 static int
3096 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
3097 {
3098         s64 gran, vdiff = curr->vruntime - se->vruntime;
3099
3100         if (vdiff <= 0)
3101                 return -1;
3102
3103         gran = wakeup_gran(curr, se);
3104         if (vdiff > gran)
3105                 return 1;
3106
3107         return 0;
3108 }
3109
3110 static void set_last_buddy(struct sched_entity *se)
3111 {
3112         if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3113                 return;
3114
3115         for_each_sched_entity(se)
3116                 cfs_rq_of(se)->last = se;
3117 }
3118
3119 static void set_next_buddy(struct sched_entity *se)
3120 {
3121         if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3122                 return;
3123
3124         for_each_sched_entity(se)
3125                 cfs_rq_of(se)->next = se;
3126 }
3127
3128 static void set_skip_buddy(struct sched_entity *se)
3129 {
3130         for_each_sched_entity(se)
3131                 cfs_rq_of(se)->skip = se;
3132 }
3133
3134 /*
3135  * Preempt the current task with a newly woken task if needed:
3136  */
3137 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
3138 {
3139         struct task_struct *curr = rq->curr;
3140         struct sched_entity *se = &curr->se, *pse = &p->se;
3141         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3142         int scale = cfs_rq->nr_running >= sched_nr_latency;
3143         int next_buddy_marked = 0;
3144
3145         if (unlikely(se == pse))
3146                 return;
3147
3148         /*
3149          * This is possible from callers such as move_task(), in which we
3150          * unconditionally check_prempt_curr() after an enqueue (which may have
3151          * lead to a throttle).  This both saves work and prevents false
3152          * next-buddy nomination below.
3153          */
3154         if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
3155                 return;
3156
3157         if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3158                 set_next_buddy(pse);
3159                 next_buddy_marked = 1;
3160         }
3161
3162         /*
3163          * We can come here with TIF_NEED_RESCHED already set from new task
3164          * wake up path.
3165          *
3166          * Note: this also catches the edge-case of curr being in a throttled
3167          * group (e.g. via set_curr_task), since update_curr() (in the
3168          * enqueue of curr) will have resulted in resched being set.  This
3169          * prevents us from potentially nominating it as a false LAST_BUDDY
3170          * below.
3171          */
3172         if (test_tsk_need_resched(curr))
3173                 return;
3174
3175         /* Idle tasks are by definition preempted by non-idle tasks. */
3176         if (unlikely(curr->policy == SCHED_IDLE) &&
3177             likely(p->policy != SCHED_IDLE))
3178                 goto preempt;
3179
3180         /*
3181          * Batch and idle tasks do not preempt non-idle tasks (their preemption
3182          * is driven by the tick):
3183          */
3184         if (unlikely(p->policy != SCHED_NORMAL))
3185                 return;
3186
3187         find_matching_se(&se, &pse);
3188         update_curr(cfs_rq_of(se));
3189         BUG_ON(!pse);
3190         if (wakeup_preempt_entity(se, pse) == 1) {
3191                 /*
3192                  * Bias pick_next to pick the sched entity that is
3193                  * triggering this preemption.
3194                  */
3195                 if (!next_buddy_marked)
3196                         set_next_buddy(pse);
3197                 goto preempt;
3198         }
3199
3200         return;
3201
3202 preempt:
3203         resched_task(curr);
3204         /*
3205          * Only set the backward buddy when the current task is still
3206          * on the rq. This can happen when a wakeup gets interleaved
3207          * with schedule on the ->pre_schedule() or idle_balance()
3208          * point, either of which can * drop the rq lock.
3209          *
3210          * Also, during early boot the idle thread is in the fair class,
3211          * for obvious reasons its a bad idea to schedule back to it.
3212          */
3213         if (unlikely(!se->on_rq || curr == rq->idle))
3214                 return;
3215
3216         if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
3217                 set_last_buddy(se);
3218 }
3219
3220 static struct task_struct *pick_next_task_fair(struct rq *rq)
3221 {
3222         struct task_struct *p;
3223         struct cfs_rq *cfs_rq = &rq->cfs;
3224         struct sched_entity *se;
3225
3226         if (!cfs_rq->nr_running)
3227                 return NULL;
3228
3229         do {
3230                 se = pick_next_entity(cfs_rq);
3231                 set_next_entity(cfs_rq, se);
3232                 cfs_rq = group_cfs_rq(se);
3233         } while (cfs_rq);
3234
3235         p = task_of(se);
3236         if (hrtick_enabled(rq))
3237                 hrtick_start_fair(rq, p);
3238
3239         return p;
3240 }
3241
3242 /*
3243  * Account for a descheduled task:
3244  */
3245 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
3246 {
3247         struct sched_entity *se = &prev->se;
3248         struct cfs_rq *cfs_rq;
3249
3250         for_each_sched_entity(se) {
3251                 cfs_rq = cfs_rq_of(se);
3252                 put_prev_entity(cfs_rq, se);
3253         }
3254 }
3255
3256 /*
3257  * sched_yield() is very simple
3258  *
3259  * The magic of dealing with the ->skip buddy is in pick_next_entity.
3260  */
3261 static void yield_task_fair(struct rq *rq)
3262 {
3263         struct task_struct *curr = rq->curr;
3264         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3265         struct sched_entity *se = &curr->se;
3266
3267         /*
3268          * Are we the only task in the tree?
3269          */
3270         if (unlikely(rq->nr_running == 1))
3271                 return;
3272
3273         clear_buddies(cfs_rq, se);
3274
3275         if (curr->policy != SCHED_BATCH) {
3276                 update_rq_clock(rq);
3277                 /*
3278                  * Update run-time statistics of the 'current'.
3279                  */
3280                 update_curr(cfs_rq);
3281                 /*
3282                  * Tell update_rq_clock() that we've just updated,
3283                  * so we don't do microscopic update in schedule()
3284                  * and double the fastpath cost.
3285                  */
3286                  rq->skip_clock_update = 1;
3287         }
3288
3289         set_skip_buddy(se);
3290 }
3291
3292 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
3293 {
3294         struct sched_entity *se = &p->se;
3295
3296         /* throttled hierarchies are not runnable */
3297         if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
3298                 return false;
3299
3300         /* Tell the scheduler that we'd really like pse to run next. */
3301         set_next_buddy(se);
3302
3303         yield_task_fair(rq);
3304
3305         return true;
3306 }
3307
3308 #ifdef CONFIG_SMP
3309 /**************************************************
3310  * Fair scheduling class load-balancing methods:
3311  */
3312
3313 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
3314
3315 #define LBF_ALL_PINNED  0x01
3316 #define LBF_NEED_BREAK  0x02
3317 #define LBF_SOME_PINNED 0x04
3318
3319 struct lb_env {
3320         struct sched_domain     *sd;
3321
3322         struct rq               *src_rq;
3323         int                     src_cpu;
3324
3325         int                     dst_cpu;
3326         struct rq               *dst_rq;
3327
3328         struct cpumask          *dst_grpmask;
3329         int                     new_dst_cpu;
3330         enum cpu_idle_type      idle;
3331         long                    imbalance;
3332         /* The set of CPUs under consideration for load-balancing */
3333         struct cpumask          *cpus;
3334
3335         unsigned int            flags;
3336
3337         struct list_head        *tasks;
3338
3339         unsigned int            loop;
3340         unsigned int            loop_break;
3341         unsigned int            loop_max;
3342
3343         struct rq *             (*find_busiest_queue)(struct lb_env *,
3344                                                       struct sched_group *);
3345 };
3346
3347 /*
3348  * move_task - move a task from one runqueue to another runqueue.
3349  * Both runqueues must be locked.
3350  */
3351 static void move_task(struct task_struct *p, struct lb_env *env)
3352 {
3353         deactivate_task(env->src_rq, p, 0);
3354         set_task_cpu(p, env->dst_cpu);
3355         activate_task(env->dst_rq, p, 0);
3356         check_preempt_curr(env->dst_rq, p, 0);
3357 }
3358
3359 static int task_numa_hot(struct task_struct *p, struct lb_env *env)
3360 {
3361         int from_dist, to_dist;
3362         int node = tsk_home_node(p);
3363
3364         if (!sched_feat_numa(NUMA_HOT) || node == -1)
3365                 return 0; /* no node preference */
3366
3367         from_dist = node_distance(cpu_to_node(env->src_cpu), node);
3368         to_dist = node_distance(cpu_to_node(env->dst_cpu), node);
3369
3370         if (to_dist < from_dist)
3371                 return 0; /* getting closer is ok */
3372
3373         return 1; /* stick to where we are */
3374 }
3375
3376 /*
3377  * Is this task likely cache-hot:
3378  */
3379 static int
3380 task_hot(struct task_struct *p, struct lb_env *env)
3381 {
3382         s64 delta;
3383
3384         if (p->sched_class != &fair_sched_class)
3385                 return 0;
3386
3387         if (unlikely(p->policy == SCHED_IDLE))
3388                 return 0;
3389
3390         /*
3391          * Buddy candidates are cache hot:
3392          */
3393         if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
3394                         (&p->se == cfs_rq_of(&p->se)->next ||
3395                          &p->se == cfs_rq_of(&p->se)->last))
3396                 return 1;
3397
3398         if (sysctl_sched_migration_cost == -1)
3399                 return 1;
3400         if (sysctl_sched_migration_cost == 0)
3401                 return 0;
3402
3403         delta = env->src_rq->clock_task - p->se.exec_start;
3404
3405         return delta < (s64)sysctl_sched_migration_cost;
3406 }
3407
3408 /*
3409  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3410  */
3411 static
3412 int can_migrate_task(struct task_struct *p, struct lb_env *env)
3413 {
3414         int tsk_cache_hot = 0;
3415         /*
3416          * We do not migrate tasks that are:
3417          * 1) running (obviously), or
3418          * 2) cannot be migrated to this CPU due to cpus_allowed, or
3419          * 3) are cache-hot on their current CPU.
3420          */
3421         if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
3422                 int new_dst_cpu;
3423
3424                 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
3425
3426                 /*
3427                  * Remember if this task can be migrated to any other cpu in
3428                  * our sched_group. We may want to revisit it if we couldn't
3429                  * meet load balance goals by pulling other tasks on src_cpu.
3430                  *
3431                  * Also avoid computing new_dst_cpu if we have already computed
3432                  * one in current iteration.
3433                  */
3434                 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
3435                         return 0;
3436
3437                 new_dst_cpu = cpumask_first_and(env->dst_grpmask,
3438                                                 tsk_cpus_allowed(p));
3439                 if (new_dst_cpu < nr_cpu_ids) {
3440                         env->flags |= LBF_SOME_PINNED;
3441                         env->new_dst_cpu = new_dst_cpu;
3442                 }
3443                 return 0;
3444         }
3445
3446         /* Record that we found atleast one task that could run on dst_cpu */
3447         env->flags &= ~LBF_ALL_PINNED;
3448
3449         if (task_running(env->src_rq, p)) {
3450                 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
3451                 return 0;
3452         }
3453
3454         /*
3455          * Aggressive migration if:
3456          * 1) task is cache cold, or
3457          * 2) too many balance attempts have failed.
3458          */
3459
3460         tsk_cache_hot = task_hot(p, env);
3461         if (env->idle == CPU_NOT_IDLE)
3462                 tsk_cache_hot |= task_numa_hot(p, env);
3463         if (!tsk_cache_hot ||
3464                 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
3465 #ifdef CONFIG_SCHEDSTATS
3466                 if (tsk_cache_hot) {
3467                         schedstat_inc(env->sd, lb_hot_gained[env->idle]);
3468                         schedstat_inc(p, se.statistics.nr_forced_migrations);
3469                 }
3470 #endif
3471                 return 1;
3472         }
3473
3474         if (tsk_cache_hot) {
3475                 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
3476                 return 0;
3477         }
3478         return 1;
3479 }
3480
3481 /*
3482  * move_one_task tries to move exactly one task from busiest to this_rq, as
3483  * part of active balancing operations within "domain".
3484  * Returns 1 if successful and 0 otherwise.
3485  *
3486  * Called with both runqueues locked.
3487  */
3488 static int __move_one_task(struct lb_env *env)
3489 {
3490         struct task_struct *p, *n;
3491
3492         list_for_each_entry_safe(p, n, env->tasks, se.group_node) {
3493                 if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
3494                         continue;
3495
3496                 if (!can_migrate_task(p, env))
3497                         continue;
3498
3499                 move_task(p, env);
3500                 /*
3501                  * Right now, this is only the second place move_task()
3502                  * is called, so we can safely collect move_task()
3503                  * stats here rather than inside move_task().
3504                  */
3505                 schedstat_inc(env->sd, lb_gained[env->idle]);
3506                 return 1;
3507         }
3508         return 0;
3509 }
3510
3511 static int move_one_task(struct lb_env *env)
3512 {
3513         if (sched_feat_numa(NUMA_PULL)) {
3514                 env->tasks = offnode_tasks(env->src_rq);
3515                 if (__move_one_task(env))
3516                         return 1;
3517         }
3518
3519         env->tasks = &env->src_rq->cfs_tasks;
3520         if (__move_one_task(env))
3521                 return 1;
3522
3523         return 0;
3524 }
3525
3526 static const unsigned int sched_nr_migrate_break = 32;
3527
3528 /*
3529  * move_tasks tries to move up to imbalance weighted load from busiest to
3530  * this_rq, as part of a balancing operation within domain "sd".
3531  * Returns 1 if successful and 0 otherwise.
3532  *
3533  * Called with both runqueues locked.
3534  */
3535 static int move_tasks(struct lb_env *env)
3536 {
3537         struct task_struct *p;
3538         unsigned long load;
3539         int pulled = 0;
3540
3541         if (env->imbalance <= 0)
3542                 return 0;
3543
3544 again:
3545         while (!list_empty(env->tasks)) {
3546                 p = list_first_entry(env->tasks, struct task_struct, se.group_node);
3547
3548                 env->loop++;
3549                 /* We've more or less seen every task there is, call it quits */
3550                 if (env->loop > env->loop_max)
3551                         break;
3552
3553                 /* take a breather every nr_migrate tasks */
3554                 if (env->loop > env->loop_break) {
3555                         env->loop_break += sched_nr_migrate_break;
3556                         env->flags |= LBF_NEED_BREAK;
3557                         goto out;
3558                 }
3559
3560                 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
3561                         goto next;
3562
3563                 load = task_h_load(p);
3564
3565                 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
3566                         goto next;
3567
3568                 if ((load / 2) > env->imbalance)
3569                         goto next;
3570
3571                 if (!can_migrate_task(p, env))
3572                         goto next;
3573
3574                 move_task(p, env);
3575                 pulled++;
3576                 env->imbalance -= load;
3577
3578 #ifdef CONFIG_PREEMPT
3579                 /*
3580                  * NEWIDLE balancing is a source of latency, so preemptible
3581                  * kernels will stop after the first task is pulled to minimize
3582                  * the critical section.
3583                  */
3584                 if (env->idle == CPU_NEWLY_IDLE)
3585                         goto out;
3586 #endif
3587
3588                 /*
3589                  * We only want to steal up to the prescribed amount of
3590                  * weighted load.
3591                  */
3592                 if (env->imbalance <= 0)
3593                         goto out;
3594
3595                 continue;
3596 next:
3597                 list_move_tail(&p->se.group_node, env->tasks);
3598         }
3599
3600         if (env->tasks == offnode_tasks(env->src_rq)) {
3601                 env->tasks = &env->src_rq->cfs_tasks;
3602                 env->loop = 0;
3603                 goto again;
3604         }
3605
3606 out:
3607         /*
3608          * Right now, this is one of only two places move_task() is called,
3609          * so we can safely collect move_task() stats here rather than
3610          * inside move_task().
3611          */
3612         schedstat_add(env->sd, lb_gained[env->idle], pulled);
3613
3614         return pulled;
3615 }
3616
3617 #ifdef CONFIG_FAIR_GROUP_SCHED
3618 /*
3619  * update tg->load_weight by folding this cpu's load_avg
3620  */
3621 static int update_shares_cpu(struct task_group *tg, int cpu)
3622 {
3623         struct cfs_rq *cfs_rq;
3624         unsigned long flags;
3625         struct rq *rq;
3626
3627         if (!tg->se[cpu])
3628                 return 0;
3629
3630         rq = cpu_rq(cpu);
3631         cfs_rq = tg->cfs_rq[cpu];
3632
3633         raw_spin_lock_irqsave(&rq->lock, flags);
3634
3635         update_rq_clock(rq);
3636         update_cfs_load(cfs_rq, 1);
3637
3638         /*
3639          * We need to update shares after updating tg->load_weight in
3640          * order to adjust the weight of groups with long running tasks.
3641          */
3642         update_cfs_shares(cfs_rq);
3643
3644         raw_spin_unlock_irqrestore(&rq->lock, flags);
3645
3646         return 0;
3647 }
3648
3649 static void update_shares(int cpu)
3650 {
3651         struct cfs_rq *cfs_rq;
3652         struct rq *rq = cpu_rq(cpu);
3653
3654         rcu_read_lock();
3655         /*
3656          * Iterates the task_group tree in a bottom up fashion, see
3657          * list_add_leaf_cfs_rq() for details.
3658          */
3659         for_each_leaf_cfs_rq(rq, cfs_rq) {
3660                 /* throttled entities do not contribute to load */
3661                 if (throttled_hierarchy(cfs_rq))
3662                         continue;
3663
3664                 update_shares_cpu(cfs_rq->tg, cpu);
3665         }
3666         rcu_read_unlock();
3667 }
3668
3669 /*
3670  * Compute the cpu's hierarchical load factor for each task group.
3671  * This needs to be done in a top-down fashion because the load of a child
3672  * group is a fraction of its parents load.
3673  */
3674 static int tg_load_down(struct task_group *tg, void *data)
3675 {
3676         unsigned long load;
3677         long cpu = (long)data;
3678
3679         if (!tg->parent) {
3680                 load = cpu_rq(cpu)->load.weight;
3681         } else {
3682                 load = tg->parent->cfs_rq[cpu]->h_load;
3683                 load *= tg->se[cpu]->load.weight;
3684                 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
3685         }
3686
3687         tg->cfs_rq[cpu]->h_load = load;
3688
3689         return 0;
3690 }
3691
3692 static void update_h_load(long cpu)
3693 {
3694         struct rq *rq = cpu_rq(cpu);
3695         unsigned long now = jiffies;
3696
3697         if (rq->h_load_throttle == now)
3698                 return;
3699
3700         rq->h_load_throttle = now;
3701
3702         rcu_read_lock();
3703         walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
3704         rcu_read_unlock();
3705 }
3706
3707 static unsigned long task_h_load(struct task_struct *p)
3708 {
3709         struct cfs_rq *cfs_rq = task_cfs_rq(p);
3710         unsigned long load;
3711
3712         load = p->se.load.weight;
3713         load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
3714
3715         return load;
3716 }
3717 #else
3718 static inline void update_shares(int cpu)
3719 {
3720 }
3721
3722 static inline void update_h_load(long cpu)
3723 {
3724 }
3725
3726 static unsigned long task_h_load(struct task_struct *p)
3727 {
3728         return p->se.load.weight;
3729 }
3730 #endif
3731
3732 /********** Helpers for find_busiest_group ************************/
3733 /*
3734  * sd_lb_stats - Structure to store the statistics of a sched_domain
3735  *              during load balancing.
3736  */
3737 struct sd_lb_stats {
3738         struct sched_group *busiest; /* Busiest group in this sd */
3739         struct sched_group *this;  /* Local group in this sd */
3740         unsigned long total_load;  /* Total load of all groups in sd */
3741         unsigned long total_pwr;   /*   Total power of all groups in sd */
3742         unsigned long avg_load;    /* Average load across all groups in sd */
3743
3744         /** Statistics of this group */
3745         unsigned long this_load;
3746         unsigned long this_load_per_task;
3747         unsigned long this_nr_running;
3748         unsigned long this_has_capacity;
3749         unsigned int  this_idle_cpus;
3750
3751         /* Statistics of the busiest group */
3752         unsigned int  busiest_idle_cpus;
3753         unsigned long max_load;
3754         unsigned long busiest_load_per_task;
3755         unsigned long busiest_nr_running;
3756         unsigned long busiest_group_capacity;
3757         unsigned long busiest_has_capacity;
3758         unsigned int  busiest_group_weight;
3759
3760         int group_imb; /* Is there imbalance in this sd */
3761 #ifdef CONFIG_SCHED_NUMA
3762         struct sched_group *numa_group; /* group which has offnode_tasks */
3763         unsigned long numa_group_weight;
3764         unsigned long numa_group_running;
3765 #endif
3766 };
3767
3768 /*
3769  * sg_lb_stats - stats of a sched_group required for load_balancing
3770  */
3771 struct sg_lb_stats {
3772         unsigned long avg_load; /*Avg load across the CPUs of the group */
3773         unsigned long group_load; /* Total load over the CPUs of the group */
3774         unsigned long sum_nr_running; /* Nr tasks running in the group */
3775         unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3776         unsigned long group_capacity;
3777         unsigned long idle_cpus;
3778         unsigned long group_weight;
3779         int group_imb; /* Is there an imbalance in the group ? */
3780         int group_has_capacity; /* Is there extra capacity in the group? */
3781 #ifdef CONFIG_SCHED_NUMA
3782         unsigned long numa_weight;
3783         unsigned long numa_running;
3784 #endif
3785 };
3786
3787 /**
3788  * get_sd_load_idx - Obtain the load index for a given sched domain.
3789  * @sd: The sched_domain whose load_idx is to be obtained.
3790  * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3791  */
3792 static inline int get_sd_load_idx(struct sched_domain *sd,
3793                                         enum cpu_idle_type idle)
3794 {
3795         int load_idx;
3796
3797         switch (idle) {
3798         case CPU_NOT_IDLE:
3799                 load_idx = sd->busy_idx;
3800                 break;
3801
3802         case CPU_NEWLY_IDLE:
3803                 load_idx = sd->newidle_idx;
3804                 break;
3805         default:
3806                 load_idx = sd->idle_idx;
3807                 break;
3808         }
3809
3810         return load_idx;
3811 }
3812
3813 #ifdef CONFIG_SCHED_NUMA
3814 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3815 {
3816         sgs->numa_weight += rq->offnode_weight;
3817         sgs->numa_running += rq->offnode_running;
3818 }
3819
3820 /*
3821  * Since the offnode lists are indiscriminate (they contain tasks for all other
3822  * nodes) it is impossible to say if there's any task on there that wants to
3823  * move towards the pulling cpu. Therefore select a random offnode list to pull
3824  * from such that eventually we'll try them all.
3825  *
3826  * Select a random group that has offnode tasks as sds->numa_group
3827  */
3828 static inline void update_sd_numa_stats(struct sched_domain *sd,
3829                 struct sched_group *group, struct sd_lb_stats *sds,
3830                 int local_group, struct sg_lb_stats *sgs)
3831 {
3832         if (!(sd->flags & SD_NUMA))
3833                 return;
3834
3835         if (local_group)
3836                 return;
3837
3838         if (!sgs->numa_running)
3839                 return;
3840
3841         if (!sds->numa_group || pick_numa_rand(sd->span_weight / group->group_weight)) {
3842                 sds->numa_group = group;
3843                 sds->numa_group_weight = sgs->numa_weight;
3844                 sds->numa_group_running = sgs->numa_running;
3845         }
3846 }
3847
3848 /*
3849  * Pick a random queue from the group that has offnode tasks.
3850  */
3851 static struct rq *find_busiest_numa_queue(struct lb_env *env,
3852                                           struct sched_group *group)
3853 {
3854         struct rq *busiest = NULL, *rq;
3855         int cpu;
3856
3857         for_each_cpu_and(cpu, sched_group_cpus(group), env->cpus) {
3858                 rq = cpu_rq(cpu);
3859                 if (!rq->offnode_running)
3860                         continue;
3861                 if (!busiest || pick_numa_rand(group->group_weight))
3862                         busiest = rq;
3863         }
3864
3865         return busiest;
3866 }
3867
3868 /*
3869  * Called in case of no other imbalance, if there is a queue running offnode
3870  * tasksk we'll say we're imbalanced anyway to nudge these tasks towards their
3871  * proper node.
3872  */
3873 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3874 {
3875         if (!sched_feat(NUMA_PULL_BIAS))
3876                 return 0;
3877
3878         if (!sds->numa_group)
3879                 return 0;
3880
3881         env->imbalance = sds->numa_group_weight / sds->numa_group_running;
3882         sds->busiest = sds->numa_group;
3883         env->find_busiest_queue = find_busiest_numa_queue;
3884         return 1;
3885 }
3886
3887 static inline bool need_active_numa_balance(struct lb_env *env)
3888 {
3889         return env->find_busiest_queue == find_busiest_numa_queue &&
3890                         env->src_rq->offnode_running == 1 &&
3891                         env->src_rq->nr_running == 1;
3892 }
3893
3894 #else /* CONFIG_SCHED_NUMA */
3895
3896 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3897 {
3898 }
3899
3900 static inline void update_sd_numa_stats(struct sched_domain *sd,
3901                 struct sched_group *group, struct sd_lb_stats *sds,
3902                 int local_group, struct sg_lb_stats *sgs)
3903 {
3904 }
3905
3906 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3907 {
3908         return 0;
3909 }
3910
3911 static inline bool need_active_numa_balance(struct lb_env *env)
3912 {
3913         return false;
3914 }
3915 #endif /* CONFIG_SCHED_NUMA */
3916
3917 unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3918 {
3919         return SCHED_POWER_SCALE;
3920 }
3921
3922 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3923 {
3924         return default_scale_freq_power(sd, cpu);
3925 }
3926
3927 unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3928 {
3929         unsigned long weight = sd->span_weight;
3930         unsigned long smt_gain = sd->smt_gain;
3931
3932         smt_gain /= weight;
3933
3934         return smt_gain;
3935 }
3936
3937 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3938 {
3939         return default_scale_smt_power(sd, cpu);
3940 }
3941
3942 unsigned long scale_rt_power(int cpu)
3943 {
3944         struct rq *rq = cpu_rq(cpu);
3945         u64 total, available, age_stamp, avg;
3946
3947         /*
3948          * Since we're reading these variables without serialization make sure
3949          * we read them once before doing sanity checks on them.
3950          */
3951         age_stamp = ACCESS_ONCE(rq->age_stamp);
3952         avg = ACCESS_ONCE(rq->rt_avg);
3953
3954         total = sched_avg_period() + (rq->clock - age_stamp);
3955
3956         if (unlikely(total < avg)) {
3957                 /* Ensures that power won't end up being negative */
3958                 available = 0;
3959         } else {
3960                 available = total - avg;
3961         }
3962
3963         if (unlikely((s64)total < SCHED_POWER_SCALE))
3964                 total = SCHED_POWER_SCALE;
3965
3966         total >>= SCHED_POWER_SHIFT;
3967
3968         return div_u64(available, total);
3969 }
3970
3971 static void update_cpu_power(struct sched_domain *sd, int cpu)
3972 {
3973         unsigned long weight = sd->span_weight;
3974         unsigned long power = SCHED_POWER_SCALE;
3975         struct sched_group *sdg = sd->groups;
3976
3977         if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
3978                 if (sched_feat(ARCH_POWER))
3979                         power *= arch_scale_smt_power(sd, cpu);
3980                 else
3981                         power *= default_scale_smt_power(sd, cpu);
3982
3983                 power >>= SCHED_POWER_SHIFT;
3984         }
3985
3986         sdg->sgp->power_orig = power;
3987
3988         if (sched_feat(ARCH_POWER))
3989                 power *= arch_scale_freq_power(sd, cpu);
3990         else
3991                 power *= default_scale_freq_power(sd, cpu);
3992
3993         power >>= SCHED_POWER_SHIFT;
3994
3995         power *= scale_rt_power(cpu);
3996         power >>= SCHED_POWER_SHIFT;
3997
3998         if (!power)
3999                 power = 1;
4000
4001         cpu_rq(cpu)->cpu_power = power;
4002         sdg->sgp->power = power;
4003 }
4004
4005 void update_group_power(struct sched_domain *sd, int cpu)
4006 {
4007         struct sched_domain *child = sd->child;
4008         struct sched_group *group, *sdg = sd->groups;
4009         unsigned long power;
4010         unsigned long interval;
4011
4012         interval = msecs_to_jiffies(sd->balance_interval);
4013         interval = clamp(interval, 1UL, max_load_balance_interval);
4014         sdg->sgp->next_update = jiffies + interval;
4015
4016         if (!child) {
4017                 update_cpu_power(sd, cpu);
4018                 return;
4019         }
4020
4021         power = 0;
4022
4023         if (child->flags & SD_OVERLAP) {
4024                 /*
4025                  * SD_OVERLAP domains cannot assume that child groups
4026                  * span the current group.
4027                  */
4028
4029                 for_each_cpu(cpu, sched_group_cpus(sdg))
4030                         power += power_of(cpu);
4031         } else  {
4032                 /*
4033                  * !SD_OVERLAP domains can assume that child groups
4034                  * span the current group.
4035                  */ 
4036
4037                 group = child->groups;
4038                 do {
4039                         power += group->sgp->power;
4040                         group = group->next;
4041                 } while (group != child->groups);
4042         }
4043
4044         sdg->sgp->power_orig = sdg->sgp->power = power;
4045 }
4046
4047 /*
4048  * Try and fix up capacity for tiny siblings, this is needed when
4049  * things like SD_ASYM_PACKING need f_b_g to select another sibling
4050  * which on its own isn't powerful enough.
4051  *
4052  * See update_sd_pick_busiest() and check_asym_packing().
4053  */
4054 static inline int
4055 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
4056 {
4057         /*
4058          * Only siblings can have significantly less than SCHED_POWER_SCALE
4059          */
4060         if (!(sd->flags & SD_SHARE_CPUPOWER))
4061                 return 0;
4062
4063         /*
4064          * If ~90% of the cpu_power is still there, we're good.
4065          */
4066         if (group->sgp->power * 32 > group->sgp->power_orig * 29)
4067                 return 1;
4068
4069         return 0;
4070 }
4071
4072 /**
4073  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
4074  * @env: The load balancing environment.
4075  * @group: sched_group whose statistics are to be updated.
4076  * @load_idx: Load index of sched_domain of this_cpu for load calc.
4077  * @local_group: Does group contain this_cpu.
4078  * @balance: Should we balance.
4079  * @sgs: variable to hold the statistics for this group.
4080  */
4081 static inline void update_sg_lb_stats(struct lb_env *env,
4082                         struct sched_group *group, int load_idx,
4083                         int local_group, int *balance, struct sg_lb_stats *sgs)
4084 {
4085         unsigned long nr_running, max_nr_running, min_nr_running;
4086         unsigned long load, max_cpu_load, min_cpu_load;
4087         unsigned int balance_cpu = -1, first_idle_cpu = 0;
4088         unsigned long avg_load_per_task = 0;
4089         int i;
4090
4091         if (local_group)
4092                 balance_cpu = group_balance_cpu(group);
4093
4094         /* Tally up the load of all CPUs in the group */
4095         max_cpu_load = 0;
4096         min_cpu_load = ~0UL;
4097         max_nr_running = 0;
4098         min_nr_running = ~0UL;
4099
4100         for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
4101                 struct rq *rq = cpu_rq(i);
4102
4103                 nr_running = rq->nr_running;
4104
4105                 /* Bias balancing toward cpus of our domain */
4106                 if (local_group) {
4107                         if (idle_cpu(i) && !first_idle_cpu &&
4108                                         cpumask_test_cpu(i, sched_group_mask(group))) {
4109                                 first_idle_cpu = 1;
4110                                 balance_cpu = i;
4111                         }
4112
4113                         load = target_load(i, load_idx);
4114                 } else {
4115                         load = source_load(i, load_idx);
4116                         if (load > max_cpu_load)
4117                                 max_cpu_load = load;
4118                         if (min_cpu_load > load)
4119                                 min_cpu_load = load;
4120
4121                         if (nr_running > max_nr_running)
4122                                 max_nr_running = nr_running;
4123                         if (min_nr_running > nr_running)
4124                                 min_nr_running = nr_running;
4125                 }
4126
4127                 sgs->group_load += load;
4128                 sgs->sum_nr_running += nr_running;
4129                 sgs->sum_weighted_load += weighted_cpuload(i);
4130                 if (idle_cpu(i))
4131                         sgs->idle_cpus++;
4132
4133                 update_sg_numa_stats(sgs, rq);
4134         }
4135
4136         /*
4137          * First idle cpu or the first cpu(busiest) in this sched group
4138          * is eligible for doing load balancing at this and above
4139          * domains. In the newly idle case, we will allow all the cpu's
4140          * to do the newly idle load balance.
4141          */
4142         if (local_group) {
4143                 if (env->idle != CPU_NEWLY_IDLE) {
4144                         if (balance_cpu != env->dst_cpu) {
4145                                 *balance = 0;
4146                                 return;
4147                         }
4148                         update_group_power(env->sd, env->dst_cpu);
4149                 } else if (time_after_eq(jiffies, group->sgp->next_update))
4150                         update_group_power(env->sd, env->dst_cpu);
4151         }
4152
4153         /* Adjust by relative CPU power of the group */
4154         sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
4155
4156         /*
4157          * Consider the group unbalanced when the imbalance is larger
4158          * than the average weight of a task.
4159          *
4160          * APZ: with cgroup the avg task weight can vary wildly and
4161          *      might not be a suitable number - should we keep a
4162          *      normalized nr_running number somewhere that negates
4163          *      the hierarchy?
4164          */
4165         if (sgs->sum_nr_running)
4166                 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
4167
4168         if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
4169             (max_nr_running - min_nr_running) > 1)
4170                 sgs->group_imb = 1;
4171
4172         sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
4173                                                 SCHED_POWER_SCALE);
4174         if (!sgs->group_capacity)
4175                 sgs->group_capacity = fix_small_capacity(env->sd, group);
4176         sgs->group_weight = group->group_weight;
4177
4178         if (sgs->group_capacity > sgs->sum_nr_running)
4179                 sgs->group_has_capacity = 1;
4180 }
4181
4182 /**
4183  * update_sd_pick_busiest - return 1 on busiest group
4184  * @env: The load balancing environment.
4185  * @sds: sched_domain statistics
4186  * @sg: sched_group candidate to be checked for being the busiest
4187  * @sgs: sched_group statistics
4188  *
4189  * Determine if @sg is a busier group than the previously selected
4190  * busiest group.
4191  */
4192 static bool update_sd_pick_busiest(struct lb_env *env,
4193                                    struct sd_lb_stats *sds,
4194                                    struct sched_group *sg,
4195                                    struct sg_lb_stats *sgs)
4196 {
4197         if (sgs->avg_load <= sds->max_load)
4198                 return false;
4199
4200         if (sgs->sum_nr_running > sgs->group_capacity)
4201                 return true;
4202
4203         if (sgs->group_imb)
4204                 return true;
4205
4206         /*
4207          * ASYM_PACKING needs to move all the work to the lowest
4208          * numbered CPUs in the group, therefore mark all groups
4209          * higher than ourself as busy.
4210          */
4211         if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
4212             env->dst_cpu < group_first_cpu(sg)) {
4213                 if (!sds->busiest)
4214                         return true;
4215
4216                 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
4217                         return true;
4218         }
4219
4220         return false;
4221 }
4222
4223 /**
4224  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
4225  * @env: The load balancing environment.
4226  * @balance: Should we balance.
4227  * @sds: variable to hold the statistics for this sched_domain.
4228  */
4229 static inline void update_sd_lb_stats(struct lb_env *env,
4230                                         int *balance, struct sd_lb_stats *sds)
4231 {
4232         struct sched_domain *child = env->sd->child;
4233         struct sched_group *sg = env->sd->groups;
4234         struct sg_lb_stats sgs;
4235         int load_idx, prefer_sibling = 0;
4236
4237         if (child && child->flags & SD_PREFER_SIBLING)
4238                 prefer_sibling = 1;
4239
4240         load_idx = get_sd_load_idx(env->sd, env->idle);
4241
4242         do {
4243                 int local_group;
4244
4245                 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
4246                 memset(&sgs, 0, sizeof(sgs));
4247                 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
4248
4249                 if (local_group && !(*balance))
4250                         return;
4251
4252                 sds->total_load += sgs.group_load;
4253                 sds->total_pwr += sg->sgp->power;
4254
4255                 /*
4256                  * In case the child domain prefers tasks go to siblings
4257                  * first, lower the sg capacity to one so that we'll try
4258                  * and move all the excess tasks away. We lower the capacity
4259                  * of a group only if the local group has the capacity to fit
4260                  * these excess tasks, i.e. nr_running < group_capacity. The
4261                  * extra check prevents the case where you always pull from the
4262                  * heaviest group when it is already under-utilized (possible
4263                  * with a large weight task outweighs the tasks on the system).
4264                  */
4265                 if (prefer_sibling && !local_group && sds->this_has_capacity)
4266                         sgs.group_capacity = min(sgs.group_capacity, 1UL);
4267
4268                 if (local_group) {
4269                         sds->this_load = sgs.avg_load;
4270                         sds->this = sg;
4271                         sds->this_nr_running = sgs.sum_nr_running;
4272                         sds->this_load_per_task = sgs.sum_weighted_load;
4273                         sds->this_has_capacity = sgs.group_has_capacity;
4274                         sds->this_idle_cpus = sgs.idle_cpus;
4275                 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
4276                         sds->max_load = sgs.avg_load;
4277                         sds->busiest = sg;
4278                         sds->busiest_nr_running = sgs.sum_nr_running;
4279                         sds->busiest_idle_cpus = sgs.idle_cpus;
4280                         sds->busiest_group_capacity = sgs.group_capacity;
4281                         sds->busiest_load_per_task = sgs.sum_weighted_load;
4282                         sds->busiest_has_capacity = sgs.group_has_capacity;
4283                         sds->busiest_group_weight = sgs.group_weight;
4284                         sds->group_imb = sgs.group_imb;
4285                 }
4286
4287                 update_sd_numa_stats(env->sd, sg, sds, local_group, &sgs);
4288
4289                 sg = sg->next;
4290         } while (sg != env->sd->groups);
4291 }
4292
4293 /**
4294  * check_asym_packing - Check to see if the group is packed into the
4295  *                      sched doman.
4296  *
4297  * This is primarily intended to used at the sibling level.  Some
4298  * cores like POWER7 prefer to use lower numbered SMT threads.  In the
4299  * case of POWER7, it can move to lower SMT modes only when higher
4300  * threads are idle.  When in lower SMT modes, the threads will
4301  * perform better since they share less core resources.  Hence when we
4302  * have idle threads, we want them to be the higher ones.
4303  *
4304  * This packing function is run on idle threads.  It checks to see if
4305  * the busiest CPU in this domain (core in the P7 case) has a higher
4306  * CPU number than the packing function is being run on.  Here we are
4307  * assuming lower CPU number will be equivalent to lower a SMT thread
4308  * number.
4309  *
4310  * Returns 1 when packing is required and a task should be moved to
4311  * this CPU.  The amount of the imbalance is returned in *imbalance.
4312  *
4313  * @env: The load balancing environment.
4314  * @sds: Statistics of the sched_domain which is to be packed
4315  */
4316 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
4317 {
4318         int busiest_cpu;
4319
4320         if (!(env->sd->flags & SD_ASYM_PACKING))
4321                 return 0;
4322
4323         if (!sds->busiest)
4324                 return 0;
4325
4326         busiest_cpu = group_first_cpu(sds->busiest);
4327         if (env->dst_cpu > busiest_cpu)
4328                 return 0;
4329
4330         env->imbalance = DIV_ROUND_CLOSEST(
4331                 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
4332
4333         return 1;
4334 }
4335
4336 /**
4337  * fix_small_imbalance - Calculate the minor imbalance that exists
4338  *                      amongst the groups of a sched_domain, during
4339  *                      load balancing.
4340  * @env: The load balancing environment.
4341  * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
4342  */
4343 static inline
4344 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4345 {
4346         unsigned long tmp, pwr_now = 0, pwr_move = 0;
4347         unsigned int imbn = 2;
4348         unsigned long scaled_busy_load_per_task;
4349
4350         if (sds->this_nr_running) {
4351                 sds->this_load_per_task /= sds->this_nr_running;
4352                 if (sds->busiest_load_per_task >
4353                                 sds->this_load_per_task)
4354                         imbn = 1;
4355         } else {
4356                 sds->this_load_per_task =
4357                         cpu_avg_load_per_task(env->dst_cpu);
4358         }
4359
4360         scaled_busy_load_per_task = sds->busiest_load_per_task
4361                                          * SCHED_POWER_SCALE;
4362         scaled_busy_load_per_task /= sds->busiest->sgp->power;
4363
4364         if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
4365                         (scaled_busy_load_per_task * imbn)) {
4366                 env->imbalance = sds->busiest_load_per_task;
4367                 return;
4368         }
4369
4370         /*
4371          * OK, we don't have enough imbalance to justify moving tasks,
4372          * however we may be able to increase total CPU power used by
4373          * moving them.
4374          */
4375
4376         pwr_now += sds->busiest->sgp->power *
4377                         min(sds->busiest_load_per_task, sds->max_load);
4378         pwr_now += sds->this->sgp->power *
4379                         min(sds->this_load_per_task, sds->this_load);
4380         pwr_now /= SCHED_POWER_SCALE;
4381
4382         /* Amount of load we'd subtract */
4383         tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4384                 sds->busiest->sgp->power;
4385         if (sds->max_load > tmp)
4386                 pwr_move += sds->busiest->sgp->power *
4387                         min(sds->busiest_load_per_task, sds->max_load - tmp);
4388
4389         /* Amount of load we'd add */
4390         if (sds->max_load * sds->busiest->sgp->power <
4391                 sds->busiest_load_per_task * SCHED_POWER_SCALE)
4392                 tmp = (sds->max_load * sds->busiest->sgp->power) /
4393                         sds->this->sgp->power;
4394         else
4395                 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4396                         sds->this->sgp->power;
4397         pwr_move += sds->this->sgp->power *
4398                         min(sds->this_load_per_task, sds->this_load + tmp);
4399         pwr_move /= SCHED_POWER_SCALE;
4400
4401         /* Move if we gain throughput */
4402         if (pwr_move > pwr_now)
4403                 env->imbalance = sds->busiest_load_per_task;
4404 }
4405
4406 /**
4407  * calculate_imbalance - Calculate the amount of imbalance present within the
4408  *                       groups of a given sched_domain during load balance.
4409  * @env: load balance environment
4410  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
4411  */
4412 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4413 {
4414         unsigned long max_pull, load_above_capacity = ~0UL;
4415
4416         sds->busiest_load_per_task /= sds->busiest_nr_running;
4417         if (sds->group_imb) {
4418                 sds->busiest_load_per_task =
4419                         min(sds->busiest_load_per_task, sds->avg_load);
4420         }
4421
4422         /*
4423          * In the presence of smp nice balancing, certain scenarios can have
4424          * max load less than avg load(as we skip the groups at or below
4425          * its cpu_power, while calculating max_load..)
4426          */
4427         if (sds->max_load < sds->avg_load) {
4428                 env->imbalance = 0;
4429                 return fix_small_imbalance(env, sds);
4430         }
4431
4432         if (!sds->group_imb) {
4433                 /*
4434                  * Don't want to pull so many tasks that a group would go idle.
4435                  */
4436                 load_above_capacity = (sds->busiest_nr_running -
4437                                                 sds->busiest_group_capacity);
4438
4439                 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
4440
4441                 load_above_capacity /= sds->busiest->sgp->power;
4442         }
4443
4444         /*
4445          * We're trying to get all the cpus to the average_load, so we don't
4446          * want to push ourselves above the average load, nor do we wish to
4447          * reduce the max loaded cpu below the average load. At the same time,
4448          * we also don't want to reduce the group load below the group capacity
4449          * (so that we can implement power-savings policies etc). Thus we look
4450          * for the minimum possible imbalance.
4451          * Be careful of negative numbers as they'll appear as very large values
4452          * with unsigned longs.
4453          */
4454         max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
4455
4456         /* How much load to actually move to equalise the imbalance */
4457         env->imbalance = min(max_pull * sds->busiest->sgp->power,
4458                 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
4459                         / SCHED_POWER_SCALE;
4460
4461         /*
4462          * if *imbalance is less than the average load per runnable task
4463          * there is no guarantee that any tasks will be moved so we'll have
4464          * a think about bumping its value to force at least one task to be
4465          * moved
4466          */
4467         if (env->imbalance < sds->busiest_load_per_task)
4468                 return fix_small_imbalance(env, sds);
4469
4470 }
4471
4472 /******* find_busiest_group() helpers end here *********************/
4473
4474 /**
4475  * find_busiest_group - Returns the busiest group within the sched_domain
4476  * if there is an imbalance. If there isn't an imbalance, and
4477  * the user has opted for power-savings, it returns a group whose
4478  * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4479  * such a group exists.
4480  *
4481  * Also calculates the amount of weighted load which should be moved
4482  * to restore balance.
4483  *
4484  * @env: The load balancing environment.
4485  * @balance: Pointer to a variable indicating if this_cpu
4486  *      is the appropriate cpu to perform load balancing at this_level.
4487  *
4488  * Returns:     - the busiest group if imbalance exists.
4489  *              - If no imbalance and user has opted for power-savings balance,
4490  *                 return the least loaded group whose CPUs can be
4491  *                 put to idle by rebalancing its tasks onto our group.
4492  */
4493 static struct sched_group *
4494 find_busiest_group(struct lb_env *env, int *balance)
4495 {
4496         struct sd_lb_stats sds;
4497
4498         memset(&sds, 0, sizeof(sds));
4499
4500         /*
4501          * Compute the various statistics relavent for load balancing at
4502          * this level.
4503          */
4504         update_sd_lb_stats(env, balance, &sds);
4505
4506         /*
4507          * this_cpu is not the appropriate cpu to perform load balancing at
4508          * this level.
4509          */
4510         if (!(*balance))
4511                 goto ret;
4512
4513         if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
4514             check_asym_packing(env, &sds))
4515                 return sds.busiest;
4516
4517         /* There is no busy sibling group to pull tasks from */
4518         if (!sds.busiest || sds.busiest_nr_running == 0)
4519                 goto ret;
4520
4521         sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
4522
4523         /*
4524          * If the busiest group is imbalanced the below checks don't
4525          * work because they assumes all things are equal, which typically
4526          * isn't true due to cpus_allowed constraints and the like.
4527          */
4528         if (sds.group_imb)
4529                 goto force_balance;
4530
4531         /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
4532         if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
4533                         !sds.busiest_has_capacity)
4534                 goto force_balance;
4535
4536         /*
4537          * If the local group is more busy than the selected busiest group
4538          * don't try and pull any tasks.
4539          */
4540         if (sds.this_load >= sds.max_load)
4541                 goto ret;
4542
4543         /*
4544          * Don't pull any tasks if this group is already above the domain
4545          * average load.
4546          */
4547         if (sds.this_load >= sds.avg_load)
4548                 goto ret;
4549
4550         if (env->idle == CPU_IDLE) {
4551                 /*
4552                  * This cpu is idle. If the busiest group load doesn't
4553                  * have more tasks than the number of available cpu's and
4554                  * there is no imbalance between this and busiest group
4555                  * wrt to idle cpu's, it is balanced.
4556                  */
4557                 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
4558                     sds.busiest_nr_running <= sds.busiest_group_weight)
4559                         goto out_balanced;
4560         } else {
4561                 /*
4562                  * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
4563                  * imbalance_pct to be conservative.
4564                  */
4565                 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
4566                         goto out_balanced;
4567         }
4568
4569 force_balance:
4570         /* Looks like there is an imbalance. Compute it */
4571         calculate_imbalance(env, &sds);
4572         return sds.busiest;
4573
4574 out_balanced:
4575         if (check_numa_busiest_group(env, &sds))
4576                 return sds.busiest;
4577
4578 ret:
4579         env->imbalance = 0;
4580         return NULL;
4581 }
4582
4583 /*
4584  * find_busiest_queue - find the busiest runqueue among the cpus in group.
4585  */
4586 static struct rq *find_busiest_queue(struct lb_env *env,
4587                                      struct sched_group *group)
4588 {
4589         struct rq *busiest = NULL, *rq;
4590         unsigned long max_load = 0;
4591         int i;
4592
4593         for_each_cpu(i, sched_group_cpus(group)) {
4594                 unsigned long power = power_of(i);
4595                 unsigned long capacity = DIV_ROUND_CLOSEST(power,
4596                                                            SCHED_POWER_SCALE);
4597                 unsigned long wl;
4598
4599                 if (!capacity)
4600                         capacity = fix_small_capacity(env->sd, group);
4601
4602                 if (!cpumask_test_cpu(i, env->cpus))
4603                         continue;
4604
4605                 rq = cpu_rq(i);
4606                 wl = weighted_cpuload(i);
4607
4608                 /*
4609                  * When comparing with imbalance, use weighted_cpuload()
4610                  * which is not scaled with the cpu power.
4611                  */
4612                 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
4613                         continue;
4614
4615                 /*
4616                  * For the load comparisons with the other cpu's, consider
4617                  * the weighted_cpuload() scaled with the cpu power, so that
4618                  * the load can be moved away from the cpu that is potentially
4619                  * running at a lower capacity.
4620                  */
4621                 wl = (wl * SCHED_POWER_SCALE) / power;
4622
4623                 if (wl > max_load) {
4624                         max_load = wl;
4625                         busiest = rq;
4626                 }
4627         }
4628
4629         return busiest;
4630 }
4631
4632 /*
4633  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4634  * so long as it is large enough.
4635  */
4636 #define MAX_PINNED_INTERVAL     512
4637
4638 /* Working cpumask for load_balance and load_balance_newidle. */
4639 DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4640
4641 static int need_active_balance(struct lb_env *env)
4642 {
4643         struct sched_domain *sd = env->sd;
4644
4645         if (env->idle == CPU_NEWLY_IDLE) {
4646
4647                 /*
4648                  * ASYM_PACKING needs to force migrate tasks from busy but
4649                  * higher numbered CPUs in order to pack all tasks in the
4650                  * lowest numbered CPUs.
4651                  */
4652                 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
4653                         return 1;
4654         }
4655
4656         if (need_active_numa_balance(env))
4657                 return 1;
4658
4659         return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
4660 }
4661
4662 static int active_load_balance_cpu_stop(void *data);
4663
4664 /*
4665  * Check this_cpu to ensure it is balanced within domain. Attempt to move
4666  * tasks if there is an imbalance.
4667  */
4668 static int load_balance(int this_cpu, struct rq *this_rq,
4669                         struct sched_domain *sd, enum cpu_idle_type idle,
4670                         int *balance)
4671 {
4672         int ld_moved, cur_ld_moved, active_balance = 0;
4673         int lb_iterations, max_lb_iterations;
4674         struct sched_group *group;
4675         struct rq *busiest;
4676         unsigned long flags;
4677         struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4678
4679         struct lb_env env = {
4680                 .sd                 = sd,
4681                 .dst_cpu            = this_cpu,
4682                 .dst_rq             = this_rq,
4683                 .dst_grpmask        = sched_group_cpus(sd->groups),
4684                 .idle               = idle,
4685                 .loop_break         = sched_nr_migrate_break,
4686                 .cpus               = cpus,
4687                 .find_busiest_queue = find_busiest_queue,
4688         };
4689
4690         cpumask_copy(cpus, cpu_active_mask);
4691         max_lb_iterations = cpumask_weight(env.dst_grpmask);
4692
4693         schedstat_inc(sd, lb_count[idle]);
4694
4695 redo:
4696         group = find_busiest_group(&env, balance);
4697
4698         if (*balance == 0)
4699                 goto out_balanced;
4700
4701         if (!group) {
4702                 schedstat_inc(sd, lb_nobusyg[idle]);
4703                 goto out_balanced;
4704         }
4705
4706         busiest = env.find_busiest_queue(&env, group);
4707         if (!busiest) {
4708                 schedstat_inc(sd, lb_nobusyq[idle]);
4709                 goto out_balanced;
4710         }
4711         env.src_rq  = busiest;
4712         env.src_cpu = busiest->cpu;
4713
4714         BUG_ON(busiest == env.dst_rq);
4715
4716         schedstat_add(sd, lb_imbalance[idle], env.imbalance);
4717
4718         ld_moved = 0;
4719         lb_iterations = 1;
4720         if (busiest->nr_running > 1) {
4721                 /*
4722                  * Attempt to move tasks. If find_busiest_group has found
4723                  * an imbalance but busiest->nr_running <= 1, the group is
4724                  * still unbalanced. ld_moved simply stays zero, so it is
4725                  * correctly treated as an imbalance.
4726                  */
4727                 env.flags |= LBF_ALL_PINNED;
4728                 env.src_cpu   = busiest->cpu;
4729                 env.src_rq    = busiest;
4730                 env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
4731                 if (sched_feat_numa(NUMA_PULL))
4732                         env.tasks = offnode_tasks(busiest);
4733                 else
4734                         env.tasks = &busiest->cfs_tasks;
4735
4736                 update_h_load(env.src_cpu);
4737 more_balance:
4738                 local_irq_save(flags);
4739                 double_rq_lock(env.dst_rq, busiest);
4740
4741                 /*
4742                  * cur_ld_moved - load moved in current iteration
4743                  * ld_moved     - cumulative load moved across iterations
4744                  */
4745                 cur_ld_moved = move_tasks(&env);
4746                 ld_moved += cur_ld_moved;
4747                 double_rq_unlock(env.dst_rq, busiest);
4748                 local_irq_restore(flags);
4749
4750                 if (env.flags & LBF_NEED_BREAK) {
4751                         env.flags &= ~LBF_NEED_BREAK;
4752                         goto more_balance;
4753                 }
4754
4755                 /*
4756                  * some other cpu did the load balance for us.
4757                  */
4758                 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
4759                         resched_cpu(env.dst_cpu);
4760
4761                 /*
4762                  * Revisit (affine) tasks on src_cpu that couldn't be moved to
4763                  * us and move them to an alternate dst_cpu in our sched_group
4764                  * where they can run. The upper limit on how many times we
4765                  * iterate on same src_cpu is dependent on number of cpus in our
4766                  * sched_group.
4767                  *
4768                  * This changes load balance semantics a bit on who can move
4769                  * load to a given_cpu. In addition to the given_cpu itself
4770                  * (or a ilb_cpu acting on its behalf where given_cpu is
4771                  * nohz-idle), we now have balance_cpu in a position to move
4772                  * load to given_cpu. In rare situations, this may cause
4773                  * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
4774                  * _independently_ and at _same_ time to move some load to
4775                  * given_cpu) causing exceess load to be moved to given_cpu.
4776                  * This however should not happen so much in practice and
4777                  * moreover subsequent load balance cycles should correct the
4778                  * excess load moved.
4779                  */
4780                 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0 &&
4781                                 lb_iterations++ < max_lb_iterations) {
4782
4783                         env.dst_rq       = cpu_rq(env.new_dst_cpu);
4784                         env.dst_cpu      = env.new_dst_cpu;
4785                         env.flags       &= ~LBF_SOME_PINNED;
4786                         env.loop         = 0;
4787                         env.loop_break   = sched_nr_migrate_break;
4788                         /*
4789                          * Go back to "more_balance" rather than "redo" since we
4790                          * need to continue with same src_cpu.
4791                          */
4792                         goto more_balance;
4793                 }
4794
4795                 /* All tasks on this runqueue were pinned by CPU affinity */
4796                 if (unlikely(env.flags & LBF_ALL_PINNED)) {
4797                         cpumask_clear_cpu(cpu_of(busiest), cpus);
4798                         if (!cpumask_empty(cpus)) {
4799                                 env.loop = 0;
4800                                 env.loop_break = sched_nr_migrate_break;
4801                                 goto redo;
4802                         }
4803                         goto out_balanced;
4804                 }
4805         }
4806
4807         if (!ld_moved) {
4808                 schedstat_inc(sd, lb_failed[idle]);
4809                 /*
4810                  * Increment the failure counter only on periodic balance.
4811                  * We do not want newidle balance, which can be very
4812                  * frequent, pollute the failure counter causing
4813                  * excessive cache_hot migrations and active balances.
4814                  */
4815                 if (idle != CPU_NEWLY_IDLE)
4816                         sd->nr_balance_failed++;
4817
4818                 if (need_active_balance(&env)) {
4819                         raw_spin_lock_irqsave(&busiest->lock, flags);
4820
4821                         /* don't kick the active_load_balance_cpu_stop,
4822                          * if the curr task on busiest cpu can't be
4823                          * moved to this_cpu
4824                          */
4825                         if (!cpumask_test_cpu(this_cpu,
4826                                         tsk_cpus_allowed(busiest->curr))) {
4827                                 raw_spin_unlock_irqrestore(&busiest->lock,
4828                                                             flags);
4829                                 env.flags |= LBF_ALL_PINNED;
4830                                 goto out_one_pinned;
4831                         }
4832
4833                         /*
4834                          * ->active_balance synchronizes accesses to
4835                          * ->active_balance_work.  Once set, it's cleared
4836                          * only after active load balance is finished.
4837                          */
4838                         if (!busiest->active_balance) {
4839                                 busiest->active_balance = 1;
4840                                 busiest->push_cpu = this_cpu;
4841                                 active_balance = 1;
4842                         }
4843                         raw_spin_unlock_irqrestore(&busiest->lock, flags);
4844
4845                         if (active_balance) {
4846                                 stop_one_cpu_nowait(cpu_of(busiest),
4847                                         active_load_balance_cpu_stop, busiest,
4848                                         &busiest->active_balance_work);
4849                         }
4850
4851                         /*
4852                          * We've kicked active balancing, reset the failure
4853                          * counter.
4854                          */
4855                         sd->nr_balance_failed = sd->cache_nice_tries+1;
4856                 }
4857         } else
4858                 sd->nr_balance_failed = 0;
4859
4860         if (likely(!active_balance)) {
4861                 /* We were unbalanced, so reset the balancing interval */
4862                 sd->balance_interval = sd->min_interval;
4863         } else {
4864                 /*
4865                  * If we've begun active balancing, start to back off. This
4866                  * case may not be covered by the all_pinned logic if there
4867                  * is only 1 task on the busy runqueue (because we don't call
4868                  * move_tasks).
4869                  */
4870                 if (sd->balance_interval < sd->max_interval)
4871                         sd->balance_interval *= 2;
4872         }
4873
4874         goto out;
4875
4876 out_balanced:
4877         schedstat_inc(sd, lb_balanced[idle]);
4878
4879         sd->nr_balance_failed = 0;
4880
4881 out_one_pinned:
4882         /* tune up the balancing interval */
4883         if (((env.flags & LBF_ALL_PINNED) &&
4884                         sd->balance_interval < MAX_PINNED_INTERVAL) ||
4885                         (sd->balance_interval < sd->max_interval))
4886                 sd->balance_interval *= 2;
4887
4888         ld_moved = 0;
4889 out:
4890         return ld_moved;
4891 }
4892
4893 /*
4894  * idle_balance is called by schedule() if this_cpu is about to become
4895  * idle. Attempts to pull tasks from other CPUs.
4896  */
4897 void idle_balance(int this_cpu, struct rq *this_rq)
4898 {
4899         struct sched_domain *sd;
4900         int pulled_task = 0;
4901         unsigned long next_balance = jiffies + HZ;
4902
4903         this_rq->idle_stamp = this_rq->clock;
4904
4905         if (this_rq->avg_idle < sysctl_sched_migration_cost)
4906                 return;
4907
4908         /*
4909          * Drop the rq->lock, but keep IRQ/preempt disabled.
4910          */
4911         raw_spin_unlock(&this_rq->lock);
4912
4913         update_shares(this_cpu);
4914         rcu_read_lock();
4915         for_each_domain(this_cpu, sd) {
4916                 unsigned long interval;
4917                 int balance = 1;
4918
4919                 if (!(sd->flags & SD_LOAD_BALANCE))
4920                         continue;
4921
4922                 if (sd->flags & SD_BALANCE_NEWIDLE) {
4923                         /* If we've pulled tasks over stop searching: */
4924                         pulled_task = load_balance(this_cpu, this_rq,
4925                                                    sd, CPU_NEWLY_IDLE, &balance);
4926                 }
4927
4928                 interval = msecs_to_jiffies(sd->balance_interval);
4929                 if (time_after(next_balance, sd->last_balance + interval))
4930                         next_balance = sd->last_balance + interval;
4931                 if (pulled_task) {
4932                         this_rq->idle_stamp = 0;
4933                         break;
4934                 }
4935         }
4936         rcu_read_unlock();
4937
4938         raw_spin_lock(&this_rq->lock);
4939
4940         if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4941                 /*
4942                  * We are going idle. next_balance may be set based on
4943                  * a busy processor. So reset next_balance.
4944                  */
4945                 this_rq->next_balance = next_balance;
4946         }
4947 }
4948
4949 /*
4950  * active_load_balance_cpu_stop is run by cpu stopper. It pushes
4951  * running tasks off the busiest CPU onto idle CPUs. It requires at
4952  * least 1 task to be running on each physical CPU where possible, and
4953  * avoids physical / logical imbalances.
4954  */
4955 static int active_load_balance_cpu_stop(void *data)
4956 {
4957         struct rq *busiest_rq = data;
4958         int busiest_cpu = cpu_of(busiest_rq);
4959         int target_cpu = busiest_rq->push_cpu;
4960         struct rq *target_rq = cpu_rq(target_cpu);
4961         struct sched_domain *sd;
4962
4963         raw_spin_lock_irq(&busiest_rq->lock);
4964
4965         /* make sure the requested cpu hasn't gone down in the meantime */
4966         if (unlikely(busiest_cpu != smp_processor_id() ||
4967                      !busiest_rq->active_balance))
4968                 goto out_unlock;
4969
4970         /* Is there any task to move? */
4971         if (busiest_rq->nr_running <= 1)
4972                 goto out_unlock;
4973
4974         /*
4975          * This condition is "impossible", if it occurs
4976          * we need to fix it. Originally reported by
4977          * Bjorn Helgaas on a 128-cpu setup.
4978          */
4979         BUG_ON(busiest_rq == target_rq);
4980
4981         /* move a task from busiest_rq to target_rq */
4982         double_lock_balance(busiest_rq, target_rq);
4983
4984         /* Search for an sd spanning us and the target CPU. */
4985         rcu_read_lock();
4986         for_each_domain(target_cpu, sd) {
4987                 if ((sd->flags & SD_LOAD_BALANCE) &&
4988                     cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4989                                 break;
4990         }
4991
4992         if (likely(sd)) {
4993                 struct lb_env env = {
4994                         .sd             = sd,
4995                         .dst_cpu        = target_cpu,
4996                         .dst_rq         = target_rq,
4997                         .src_cpu        = busiest_rq->cpu,
4998                         .src_rq         = busiest_rq,
4999                         .idle           = CPU_IDLE,
5000                 };
5001
5002                 schedstat_inc(sd, alb_count);
5003
5004                 if (move_one_task(&env))
5005                         schedstat_inc(sd, alb_pushed);
5006                 else
5007                         schedstat_inc(sd, alb_failed);
5008         }
5009         rcu_read_unlock();
5010         double_unlock_balance(busiest_rq, target_rq);
5011 out_unlock:
5012         busiest_rq->active_balance = 0;
5013         raw_spin_unlock_irq(&busiest_rq->lock);
5014         return 0;
5015 }
5016
5017 #ifdef CONFIG_NO_HZ
5018 /*
5019  * idle load balancing details
5020  * - When one of the busy CPUs notice that there may be an idle rebalancing
5021  *   needed, they will kick the idle load balancer, which then does idle
5022  *   load balancing for all the idle CPUs.
5023  */
5024 static struct {
5025         cpumask_var_t idle_cpus_mask;
5026         atomic_t nr_cpus;
5027         unsigned long next_balance;     /* in jiffy units */
5028 } nohz ____cacheline_aligned;
5029
5030 static inline int find_new_ilb(int call_cpu)
5031 {
5032         int ilb = cpumask_first(nohz.idle_cpus_mask);
5033
5034         if (ilb < nr_cpu_ids && idle_cpu(ilb))
5035                 return ilb;
5036
5037         return nr_cpu_ids;
5038 }
5039
5040 /*
5041  * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
5042  * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
5043  * CPU (if there is one).
5044  */
5045 static void nohz_balancer_kick(int cpu)
5046 {
5047         int ilb_cpu;
5048
5049         nohz.next_balance++;
5050
5051         ilb_cpu = find_new_ilb(cpu);
5052
5053         if (ilb_cpu >= nr_cpu_ids)
5054                 return;
5055
5056         if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
5057                 return;
5058         /*
5059          * Use smp_send_reschedule() instead of resched_cpu().
5060          * This way we generate a sched IPI on the target cpu which
5061          * is idle. And the softirq performing nohz idle load balance
5062          * will be run before returning from the IPI.
5063          */
5064         smp_send_reschedule(ilb_cpu);
5065         return;
5066 }
5067
5068 static inline void nohz_balance_exit_idle(int cpu)
5069 {
5070         if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
5071                 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
5072                 atomic_dec(&nohz.nr_cpus);
5073                 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5074         }
5075 }
5076
5077 static inline void set_cpu_sd_state_busy(void)
5078 {
5079         struct sched_domain *sd;
5080         int cpu = smp_processor_id();
5081
5082         if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5083                 return;
5084         clear_bit(NOHZ_IDLE, nohz_flags(cpu));
5085
5086         rcu_read_lock();
5087         for_each_domain(cpu, sd)
5088                 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
5089         rcu_read_unlock();
5090 }
5091
5092 void set_cpu_sd_state_idle(void)
5093 {
5094         struct sched_domain *sd;
5095         int cpu = smp_processor_id();
5096
5097         if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5098                 return;
5099         set_bit(NOHZ_IDLE, nohz_flags(cpu));
5100
5101         rcu_read_lock();
5102         for_each_domain(cpu, sd)
5103                 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
5104         rcu_read_unlock();
5105 }
5106
5107 /*
5108  * This routine will record that the cpu is going idle with tick stopped.
5109  * This info will be used in performing idle load balancing in the future.
5110  */
5111 void nohz_balance_enter_idle(int cpu)
5112 {
5113         /*
5114          * If this cpu is going down, then nothing needs to be done.
5115          */
5116         if (!cpu_active(cpu))
5117                 return;
5118
5119         if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
5120                 return;
5121
5122         cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
5123         atomic_inc(&nohz.nr_cpus);
5124         set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5125 }
5126
5127 static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
5128                                         unsigned long action, void *hcpu)
5129 {
5130         switch (action & ~CPU_TASKS_FROZEN) {
5131         case CPU_DYING:
5132                 nohz_balance_exit_idle(smp_processor_id());
5133                 return NOTIFY_OK;
5134         default:
5135                 return NOTIFY_DONE;
5136         }
5137 }
5138 #endif
5139
5140 static DEFINE_SPINLOCK(balancing);
5141
5142 /*
5143  * Scale the max load_balance interval with the number of CPUs in the system.
5144  * This trades load-balance latency on larger machines for less cross talk.
5145  */
5146 void update_max_interval(void)
5147 {
5148         max_load_balance_interval = HZ*num_online_cpus()/10;
5149 }
5150
5151 /*
5152  * It checks each scheduling domain to see if it is due to be balanced,
5153  * and initiates a balancing operation if so.
5154  *
5155  * Balancing parameters are set up in arch_init_sched_domains.
5156  */
5157 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
5158 {
5159         int balance = 1;
5160         struct rq *rq = cpu_rq(cpu);
5161         unsigned long interval;
5162         struct sched_domain *sd;
5163         /* Earliest time when we have to do rebalance again */
5164         unsigned long next_balance = jiffies + 60*HZ;
5165         int update_next_balance = 0;
5166         int need_serialize;
5167
5168         update_shares(cpu);
5169
5170         rcu_read_lock();
5171         for_each_domain(cpu, sd) {
5172                 if (!(sd->flags & SD_LOAD_BALANCE))
5173                         continue;
5174
5175                 interval = sd->balance_interval;
5176                 if (idle != CPU_IDLE)
5177                         interval *= sd->busy_factor;
5178
5179                 /* scale ms to jiffies */
5180                 interval = msecs_to_jiffies(interval);
5181                 interval = clamp(interval, 1UL, max_load_balance_interval);
5182
5183                 need_serialize = sd->flags & SD_SERIALIZE;
5184
5185                 if (need_serialize) {
5186                         if (!spin_trylock(&balancing))
5187                                 goto out;
5188                 }
5189
5190                 if (time_after_eq(jiffies, sd->last_balance + interval)) {
5191                         if (load_balance(cpu, rq, sd, idle, &balance)) {
5192                                 /*
5193                                  * We've pulled tasks over so either we're no
5194                                  * longer idle.
5195                                  */
5196                                 idle = CPU_NOT_IDLE;
5197                         }
5198                         sd->last_balance = jiffies;
5199                 }
5200                 if (need_serialize)
5201                         spin_unlock(&balancing);
5202 out:
5203                 if (time_after(next_balance, sd->last_balance + interval)) {
5204                         next_balance = sd->last_balance + interval;
5205                         update_next_balance = 1;
5206                 }
5207
5208                 /*
5209                  * Stop the load balance at this level. There is another
5210                  * CPU in our sched group which is doing load balancing more
5211                  * actively.
5212                  */
5213                 if (!balance)
5214                         break;
5215         }
5216         rcu_read_unlock();
5217
5218         /*
5219          * next_balance will be updated only when there is a need.
5220          * When the cpu is attached to null domain for ex, it will not be
5221          * updated.
5222          */
5223         if (likely(update_next_balance))
5224                 rq->next_balance = next_balance;
5225 }
5226
5227 #ifdef CONFIG_NO_HZ
5228 /*
5229  * In CONFIG_NO_HZ case, the idle balance kickee will do the
5230  * rebalancing for all the cpus for whom scheduler ticks are stopped.
5231  */
5232 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
5233 {
5234         struct rq *this_rq = cpu_rq(this_cpu);
5235         struct rq *rq;
5236         int balance_cpu;
5237
5238         if (idle != CPU_IDLE ||
5239             !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
5240                 goto end;
5241
5242         for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
5243                 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
5244                         continue;
5245
5246                 /*
5247                  * If this cpu gets work to do, stop the load balancing
5248                  * work being done for other cpus. Next load
5249                  * balancing owner will pick it up.
5250                  */
5251                 if (need_resched())
5252                         break;
5253
5254                 rq = cpu_rq(balance_cpu);
5255
5256                 raw_spin_lock_irq(&rq->lock);
5257                 update_rq_clock(rq);
5258                 update_idle_cpu_load(rq);
5259                 raw_spin_unlock_irq(&rq->lock);
5260
5261                 rebalance_domains(balance_cpu, CPU_IDLE);
5262
5263                 if (time_after(this_rq->next_balance, rq->next_balance))
5264                         this_rq->next_balance = rq->next_balance;
5265         }
5266         nohz.next_balance = this_rq->next_balance;
5267 end:
5268         clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
5269 }
5270
5271 /*
5272  * Current heuristic for kicking the idle load balancer in the presence
5273  * of an idle cpu is the system.
5274  *   - This rq has more than one task.
5275  *   - At any scheduler domain level, this cpu's scheduler group has multiple
5276  *     busy cpu's exceeding the group's power.
5277  *   - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
5278  *     domain span are idle.
5279  */
5280 static inline int nohz_kick_needed(struct rq *rq, int cpu)
5281 {
5282         unsigned long now = jiffies;
5283         struct sched_domain *sd;
5284
5285         if (unlikely(idle_cpu(cpu)))
5286                 return 0;
5287
5288        /*
5289         * We may be recently in ticked or tickless idle mode. At the first
5290         * busy tick after returning from idle, we will update the busy stats.
5291         */
5292         set_cpu_sd_state_busy();
5293         nohz_balance_exit_idle(cpu);
5294
5295         /*
5296          * None are in tickless mode and hence no need for NOHZ idle load
5297          * balancing.
5298          */
5299         if (likely(!atomic_read(&nohz.nr_cpus)))
5300                 return 0;
5301
5302         if (time_before(now, nohz.next_balance))
5303                 return 0;
5304
5305         if (rq->nr_running >= 2)
5306                 goto need_kick;
5307
5308         rcu_read_lock();
5309         for_each_domain(cpu, sd) {
5310                 struct sched_group *sg = sd->groups;
5311                 struct sched_group_power *sgp = sg->sgp;
5312                 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
5313
5314                 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
5315                         goto need_kick_unlock;
5316
5317                 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
5318                     && (cpumask_first_and(nohz.idle_cpus_mask,
5319                                           sched_domain_span(sd)) < cpu))
5320                         goto need_kick_unlock;
5321
5322                 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
5323                         break;
5324         }
5325         rcu_read_unlock();
5326         return 0;
5327
5328 need_kick_unlock:
5329         rcu_read_unlock();
5330 need_kick:
5331         return 1;
5332 }
5333 #else
5334 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
5335 #endif
5336
5337 /*
5338  * run_rebalance_domains is triggered when needed from the scheduler tick.
5339  * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
5340  */
5341 static void run_rebalance_domains(struct softirq_action *h)
5342 {
5343         int this_cpu = smp_processor_id();
5344         struct rq *this_rq = cpu_rq(this_cpu);
5345         enum cpu_idle_type idle = this_rq->idle_balance ?
5346                                                 CPU_IDLE : CPU_NOT_IDLE;
5347
5348         rebalance_domains(this_cpu, idle);
5349
5350         /*
5351          * If this cpu has a pending nohz_balance_kick, then do the
5352          * balancing on behalf of the other idle cpus whose ticks are
5353          * stopped.
5354          */
5355         nohz_idle_balance(this_cpu, idle);
5356 }
5357
5358 static inline int on_null_domain(int cpu)
5359 {
5360         return !rcu_dereference_sched(cpu_rq(cpu)->sd);
5361 }
5362
5363 /*
5364  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
5365  */
5366 void trigger_load_balance(struct rq *rq, int cpu)
5367 {
5368         /* Don't need to rebalance while attached to NULL domain */
5369         if (time_after_eq(jiffies, rq->next_balance) &&
5370             likely(!on_null_domain(cpu)))
5371                 raise_softirq(SCHED_SOFTIRQ);
5372 #ifdef CONFIG_NO_HZ
5373         if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
5374                 nohz_balancer_kick(cpu);
5375 #endif
5376 }
5377
5378 static void rq_online_fair(struct rq *rq)
5379 {
5380         update_sysctl();
5381 }
5382
5383 static void rq_offline_fair(struct rq *rq)
5384 {
5385         update_sysctl();
5386
5387         /* Ensure any throttled groups are reachable by pick_next_task */
5388         unthrottle_offline_cfs_rqs(rq);
5389 }
5390
5391 #endif /* CONFIG_SMP */
5392
5393 /*
5394  * scheduler tick hitting a task of our scheduling class:
5395  */
5396 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
5397 {
5398         struct cfs_rq *cfs_rq;
5399         struct sched_entity *se = &curr->se;
5400
5401         for_each_sched_entity(se) {
5402                 cfs_rq = cfs_rq_of(se);
5403                 entity_tick(cfs_rq, se, queued);
5404         }
5405
5406         if (sched_feat_numa(NUMA))
5407                 task_tick_numa(rq, curr);
5408 }
5409
5410 /*
5411  * called on fork with the child task as argument from the parent's context
5412  *  - child not yet on the tasklist
5413  *  - preemption disabled
5414  */
5415 static void task_fork_fair(struct task_struct *p)
5416 {
5417         struct cfs_rq *cfs_rq;
5418         struct sched_entity *se = &p->se, *curr;
5419         int this_cpu = smp_processor_id();
5420         struct rq *rq = this_rq();
5421         unsigned long flags;
5422
5423         raw_spin_lock_irqsave(&rq->lock, flags);
5424
5425         update_rq_clock(rq);
5426
5427         cfs_rq = task_cfs_rq(current);
5428         curr = cfs_rq->curr;
5429
5430         if (unlikely(task_cpu(p) != this_cpu)) {
5431                 rcu_read_lock();
5432                 __set_task_cpu(p, this_cpu);
5433                 rcu_read_unlock();
5434         }
5435
5436         update_curr(cfs_rq);
5437
5438         if (curr)
5439                 se->vruntime = curr->vruntime;
5440         place_entity(cfs_rq, se, 1);
5441
5442         if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
5443                 /*
5444                  * Upon rescheduling, sched_class::put_prev_task() will place
5445                  * 'current' within the tree based on its new key value.
5446                  */
5447                 swap(curr->vruntime, se->vruntime);
5448                 resched_task(rq->curr);
5449         }
5450
5451         se->vruntime -= cfs_rq->min_vruntime;
5452
5453         raw_spin_unlock_irqrestore(&rq->lock, flags);
5454 }
5455
5456 /*
5457  * Priority of the task has changed. Check to see if we preempt
5458  * the current task.
5459  */
5460 static void
5461 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
5462 {
5463         if (!p->se.on_rq)
5464                 return;
5465
5466         /*
5467          * Reschedule if we are currently running on this runqueue and
5468          * our priority decreased, or if we are not currently running on
5469          * this runqueue and our priority is higher than the current's
5470          */
5471         if (rq->curr == p) {
5472                 if (p->prio > oldprio)
5473                         resched_task(rq->curr);
5474         } else
5475                 check_preempt_curr(rq, p, 0);
5476 }
5477
5478 static void switched_from_fair(struct rq *rq, struct task_struct *p)
5479 {
5480         struct sched_entity *se = &p->se;
5481         struct cfs_rq *cfs_rq = cfs_rq_of(se);
5482
5483         /*
5484          * Ensure the task's vruntime is normalized, so that when its
5485          * switched back to the fair class the enqueue_entity(.flags=0) will
5486          * do the right thing.
5487          *
5488          * If it was on_rq, then the dequeue_entity(.flags=0) will already
5489          * have normalized the vruntime, if it was !on_rq, then only when
5490          * the task is sleeping will it still have non-normalized vruntime.
5491          */
5492         if (!se->on_rq && p->state != TASK_RUNNING) {
5493                 /*
5494                  * Fix up our vruntime so that the current sleep doesn't
5495                  * cause 'unlimited' sleep bonus.
5496                  */
5497                 place_entity(cfs_rq, se, 0);
5498                 se->vruntime -= cfs_rq->min_vruntime;
5499         }
5500 }
5501
5502 /*
5503  * We switched to the sched_fair class.
5504  */
5505 static void switched_to_fair(struct rq *rq, struct task_struct *p)
5506 {
5507         if (!p->se.on_rq)
5508                 return;
5509
5510         /*
5511          * We were most likely switched from sched_rt, so
5512          * kick off the schedule if running, otherwise just see
5513          * if we can still preempt the current task.
5514          */
5515         if (rq->curr == p)
5516                 resched_task(rq->curr);
5517         else
5518                 check_preempt_curr(rq, p, 0);
5519 }
5520
5521 /* Account for a task changing its policy or group.
5522  *
5523  * This routine is mostly called to set cfs_rq->curr field when a task
5524  * migrates between groups/classes.
5525  */
5526 static void set_curr_task_fair(struct rq *rq)
5527 {
5528         struct sched_entity *se = &rq->curr->se;
5529
5530         for_each_sched_entity(se) {
5531                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5532
5533                 set_next_entity(cfs_rq, se);
5534                 /* ensure bandwidth has been allocated on our new cfs_rq */
5535                 account_cfs_rq_runtime(cfs_rq, 0);
5536         }
5537 }
5538
5539 void init_cfs_rq(struct cfs_rq *cfs_rq)
5540 {
5541         cfs_rq->tasks_timeline = RB_ROOT;
5542         cfs_rq->min_vruntime = (u64)(-(1LL << 20));
5543 #ifndef CONFIG_64BIT
5544         cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
5545 #endif
5546 }
5547
5548 #ifdef CONFIG_FAIR_GROUP_SCHED
5549 static void task_move_group_fair(struct task_struct *p, int on_rq)
5550 {
5551         /*
5552          * If the task was not on the rq at the time of this cgroup movement
5553          * it must have been asleep, sleeping tasks keep their ->vruntime
5554          * absolute on their old rq until wakeup (needed for the fair sleeper
5555          * bonus in place_entity()).
5556          *
5557          * If it was on the rq, we've just 'preempted' it, which does convert
5558          * ->vruntime to a relative base.
5559          *
5560          * Make sure both cases convert their relative position when migrating
5561          * to another cgroup's rq. This does somewhat interfere with the
5562          * fair sleeper stuff for the first placement, but who cares.
5563          */
5564         /*
5565          * When !on_rq, vruntime of the task has usually NOT been normalized.
5566          * But there are some cases where it has already been normalized:
5567          *
5568          * - Moving a forked child which is waiting for being woken up by
5569          *   wake_up_new_task().
5570          * - Moving a task which has been woken up by try_to_wake_up() and
5571          *   waiting for actually being woken up by sched_ttwu_pending().
5572          *
5573          * To prevent boost or penalty in the new cfs_rq caused by delta
5574          * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
5575          */
5576         if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
5577                 on_rq = 1;
5578
5579         if (!on_rq)
5580                 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
5581         set_task_rq(p, task_cpu(p));
5582         if (!on_rq)
5583                 p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
5584 }
5585
5586 void free_fair_sched_group(struct task_group *tg)
5587 {
5588         int i;
5589
5590         destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
5591
5592         for_each_possible_cpu(i) {
5593                 if (tg->cfs_rq)
5594                         kfree(tg->cfs_rq[i]);
5595                 if (tg->se)
5596                         kfree(tg->se[i]);
5597         }
5598
5599         kfree(tg->cfs_rq);
5600         kfree(tg->se);
5601 }
5602
5603 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5604 {
5605         struct cfs_rq *cfs_rq;
5606         struct sched_entity *se;
5607         int i;
5608
5609         tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
5610         if (!tg->cfs_rq)
5611                 goto err;
5612         tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
5613         if (!tg->se)
5614                 goto err;
5615
5616         tg->shares = NICE_0_LOAD;
5617
5618         init_cfs_bandwidth(tg_cfs_bandwidth(tg));
5619
5620         for_each_possible_cpu(i) {
5621                 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
5622                                       GFP_KERNEL, cpu_to_node(i));
5623                 if (!cfs_rq)
5624                         goto err;
5625
5626                 se = kzalloc_node(sizeof(struct sched_entity),
5627                                   GFP_KERNEL, cpu_to_node(i));
5628                 if (!se)
5629                         goto err_free_rq;
5630
5631                 init_cfs_rq(cfs_rq);
5632                 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
5633         }
5634
5635         return 1;
5636
5637 err_free_rq:
5638         kfree(cfs_rq);
5639 err:
5640         return 0;
5641 }
5642
5643 void unregister_fair_sched_group(struct task_group *tg, int cpu)
5644 {
5645         struct rq *rq = cpu_rq(cpu);
5646         unsigned long flags;
5647
5648         /*
5649         * Only empty task groups can be destroyed; so we can speculatively
5650         * check on_list without danger of it being re-added.
5651         */
5652         if (!tg->cfs_rq[cpu]->on_list)
5653                 return;
5654
5655         raw_spin_lock_irqsave(&rq->lock, flags);
5656         list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
5657         raw_spin_unlock_irqrestore(&rq->lock, flags);
5658 }
5659
5660 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
5661                         struct sched_entity *se, int cpu,
5662                         struct sched_entity *parent)
5663 {
5664         struct rq *rq = cpu_rq(cpu);
5665
5666         cfs_rq->tg = tg;
5667         cfs_rq->rq = rq;
5668 #ifdef CONFIG_SMP
5669         /* allow initial update_cfs_load() to truncate */
5670         cfs_rq->load_stamp = 1;
5671 #endif
5672         init_cfs_rq_runtime(cfs_rq);
5673
5674         tg->cfs_rq[cpu] = cfs_rq;
5675         tg->se[cpu] = se;
5676
5677         /* se could be NULL for root_task_group */
5678         if (!se)
5679                 return;
5680
5681         if (!parent)
5682                 se->cfs_rq = &rq->cfs;
5683         else
5684                 se->cfs_rq = parent->my_q;
5685
5686         se->my_q = cfs_rq;
5687         update_load_set(&se->load, 0);
5688         se->parent = parent;
5689 }
5690
5691 static DEFINE_MUTEX(shares_mutex);
5692
5693 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
5694 {
5695         int i;
5696         unsigned long flags;
5697
5698         /*
5699          * We can't change the weight of the root cgroup.
5700          */
5701         if (!tg->se[0])
5702                 return -EINVAL;
5703
5704         shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
5705
5706         mutex_lock(&shares_mutex);
5707         if (tg->shares == shares)
5708                 goto done;
5709
5710         tg->shares = shares;
5711         for_each_possible_cpu(i) {
5712                 struct rq *rq = cpu_rq(i);
5713                 struct sched_entity *se;
5714
5715                 se = tg->se[i];
5716                 /* Propagate contribution to hierarchy */
5717                 raw_spin_lock_irqsave(&rq->lock, flags);
5718                 for_each_sched_entity(se)
5719                         update_cfs_shares(group_cfs_rq(se));
5720                 raw_spin_unlock_irqrestore(&rq->lock, flags);
5721         }
5722
5723 done:
5724         mutex_unlock(&shares_mutex);
5725         return 0;
5726 }
5727 #else /* CONFIG_FAIR_GROUP_SCHED */
5728
5729 void free_fair_sched_group(struct task_group *tg) { }
5730
5731 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5732 {
5733         return 1;
5734 }
5735
5736 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
5737
5738 #endif /* CONFIG_FAIR_GROUP_SCHED */
5739
5740
5741 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
5742 {
5743         struct sched_entity *se = &task->se;
5744         unsigned int rr_interval = 0;
5745
5746         /*
5747          * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
5748          * idle runqueue:
5749          */
5750         if (rq->cfs.load.weight)
5751                 rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5752
5753         return rr_interval;
5754 }
5755
5756 /*
5757  * All the scheduling class methods:
5758  */
5759 const struct sched_class fair_sched_class = {
5760         .next                   = &idle_sched_class,
5761         .enqueue_task           = enqueue_task_fair,
5762         .dequeue_task           = dequeue_task_fair,
5763         .yield_task             = yield_task_fair,
5764         .yield_to_task          = yield_to_task_fair,
5765
5766         .check_preempt_curr     = check_preempt_wakeup,
5767
5768         .pick_next_task         = pick_next_task_fair,
5769         .put_prev_task          = put_prev_task_fair,
5770
5771 #ifdef CONFIG_SMP
5772         .select_task_rq         = select_task_rq_fair,
5773
5774         .rq_online              = rq_online_fair,
5775         .rq_offline             = rq_offline_fair,
5776
5777         .task_waking            = task_waking_fair,
5778 #endif
5779
5780         .set_curr_task          = set_curr_task_fair,
5781         .task_tick              = task_tick_fair,
5782         .task_fork              = task_fork_fair,
5783
5784         .prio_changed           = prio_changed_fair,
5785         .switched_from          = switched_from_fair,
5786         .switched_to            = switched_to_fair,
5787
5788         .get_rr_interval        = get_rr_interval_fair,
5789
5790 #ifdef CONFIG_FAIR_GROUP_SCHED
5791         .task_move_group        = task_move_group_fair,
5792 #endif
5793 };
5794
5795 #ifdef CONFIG_SCHED_DEBUG
5796 void print_cfs_stats(struct seq_file *m, int cpu)
5797 {
5798         struct cfs_rq *cfs_rq;
5799
5800         rcu_read_lock();
5801         for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5802                 print_cfs_rq(m, cpu, cfs_rq);
5803         rcu_read_unlock();
5804 }
5805 #endif
5806
5807 __init void init_sched_fair_class(void)
5808 {
5809 #ifdef CONFIG_SMP
5810         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
5811
5812 #ifdef CONFIG_NO_HZ
5813         nohz.next_balance = jiffies;
5814         zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
5815         cpu_notifier(sched_ilb_notifier, 0);
5816 #endif
5817 #endif /* SMP */
5818
5819 }