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