hmp: Remove potential for task_struct access race
[firefly-linux-kernel-4.4.55.git] / kernel / sched / fair.c
1 /*
2  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
3  *
4  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
5  *
6  *  Interactivity improvements by Mike Galbraith
7  *  (C) 2007 Mike Galbraith <efault@gmx.de>
8  *
9  *  Various enhancements by Dmitry Adamushko.
10  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
11  *
12  *  Group scheduling enhancements by Srivatsa Vaddagiri
13  *  Copyright IBM Corporation, 2007
14  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
15  *
16  *  Scaled math optimizations by Thomas Gleixner
17  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
18  *
19  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
21  */
22
23 #include <linux/latencytop.h>
24 #include <linux/sched.h>
25 #include <linux/cpumask.h>
26 #include <linux/slab.h>
27 #include <linux/profile.h>
28 #include <linux/interrupt.h>
29 #include <linux/mempolicy.h>
30 #include <linux/migrate.h>
31 #include <linux/task_work.h>
32
33 #include <trace/events/sched.h>
34 #ifdef CONFIG_HMP_VARIABLE_SCALE
35 #include <linux/sysfs.h>
36 #include <linux/vmalloc.h>
37 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
38 /* Include cpufreq header to add a notifier so that cpu frequency
39  * scaling can track the current CPU frequency
40  */
41 #include <linux/cpufreq.h>
42 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
43 #endif /* CONFIG_HMP_VARIABLE_SCALE */
44
45 #include "sched.h"
46
47
48 /*
49  * Targeted preemption latency for CPU-bound tasks:
50  * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
51  *
52  * NOTE: this latency value is not the same as the concept of
53  * 'timeslice length' - timeslices in CFS are of variable length
54  * and have no persistent notion like in traditional, time-slice
55  * based scheduling concepts.
56  *
57  * (to see the precise effective timeslice length of your workload,
58  *  run vmstat and monitor the context-switches (cs) field)
59  */
60 unsigned int sysctl_sched_latency = 6000000ULL;
61 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
62
63 /*
64  * The initial- and re-scaling of tunables is configurable
65  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
66  *
67  * Options are:
68  * SCHED_TUNABLESCALING_NONE - unscaled, always *1
69  * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
70  * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
71  */
72 enum sched_tunable_scaling sysctl_sched_tunable_scaling
73         = SCHED_TUNABLESCALING_LOG;
74
75 /*
76  * Minimal preemption granularity for CPU-bound tasks:
77  * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
78  */
79 unsigned int sysctl_sched_min_granularity = 750000ULL;
80 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
81
82 /*
83  * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
84  */
85 static unsigned int sched_nr_latency = 8;
86
87 /*
88  * After fork, child runs first. If set to 0 (default) then
89  * parent will (try to) run first.
90  */
91 unsigned int sysctl_sched_child_runs_first __read_mostly;
92
93 /*
94  * SCHED_OTHER wake-up granularity.
95  * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
96  *
97  * This option delays the preemption effects of decoupled workloads
98  * and reduces their over-scheduling. Synchronous workloads will still
99  * have immediate wakeup/sleep latencies.
100  */
101 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
102 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
103
104 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
105
106 /*
107  * The exponential sliding  window over which load is averaged for shares
108  * distribution.
109  * (default: 10msec)
110  */
111 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
112
113 #ifdef CONFIG_CFS_BANDWIDTH
114 /*
115  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
116  * each time a cfs_rq requests quota.
117  *
118  * Note: in the case that the slice exceeds the runtime remaining (either due
119  * to consumption or the quota being specified to be smaller than the slice)
120  * we will always only issue the remaining available time.
121  *
122  * default: 5 msec, units: microseconds
123   */
124 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
125 #endif
126
127 /*
128  * Increase the granularity value when there are more CPUs,
129  * because with more CPUs the 'effective latency' as visible
130  * to users decreases. But the relationship is not linear,
131  * so pick a second-best guess by going with the log2 of the
132  * number of CPUs.
133  *
134  * This idea comes from the SD scheduler of Con Kolivas:
135  */
136 static int get_update_sysctl_factor(void)
137 {
138         unsigned int cpus = min_t(int, num_online_cpus(), 8);
139         unsigned int factor;
140
141         switch (sysctl_sched_tunable_scaling) {
142         case SCHED_TUNABLESCALING_NONE:
143                 factor = 1;
144                 break;
145         case SCHED_TUNABLESCALING_LINEAR:
146                 factor = cpus;
147                 break;
148         case SCHED_TUNABLESCALING_LOG:
149         default:
150                 factor = 1 + ilog2(cpus);
151                 break;
152         }
153
154         return factor;
155 }
156
157 static void update_sysctl(void)
158 {
159         unsigned int factor = get_update_sysctl_factor();
160
161 #define SET_SYSCTL(name) \
162         (sysctl_##name = (factor) * normalized_sysctl_##name)
163         SET_SYSCTL(sched_min_granularity);
164         SET_SYSCTL(sched_latency);
165         SET_SYSCTL(sched_wakeup_granularity);
166 #undef SET_SYSCTL
167 }
168
169 void sched_init_granularity(void)
170 {
171         update_sysctl();
172 }
173
174 #if BITS_PER_LONG == 32
175 # define WMULT_CONST    (~0UL)
176 #else
177 # define WMULT_CONST    (1UL << 32)
178 #endif
179
180 #define WMULT_SHIFT     32
181
182 /*
183  * Shift right and round:
184  */
185 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
186
187 /*
188  * delta *= weight / lw
189  */
190 static unsigned long
191 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
192                 struct load_weight *lw)
193 {
194         u64 tmp;
195
196         /*
197          * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
198          * entities since MIN_SHARES = 2. Treat weight as 1 if less than
199          * 2^SCHED_LOAD_RESOLUTION.
200          */
201         if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
202                 tmp = (u64)delta_exec * scale_load_down(weight);
203         else
204                 tmp = (u64)delta_exec;
205
206         if (!lw->inv_weight) {
207                 unsigned long w = scale_load_down(lw->weight);
208
209                 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
210                         lw->inv_weight = 1;
211                 else if (unlikely(!w))
212                         lw->inv_weight = WMULT_CONST;
213                 else
214                         lw->inv_weight = WMULT_CONST / w;
215         }
216
217         /*
218          * Check whether we'd overflow the 64-bit multiplication:
219          */
220         if (unlikely(tmp > WMULT_CONST))
221                 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
222                         WMULT_SHIFT/2);
223         else
224                 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
225
226         return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
227 }
228
229
230 const struct sched_class fair_sched_class;
231
232 /**************************************************************
233  * CFS operations on generic schedulable entities:
234  */
235
236 #ifdef CONFIG_FAIR_GROUP_SCHED
237
238 /* cpu runqueue to which this cfs_rq is attached */
239 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
240 {
241         return cfs_rq->rq;
242 }
243
244 /* An entity is a task if it doesn't "own" a runqueue */
245 #define entity_is_task(se)      (!se->my_q)
246
247 static inline struct task_struct *task_of(struct sched_entity *se)
248 {
249 #ifdef CONFIG_SCHED_DEBUG
250         WARN_ON_ONCE(!entity_is_task(se));
251 #endif
252         return container_of(se, struct task_struct, se);
253 }
254
255 /* Walk up scheduling entities hierarchy */
256 #define for_each_sched_entity(se) \
257                 for (; se; se = se->parent)
258
259 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
260 {
261         return p->se.cfs_rq;
262 }
263
264 /* runqueue on which this entity is (to be) queued */
265 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
266 {
267         return se->cfs_rq;
268 }
269
270 /* runqueue "owned" by this group */
271 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
272 {
273         return grp->my_q;
274 }
275
276 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
277                                        int force_update);
278
279 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
280 {
281         if (!cfs_rq->on_list) {
282                 /*
283                  * Ensure we either appear before our parent (if already
284                  * enqueued) or force our parent to appear after us when it is
285                  * enqueued.  The fact that we always enqueue bottom-up
286                  * reduces this to two cases.
287                  */
288                 if (cfs_rq->tg->parent &&
289                     cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
290                         list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
291                                 &rq_of(cfs_rq)->leaf_cfs_rq_list);
292                 } else {
293                         list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
294                                 &rq_of(cfs_rq)->leaf_cfs_rq_list);
295                 }
296
297                 cfs_rq->on_list = 1;
298                 /* We should have no load, but we need to update last_decay. */
299                 update_cfs_rq_blocked_load(cfs_rq, 0);
300         }
301 }
302
303 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
304 {
305         if (cfs_rq->on_list) {
306                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
307                 cfs_rq->on_list = 0;
308         }
309 }
310
311 /* Iterate thr' all leaf cfs_rq's on a runqueue */
312 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
313         list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
314
315 /* Do the two (enqueued) entities belong to the same group ? */
316 static inline int
317 is_same_group(struct sched_entity *se, struct sched_entity *pse)
318 {
319         if (se->cfs_rq == pse->cfs_rq)
320                 return 1;
321
322         return 0;
323 }
324
325 static inline struct sched_entity *parent_entity(struct sched_entity *se)
326 {
327         return se->parent;
328 }
329
330 /* return depth at which a sched entity is present in the hierarchy */
331 static inline int depth_se(struct sched_entity *se)
332 {
333         int depth = 0;
334
335         for_each_sched_entity(se)
336                 depth++;
337
338         return depth;
339 }
340
341 static void
342 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
343 {
344         int se_depth, pse_depth;
345
346         /*
347          * preemption test can be made between sibling entities who are in the
348          * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
349          * both tasks until we find their ancestors who are siblings of common
350          * parent.
351          */
352
353         /* First walk up until both entities are at same depth */
354         se_depth = depth_se(*se);
355         pse_depth = depth_se(*pse);
356
357         while (se_depth > pse_depth) {
358                 se_depth--;
359                 *se = parent_entity(*se);
360         }
361
362         while (pse_depth > se_depth) {
363                 pse_depth--;
364                 *pse = parent_entity(*pse);
365         }
366
367         while (!is_same_group(*se, *pse)) {
368                 *se = parent_entity(*se);
369                 *pse = parent_entity(*pse);
370         }
371 }
372
373 #else   /* !CONFIG_FAIR_GROUP_SCHED */
374
375 static inline struct task_struct *task_of(struct sched_entity *se)
376 {
377         return container_of(se, struct task_struct, se);
378 }
379
380 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
381 {
382         return container_of(cfs_rq, struct rq, cfs);
383 }
384
385 #define entity_is_task(se)      1
386
387 #define for_each_sched_entity(se) \
388                 for (; se; se = NULL)
389
390 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
391 {
392         return &task_rq(p)->cfs;
393 }
394
395 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
396 {
397         struct task_struct *p = task_of(se);
398         struct rq *rq = task_rq(p);
399
400         return &rq->cfs;
401 }
402
403 /* runqueue "owned" by this group */
404 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
405 {
406         return NULL;
407 }
408
409 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
410 {
411 }
412
413 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
414 {
415 }
416
417 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
418                 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
419
420 static inline int
421 is_same_group(struct sched_entity *se, struct sched_entity *pse)
422 {
423         return 1;
424 }
425
426 static inline struct sched_entity *parent_entity(struct sched_entity *se)
427 {
428         return NULL;
429 }
430
431 static inline void
432 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
433 {
434 }
435
436 #endif  /* CONFIG_FAIR_GROUP_SCHED */
437
438 static __always_inline
439 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
440
441 /**************************************************************
442  * Scheduling class tree data structure manipulation methods:
443  */
444
445 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
446 {
447         s64 delta = (s64)(vruntime - max_vruntime);
448         if (delta > 0)
449                 max_vruntime = vruntime;
450
451         return max_vruntime;
452 }
453
454 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
455 {
456         s64 delta = (s64)(vruntime - min_vruntime);
457         if (delta < 0)
458                 min_vruntime = vruntime;
459
460         return min_vruntime;
461 }
462
463 static inline int entity_before(struct sched_entity *a,
464                                 struct sched_entity *b)
465 {
466         return (s64)(a->vruntime - b->vruntime) < 0;
467 }
468
469 static void update_min_vruntime(struct cfs_rq *cfs_rq)
470 {
471         u64 vruntime = cfs_rq->min_vruntime;
472
473         if (cfs_rq->curr)
474                 vruntime = cfs_rq->curr->vruntime;
475
476         if (cfs_rq->rb_leftmost) {
477                 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
478                                                    struct sched_entity,
479                                                    run_node);
480
481                 if (!cfs_rq->curr)
482                         vruntime = se->vruntime;
483                 else
484                         vruntime = min_vruntime(vruntime, se->vruntime);
485         }
486
487         /* ensure we never gain time by being placed backwards. */
488         cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
489 #ifndef CONFIG_64BIT
490         smp_wmb();
491         cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
492 #endif
493 }
494
495 /*
496  * Enqueue an entity into the rb-tree:
497  */
498 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
499 {
500         struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
501         struct rb_node *parent = NULL;
502         struct sched_entity *entry;
503         int leftmost = 1;
504
505         /*
506          * Find the right place in the rbtree:
507          */
508         while (*link) {
509                 parent = *link;
510                 entry = rb_entry(parent, struct sched_entity, run_node);
511                 /*
512                  * We dont care about collisions. Nodes with
513                  * the same key stay together.
514                  */
515                 if (entity_before(se, entry)) {
516                         link = &parent->rb_left;
517                 } else {
518                         link = &parent->rb_right;
519                         leftmost = 0;
520                 }
521         }
522
523         /*
524          * Maintain a cache of leftmost tree entries (it is frequently
525          * used):
526          */
527         if (leftmost)
528                 cfs_rq->rb_leftmost = &se->run_node;
529
530         rb_link_node(&se->run_node, parent, link);
531         rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
532 }
533
534 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
535 {
536         if (cfs_rq->rb_leftmost == &se->run_node) {
537                 struct rb_node *next_node;
538
539                 next_node = rb_next(&se->run_node);
540                 cfs_rq->rb_leftmost = next_node;
541         }
542
543         rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
544 }
545
546 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
547 {
548         struct rb_node *left = cfs_rq->rb_leftmost;
549
550         if (!left)
551                 return NULL;
552
553         return rb_entry(left, struct sched_entity, run_node);
554 }
555
556 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
557 {
558         struct rb_node *next = rb_next(&se->run_node);
559
560         if (!next)
561                 return NULL;
562
563         return rb_entry(next, struct sched_entity, run_node);
564 }
565
566 #ifdef CONFIG_SCHED_DEBUG
567 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
568 {
569         struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
570
571         if (!last)
572                 return NULL;
573
574         return rb_entry(last, struct sched_entity, run_node);
575 }
576
577 /**************************************************************
578  * Scheduling class statistics methods:
579  */
580
581 int sched_proc_update_handler(struct ctl_table *table, int write,
582                 void __user *buffer, size_t *lenp,
583                 loff_t *ppos)
584 {
585         int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
586         int factor = get_update_sysctl_factor();
587
588         if (ret || !write)
589                 return ret;
590
591         sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
592                                         sysctl_sched_min_granularity);
593
594 #define WRT_SYSCTL(name) \
595         (normalized_sysctl_##name = sysctl_##name / (factor))
596         WRT_SYSCTL(sched_min_granularity);
597         WRT_SYSCTL(sched_latency);
598         WRT_SYSCTL(sched_wakeup_granularity);
599 #undef WRT_SYSCTL
600
601         return 0;
602 }
603 #endif
604
605 /*
606  * delta /= w
607  */
608 static inline unsigned long
609 calc_delta_fair(unsigned long delta, struct sched_entity *se)
610 {
611         if (unlikely(se->load.weight != NICE_0_LOAD))
612                 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
613
614         return delta;
615 }
616
617 /*
618  * The idea is to set a period in which each task runs once.
619  *
620  * When there are too many tasks (sched_nr_latency) we have to stretch
621  * this period because otherwise the slices get too small.
622  *
623  * p = (nr <= nl) ? l : l*nr/nl
624  */
625 static u64 __sched_period(unsigned long nr_running)
626 {
627         u64 period = sysctl_sched_latency;
628         unsigned long nr_latency = sched_nr_latency;
629
630         if (unlikely(nr_running > nr_latency)) {
631                 period = sysctl_sched_min_granularity;
632                 period *= nr_running;
633         }
634
635         return period;
636 }
637
638 /*
639  * We calculate the wall-time slice from the period by taking a part
640  * proportional to the weight.
641  *
642  * s = p*P[w/rw]
643  */
644 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
645 {
646         u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
647
648         for_each_sched_entity(se) {
649                 struct load_weight *load;
650                 struct load_weight lw;
651
652                 cfs_rq = cfs_rq_of(se);
653                 load = &cfs_rq->load;
654
655                 if (unlikely(!se->on_rq)) {
656                         lw = cfs_rq->load;
657
658                         update_load_add(&lw, se->load.weight);
659                         load = &lw;
660                 }
661                 slice = calc_delta_mine(slice, se->load.weight, load);
662         }
663         return slice;
664 }
665
666 /*
667  * We calculate the vruntime slice of a to-be-inserted task.
668  *
669  * vs = s/w
670  */
671 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
672 {
673         return calc_delta_fair(sched_slice(cfs_rq, se), se);
674 }
675
676 /*
677  * Update the current task's runtime statistics. Skip current tasks that
678  * are not in our scheduling class.
679  */
680 static inline void
681 __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
682               unsigned long delta_exec)
683 {
684         unsigned long delta_exec_weighted;
685
686         schedstat_set(curr->statistics.exec_max,
687                       max((u64)delta_exec, curr->statistics.exec_max));
688
689         curr->sum_exec_runtime += delta_exec;
690         schedstat_add(cfs_rq, exec_clock, delta_exec);
691         delta_exec_weighted = calc_delta_fair(delta_exec, curr);
692
693         curr->vruntime += delta_exec_weighted;
694         update_min_vruntime(cfs_rq);
695 }
696
697 static void update_curr(struct cfs_rq *cfs_rq)
698 {
699         struct sched_entity *curr = cfs_rq->curr;
700         u64 now = rq_of(cfs_rq)->clock_task;
701         unsigned long delta_exec;
702
703         if (unlikely(!curr))
704                 return;
705
706         /*
707          * Get the amount of time the current task was running
708          * since the last time we changed load (this cannot
709          * overflow on 32 bits):
710          */
711         delta_exec = (unsigned long)(now - curr->exec_start);
712         if (!delta_exec)
713                 return;
714
715         __update_curr(cfs_rq, curr, delta_exec);
716         curr->exec_start = now;
717
718         if (entity_is_task(curr)) {
719                 struct task_struct *curtask = task_of(curr);
720
721                 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
722                 cpuacct_charge(curtask, delta_exec);
723                 account_group_exec_runtime(curtask, delta_exec);
724         }
725
726         account_cfs_rq_runtime(cfs_rq, delta_exec);
727 }
728
729 static inline void
730 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
731 {
732         schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
733 }
734
735 /*
736  * Task is being enqueued - update stats:
737  */
738 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
739 {
740         /*
741          * Are we enqueueing a waiting task? (for current tasks
742          * a dequeue/enqueue event is a NOP)
743          */
744         if (se != cfs_rq->curr)
745                 update_stats_wait_start(cfs_rq, se);
746 }
747
748 static void
749 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
750 {
751         schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
752                         rq_of(cfs_rq)->clock - se->statistics.wait_start));
753         schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
754         schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
755                         rq_of(cfs_rq)->clock - se->statistics.wait_start);
756 #ifdef CONFIG_SCHEDSTATS
757         if (entity_is_task(se)) {
758                 trace_sched_stat_wait(task_of(se),
759                         rq_of(cfs_rq)->clock - se->statistics.wait_start);
760         }
761 #endif
762         schedstat_set(se->statistics.wait_start, 0);
763 }
764
765 static inline void
766 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
767 {
768         /*
769          * Mark the end of the wait period if dequeueing a
770          * waiting task:
771          */
772         if (se != cfs_rq->curr)
773                 update_stats_wait_end(cfs_rq, se);
774 }
775
776 /*
777  * We are picking a new current task - update its stats:
778  */
779 static inline void
780 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
781 {
782         /*
783          * We are starting a new run period:
784          */
785         se->exec_start = rq_of(cfs_rq)->clock_task;
786 }
787
788 /**************************************************
789  * Scheduling class queueing methods:
790  */
791
792 #ifdef CONFIG_NUMA_BALANCING
793 /*
794  * numa task sample period in ms
795  */
796 unsigned int sysctl_numa_balancing_scan_period_min = 100;
797 unsigned int sysctl_numa_balancing_scan_period_max = 100*50;
798 unsigned int sysctl_numa_balancing_scan_period_reset = 100*600;
799
800 /* Portion of address space to scan in MB */
801 unsigned int sysctl_numa_balancing_scan_size = 256;
802
803 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
804 unsigned int sysctl_numa_balancing_scan_delay = 1000;
805
806 static void task_numa_placement(struct task_struct *p)
807 {
808         int seq;
809
810         if (!p->mm)     /* for example, ksmd faulting in a user's mm */
811                 return;
812         seq = ACCESS_ONCE(p->mm->numa_scan_seq);
813         if (p->numa_scan_seq == seq)
814                 return;
815         p->numa_scan_seq = seq;
816
817         /* FIXME: Scheduling placement policy hints go here */
818 }
819
820 /*
821  * Got a PROT_NONE fault for a page on @node.
822  */
823 void task_numa_fault(int node, int pages, bool migrated)
824 {
825         struct task_struct *p = current;
826
827         if (!sched_feat_numa(NUMA))
828                 return;
829
830         /* FIXME: Allocate task-specific structure for placement policy here */
831
832         /*
833          * If pages are properly placed (did not migrate) then scan slower.
834          * This is reset periodically in case of phase changes
835          */
836         if (!migrated)
837                 p->numa_scan_period = min(sysctl_numa_balancing_scan_period_max,
838                         p->numa_scan_period + jiffies_to_msecs(10));
839
840         task_numa_placement(p);
841 }
842
843 static void reset_ptenuma_scan(struct task_struct *p)
844 {
845         ACCESS_ONCE(p->mm->numa_scan_seq)++;
846         p->mm->numa_scan_offset = 0;
847 }
848
849 /*
850  * The expensive part of numa migration is done from task_work context.
851  * Triggered from task_tick_numa().
852  */
853 void task_numa_work(struct callback_head *work)
854 {
855         unsigned long migrate, next_scan, now = jiffies;
856         struct task_struct *p = current;
857         struct mm_struct *mm = p->mm;
858         struct vm_area_struct *vma;
859         unsigned long start, end;
860         long pages;
861
862         WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
863
864         work->next = work; /* protect against double add */
865         /*
866          * Who cares about NUMA placement when they're dying.
867          *
868          * NOTE: make sure not to dereference p->mm before this check,
869          * exit_task_work() happens _after_ exit_mm() so we could be called
870          * without p->mm even though we still had it when we enqueued this
871          * work.
872          */
873         if (p->flags & PF_EXITING)
874                 return;
875
876         /*
877          * We do not care about task placement until a task runs on a node
878          * other than the first one used by the address space. This is
879          * largely because migrations are driven by what CPU the task
880          * is running on. If it's never scheduled on another node, it'll
881          * not migrate so why bother trapping the fault.
882          */
883         if (mm->first_nid == NUMA_PTE_SCAN_INIT)
884                 mm->first_nid = numa_node_id();
885         if (mm->first_nid != NUMA_PTE_SCAN_ACTIVE) {
886                 /* Are we running on a new node yet? */
887                 if (numa_node_id() == mm->first_nid &&
888                     !sched_feat_numa(NUMA_FORCE))
889                         return;
890
891                 mm->first_nid = NUMA_PTE_SCAN_ACTIVE;
892         }
893
894         /*
895          * Reset the scan period if enough time has gone by. Objective is that
896          * scanning will be reduced if pages are properly placed. As tasks
897          * can enter different phases this needs to be re-examined. Lacking
898          * proper tracking of reference behaviour, this blunt hammer is used.
899          */
900         migrate = mm->numa_next_reset;
901         if (time_after(now, migrate)) {
902                 p->numa_scan_period = sysctl_numa_balancing_scan_period_min;
903                 next_scan = now + msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
904                 xchg(&mm->numa_next_reset, next_scan);
905         }
906
907         /*
908          * Enforce maximal scan/migration frequency..
909          */
910         migrate = mm->numa_next_scan;
911         if (time_before(now, migrate))
912                 return;
913
914         if (p->numa_scan_period == 0)
915                 p->numa_scan_period = sysctl_numa_balancing_scan_period_min;
916
917         next_scan = now + msecs_to_jiffies(p->numa_scan_period);
918         if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
919                 return;
920
921         /*
922          * Do not set pte_numa if the current running node is rate-limited.
923          * This loses statistics on the fault but if we are unwilling to
924          * migrate to this node, it is less likely we can do useful work
925          */
926         if (migrate_ratelimited(numa_node_id()))
927                 return;
928
929         start = mm->numa_scan_offset;
930         pages = sysctl_numa_balancing_scan_size;
931         pages <<= 20 - PAGE_SHIFT; /* MB in pages */
932         if (!pages)
933                 return;
934
935         down_read(&mm->mmap_sem);
936         vma = find_vma(mm, start);
937         if (!vma) {
938                 reset_ptenuma_scan(p);
939                 start = 0;
940                 vma = mm->mmap;
941         }
942         for (; vma; vma = vma->vm_next) {
943                 if (!vma_migratable(vma))
944                         continue;
945
946                 /* Skip small VMAs. They are not likely to be of relevance */
947                 if (vma->vm_end - vma->vm_start < HPAGE_SIZE)
948                         continue;
949
950                 do {
951                         start = max(start, vma->vm_start);
952                         end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
953                         end = min(end, vma->vm_end);
954                         pages -= change_prot_numa(vma, start, end);
955
956                         start = end;
957                         if (pages <= 0)
958                                 goto out;
959                 } while (end != vma->vm_end);
960         }
961
962 out:
963         /*
964          * It is possible to reach the end of the VMA list but the last few VMAs are
965          * not guaranteed to the vma_migratable. If they are not, we would find the
966          * !migratable VMA on the next scan but not reset the scanner to the start
967          * so check it now.
968          */
969         if (vma)
970                 mm->numa_scan_offset = start;
971         else
972                 reset_ptenuma_scan(p);
973         up_read(&mm->mmap_sem);
974 }
975
976 /*
977  * Drive the periodic memory faults..
978  */
979 void task_tick_numa(struct rq *rq, struct task_struct *curr)
980 {
981         struct callback_head *work = &curr->numa_work;
982         u64 period, now;
983
984         /*
985          * We don't care about NUMA placement if we don't have memory.
986          */
987         if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
988                 return;
989
990         /*
991          * Using runtime rather than walltime has the dual advantage that
992          * we (mostly) drive the selection from busy threads and that the
993          * task needs to have done some actual work before we bother with
994          * NUMA placement.
995          */
996         now = curr->se.sum_exec_runtime;
997         period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
998
999         if (now - curr->node_stamp > period) {
1000                 if (!curr->node_stamp)
1001                         curr->numa_scan_period = sysctl_numa_balancing_scan_period_min;
1002                 curr->node_stamp = now;
1003
1004                 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
1005                         init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
1006                         task_work_add(curr, work, true);
1007                 }
1008         }
1009 }
1010 #else
1011 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
1012 {
1013 }
1014 #endif /* CONFIG_NUMA_BALANCING */
1015
1016 static void
1017 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1018 {
1019         update_load_add(&cfs_rq->load, se->load.weight);
1020         if (!parent_entity(se))
1021                 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
1022 #ifdef CONFIG_SMP
1023         if (entity_is_task(se))
1024                 list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
1025 #endif
1026         cfs_rq->nr_running++;
1027 }
1028
1029 static void
1030 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1031 {
1032         update_load_sub(&cfs_rq->load, se->load.weight);
1033         if (!parent_entity(se))
1034                 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
1035         if (entity_is_task(se))
1036                 list_del_init(&se->group_node);
1037         cfs_rq->nr_running--;
1038 }
1039
1040 #ifdef CONFIG_FAIR_GROUP_SCHED
1041 # ifdef CONFIG_SMP
1042 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
1043 {
1044         long tg_weight;
1045
1046         /*
1047          * Use this CPU's actual weight instead of the last load_contribution
1048          * to gain a more accurate current total weight. See
1049          * update_cfs_rq_load_contribution().
1050          */
1051         tg_weight = atomic64_read(&tg->load_avg);
1052         tg_weight -= cfs_rq->tg_load_contrib;
1053         tg_weight += cfs_rq->load.weight;
1054
1055         return tg_weight;
1056 }
1057
1058 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1059 {
1060         long tg_weight, load, shares;
1061
1062         tg_weight = calc_tg_weight(tg, cfs_rq);
1063         load = cfs_rq->load.weight;
1064
1065         shares = (tg->shares * load);
1066         if (tg_weight)
1067                 shares /= tg_weight;
1068
1069         if (shares < MIN_SHARES)
1070                 shares = MIN_SHARES;
1071         if (shares > tg->shares)
1072                 shares = tg->shares;
1073
1074         return shares;
1075 }
1076 # else /* CONFIG_SMP */
1077 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1078 {
1079         return tg->shares;
1080 }
1081 # endif /* CONFIG_SMP */
1082 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
1083                             unsigned long weight)
1084 {
1085         if (se->on_rq) {
1086                 /* commit outstanding execution time */
1087                 if (cfs_rq->curr == se)
1088                         update_curr(cfs_rq);
1089                 account_entity_dequeue(cfs_rq, se);
1090         }
1091
1092         update_load_set(&se->load, weight);
1093
1094         if (se->on_rq)
1095                 account_entity_enqueue(cfs_rq, se);
1096 }
1097
1098 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
1099
1100 static void update_cfs_shares(struct cfs_rq *cfs_rq)
1101 {
1102         struct task_group *tg;
1103         struct sched_entity *se;
1104         long shares;
1105
1106         tg = cfs_rq->tg;
1107         se = tg->se[cpu_of(rq_of(cfs_rq))];
1108         if (!se || throttled_hierarchy(cfs_rq))
1109                 return;
1110 #ifndef CONFIG_SMP
1111         if (likely(se->load.weight == tg->shares))
1112                 return;
1113 #endif
1114         shares = calc_cfs_shares(cfs_rq, tg);
1115
1116         reweight_entity(cfs_rq_of(se), se, shares);
1117 }
1118 #else /* CONFIG_FAIR_GROUP_SCHED */
1119 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
1120 {
1121 }
1122 #endif /* CONFIG_FAIR_GROUP_SCHED */
1123
1124 /* Only depends on SMP, FAIR_GROUP_SCHED may be removed when useful in lb */
1125 #if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
1126 /*
1127  * We choose a half-life close to 1 scheduling period.
1128  * Note: The tables below are dependent on this value.
1129  */
1130 #define LOAD_AVG_PERIOD 32
1131 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
1132 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
1133
1134 /* Precomputed fixed inverse multiplies for multiplication by y^n */
1135 static const u32 runnable_avg_yN_inv[] = {
1136         0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
1137         0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
1138         0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
1139         0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
1140         0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
1141         0x85aac367, 0x82cd8698,
1142 };
1143
1144 /*
1145  * Precomputed \Sum y^k { 1<=k<=n }.  These are floor(true_value) to prevent
1146  * over-estimates when re-combining.
1147  */
1148 static const u32 runnable_avg_yN_sum[] = {
1149             0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
1150          9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
1151         17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
1152 };
1153
1154 /*
1155  * Approximate:
1156  *   val * y^n,    where y^32 ~= 0.5 (~1 scheduling period)
1157  */
1158 static __always_inline u64 decay_load(u64 val, u64 n)
1159 {
1160         unsigned int local_n;
1161
1162         if (!n)
1163                 return val;
1164         else if (unlikely(n > LOAD_AVG_PERIOD * 63))
1165                 return 0;
1166
1167         /* after bounds checking we can collapse to 32-bit */
1168         local_n = n;
1169
1170         /*
1171          * As y^PERIOD = 1/2, we can combine
1172          *    y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
1173          * With a look-up table which covers k^n (n<PERIOD)
1174          *
1175          * To achieve constant time decay_load.
1176          */
1177         if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
1178                 val >>= local_n / LOAD_AVG_PERIOD;
1179                 local_n %= LOAD_AVG_PERIOD;
1180         }
1181
1182         val *= runnable_avg_yN_inv[local_n];
1183         /* We don't use SRR here since we always want to round down. */
1184         return val >> 32;
1185 }
1186
1187 /*
1188  * For updates fully spanning n periods, the contribution to runnable
1189  * average will be: \Sum 1024*y^n
1190  *
1191  * We can compute this reasonably efficiently by combining:
1192  *   y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for  n <PERIOD}
1193  */
1194 static u32 __compute_runnable_contrib(u64 n)
1195 {
1196         u32 contrib = 0;
1197
1198         if (likely(n <= LOAD_AVG_PERIOD))
1199                 return runnable_avg_yN_sum[n];
1200         else if (unlikely(n >= LOAD_AVG_MAX_N))
1201                 return LOAD_AVG_MAX;
1202
1203         /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
1204         do {
1205                 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
1206                 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
1207
1208                 n -= LOAD_AVG_PERIOD;
1209         } while (n > LOAD_AVG_PERIOD);
1210
1211         contrib = decay_load(contrib, n);
1212         return contrib + runnable_avg_yN_sum[n];
1213 }
1214
1215 #ifdef CONFIG_HMP_VARIABLE_SCALE
1216
1217 #define HMP_VARIABLE_SCALE_SHIFT 16ULL
1218 struct hmp_global_attr {
1219         struct attribute attr;
1220         ssize_t (*show)(struct kobject *kobj,
1221                         struct attribute *attr, char *buf);
1222         ssize_t (*store)(struct kobject *a, struct attribute *b,
1223                         const char *c, size_t count);
1224         int *value;
1225         int (*to_sysfs)(int);
1226         int (*from_sysfs)(int);
1227 };
1228
1229 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1230 #define HMP_DATA_SYSFS_MAX 4
1231 #else
1232 #define HMP_DATA_SYSFS_MAX 3
1233 #endif
1234
1235 struct hmp_data_struct {
1236 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1237         int freqinvar_load_scale_enabled;
1238 #endif
1239         int multiplier; /* used to scale the time delta */
1240         struct attribute_group attr_group;
1241         struct attribute *attributes[HMP_DATA_SYSFS_MAX + 1];
1242         struct hmp_global_attr attr[HMP_DATA_SYSFS_MAX];
1243 } hmp_data;
1244
1245 static u64 hmp_variable_scale_convert(u64 delta);
1246 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1247 /* Frequency-Invariant Load Modification:
1248  * Loads are calculated as in PJT's patch however we also scale the current
1249  * contribution in line with the frequency of the CPU that the task was
1250  * executed on.
1251  * In this version, we use a simple linear scale derived from the maximum
1252  * frequency reported by CPUFreq. As an example:
1253  *
1254  * Consider that we ran a task for 100% of the previous interval.
1255  *
1256  * Our CPU was under asynchronous frequency control through one of the
1257  * CPUFreq governors.
1258  *
1259  * The CPUFreq governor reports that it is able to scale the CPU between
1260  * 500MHz and 1GHz.
1261  *
1262  * During the period, the CPU was running at 1GHz.
1263  *
1264  * In this case, our load contribution for that period is calculated as
1265  * 1 * (number_of_active_microseconds)
1266  *
1267  * This results in our task being able to accumulate maximum load as normal.
1268  *
1269  *
1270  * Consider now that our CPU was executing at 500MHz.
1271  *
1272  * We now scale the load contribution such that it is calculated as
1273  * 0.5 * (number_of_active_microseconds)
1274  *
1275  * Our task can only record 50% maximum load during this period.
1276  *
1277  * This represents the task consuming 50% of the CPU's *possible* compute
1278  * capacity. However the task did consume 100% of the CPU's *available*
1279  * compute capacity which is the value seen by the CPUFreq governor and
1280  * user-side CPU Utilization tools.
1281  *
1282  * Restricting tracked load to be scaled by the CPU's frequency accurately
1283  * represents the consumption of possible compute capacity and allows the
1284  * HMP migration's simple threshold migration strategy to interact more
1285  * predictably with CPUFreq's asynchronous compute capacity changes.
1286  */
1287 #define SCHED_FREQSCALE_SHIFT 10
1288 struct cpufreq_extents {
1289         u32 curr_scale;
1290         u32 min;
1291         u32 max;
1292         u32 flags;
1293 };
1294 /* Flag set when the governor in use only allows one frequency.
1295  * Disables scaling.
1296  */
1297 #define SCHED_LOAD_FREQINVAR_SINGLEFREQ 0x01
1298
1299 static struct cpufreq_extents freq_scale[CONFIG_NR_CPUS];
1300 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1301 #endif /* CONFIG_HMP_VARIABLE_SCALE */
1302
1303 /* We can represent the historical contribution to runnable average as the
1304  * coefficients of a geometric series.  To do this we sub-divide our runnable
1305  * history into segments of approximately 1ms (1024us); label the segment that
1306  * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
1307  *
1308  * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
1309  *      p0            p1           p2
1310  *     (now)       (~1ms ago)  (~2ms ago)
1311  *
1312  * Let u_i denote the fraction of p_i that the entity was runnable.
1313  *
1314  * We then designate the fractions u_i as our co-efficients, yielding the
1315  * following representation of historical load:
1316  *   u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
1317  *
1318  * We choose y based on the with of a reasonably scheduling period, fixing:
1319  *   y^32 = 0.5
1320  *
1321  * This means that the contribution to load ~32ms ago (u_32) will be weighted
1322  * approximately half as much as the contribution to load within the last ms
1323  * (u_0).
1324  *
1325  * When a period "rolls over" and we have new u_0`, multiplying the previous
1326  * sum again by y is sufficient to update:
1327  *   load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
1328  *            = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
1329  */
1330 static __always_inline int __update_entity_runnable_avg(u64 now,
1331                                                         struct sched_avg *sa,
1332                                                         int runnable,
1333                                                         int running,
1334                                                         int cpu)
1335 {
1336         u64 delta, periods;
1337         u32 runnable_contrib;
1338         int delta_w, decayed = 0;
1339 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1340         u64 scaled_delta;
1341         u32 scaled_runnable_contrib;
1342         int scaled_delta_w;
1343         u32 curr_scale = 1024;
1344 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1345
1346         delta = now - sa->last_runnable_update;
1347 #ifdef CONFIG_HMP_VARIABLE_SCALE
1348         delta = hmp_variable_scale_convert(delta);
1349 #endif
1350         /*
1351          * This should only happen when time goes backwards, which it
1352          * unfortunately does during sched clock init when we swap over to TSC.
1353          */
1354         if ((s64)delta < 0) {
1355                 sa->last_runnable_update = now;
1356                 return 0;
1357         }
1358
1359         /*
1360          * Use 1024ns as the unit of measurement since it's a reasonable
1361          * approximation of 1us and fast to compute.
1362          */
1363         delta >>= 10;
1364         if (!delta)
1365                 return 0;
1366         sa->last_runnable_update = now;
1367
1368 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1369         /* retrieve scale factor for load */
1370         if (hmp_data.freqinvar_load_scale_enabled)
1371                 curr_scale = freq_scale[cpu].curr_scale;
1372 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1373
1374         /* delta_w is the amount already accumulated against our next period */
1375         delta_w = sa->runnable_avg_period % 1024;
1376         if (delta + delta_w >= 1024) {
1377                 /* period roll-over */
1378                 decayed = 1;
1379
1380                 /*
1381                  * Now that we know we're crossing a period boundary, figure
1382                  * out how much from delta we need to complete the current
1383                  * period and accrue it.
1384                  */
1385                 delta_w = 1024 - delta_w;
1386                 /* scale runnable time if necessary */
1387 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1388                 scaled_delta_w = (delta_w * curr_scale)
1389                                 >> SCHED_FREQSCALE_SHIFT;
1390                 if (runnable)
1391                         sa->runnable_avg_sum += scaled_delta_w;
1392                 if (running)
1393                         sa->usage_avg_sum += scaled_delta_w;
1394 #else
1395                 if (runnable)
1396                         sa->runnable_avg_sum += delta_w;
1397                 if (running)
1398                         sa->usage_avg_sum += delta_w;
1399 #endif /* #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1400                 sa->runnable_avg_period += delta_w;
1401
1402                 delta -= delta_w;
1403
1404                 /* Figure out how many additional periods this update spans */
1405                 periods = delta / 1024;
1406                 delta %= 1024;
1407                 /* decay the load we have accumulated so far */
1408                 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
1409                                                   periods + 1);
1410                 sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
1411                                                      periods + 1);
1412                 sa->usage_avg_sum = decay_load(sa->usage_avg_sum, periods + 1);
1413                 /* add the contribution from this period */
1414                 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
1415                 runnable_contrib = __compute_runnable_contrib(periods);
1416                 /* Apply load scaling if necessary.
1417                  * Note that multiplying the whole series is same as
1418                  * multiplying all terms
1419                  */
1420 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1421                 scaled_runnable_contrib = (runnable_contrib * curr_scale)
1422                                 >> SCHED_FREQSCALE_SHIFT;
1423                 if (runnable)
1424                         sa->runnable_avg_sum += scaled_runnable_contrib;
1425                 if (running)
1426                         sa->usage_avg_sum += scaled_runnable_contrib;
1427 #else
1428                 if (runnable)
1429                         sa->runnable_avg_sum += runnable_contrib;
1430                 if (running)
1431                         sa->usage_avg_sum += runnable_contrib;
1432 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1433                 sa->runnable_avg_period += runnable_contrib;
1434         }
1435
1436         /* Remainder of delta accrued against u_0` */
1437         /* scale if necessary */
1438 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1439         scaled_delta = ((delta * curr_scale) >> SCHED_FREQSCALE_SHIFT);
1440         if (runnable)
1441                 sa->runnable_avg_sum += scaled_delta;
1442         if (running)
1443                 sa->usage_avg_sum += scaled_delta;
1444 #else
1445         if (runnable)
1446                 sa->runnable_avg_sum += delta;
1447         if (running)
1448                 sa->usage_avg_sum += delta;
1449 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1450         sa->runnable_avg_period += delta;
1451
1452         return decayed;
1453 }
1454
1455 /* Synchronize an entity's decay with its parenting cfs_rq.*/
1456 static inline u64 __synchronize_entity_decay(struct sched_entity *se)
1457 {
1458         struct cfs_rq *cfs_rq = cfs_rq_of(se);
1459         u64 decays = atomic64_read(&cfs_rq->decay_counter);
1460
1461         decays -= se->avg.decay_count;
1462         if (!decays)
1463                 return 0;
1464
1465         se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
1466         se->avg.decay_count = 0;
1467
1468         return decays;
1469 }
1470
1471 #ifdef CONFIG_FAIR_GROUP_SCHED
1472 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1473                                                  int force_update)
1474 {
1475         struct task_group *tg = cfs_rq->tg;
1476         s64 tg_contrib;
1477
1478         tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
1479         tg_contrib -= cfs_rq->tg_load_contrib;
1480
1481         if (force_update || abs64(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
1482                 atomic64_add(tg_contrib, &tg->load_avg);
1483                 cfs_rq->tg_load_contrib += tg_contrib;
1484         }
1485 }
1486
1487 /*
1488  * Aggregate cfs_rq runnable averages into an equivalent task_group
1489  * representation for computing load contributions.
1490  */
1491 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1492                                                   struct cfs_rq *cfs_rq)
1493 {
1494         struct task_group *tg = cfs_rq->tg;
1495         long contrib, usage_contrib;
1496
1497         /* The fraction of a cpu used by this cfs_rq */
1498         contrib = div_u64(sa->runnable_avg_sum << NICE_0_SHIFT,
1499                           sa->runnable_avg_period + 1);
1500         contrib -= cfs_rq->tg_runnable_contrib;
1501
1502         usage_contrib = div_u64(sa->usage_avg_sum << NICE_0_SHIFT,
1503                                 sa->runnable_avg_period + 1);
1504         usage_contrib -= cfs_rq->tg_usage_contrib;
1505
1506         /*
1507          * contrib/usage at this point represent deltas, only update if they
1508          * are substantive.
1509          */
1510         if ((abs(contrib) > cfs_rq->tg_runnable_contrib / 64) ||
1511             (abs(usage_contrib) > cfs_rq->tg_usage_contrib / 64)) {
1512                 atomic_add(contrib, &tg->runnable_avg);
1513                 cfs_rq->tg_runnable_contrib += contrib;
1514
1515                 atomic_add(usage_contrib, &tg->usage_avg);
1516                 cfs_rq->tg_usage_contrib += usage_contrib;
1517         }
1518 }
1519
1520 static inline void __update_group_entity_contrib(struct sched_entity *se)
1521 {
1522         struct cfs_rq *cfs_rq = group_cfs_rq(se);
1523         struct task_group *tg = cfs_rq->tg;
1524         int runnable_avg;
1525
1526         u64 contrib;
1527
1528         contrib = cfs_rq->tg_load_contrib * tg->shares;
1529         se->avg.load_avg_contrib = div64_u64(contrib,
1530                                              atomic64_read(&tg->load_avg) + 1);
1531
1532         /*
1533          * For group entities we need to compute a correction term in the case
1534          * that they are consuming <1 cpu so that we would contribute the same
1535          * load as a task of equal weight.
1536          *
1537          * Explicitly co-ordinating this measurement would be expensive, but
1538          * fortunately the sum of each cpus contribution forms a usable
1539          * lower-bound on the true value.
1540          *
1541          * Consider the aggregate of 2 contributions.  Either they are disjoint
1542          * (and the sum represents true value) or they are disjoint and we are
1543          * understating by the aggregate of their overlap.
1544          *
1545          * Extending this to N cpus, for a given overlap, the maximum amount we
1546          * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
1547          * cpus that overlap for this interval and w_i is the interval width.
1548          *
1549          * On a small machine; the first term is well-bounded which bounds the
1550          * total error since w_i is a subset of the period.  Whereas on a
1551          * larger machine, while this first term can be larger, if w_i is the
1552          * of consequential size guaranteed to see n_i*w_i quickly converge to
1553          * our upper bound of 1-cpu.
1554          */
1555         runnable_avg = atomic_read(&tg->runnable_avg);
1556         if (runnable_avg < NICE_0_LOAD) {
1557                 se->avg.load_avg_contrib *= runnable_avg;
1558                 se->avg.load_avg_contrib >>= NICE_0_SHIFT;
1559         }
1560 }
1561 #else
1562 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1563                                                  int force_update) {}
1564 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1565                                                   struct cfs_rq *cfs_rq) {}
1566 static inline void __update_group_entity_contrib(struct sched_entity *se) {}
1567 #endif
1568
1569 static inline void __update_task_entity_contrib(struct sched_entity *se)
1570 {
1571         u32 contrib;
1572
1573         /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
1574         contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
1575         contrib /= (se->avg.runnable_avg_period + 1);
1576         se->avg.load_avg_contrib = scale_load(contrib);
1577         trace_sched_task_load_contrib(task_of(se), se->avg.load_avg_contrib);
1578         contrib = se->avg.runnable_avg_sum * scale_load_down(NICE_0_LOAD);
1579         contrib /= (se->avg.runnable_avg_period + 1);
1580         se->avg.load_avg_ratio = scale_load(contrib);
1581         trace_sched_task_runnable_ratio(task_of(se), se->avg.load_avg_ratio);
1582 }
1583
1584 /* Compute the current contribution to load_avg by se, return any delta */
1585 static long __update_entity_load_avg_contrib(struct sched_entity *se, long *ratio)
1586 {
1587         long old_contrib = se->avg.load_avg_contrib;
1588         long old_ratio   = se->avg.load_avg_ratio;
1589
1590         if (entity_is_task(se)) {
1591                 __update_task_entity_contrib(se);
1592         } else {
1593                 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
1594                 __update_group_entity_contrib(se);
1595         }
1596
1597         if (ratio)
1598                 *ratio = se->avg.load_avg_ratio - old_ratio;
1599         return se->avg.load_avg_contrib - old_contrib;
1600 }
1601
1602 static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
1603                                                  long load_contrib)
1604 {
1605         if (likely(load_contrib < cfs_rq->blocked_load_avg))
1606                 cfs_rq->blocked_load_avg -= load_contrib;
1607         else
1608                 cfs_rq->blocked_load_avg = 0;
1609 }
1610
1611 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
1612
1613 /* Update a sched_entity's runnable average */
1614 static inline void update_entity_load_avg(struct sched_entity *se,
1615                                           int update_cfs_rq)
1616 {
1617         struct cfs_rq *cfs_rq = cfs_rq_of(se);
1618         long contrib_delta, ratio_delta;
1619         u64 now;
1620         int cpu = -1;   /* not used in normal case */
1621
1622 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1623         cpu = cfs_rq->rq->cpu;
1624 #endif
1625         /*
1626          * For a group entity we need to use their owned cfs_rq_clock_task() in
1627          * case they are the parent of a throttled hierarchy.
1628          */
1629         if (entity_is_task(se))
1630                 now = cfs_rq_clock_task(cfs_rq);
1631         else
1632                 now = cfs_rq_clock_task(group_cfs_rq(se));
1633
1634         if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq,
1635                         cfs_rq->curr == se, cpu))
1636                 return;
1637
1638         contrib_delta = __update_entity_load_avg_contrib(se, &ratio_delta);
1639
1640         if (!update_cfs_rq)
1641                 return;
1642
1643         if (se->on_rq) {
1644                 cfs_rq->runnable_load_avg += contrib_delta;
1645                 rq_of(cfs_rq)->avg.load_avg_ratio += ratio_delta;
1646         } else {
1647                 subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
1648         }
1649 }
1650
1651 /*
1652  * Decay the load contributed by all blocked children and account this so that
1653  * their contribution may appropriately discounted when they wake up.
1654  */
1655 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
1656 {
1657         u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
1658         u64 decays;
1659
1660         decays = now - cfs_rq->last_decay;
1661         if (!decays && !force_update)
1662                 return;
1663
1664         if (atomic64_read(&cfs_rq->removed_load)) {
1665                 u64 removed_load = atomic64_xchg(&cfs_rq->removed_load, 0);
1666                 subtract_blocked_load_contrib(cfs_rq, removed_load);
1667         }
1668
1669         if (decays) {
1670                 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
1671                                                       decays);
1672                 atomic64_add(decays, &cfs_rq->decay_counter);
1673                 cfs_rq->last_decay = now;
1674         }
1675
1676         __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
1677 }
1678
1679 static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
1680 {
1681         int cpu = -1;   /* not used in normal case */
1682
1683 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1684         cpu = rq->cpu;
1685 #endif
1686         __update_entity_runnable_avg(rq->clock_task, &rq->avg, runnable,
1687                                      runnable, cpu);
1688         __update_tg_runnable_avg(&rq->avg, &rq->cfs);
1689         trace_sched_rq_runnable_ratio(cpu_of(rq), rq->avg.load_avg_ratio);
1690         trace_sched_rq_runnable_load(cpu_of(rq), rq->cfs.runnable_load_avg);
1691         trace_sched_rq_nr_running(cpu_of(rq), rq->nr_running, rq->nr_iowait.counter);
1692 }
1693
1694 /* Add the load generated by se into cfs_rq's child load-average */
1695 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
1696                                                   struct sched_entity *se,
1697                                                   int wakeup)
1698 {
1699         /*
1700          * We track migrations using entity decay_count <= 0, on a wake-up
1701          * migration we use a negative decay count to track the remote decays
1702          * accumulated while sleeping.
1703          */
1704         if (unlikely(se->avg.decay_count <= 0)) {
1705                 se->avg.last_runnable_update = rq_of(cfs_rq)->clock_task;
1706                 if (se->avg.decay_count) {
1707                         /*
1708                          * In a wake-up migration we have to approximate the
1709                          * time sleeping.  This is because we can't synchronize
1710                          * clock_task between the two cpus, and it is not
1711                          * guaranteed to be read-safe.  Instead, we can
1712                          * approximate this using our carried decays, which are
1713                          * explicitly atomically readable.
1714                          */
1715                         se->avg.last_runnable_update -= (-se->avg.decay_count)
1716                                                         << 20;
1717                         update_entity_load_avg(se, 0);
1718                         /* Indicate that we're now synchronized and on-rq */
1719                         se->avg.decay_count = 0;
1720                 }
1721                 wakeup = 0;
1722         } else {
1723                 __synchronize_entity_decay(se);
1724         }
1725
1726         /* migrated tasks did not contribute to our blocked load */
1727         if (wakeup) {
1728                 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
1729                 update_entity_load_avg(se, 0);
1730         }
1731
1732         cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
1733         rq_of(cfs_rq)->avg.load_avg_ratio += se->avg.load_avg_ratio;
1734
1735         /* we force update consideration on load-balancer moves */
1736         update_cfs_rq_blocked_load(cfs_rq, !wakeup);
1737 }
1738
1739 /*
1740  * Remove se's load from this cfs_rq child load-average, if the entity is
1741  * transitioning to a blocked state we track its projected decay using
1742  * blocked_load_avg.
1743  */
1744 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
1745                                                   struct sched_entity *se,
1746                                                   int sleep)
1747 {
1748         update_entity_load_avg(se, 1);
1749         /* we force update consideration on load-balancer moves */
1750         update_cfs_rq_blocked_load(cfs_rq, !sleep);
1751
1752         cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
1753         rq_of(cfs_rq)->avg.load_avg_ratio -= se->avg.load_avg_ratio;
1754
1755         if (sleep) {
1756                 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
1757                 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
1758         } /* migrations, e.g. sleep=0 leave decay_count == 0 */
1759 }
1760
1761 /*
1762  * Update the rq's load with the elapsed running time before entering
1763  * idle. if the last scheduled task is not a CFS task, idle_enter will
1764  * be the only way to update the runnable statistic.
1765  */
1766 void idle_enter_fair(struct rq *this_rq)
1767 {
1768         update_rq_runnable_avg(this_rq, 1);
1769 }
1770
1771 /*
1772  * Update the rq's load with the elapsed idle time before a task is
1773  * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
1774  * be the only way to update the runnable statistic.
1775  */
1776 void idle_exit_fair(struct rq *this_rq)
1777 {
1778         update_rq_runnable_avg(this_rq, 0);
1779 }
1780
1781 #else
1782 static inline void update_entity_load_avg(struct sched_entity *se,
1783                                           int update_cfs_rq) {}
1784 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
1785 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
1786                                            struct sched_entity *se,
1787                                            int wakeup) {}
1788 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
1789                                            struct sched_entity *se,
1790                                            int sleep) {}
1791 static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
1792                                               int force_update) {}
1793 #endif
1794
1795 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
1796 {
1797 #ifdef CONFIG_SCHEDSTATS
1798         struct task_struct *tsk = NULL;
1799
1800         if (entity_is_task(se))
1801                 tsk = task_of(se);
1802
1803         if (se->statistics.sleep_start) {
1804                 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
1805
1806                 if ((s64)delta < 0)
1807                         delta = 0;
1808
1809                 if (unlikely(delta > se->statistics.sleep_max))
1810                         se->statistics.sleep_max = delta;
1811
1812                 se->statistics.sleep_start = 0;
1813                 se->statistics.sum_sleep_runtime += delta;
1814
1815                 if (tsk) {
1816                         account_scheduler_latency(tsk, delta >> 10, 1);
1817                         trace_sched_stat_sleep(tsk, delta);
1818                 }
1819         }
1820         if (se->statistics.block_start) {
1821                 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
1822
1823                 if ((s64)delta < 0)
1824                         delta = 0;
1825
1826                 if (unlikely(delta > se->statistics.block_max))
1827                         se->statistics.block_max = delta;
1828
1829                 se->statistics.block_start = 0;
1830                 se->statistics.sum_sleep_runtime += delta;
1831
1832                 if (tsk) {
1833                         if (tsk->in_iowait) {
1834                                 se->statistics.iowait_sum += delta;
1835                                 se->statistics.iowait_count++;
1836                                 trace_sched_stat_iowait(tsk, delta);
1837                         }
1838
1839                         trace_sched_stat_blocked(tsk, delta);
1840
1841                         /*
1842                          * Blocking time is in units of nanosecs, so shift by
1843                          * 20 to get a milliseconds-range estimation of the
1844                          * amount of time that the task spent sleeping:
1845                          */
1846                         if (unlikely(prof_on == SLEEP_PROFILING)) {
1847                                 profile_hits(SLEEP_PROFILING,
1848                                                 (void *)get_wchan(tsk),
1849                                                 delta >> 20);
1850                         }
1851                         account_scheduler_latency(tsk, delta >> 10, 0);
1852                 }
1853         }
1854 #endif
1855 }
1856
1857 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1858 {
1859 #ifdef CONFIG_SCHED_DEBUG
1860         s64 d = se->vruntime - cfs_rq->min_vruntime;
1861
1862         if (d < 0)
1863                 d = -d;
1864
1865         if (d > 3*sysctl_sched_latency)
1866                 schedstat_inc(cfs_rq, nr_spread_over);
1867 #endif
1868 }
1869
1870 static void
1871 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1872 {
1873         u64 vruntime = cfs_rq->min_vruntime;
1874
1875         /*
1876          * The 'current' period is already promised to the current tasks,
1877          * however the extra weight of the new task will slow them down a
1878          * little, place the new task so that it fits in the slot that
1879          * stays open at the end.
1880          */
1881         if (initial && sched_feat(START_DEBIT))
1882                 vruntime += sched_vslice(cfs_rq, se);
1883
1884         /* sleeps up to a single latency don't count. */
1885         if (!initial) {
1886                 unsigned long thresh = sysctl_sched_latency;
1887
1888                 /*
1889                  * Halve their sleep time's effect, to allow
1890                  * for a gentler effect of sleepers:
1891                  */
1892                 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1893                         thresh >>= 1;
1894
1895                 vruntime -= thresh;
1896         }
1897
1898         /* ensure we never gain time by being placed backwards. */
1899         se->vruntime = max_vruntime(se->vruntime, vruntime);
1900 }
1901
1902 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1903
1904 static void
1905 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1906 {
1907         /*
1908          * Update the normalized vruntime before updating min_vruntime
1909          * through callig update_curr().
1910          */
1911         if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
1912                 se->vruntime += cfs_rq->min_vruntime;
1913
1914         /*
1915          * Update run-time statistics of the 'current'.
1916          */
1917         update_curr(cfs_rq);
1918         enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
1919         account_entity_enqueue(cfs_rq, se);
1920         update_cfs_shares(cfs_rq);
1921
1922         if (flags & ENQUEUE_WAKEUP) {
1923                 place_entity(cfs_rq, se, 0);
1924                 enqueue_sleeper(cfs_rq, se);
1925         }
1926
1927         update_stats_enqueue(cfs_rq, se);
1928         check_spread(cfs_rq, se);
1929         if (se != cfs_rq->curr)
1930                 __enqueue_entity(cfs_rq, se);
1931         se->on_rq = 1;
1932
1933         if (cfs_rq->nr_running == 1) {
1934                 list_add_leaf_cfs_rq(cfs_rq);
1935                 check_enqueue_throttle(cfs_rq);
1936         }
1937 }
1938
1939 static void __clear_buddies_last(struct sched_entity *se)
1940 {
1941         for_each_sched_entity(se) {
1942                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1943                 if (cfs_rq->last == se)
1944                         cfs_rq->last = NULL;
1945                 else
1946                         break;
1947         }
1948 }
1949
1950 static void __clear_buddies_next(struct sched_entity *se)
1951 {
1952         for_each_sched_entity(se) {
1953                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1954                 if (cfs_rq->next == se)
1955                         cfs_rq->next = NULL;
1956                 else
1957                         break;
1958         }
1959 }
1960
1961 static void __clear_buddies_skip(struct sched_entity *se)
1962 {
1963         for_each_sched_entity(se) {
1964                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1965                 if (cfs_rq->skip == se)
1966                         cfs_rq->skip = NULL;
1967                 else
1968                         break;
1969         }
1970 }
1971
1972 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1973 {
1974         if (cfs_rq->last == se)
1975                 __clear_buddies_last(se);
1976
1977         if (cfs_rq->next == se)
1978                 __clear_buddies_next(se);
1979
1980         if (cfs_rq->skip == se)
1981                 __clear_buddies_skip(se);
1982 }
1983
1984 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1985
1986 static void
1987 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1988 {
1989         /*
1990          * Update run-time statistics of the 'current'.
1991          */
1992         update_curr(cfs_rq);
1993         dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
1994
1995         update_stats_dequeue(cfs_rq, se);
1996         if (flags & DEQUEUE_SLEEP) {
1997 #ifdef CONFIG_SCHEDSTATS
1998                 if (entity_is_task(se)) {
1999                         struct task_struct *tsk = task_of(se);
2000
2001                         if (tsk->state & TASK_INTERRUPTIBLE)
2002                                 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
2003                         if (tsk->state & TASK_UNINTERRUPTIBLE)
2004                                 se->statistics.block_start = rq_of(cfs_rq)->clock;
2005                 }
2006 #endif
2007         }
2008
2009         clear_buddies(cfs_rq, se);
2010
2011         if (se != cfs_rq->curr)
2012                 __dequeue_entity(cfs_rq, se);
2013         se->on_rq = 0;
2014         account_entity_dequeue(cfs_rq, se);
2015
2016         /*
2017          * Normalize the entity after updating the min_vruntime because the
2018          * update can refer to the ->curr item and we need to reflect this
2019          * movement in our normalized position.
2020          */
2021         if (!(flags & DEQUEUE_SLEEP))
2022                 se->vruntime -= cfs_rq->min_vruntime;
2023
2024         /* return excess runtime on last dequeue */
2025         return_cfs_rq_runtime(cfs_rq);
2026
2027         update_min_vruntime(cfs_rq);
2028         update_cfs_shares(cfs_rq);
2029 }
2030
2031 /*
2032  * Preempt the current task with a newly woken task if needed:
2033  */
2034 static void
2035 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
2036 {
2037         unsigned long ideal_runtime, delta_exec;
2038         struct sched_entity *se;
2039         s64 delta;
2040
2041         ideal_runtime = sched_slice(cfs_rq, curr);
2042         delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
2043         if (delta_exec > ideal_runtime) {
2044                 resched_task(rq_of(cfs_rq)->curr);
2045                 /*
2046                  * The current task ran long enough, ensure it doesn't get
2047                  * re-elected due to buddy favours.
2048                  */
2049                 clear_buddies(cfs_rq, curr);
2050                 return;
2051         }
2052
2053         /*
2054          * Ensure that a task that missed wakeup preemption by a
2055          * narrow margin doesn't have to wait for a full slice.
2056          * This also mitigates buddy induced latencies under load.
2057          */
2058         if (delta_exec < sysctl_sched_min_granularity)
2059                 return;
2060
2061         se = __pick_first_entity(cfs_rq);
2062         delta = curr->vruntime - se->vruntime;
2063
2064         if (delta < 0)
2065                 return;
2066
2067         if (delta > ideal_runtime)
2068                 resched_task(rq_of(cfs_rq)->curr);
2069 }
2070
2071 static void
2072 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
2073 {
2074         /* 'current' is not kept within the tree. */
2075         if (se->on_rq) {
2076                 /*
2077                  * Any task has to be enqueued before it get to execute on
2078                  * a CPU. So account for the time it spent waiting on the
2079                  * runqueue.
2080                  */
2081                 update_stats_wait_end(cfs_rq, se);
2082                 __dequeue_entity(cfs_rq, se);
2083                 update_entity_load_avg(se, 1);
2084         }
2085
2086         update_stats_curr_start(cfs_rq, se);
2087         cfs_rq->curr = se;
2088 #ifdef CONFIG_SCHEDSTATS
2089         /*
2090          * Track our maximum slice length, if the CPU's load is at
2091          * least twice that of our own weight (i.e. dont track it
2092          * when there are only lesser-weight tasks around):
2093          */
2094         if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
2095                 se->statistics.slice_max = max(se->statistics.slice_max,
2096                         se->sum_exec_runtime - se->prev_sum_exec_runtime);
2097         }
2098 #endif
2099         se->prev_sum_exec_runtime = se->sum_exec_runtime;
2100 }
2101
2102 static int
2103 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
2104
2105 /*
2106  * Pick the next process, keeping these things in mind, in this order:
2107  * 1) keep things fair between processes/task groups
2108  * 2) pick the "next" process, since someone really wants that to run
2109  * 3) pick the "last" process, for cache locality
2110  * 4) do not run the "skip" process, if something else is available
2111  */
2112 static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
2113 {
2114         struct sched_entity *se = __pick_first_entity(cfs_rq);
2115         struct sched_entity *left = se;
2116
2117         /*
2118          * Avoid running the skip buddy, if running something else can
2119          * be done without getting too unfair.
2120          */
2121         if (cfs_rq->skip == se) {
2122                 struct sched_entity *second = __pick_next_entity(se);
2123                 if (second && wakeup_preempt_entity(second, left) < 1)
2124                         se = second;
2125         }
2126
2127         /*
2128          * Prefer last buddy, try to return the CPU to a preempted task.
2129          */
2130         if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
2131                 se = cfs_rq->last;
2132
2133         /*
2134          * Someone really wants this to run. If it's not unfair, run it.
2135          */
2136         if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
2137                 se = cfs_rq->next;
2138
2139         clear_buddies(cfs_rq, se);
2140
2141         return se;
2142 }
2143
2144 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
2145
2146 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
2147 {
2148         /*
2149          * If still on the runqueue then deactivate_task()
2150          * was not called and update_curr() has to be done:
2151          */
2152         if (prev->on_rq)
2153                 update_curr(cfs_rq);
2154
2155         /* throttle cfs_rqs exceeding runtime */
2156         check_cfs_rq_runtime(cfs_rq);
2157
2158         check_spread(cfs_rq, prev);
2159         if (prev->on_rq) {
2160                 update_stats_wait_start(cfs_rq, prev);
2161                 /* Put 'current' back into the tree. */
2162                 __enqueue_entity(cfs_rq, prev);
2163                 /* in !on_rq case, update occurred at dequeue */
2164                 update_entity_load_avg(prev, 1);
2165         }
2166         cfs_rq->curr = NULL;
2167 }
2168
2169 static void
2170 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
2171 {
2172         /*
2173          * Update run-time statistics of the 'current'.
2174          */
2175         update_curr(cfs_rq);
2176
2177         /*
2178          * Ensure that runnable average is periodically updated.
2179          */
2180         update_entity_load_avg(curr, 1);
2181         update_cfs_rq_blocked_load(cfs_rq, 1);
2182
2183 #ifdef CONFIG_SCHED_HRTICK
2184         /*
2185          * queued ticks are scheduled to match the slice, so don't bother
2186          * validating it and just reschedule.
2187          */
2188         if (queued) {
2189                 resched_task(rq_of(cfs_rq)->curr);
2190                 return;
2191         }
2192         /*
2193          * don't let the period tick interfere with the hrtick preemption
2194          */
2195         if (!sched_feat(DOUBLE_TICK) &&
2196                         hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
2197                 return;
2198 #endif
2199
2200         if (cfs_rq->nr_running > 1)
2201                 check_preempt_tick(cfs_rq, curr);
2202 }
2203
2204
2205 /**************************************************
2206  * CFS bandwidth control machinery
2207  */
2208
2209 #ifdef CONFIG_CFS_BANDWIDTH
2210
2211 #ifdef HAVE_JUMP_LABEL
2212 static struct static_key __cfs_bandwidth_used;
2213
2214 static inline bool cfs_bandwidth_used(void)
2215 {
2216         return static_key_false(&__cfs_bandwidth_used);
2217 }
2218
2219 void account_cfs_bandwidth_used(int enabled, int was_enabled)
2220 {
2221         /* only need to count groups transitioning between enabled/!enabled */
2222         if (enabled && !was_enabled)
2223                 static_key_slow_inc(&__cfs_bandwidth_used);
2224         else if (!enabled && was_enabled)
2225                 static_key_slow_dec(&__cfs_bandwidth_used);
2226 }
2227 #else /* HAVE_JUMP_LABEL */
2228 static bool cfs_bandwidth_used(void)
2229 {
2230         return true;
2231 }
2232
2233 void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
2234 #endif /* HAVE_JUMP_LABEL */
2235
2236 /*
2237  * default period for cfs group bandwidth.
2238  * default: 0.1s, units: nanoseconds
2239  */
2240 static inline u64 default_cfs_period(void)
2241 {
2242         return 100000000ULL;
2243 }
2244
2245 static inline u64 sched_cfs_bandwidth_slice(void)
2246 {
2247         return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
2248 }
2249
2250 /*
2251  * Replenish runtime according to assigned quota and update expiration time.
2252  * We use sched_clock_cpu directly instead of rq->clock to avoid adding
2253  * additional synchronization around rq->lock.
2254  *
2255  * requires cfs_b->lock
2256  */
2257 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
2258 {
2259         u64 now;
2260
2261         if (cfs_b->quota == RUNTIME_INF)
2262                 return;
2263
2264         now = sched_clock_cpu(smp_processor_id());
2265         cfs_b->runtime = cfs_b->quota;
2266         cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
2267 }
2268
2269 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2270 {
2271         return &tg->cfs_bandwidth;
2272 }
2273
2274 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
2275 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
2276 {
2277         if (unlikely(cfs_rq->throttle_count))
2278                 return cfs_rq->throttled_clock_task;
2279
2280         return rq_of(cfs_rq)->clock_task - cfs_rq->throttled_clock_task_time;
2281 }
2282
2283 /* returns 0 on failure to allocate runtime */
2284 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2285 {
2286         struct task_group *tg = cfs_rq->tg;
2287         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
2288         u64 amount = 0, min_amount, expires;
2289
2290         /* note: this is a positive sum as runtime_remaining <= 0 */
2291         min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
2292
2293         raw_spin_lock(&cfs_b->lock);
2294         if (cfs_b->quota == RUNTIME_INF)
2295                 amount = min_amount;
2296         else {
2297                 /*
2298                  * If the bandwidth pool has become inactive, then at least one
2299                  * period must have elapsed since the last consumption.
2300                  * Refresh the global state and ensure bandwidth timer becomes
2301                  * active.
2302                  */
2303                 if (!cfs_b->timer_active) {
2304                         __refill_cfs_bandwidth_runtime(cfs_b);
2305                         __start_cfs_bandwidth(cfs_b);
2306                 }
2307
2308                 if (cfs_b->runtime > 0) {
2309                         amount = min(cfs_b->runtime, min_amount);
2310                         cfs_b->runtime -= amount;
2311                         cfs_b->idle = 0;
2312                 }
2313         }
2314         expires = cfs_b->runtime_expires;
2315         raw_spin_unlock(&cfs_b->lock);
2316
2317         cfs_rq->runtime_remaining += amount;
2318         /*
2319          * we may have advanced our local expiration to account for allowed
2320          * spread between our sched_clock and the one on which runtime was
2321          * issued.
2322          */
2323         if ((s64)(expires - cfs_rq->runtime_expires) > 0)
2324                 cfs_rq->runtime_expires = expires;
2325
2326         return cfs_rq->runtime_remaining > 0;
2327 }
2328
2329 /*
2330  * Note: This depends on the synchronization provided by sched_clock and the
2331  * fact that rq->clock snapshots this value.
2332  */
2333 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2334 {
2335         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2336         struct rq *rq = rq_of(cfs_rq);
2337
2338         /* if the deadline is ahead of our clock, nothing to do */
2339         if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
2340                 return;
2341
2342         if (cfs_rq->runtime_remaining < 0)
2343                 return;
2344
2345         /*
2346          * If the local deadline has passed we have to consider the
2347          * possibility that our sched_clock is 'fast' and the global deadline
2348          * has not truly expired.
2349          *
2350          * Fortunately we can check determine whether this the case by checking
2351          * whether the global deadline has advanced.
2352          */
2353
2354         if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
2355                 /* extend local deadline, drift is bounded above by 2 ticks */
2356                 cfs_rq->runtime_expires += TICK_NSEC;
2357         } else {
2358                 /* global deadline is ahead, expiration has passed */
2359                 cfs_rq->runtime_remaining = 0;
2360         }
2361 }
2362
2363 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
2364                                      unsigned long delta_exec)
2365 {
2366         /* dock delta_exec before expiring quota (as it could span periods) */
2367         cfs_rq->runtime_remaining -= delta_exec;
2368         expire_cfs_rq_runtime(cfs_rq);
2369
2370         if (likely(cfs_rq->runtime_remaining > 0))
2371                 return;
2372
2373         /*
2374          * if we're unable to extend our runtime we resched so that the active
2375          * hierarchy can be throttled
2376          */
2377         if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
2378                 resched_task(rq_of(cfs_rq)->curr);
2379 }
2380
2381 static __always_inline
2382 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
2383 {
2384         if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
2385                 return;
2386
2387         __account_cfs_rq_runtime(cfs_rq, delta_exec);
2388 }
2389
2390 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2391 {
2392         return cfs_bandwidth_used() && cfs_rq->throttled;
2393 }
2394
2395 /* check whether cfs_rq, or any parent, is throttled */
2396 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2397 {
2398         return cfs_bandwidth_used() && cfs_rq->throttle_count;
2399 }
2400
2401 /*
2402  * Ensure that neither of the group entities corresponding to src_cpu or
2403  * dest_cpu are members of a throttled hierarchy when performing group
2404  * load-balance operations.
2405  */
2406 static inline int throttled_lb_pair(struct task_group *tg,
2407                                     int src_cpu, int dest_cpu)
2408 {
2409         struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
2410
2411         src_cfs_rq = tg->cfs_rq[src_cpu];
2412         dest_cfs_rq = tg->cfs_rq[dest_cpu];
2413
2414         return throttled_hierarchy(src_cfs_rq) ||
2415                throttled_hierarchy(dest_cfs_rq);
2416 }
2417
2418 /* updated child weight may affect parent so we have to do this bottom up */
2419 static int tg_unthrottle_up(struct task_group *tg, void *data)
2420 {
2421         struct rq *rq = data;
2422         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
2423
2424         cfs_rq->throttle_count--;
2425 #ifdef CONFIG_SMP
2426         if (!cfs_rq->throttle_count) {
2427                 /* adjust cfs_rq_clock_task() */
2428                 cfs_rq->throttled_clock_task_time += rq->clock_task -
2429                                              cfs_rq->throttled_clock_task;
2430         }
2431 #endif
2432
2433         return 0;
2434 }
2435
2436 static int tg_throttle_down(struct task_group *tg, void *data)
2437 {
2438         struct rq *rq = data;
2439         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
2440
2441         /* group is entering throttled state, stop time */
2442         if (!cfs_rq->throttle_count)
2443                 cfs_rq->throttled_clock_task = rq->clock_task;
2444         cfs_rq->throttle_count++;
2445
2446         return 0;
2447 }
2448
2449 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
2450 {
2451         struct rq *rq = rq_of(cfs_rq);
2452         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2453         struct sched_entity *se;
2454         long task_delta, dequeue = 1;
2455
2456         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2457
2458         /* freeze hierarchy runnable averages while throttled */
2459         rcu_read_lock();
2460         walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
2461         rcu_read_unlock();
2462
2463         task_delta = cfs_rq->h_nr_running;
2464         for_each_sched_entity(se) {
2465                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
2466                 /* throttled entity or throttle-on-deactivate */
2467                 if (!se->on_rq)
2468                         break;
2469
2470                 if (dequeue)
2471                         dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
2472                 qcfs_rq->h_nr_running -= task_delta;
2473
2474                 if (qcfs_rq->load.weight)
2475                         dequeue = 0;
2476         }
2477
2478         if (!se)
2479                 rq->nr_running -= task_delta;
2480
2481         cfs_rq->throttled = 1;
2482         cfs_rq->throttled_clock = rq->clock;
2483         raw_spin_lock(&cfs_b->lock);
2484         list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
2485         raw_spin_unlock(&cfs_b->lock);
2486 }
2487
2488 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
2489 {
2490         struct rq *rq = rq_of(cfs_rq);
2491         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2492         struct sched_entity *se;
2493         int enqueue = 1;
2494         long task_delta;
2495
2496         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2497
2498         cfs_rq->throttled = 0;
2499         raw_spin_lock(&cfs_b->lock);
2500         cfs_b->throttled_time += rq->clock - cfs_rq->throttled_clock;
2501         list_del_rcu(&cfs_rq->throttled_list);
2502         raw_spin_unlock(&cfs_b->lock);
2503
2504         update_rq_clock(rq);
2505         /* update hierarchical throttle state */
2506         walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
2507
2508         if (!cfs_rq->load.weight)
2509                 return;
2510
2511         task_delta = cfs_rq->h_nr_running;
2512         for_each_sched_entity(se) {
2513                 if (se->on_rq)
2514                         enqueue = 0;
2515
2516                 cfs_rq = cfs_rq_of(se);
2517                 if (enqueue)
2518                         enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
2519                 cfs_rq->h_nr_running += task_delta;
2520
2521                 if (cfs_rq_throttled(cfs_rq))
2522                         break;
2523         }
2524
2525         if (!se)
2526                 rq->nr_running += task_delta;
2527
2528         /* determine whether we need to wake up potentially idle cpu */
2529         if (rq->curr == rq->idle && rq->cfs.nr_running)
2530                 resched_task(rq->curr);
2531 }
2532
2533 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
2534                 u64 remaining, u64 expires)
2535 {
2536         struct cfs_rq *cfs_rq;
2537         u64 runtime = remaining;
2538
2539         rcu_read_lock();
2540         list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
2541                                 throttled_list) {
2542                 struct rq *rq = rq_of(cfs_rq);
2543
2544                 raw_spin_lock(&rq->lock);
2545                 if (!cfs_rq_throttled(cfs_rq))
2546                         goto next;
2547
2548                 runtime = -cfs_rq->runtime_remaining + 1;
2549                 if (runtime > remaining)
2550                         runtime = remaining;
2551                 remaining -= runtime;
2552
2553                 cfs_rq->runtime_remaining += runtime;
2554                 cfs_rq->runtime_expires = expires;
2555
2556                 /* we check whether we're throttled above */
2557                 if (cfs_rq->runtime_remaining > 0)
2558                         unthrottle_cfs_rq(cfs_rq);
2559
2560 next:
2561                 raw_spin_unlock(&rq->lock);
2562
2563                 if (!remaining)
2564                         break;
2565         }
2566         rcu_read_unlock();
2567
2568         return remaining;
2569 }
2570
2571 /*
2572  * Responsible for refilling a task_group's bandwidth and unthrottling its
2573  * cfs_rqs as appropriate. If there has been no activity within the last
2574  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
2575  * used to track this state.
2576  */
2577 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
2578 {
2579         u64 runtime, runtime_expires;
2580         int idle = 1, throttled;
2581
2582         raw_spin_lock(&cfs_b->lock);
2583         /* no need to continue the timer with no bandwidth constraint */
2584         if (cfs_b->quota == RUNTIME_INF)
2585                 goto out_unlock;
2586
2587         throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2588         /* idle depends on !throttled (for the case of a large deficit) */
2589         idle = cfs_b->idle && !throttled;
2590         cfs_b->nr_periods += overrun;
2591
2592         /* if we're going inactive then everything else can be deferred */
2593         if (idle)
2594                 goto out_unlock;
2595
2596         __refill_cfs_bandwidth_runtime(cfs_b);
2597
2598         if (!throttled) {
2599                 /* mark as potentially idle for the upcoming period */
2600                 cfs_b->idle = 1;
2601                 goto out_unlock;
2602         }
2603
2604         /* account preceding periods in which throttling occurred */
2605         cfs_b->nr_throttled += overrun;
2606
2607         /*
2608          * There are throttled entities so we must first use the new bandwidth
2609          * to unthrottle them before making it generally available.  This
2610          * ensures that all existing debts will be paid before a new cfs_rq is
2611          * allowed to run.
2612          */
2613         runtime = cfs_b->runtime;
2614         runtime_expires = cfs_b->runtime_expires;
2615         cfs_b->runtime = 0;
2616
2617         /*
2618          * This check is repeated as we are holding onto the new bandwidth
2619          * while we unthrottle.  This can potentially race with an unthrottled
2620          * group trying to acquire new bandwidth from the global pool.
2621          */
2622         while (throttled && runtime > 0) {
2623                 raw_spin_unlock(&cfs_b->lock);
2624                 /* we can't nest cfs_b->lock while distributing bandwidth */
2625                 runtime = distribute_cfs_runtime(cfs_b, runtime,
2626                                                  runtime_expires);
2627                 raw_spin_lock(&cfs_b->lock);
2628
2629                 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2630         }
2631
2632         /* return (any) remaining runtime */
2633         cfs_b->runtime = runtime;
2634         /*
2635          * While we are ensured activity in the period following an
2636          * unthrottle, this also covers the case in which the new bandwidth is
2637          * insufficient to cover the existing bandwidth deficit.  (Forcing the
2638          * timer to remain active while there are any throttled entities.)
2639          */
2640         cfs_b->idle = 0;
2641 out_unlock:
2642         if (idle)
2643                 cfs_b->timer_active = 0;
2644         raw_spin_unlock(&cfs_b->lock);
2645
2646         return idle;
2647 }
2648
2649 /* a cfs_rq won't donate quota below this amount */
2650 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2651 /* minimum remaining period time to redistribute slack quota */
2652 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2653 /* how long we wait to gather additional slack before distributing */
2654 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2655
2656 /* are we near the end of the current quota period? */
2657 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2658 {
2659         struct hrtimer *refresh_timer = &cfs_b->period_timer;
2660         u64 remaining;
2661
2662         /* if the call-back is running a quota refresh is already occurring */
2663         if (hrtimer_callback_running(refresh_timer))
2664                 return 1;
2665
2666         /* is a quota refresh about to occur? */
2667         remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2668         if (remaining < min_expire)
2669                 return 1;
2670
2671         return 0;
2672 }
2673
2674 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2675 {
2676         u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2677
2678         /* if there's a quota refresh soon don't bother with slack */
2679         if (runtime_refresh_within(cfs_b, min_left))
2680                 return;
2681
2682         start_bandwidth_timer(&cfs_b->slack_timer,
2683                                 ns_to_ktime(cfs_bandwidth_slack_period));
2684 }
2685
2686 /* we know any runtime found here is valid as update_curr() precedes return */
2687 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2688 {
2689         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2690         s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2691
2692         if (slack_runtime <= 0)
2693                 return;
2694
2695         raw_spin_lock(&cfs_b->lock);
2696         if (cfs_b->quota != RUNTIME_INF &&
2697             cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2698                 cfs_b->runtime += slack_runtime;
2699
2700                 /* we are under rq->lock, defer unthrottling using a timer */
2701                 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2702                     !list_empty(&cfs_b->throttled_cfs_rq))
2703                         start_cfs_slack_bandwidth(cfs_b);
2704         }
2705         raw_spin_unlock(&cfs_b->lock);
2706
2707         /* even if it's not valid for return we don't want to try again */
2708         cfs_rq->runtime_remaining -= slack_runtime;
2709 }
2710
2711 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2712 {
2713         if (!cfs_bandwidth_used())
2714                 return;
2715
2716         if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
2717                 return;
2718
2719         __return_cfs_rq_runtime(cfs_rq);
2720 }
2721
2722 /*
2723  * This is done with a timer (instead of inline with bandwidth return) since
2724  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2725  */
2726 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2727 {
2728         u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2729         u64 expires;
2730
2731         /* confirm we're still not at a refresh boundary */
2732         if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2733                 return;
2734
2735         raw_spin_lock(&cfs_b->lock);
2736         if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2737                 runtime = cfs_b->runtime;
2738                 cfs_b->runtime = 0;
2739         }
2740         expires = cfs_b->runtime_expires;
2741         raw_spin_unlock(&cfs_b->lock);
2742
2743         if (!runtime)
2744                 return;
2745
2746         runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2747
2748         raw_spin_lock(&cfs_b->lock);
2749         if (expires == cfs_b->runtime_expires)
2750                 cfs_b->runtime = runtime;
2751         raw_spin_unlock(&cfs_b->lock);
2752 }
2753
2754 /*
2755  * When a group wakes up we want to make sure that its quota is not already
2756  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2757  * runtime as update_curr() throttling can not not trigger until it's on-rq.
2758  */
2759 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2760 {
2761         if (!cfs_bandwidth_used())
2762                 return;
2763
2764         /* an active group must be handled by the update_curr()->put() path */
2765         if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2766                 return;
2767
2768         /* ensure the group is not already throttled */
2769         if (cfs_rq_throttled(cfs_rq))
2770                 return;
2771
2772         /* update runtime allocation */
2773         account_cfs_rq_runtime(cfs_rq, 0);
2774         if (cfs_rq->runtime_remaining <= 0)
2775                 throttle_cfs_rq(cfs_rq);
2776 }
2777
2778 /* conditionally throttle active cfs_rq's from put_prev_entity() */
2779 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2780 {
2781         if (!cfs_bandwidth_used())
2782                 return;
2783
2784         if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2785                 return;
2786
2787         /*
2788          * it's possible for a throttled entity to be forced into a running
2789          * state (e.g. set_curr_task), in this case we're finished.
2790          */
2791         if (cfs_rq_throttled(cfs_rq))
2792                 return;
2793
2794         throttle_cfs_rq(cfs_rq);
2795 }
2796
2797 static inline u64 default_cfs_period(void);
2798 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2799 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2800
2801 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2802 {
2803         struct cfs_bandwidth *cfs_b =
2804                 container_of(timer, struct cfs_bandwidth, slack_timer);
2805         do_sched_cfs_slack_timer(cfs_b);
2806
2807         return HRTIMER_NORESTART;
2808 }
2809
2810 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2811 {
2812         struct cfs_bandwidth *cfs_b =
2813                 container_of(timer, struct cfs_bandwidth, period_timer);
2814         ktime_t now;
2815         int overrun;
2816         int idle = 0;
2817
2818         for (;;) {
2819                 now = hrtimer_cb_get_time(timer);
2820                 overrun = hrtimer_forward(timer, now, cfs_b->period);
2821
2822                 if (!overrun)
2823                         break;
2824
2825                 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2826         }
2827
2828         return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2829 }
2830
2831 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2832 {
2833         raw_spin_lock_init(&cfs_b->lock);
2834         cfs_b->runtime = 0;
2835         cfs_b->quota = RUNTIME_INF;
2836         cfs_b->period = ns_to_ktime(default_cfs_period());
2837
2838         INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2839         hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2840         cfs_b->period_timer.function = sched_cfs_period_timer;
2841         hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2842         cfs_b->slack_timer.function = sched_cfs_slack_timer;
2843 }
2844
2845 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2846 {
2847         cfs_rq->runtime_enabled = 0;
2848         INIT_LIST_HEAD(&cfs_rq->throttled_list);
2849 }
2850
2851 /* requires cfs_b->lock, may release to reprogram timer */
2852 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2853 {
2854         /*
2855          * The timer may be active because we're trying to set a new bandwidth
2856          * period or because we're racing with the tear-down path
2857          * (timer_active==0 becomes visible before the hrtimer call-back
2858          * terminates).  In either case we ensure that it's re-programmed
2859          */
2860         while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2861                 raw_spin_unlock(&cfs_b->lock);
2862                 /* ensure cfs_b->lock is available while we wait */
2863                 hrtimer_cancel(&cfs_b->period_timer);
2864
2865                 raw_spin_lock(&cfs_b->lock);
2866                 /* if someone else restarted the timer then we're done */
2867                 if (cfs_b->timer_active)
2868                         return;
2869         }
2870
2871         cfs_b->timer_active = 1;
2872         start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2873 }
2874
2875 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2876 {
2877         hrtimer_cancel(&cfs_b->period_timer);
2878         hrtimer_cancel(&cfs_b->slack_timer);
2879 }
2880
2881 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
2882 {
2883         struct cfs_rq *cfs_rq;
2884
2885         for_each_leaf_cfs_rq(rq, cfs_rq) {
2886                 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2887
2888                 if (!cfs_rq->runtime_enabled)
2889                         continue;
2890
2891                 /*
2892                  * clock_task is not advancing so we just need to make sure
2893                  * there's some valid quota amount
2894                  */
2895                 cfs_rq->runtime_remaining = cfs_b->quota;
2896                 if (cfs_rq_throttled(cfs_rq))
2897                         unthrottle_cfs_rq(cfs_rq);
2898         }
2899 }
2900
2901 #else /* CONFIG_CFS_BANDWIDTH */
2902 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
2903 {
2904         return rq_of(cfs_rq)->clock_task;
2905 }
2906
2907 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
2908                                      unsigned long delta_exec) {}
2909 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2910 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
2911 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2912
2913 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2914 {
2915         return 0;
2916 }
2917
2918 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2919 {
2920         return 0;
2921 }
2922
2923 static inline int throttled_lb_pair(struct task_group *tg,
2924                                     int src_cpu, int dest_cpu)
2925 {
2926         return 0;
2927 }
2928
2929 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2930
2931 #ifdef CONFIG_FAIR_GROUP_SCHED
2932 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2933 #endif
2934
2935 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2936 {
2937         return NULL;
2938 }
2939 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2940 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
2941
2942 #endif /* CONFIG_CFS_BANDWIDTH */
2943
2944 /**************************************************
2945  * CFS operations on tasks:
2946  */
2947
2948 #ifdef CONFIG_SCHED_HRTICK
2949 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2950 {
2951         struct sched_entity *se = &p->se;
2952         struct cfs_rq *cfs_rq = cfs_rq_of(se);
2953
2954         WARN_ON(task_rq(p) != rq);
2955
2956         if (cfs_rq->nr_running > 1) {
2957                 u64 slice = sched_slice(cfs_rq, se);
2958                 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2959                 s64 delta = slice - ran;
2960
2961                 if (delta < 0) {
2962                         if (rq->curr == p)
2963                                 resched_task(p);
2964                         return;
2965                 }
2966
2967                 /*
2968                  * Don't schedule slices shorter than 10000ns, that just
2969                  * doesn't make sense. Rely on vruntime for fairness.
2970                  */
2971                 if (rq->curr != p)
2972                         delta = max_t(s64, 10000LL, delta);
2973
2974                 hrtick_start(rq, delta);
2975         }
2976 }
2977
2978 /*
2979  * called from enqueue/dequeue and updates the hrtick when the
2980  * current task is from our class and nr_running is low enough
2981  * to matter.
2982  */
2983 static void hrtick_update(struct rq *rq)
2984 {
2985         struct task_struct *curr = rq->curr;
2986
2987         if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
2988                 return;
2989
2990         if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2991                 hrtick_start_fair(rq, curr);
2992 }
2993 #else /* !CONFIG_SCHED_HRTICK */
2994 static inline void
2995 hrtick_start_fair(struct rq *rq, struct task_struct *p)
2996 {
2997 }
2998
2999 static inline void hrtick_update(struct rq *rq)
3000 {
3001 }
3002 #endif
3003
3004 /*
3005  * The enqueue_task method is called before nr_running is
3006  * increased. Here we update the fair scheduling stats and
3007  * then put the task into the rbtree:
3008  */
3009 static void
3010 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
3011 {
3012         struct cfs_rq *cfs_rq;
3013         struct sched_entity *se = &p->se;
3014
3015         for_each_sched_entity(se) {
3016                 if (se->on_rq)
3017                         break;
3018                 cfs_rq = cfs_rq_of(se);
3019                 enqueue_entity(cfs_rq, se, flags);
3020
3021                 /*
3022                  * end evaluation on encountering a throttled cfs_rq
3023                  *
3024                  * note: in the case of encountering a throttled cfs_rq we will
3025                  * post the final h_nr_running increment below.
3026                 */
3027                 if (cfs_rq_throttled(cfs_rq))
3028                         break;
3029                 cfs_rq->h_nr_running++;
3030
3031                 flags = ENQUEUE_WAKEUP;
3032         }
3033
3034         for_each_sched_entity(se) {
3035                 cfs_rq = cfs_rq_of(se);
3036                 cfs_rq->h_nr_running++;
3037
3038                 if (cfs_rq_throttled(cfs_rq))
3039                         break;
3040
3041                 update_cfs_shares(cfs_rq);
3042                 update_entity_load_avg(se, 1);
3043         }
3044
3045         if (!se) {
3046                 update_rq_runnable_avg(rq, rq->nr_running);
3047                 inc_nr_running(rq);
3048         }
3049         hrtick_update(rq);
3050 }
3051
3052 static void set_next_buddy(struct sched_entity *se);
3053
3054 /*
3055  * The dequeue_task method is called before nr_running is
3056  * decreased. We remove the task from the rbtree and
3057  * update the fair scheduling stats:
3058  */
3059 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
3060 {
3061         struct cfs_rq *cfs_rq;
3062         struct sched_entity *se = &p->se;
3063         int task_sleep = flags & DEQUEUE_SLEEP;
3064
3065         for_each_sched_entity(se) {
3066                 cfs_rq = cfs_rq_of(se);
3067                 dequeue_entity(cfs_rq, se, flags);
3068
3069                 /*
3070                  * end evaluation on encountering a throttled cfs_rq
3071                  *
3072                  * note: in the case of encountering a throttled cfs_rq we will
3073                  * post the final h_nr_running decrement below.
3074                 */
3075                 if (cfs_rq_throttled(cfs_rq))
3076                         break;
3077                 cfs_rq->h_nr_running--;
3078
3079                 /* Don't dequeue parent if it has other entities besides us */
3080                 if (cfs_rq->load.weight) {
3081                         /*
3082                          * Bias pick_next to pick a task from this cfs_rq, as
3083                          * p is sleeping when it is within its sched_slice.
3084                          */
3085                         if (task_sleep && parent_entity(se))
3086                                 set_next_buddy(parent_entity(se));
3087
3088                         /* avoid re-evaluating load for this entity */
3089                         se = parent_entity(se);
3090                         break;
3091                 }
3092                 flags |= DEQUEUE_SLEEP;
3093         }
3094
3095         for_each_sched_entity(se) {
3096                 cfs_rq = cfs_rq_of(se);
3097                 cfs_rq->h_nr_running--;
3098
3099                 if (cfs_rq_throttled(cfs_rq))
3100                         break;
3101
3102                 update_cfs_shares(cfs_rq);
3103                 update_entity_load_avg(se, 1);
3104         }
3105
3106         if (!se) {
3107                 dec_nr_running(rq);
3108                 update_rq_runnable_avg(rq, 1);
3109         }
3110         hrtick_update(rq);
3111 }
3112
3113 #ifdef CONFIG_SMP
3114 /* Used instead of source_load when we know the type == 0 */
3115 static unsigned long weighted_cpuload(const int cpu)
3116 {
3117         return cpu_rq(cpu)->load.weight;
3118 }
3119
3120 /*
3121  * Return a low guess at the load of a migration-source cpu weighted
3122  * according to the scheduling class and "nice" value.
3123  *
3124  * We want to under-estimate the load of migration sources, to
3125  * balance conservatively.
3126  */
3127 static unsigned long source_load(int cpu, int type)
3128 {
3129         struct rq *rq = cpu_rq(cpu);
3130         unsigned long total = weighted_cpuload(cpu);
3131
3132         if (type == 0 || !sched_feat(LB_BIAS))
3133                 return total;
3134
3135         return min(rq->cpu_load[type-1], total);
3136 }
3137
3138 /*
3139  * Return a high guess at the load of a migration-target cpu weighted
3140  * according to the scheduling class and "nice" value.
3141  */
3142 static unsigned long target_load(int cpu, int type)
3143 {
3144         struct rq *rq = cpu_rq(cpu);
3145         unsigned long total = weighted_cpuload(cpu);
3146
3147         if (type == 0 || !sched_feat(LB_BIAS))
3148                 return total;
3149
3150         return max(rq->cpu_load[type-1], total);
3151 }
3152
3153 static unsigned long power_of(int cpu)
3154 {
3155         return cpu_rq(cpu)->cpu_power;
3156 }
3157
3158 static unsigned long cpu_avg_load_per_task(int cpu)
3159 {
3160         struct rq *rq = cpu_rq(cpu);
3161         unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
3162
3163         if (nr_running)
3164                 return rq->load.weight / nr_running;
3165
3166         return 0;
3167 }
3168
3169
3170 static void task_waking_fair(struct task_struct *p)
3171 {
3172         struct sched_entity *se = &p->se;
3173         struct cfs_rq *cfs_rq = cfs_rq_of(se);
3174         u64 min_vruntime;
3175
3176 #ifndef CONFIG_64BIT
3177         u64 min_vruntime_copy;
3178
3179         do {
3180                 min_vruntime_copy = cfs_rq->min_vruntime_copy;
3181                 smp_rmb();
3182                 min_vruntime = cfs_rq->min_vruntime;
3183         } while (min_vruntime != min_vruntime_copy);
3184 #else
3185         min_vruntime = cfs_rq->min_vruntime;
3186 #endif
3187
3188         se->vruntime -= min_vruntime;
3189 }
3190
3191 #ifdef CONFIG_FAIR_GROUP_SCHED
3192 /*
3193  * effective_load() calculates the load change as seen from the root_task_group
3194  *
3195  * Adding load to a group doesn't make a group heavier, but can cause movement
3196  * of group shares between cpus. Assuming the shares were perfectly aligned one
3197  * can calculate the shift in shares.
3198  *
3199  * Calculate the effective load difference if @wl is added (subtracted) to @tg
3200  * on this @cpu and results in a total addition (subtraction) of @wg to the
3201  * total group weight.
3202  *
3203  * Given a runqueue weight distribution (rw_i) we can compute a shares
3204  * distribution (s_i) using:
3205  *
3206  *   s_i = rw_i / \Sum rw_j                                             (1)
3207  *
3208  * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
3209  * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
3210  * shares distribution (s_i):
3211  *
3212  *   rw_i = {   2,   4,   1,   0 }
3213  *   s_i  = { 2/7, 4/7, 1/7,   0 }
3214  *
3215  * As per wake_affine() we're interested in the load of two CPUs (the CPU the
3216  * task used to run on and the CPU the waker is running on), we need to
3217  * compute the effect of waking a task on either CPU and, in case of a sync
3218  * wakeup, compute the effect of the current task going to sleep.
3219  *
3220  * So for a change of @wl to the local @cpu with an overall group weight change
3221  * of @wl we can compute the new shares distribution (s'_i) using:
3222  *
3223  *   s'_i = (rw_i + @wl) / (@wg + \Sum rw_j)                            (2)
3224  *
3225  * Suppose we're interested in CPUs 0 and 1, and want to compute the load
3226  * differences in waking a task to CPU 0. The additional task changes the
3227  * weight and shares distributions like:
3228  *
3229  *   rw'_i = {   3,   4,   1,   0 }
3230  *   s'_i  = { 3/8, 4/8, 1/8,   0 }
3231  *
3232  * We can then compute the difference in effective weight by using:
3233  *
3234  *   dw_i = S * (s'_i - s_i)                                            (3)
3235  *
3236  * Where 'S' is the group weight as seen by its parent.
3237  *
3238  * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
3239  * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
3240  * 4/7) times the weight of the group.
3241  */
3242 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
3243 {
3244         struct sched_entity *se = tg->se[cpu];
3245
3246         if (!tg->parent)        /* the trivial, non-cgroup case */
3247                 return wl;
3248
3249         for_each_sched_entity(se) {
3250                 long w, W;
3251
3252                 tg = se->my_q->tg;
3253
3254                 /*
3255                  * W = @wg + \Sum rw_j
3256                  */
3257                 W = wg + calc_tg_weight(tg, se->my_q);
3258
3259                 /*
3260                  * w = rw_i + @wl
3261                  */
3262                 w = se->my_q->load.weight + wl;
3263
3264                 /*
3265                  * wl = S * s'_i; see (2)
3266                  */
3267                 if (W > 0 && w < W)
3268                         wl = (w * tg->shares) / W;
3269                 else
3270                         wl = tg->shares;
3271
3272                 /*
3273                  * Per the above, wl is the new se->load.weight value; since
3274                  * those are clipped to [MIN_SHARES, ...) do so now. See
3275                  * calc_cfs_shares().
3276                  */
3277                 if (wl < MIN_SHARES)
3278                         wl = MIN_SHARES;
3279
3280                 /*
3281                  * wl = dw_i = S * (s'_i - s_i); see (3)
3282                  */
3283                 wl -= se->load.weight;
3284
3285                 /*
3286                  * Recursively apply this logic to all parent groups to compute
3287                  * the final effective load change on the root group. Since
3288                  * only the @tg group gets extra weight, all parent groups can
3289                  * only redistribute existing shares. @wl is the shift in shares
3290                  * resulting from this level per the above.
3291                  */
3292                 wg = 0;
3293         }
3294
3295         return wl;
3296 }
3297 #else
3298
3299 static inline unsigned long effective_load(struct task_group *tg, int cpu,
3300                 unsigned long wl, unsigned long wg)
3301 {
3302         return wl;
3303 }
3304
3305 #endif
3306
3307 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
3308 {
3309         s64 this_load, load;
3310         int idx, this_cpu, prev_cpu;
3311         unsigned long tl_per_task;
3312         struct task_group *tg;
3313         unsigned long weight;
3314         int balanced;
3315
3316         idx       = sd->wake_idx;
3317         this_cpu  = smp_processor_id();
3318         prev_cpu  = task_cpu(p);
3319         load      = source_load(prev_cpu, idx);
3320         this_load = target_load(this_cpu, idx);
3321
3322         /*
3323          * If sync wakeup then subtract the (maximum possible)
3324          * effect of the currently running task from the load
3325          * of the current CPU:
3326          */
3327         if (sync) {
3328                 tg = task_group(current);
3329                 weight = current->se.load.weight;
3330
3331                 this_load += effective_load(tg, this_cpu, -weight, -weight);
3332                 load += effective_load(tg, prev_cpu, 0, -weight);
3333         }
3334
3335         tg = task_group(p);
3336         weight = p->se.load.weight;
3337
3338         /*
3339          * In low-load situations, where prev_cpu is idle and this_cpu is idle
3340          * due to the sync cause above having dropped this_load to 0, we'll
3341          * always have an imbalance, but there's really nothing you can do
3342          * about that, so that's good too.
3343          *
3344          * Otherwise check if either cpus are near enough in load to allow this
3345          * task to be woken on this_cpu.
3346          */
3347         if (this_load > 0) {
3348                 s64 this_eff_load, prev_eff_load;
3349
3350                 this_eff_load = 100;
3351                 this_eff_load *= power_of(prev_cpu);
3352                 this_eff_load *= this_load +
3353                         effective_load(tg, this_cpu, weight, weight);
3354
3355                 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
3356                 prev_eff_load *= power_of(this_cpu);
3357                 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
3358
3359                 balanced = this_eff_load <= prev_eff_load;
3360         } else
3361                 balanced = true;
3362
3363         /*
3364          * If the currently running task will sleep within
3365          * a reasonable amount of time then attract this newly
3366          * woken task:
3367          */
3368         if (sync && balanced)
3369                 return 1;
3370
3371         schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
3372         tl_per_task = cpu_avg_load_per_task(this_cpu);
3373
3374         if (balanced ||
3375             (this_load <= load &&
3376              this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
3377                 /*
3378                  * This domain has SD_WAKE_AFFINE and
3379                  * p is cache cold in this domain, and
3380                  * there is no bad imbalance.
3381                  */
3382                 schedstat_inc(sd, ttwu_move_affine);
3383                 schedstat_inc(p, se.statistics.nr_wakeups_affine);
3384
3385                 return 1;
3386         }
3387         return 0;
3388 }
3389
3390 /*
3391  * find_idlest_group finds and returns the least busy CPU group within the
3392  * domain.
3393  */
3394 static struct sched_group *
3395 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
3396                   int this_cpu, int load_idx)
3397 {
3398         struct sched_group *idlest = NULL, *group = sd->groups;
3399         unsigned long min_load = ULONG_MAX, this_load = 0;
3400         int imbalance = 100 + (sd->imbalance_pct-100)/2;
3401
3402         do {
3403                 unsigned long load, avg_load;
3404                 int local_group;
3405                 int i;
3406
3407                 /* Skip over this group if it has no CPUs allowed */
3408                 if (!cpumask_intersects(sched_group_cpus(group),
3409                                         tsk_cpus_allowed(p)))
3410                         continue;
3411
3412                 local_group = cpumask_test_cpu(this_cpu,
3413                                                sched_group_cpus(group));
3414
3415                 /* Tally up the load of all CPUs in the group */
3416                 avg_load = 0;
3417
3418                 for_each_cpu(i, sched_group_cpus(group)) {
3419                         /* Bias balancing toward cpus of our domain */
3420                         if (local_group)
3421                                 load = source_load(i, load_idx);
3422                         else
3423                                 load = target_load(i, load_idx);
3424
3425                         avg_load += load;
3426                 }
3427
3428                 /* Adjust by relative CPU power of the group */
3429                 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
3430
3431                 if (local_group) {
3432                         this_load = avg_load;
3433                 } else if (avg_load < min_load) {
3434                         min_load = avg_load;
3435                         idlest = group;
3436                 }
3437         } while (group = group->next, group != sd->groups);
3438
3439         if (!idlest || 100*this_load < imbalance*min_load)
3440                 return NULL;
3441         return idlest;
3442 }
3443
3444 /*
3445  * find_idlest_cpu - find the idlest cpu among the cpus in group.
3446  */
3447 static int
3448 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
3449 {
3450         unsigned long load, min_load = ULONG_MAX;
3451         int idlest = -1;
3452         int i;
3453
3454         /* Traverse only the allowed CPUs */
3455         for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
3456                 load = weighted_cpuload(i);
3457
3458                 if (load < min_load || (load == min_load && i == this_cpu)) {
3459                         min_load = load;
3460                         idlest = i;
3461                 }
3462         }
3463
3464         return idlest;
3465 }
3466
3467 /*
3468  * Try and locate an idle CPU in the sched_domain.
3469  */
3470 static int select_idle_sibling(struct task_struct *p, int target)
3471 {
3472         struct sched_domain *sd;
3473         struct sched_group *sg;
3474         int i = task_cpu(p);
3475
3476         if (idle_cpu(target))
3477                 return target;
3478
3479         /*
3480          * If the prevous cpu is cache affine and idle, don't be stupid.
3481          */
3482         if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
3483                 return i;
3484
3485         /*
3486          * Otherwise, iterate the domains and find an elegible idle cpu.
3487          */
3488         sd = rcu_dereference(per_cpu(sd_llc, target));
3489         for_each_lower_domain(sd) {
3490                 sg = sd->groups;
3491                 do {
3492                         if (!cpumask_intersects(sched_group_cpus(sg),
3493                                                 tsk_cpus_allowed(p)))
3494                                 goto next;
3495
3496                         for_each_cpu(i, sched_group_cpus(sg)) {
3497                                 if (i == target || !idle_cpu(i))
3498                                         goto next;
3499                         }
3500
3501                         target = cpumask_first_and(sched_group_cpus(sg),
3502                                         tsk_cpus_allowed(p));
3503                         goto done;
3504 next:
3505                         sg = sg->next;
3506                 } while (sg != sd->groups);
3507         }
3508 done:
3509         return target;
3510 }
3511
3512 #ifdef CONFIG_SCHED_HMP
3513 /*
3514  * Heterogenous multiprocessor (HMP) optimizations
3515  *
3516  * The cpu types are distinguished using a list of hmp_domains
3517  * which each represent one cpu type using a cpumask.
3518  * The list is assumed ordered by compute capacity with the
3519  * fastest domain first.
3520  */
3521 DEFINE_PER_CPU(struct hmp_domain *, hmp_cpu_domain);
3522 static const int hmp_max_tasks = 5;
3523
3524 extern void __init arch_get_hmp_domains(struct list_head *hmp_domains_list);
3525
3526 /* Setup hmp_domains */
3527 static int __init hmp_cpu_mask_setup(void)
3528 {
3529         char buf[64];
3530         struct hmp_domain *domain;
3531         struct list_head *pos;
3532         int dc, cpu;
3533
3534         pr_debug("Initializing HMP scheduler:\n");
3535
3536         /* Initialize hmp_domains using platform code */
3537         arch_get_hmp_domains(&hmp_domains);
3538         if (list_empty(&hmp_domains)) {
3539                 pr_debug("HMP domain list is empty!\n");
3540                 return 0;
3541         }
3542
3543         /* Print hmp_domains */
3544         dc = 0;
3545         list_for_each(pos, &hmp_domains) {
3546                 domain = list_entry(pos, struct hmp_domain, hmp_domains);
3547                 cpulist_scnprintf(buf, 64, &domain->possible_cpus);
3548                 pr_debug("  HMP domain %d: %s\n", dc, buf);
3549
3550                 for_each_cpu_mask(cpu, domain->possible_cpus) {
3551                         per_cpu(hmp_cpu_domain, cpu) = domain;
3552                 }
3553                 dc++;
3554         }
3555
3556         return 1;
3557 }
3558
3559 static struct hmp_domain *hmp_get_hmp_domain_for_cpu(int cpu)
3560 {
3561         struct hmp_domain *domain;
3562         struct list_head *pos;
3563
3564         list_for_each(pos, &hmp_domains) {
3565                 domain = list_entry(pos, struct hmp_domain, hmp_domains);
3566                 if(cpumask_test_cpu(cpu, &domain->possible_cpus))
3567                         return domain;
3568         }
3569         return NULL;
3570 }
3571
3572 static void hmp_online_cpu(int cpu)
3573 {
3574         struct hmp_domain *domain = hmp_get_hmp_domain_for_cpu(cpu);
3575
3576         if(domain)
3577                 cpumask_set_cpu(cpu, &domain->cpus);
3578 }
3579
3580 static void hmp_offline_cpu(int cpu)
3581 {
3582         struct hmp_domain *domain = hmp_get_hmp_domain_for_cpu(cpu);
3583
3584         if(domain)
3585                 cpumask_clear_cpu(cpu, &domain->cpus);
3586 }
3587 /*
3588  * Needed to determine heaviest tasks etc.
3589  */
3590 static inline unsigned int hmp_cpu_is_fastest(int cpu);
3591 static inline unsigned int hmp_cpu_is_slowest(int cpu);
3592 static inline struct hmp_domain *hmp_slower_domain(int cpu);
3593 static inline struct hmp_domain *hmp_faster_domain(int cpu);
3594
3595 /* must hold runqueue lock for queue se is currently on */
3596 static struct sched_entity *hmp_get_heaviest_task(
3597                                 struct sched_entity *se, int migrate_up)
3598 {
3599         int num_tasks = hmp_max_tasks;
3600         struct sched_entity *max_se = se;
3601         unsigned long int max_ratio = se->avg.load_avg_ratio;
3602         const struct cpumask *hmp_target_mask = NULL;
3603
3604         if (migrate_up) {
3605                 struct hmp_domain *hmp;
3606                 if (hmp_cpu_is_fastest(cpu_of(se->cfs_rq->rq)))
3607                         return max_se;
3608
3609                 hmp = hmp_faster_domain(cpu_of(se->cfs_rq->rq));
3610                 hmp_target_mask = &hmp->cpus;
3611         }
3612         /* The currently running task is not on the runqueue */
3613         se = __pick_first_entity(cfs_rq_of(se));
3614
3615         while (num_tasks && se) {
3616                 if (entity_is_task(se) &&
3617                         (se->avg.load_avg_ratio > max_ratio &&
3618                          hmp_target_mask &&
3619                          cpumask_intersects(hmp_target_mask,
3620                                 tsk_cpus_allowed(task_of(se))))) {
3621                         max_se = se;
3622                         max_ratio = se->avg.load_avg_ratio;
3623                 }
3624                 se = __pick_next_entity(se);
3625                 num_tasks--;
3626         }
3627         return max_se;
3628 }
3629
3630 static struct sched_entity *hmp_get_lightest_task(
3631                                 struct sched_entity *se, int migrate_down)
3632 {
3633         int num_tasks = hmp_max_tasks;
3634         struct sched_entity *min_se = se;
3635         unsigned long int min_ratio = se->avg.load_avg_ratio;
3636         const struct cpumask *hmp_target_mask = NULL;
3637
3638         if (migrate_down) {
3639                 struct hmp_domain *hmp;
3640                 if (hmp_cpu_is_slowest(cpu_of(se->cfs_rq->rq)))
3641                         return min_se;
3642                 hmp = hmp_slower_domain(cpu_of(se->cfs_rq->rq));
3643                 hmp_target_mask = &hmp->cpus;
3644         }
3645         /* The currently running task is not on the runqueue */
3646         se = __pick_first_entity(cfs_rq_of(se));
3647
3648         while (num_tasks && se) {
3649                 if (entity_is_task(se) &&
3650                         (se->avg.load_avg_ratio < min_ratio &&
3651                         hmp_target_mask &&
3652                                 cpumask_intersects(hmp_target_mask,
3653                                 tsk_cpus_allowed(task_of(se))))) {
3654                         min_se = se;
3655                         min_ratio = se->avg.load_avg_ratio;
3656                 }
3657                 se = __pick_next_entity(se);
3658                 num_tasks--;
3659         }
3660         return min_se;
3661 }
3662
3663 /*
3664  * Migration thresholds should be in the range [0..1023]
3665  * hmp_up_threshold: min. load required for migrating tasks to a faster cpu
3666  * hmp_down_threshold: max. load allowed for tasks migrating to a slower cpu
3667  *
3668  * hmp_up_prio: Only up migrate task with high priority (<hmp_up_prio)
3669  * hmp_next_up_threshold: Delay before next up migration (1024 ~= 1 ms)
3670  * hmp_next_down_threshold: Delay before next down migration (1024 ~= 1 ms)
3671  */
3672 unsigned int hmp_up_threshold = 700;
3673 unsigned int hmp_down_threshold = 512;
3674 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
3675 unsigned int hmp_up_prio = NICE_TO_PRIO(CONFIG_SCHED_HMP_PRIO_FILTER_VAL);
3676 #endif
3677 unsigned int hmp_next_up_threshold = 4096;
3678 unsigned int hmp_next_down_threshold = 4096;
3679
3680 static unsigned int hmp_up_migration(int cpu, int *target_cpu, struct sched_entity *se);
3681 static unsigned int hmp_down_migration(int cpu, struct sched_entity *se);
3682 static inline unsigned int hmp_domain_min_load(struct hmp_domain *hmpd,
3683                                                 int *min_cpu, struct cpumask *affinity);
3684
3685 /* Check if cpu is in fastest hmp_domain */
3686 static inline unsigned int hmp_cpu_is_fastest(int cpu)
3687 {
3688         struct list_head *pos;
3689
3690         pos = &hmp_cpu_domain(cpu)->hmp_domains;
3691         return pos == hmp_domains.next;
3692 }
3693
3694 /* Check if cpu is in slowest hmp_domain */
3695 static inline unsigned int hmp_cpu_is_slowest(int cpu)
3696 {
3697         struct list_head *pos;
3698
3699         pos = &hmp_cpu_domain(cpu)->hmp_domains;
3700         return list_is_last(pos, &hmp_domains);
3701 }
3702
3703 /* Next (slower) hmp_domain relative to cpu */
3704 static inline struct hmp_domain *hmp_slower_domain(int cpu)
3705 {
3706         struct list_head *pos;
3707
3708         pos = &hmp_cpu_domain(cpu)->hmp_domains;
3709         return list_entry(pos->next, struct hmp_domain, hmp_domains);
3710 }
3711
3712 /* Previous (faster) hmp_domain relative to cpu */
3713 static inline struct hmp_domain *hmp_faster_domain(int cpu)
3714 {
3715         struct list_head *pos;
3716
3717         pos = &hmp_cpu_domain(cpu)->hmp_domains;
3718         return list_entry(pos->prev, struct hmp_domain, hmp_domains);
3719 }
3720
3721 /*
3722  * Selects a cpu in previous (faster) hmp_domain
3723  */
3724 static inline unsigned int hmp_select_faster_cpu(struct task_struct *tsk,
3725                                                         int cpu)
3726 {
3727         int lowest_cpu=NR_CPUS;
3728         __always_unused int lowest_ratio;
3729         struct hmp_domain *hmp;
3730
3731         if (hmp_cpu_is_fastest(cpu))
3732                 hmp = hmp_cpu_domain(cpu);
3733         else
3734                 hmp = hmp_faster_domain(cpu);
3735
3736         lowest_ratio = hmp_domain_min_load(hmp, &lowest_cpu,
3737                         tsk_cpus_allowed(tsk));
3738
3739         return lowest_cpu;
3740 }
3741
3742 /*
3743  * Selects a cpu in next (slower) hmp_domain
3744  * Note that cpumask_any_and() returns the first cpu in the cpumask
3745  */
3746 static inline unsigned int hmp_select_slower_cpu(struct task_struct *tsk,
3747                                                         int cpu)
3748 {
3749         int lowest_cpu=NR_CPUS;
3750         struct hmp_domain *hmp;
3751         __always_unused int lowest_ratio;
3752
3753         if (hmp_cpu_is_slowest(cpu))
3754                 hmp = hmp_cpu_domain(cpu);
3755         else
3756                 hmp = hmp_slower_domain(cpu);
3757
3758         lowest_ratio = hmp_domain_min_load(hmp, &lowest_cpu,
3759                         tsk_cpus_allowed(tsk));
3760
3761         return lowest_cpu;
3762 }
3763
3764 static inline void hmp_next_up_delay(struct sched_entity *se, int cpu)
3765 {
3766         /* hack - always use clock from first online CPU */
3767         u64 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
3768         se->avg.hmp_last_up_migration = now;
3769         se->avg.hmp_last_down_migration = 0;
3770         cpu_rq(cpu)->avg.hmp_last_up_migration = now;
3771         cpu_rq(cpu)->avg.hmp_last_down_migration = 0;
3772 }
3773
3774 static inline void hmp_next_down_delay(struct sched_entity *se, int cpu)
3775 {
3776         /* hack - always use clock from first online CPU */
3777         u64 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
3778         se->avg.hmp_last_down_migration = now;
3779         se->avg.hmp_last_up_migration = 0;
3780         cpu_rq(cpu)->avg.hmp_last_down_migration = now;
3781         cpu_rq(cpu)->avg.hmp_last_up_migration = 0;
3782 }
3783
3784 #ifdef CONFIG_HMP_VARIABLE_SCALE
3785 /*
3786  * Heterogenous multiprocessor (HMP) optimizations
3787  *
3788  * These functions allow to change the growing speed of the load_avg_ratio
3789  * by default it goes from 0 to 0.5 in LOAD_AVG_PERIOD = 32ms
3790  * This can now be changed with /sys/kernel/hmp/load_avg_period_ms.
3791  *
3792  * These functions also allow to change the up and down threshold of HMP
3793  * using /sys/kernel/hmp/{up,down}_threshold.
3794  * Both must be between 0 and 1023. The threshold that is compared
3795  * to the load_avg_ratio is up_threshold/1024 and down_threshold/1024.
3796  *
3797  * For instance, if load_avg_period = 64 and up_threshold = 512, an idle
3798  * task with a load of 0 will reach the threshold after 64ms of busy loop.
3799  *
3800  * Changing load_avg_periods_ms has the same effect than changing the
3801  * default scaling factor Y=1002/1024 in the load_avg_ratio computation to
3802  * (1002/1024.0)^(LOAD_AVG_PERIOD/load_avg_period_ms), but the last one
3803  * could trigger overflows.
3804  * For instance, with Y = 1023/1024 in __update_task_entity_contrib()
3805  * "contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);"
3806  * could be overflowed for a weight > 2^12 even is the load_avg_contrib
3807  * should still be a 32bits result. This would not happen by multiplicating
3808  * delta time by 1/22 and setting load_avg_period_ms = 706.
3809  */
3810
3811 /*
3812  * By scaling the delta time it end-up increasing or decrease the
3813  * growing speed of the per entity load_avg_ratio
3814  * The scale factor hmp_data.multiplier is a fixed point
3815  * number: (32-HMP_VARIABLE_SCALE_SHIFT).HMP_VARIABLE_SCALE_SHIFT
3816  */
3817 static u64 hmp_variable_scale_convert(u64 delta)
3818 {
3819         u64 high = delta >> 32ULL;
3820         u64 low = delta & 0xffffffffULL;
3821         low *= hmp_data.multiplier;
3822         high *= hmp_data.multiplier;
3823         return (low >> HMP_VARIABLE_SCALE_SHIFT)
3824                         + (high << (32ULL - HMP_VARIABLE_SCALE_SHIFT));
3825 }
3826
3827 static ssize_t hmp_show(struct kobject *kobj,
3828                                 struct attribute *attr, char *buf)
3829 {
3830         ssize_t ret = 0;
3831         struct hmp_global_attr *hmp_attr =
3832                 container_of(attr, struct hmp_global_attr, attr);
3833         int temp = *(hmp_attr->value);
3834         if (hmp_attr->to_sysfs != NULL)
3835                 temp = hmp_attr->to_sysfs(temp);
3836         ret = sprintf(buf, "%d\n", temp);
3837         return ret;
3838 }
3839
3840 static ssize_t hmp_store(struct kobject *a, struct attribute *attr,
3841                                 const char *buf, size_t count)
3842 {
3843         int temp;
3844         ssize_t ret = count;
3845         struct hmp_global_attr *hmp_attr =
3846                 container_of(attr, struct hmp_global_attr, attr);
3847         char *str = vmalloc(count + 1);
3848         if (str == NULL)
3849                 return -ENOMEM;
3850         memcpy(str, buf, count);
3851         str[count] = 0;
3852         if (sscanf(str, "%d", &temp) < 1)
3853                 ret = -EINVAL;
3854         else {
3855                 if (hmp_attr->from_sysfs != NULL)
3856                         temp = hmp_attr->from_sysfs(temp);
3857                 if (temp < 0)
3858                         ret = -EINVAL;
3859                 else
3860                         *(hmp_attr->value) = temp;
3861         }
3862         vfree(str);
3863         return ret;
3864 }
3865
3866 static int hmp_period_tofrom_sysfs(int value)
3867 {
3868         return (LOAD_AVG_PERIOD << HMP_VARIABLE_SCALE_SHIFT) / value;
3869 }
3870
3871 /* max value for threshold is 1024 */
3872 static int hmp_theshold_from_sysfs(int value)
3873 {
3874         if (value > 1024)
3875                 return -1;
3876         return value;
3877 }
3878 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
3879 /* freqinvar control is only 0,1 off/on */
3880 static int hmp_freqinvar_from_sysfs(int value)
3881 {
3882         if (value < 0 || value > 1)
3883                 return -1;
3884         return value;
3885 }
3886 #endif
3887 static void hmp_attr_add(
3888         const char *name,
3889         int *value,
3890         int (*to_sysfs)(int),
3891         int (*from_sysfs)(int))
3892 {
3893         int i = 0;
3894         while (hmp_data.attributes[i] != NULL) {
3895                 i++;
3896                 if (i >= HMP_DATA_SYSFS_MAX)
3897                         return;
3898         }
3899         hmp_data.attr[i].attr.mode = 0644;
3900         hmp_data.attr[i].show = hmp_show;
3901         hmp_data.attr[i].store = hmp_store;
3902         hmp_data.attr[i].attr.name = name;
3903         hmp_data.attr[i].value = value;
3904         hmp_data.attr[i].to_sysfs = to_sysfs;
3905         hmp_data.attr[i].from_sysfs = from_sysfs;
3906         hmp_data.attributes[i] = &hmp_data.attr[i].attr;
3907         hmp_data.attributes[i + 1] = NULL;
3908 }
3909
3910 static int hmp_attr_init(void)
3911 {
3912         int ret;
3913         memset(&hmp_data, sizeof(hmp_data), 0);
3914         /* by default load_avg_period_ms == LOAD_AVG_PERIOD
3915          * meaning no change
3916          */
3917         hmp_data.multiplier = hmp_period_tofrom_sysfs(LOAD_AVG_PERIOD);
3918
3919         hmp_attr_add("load_avg_period_ms",
3920                 &hmp_data.multiplier,
3921                 hmp_period_tofrom_sysfs,
3922                 hmp_period_tofrom_sysfs);
3923         hmp_attr_add("up_threshold",
3924                 &hmp_up_threshold,
3925                 NULL,
3926                 hmp_theshold_from_sysfs);
3927         hmp_attr_add("down_threshold",
3928                 &hmp_down_threshold,
3929                 NULL,
3930                 hmp_theshold_from_sysfs);
3931 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
3932         /* default frequency-invariant scaling ON */
3933         hmp_data.freqinvar_load_scale_enabled = 1;
3934         hmp_attr_add("frequency_invariant_load_scale",
3935                 &hmp_data.freqinvar_load_scale_enabled,
3936                 NULL,
3937                 hmp_freqinvar_from_sysfs);
3938 #endif
3939         hmp_data.attr_group.name = "hmp";
3940         hmp_data.attr_group.attrs = hmp_data.attributes;
3941         ret = sysfs_create_group(kernel_kobj,
3942                 &hmp_data.attr_group);
3943         return 0;
3944 }
3945 late_initcall(hmp_attr_init);
3946 #endif /* CONFIG_HMP_VARIABLE_SCALE */
3947 /*
3948  * return the load of the lowest-loaded CPU in a given HMP domain
3949  * min_cpu optionally points to an int to receive the CPU.
3950  * affinity optionally points to a cpumask containing the
3951  * CPUs to be considered. note:
3952  *   + min_cpu = NR_CPUS only if no CPUs are in the set of
3953  *     affinity && hmp_domain cpus
3954  *   + min_cpu will always otherwise equal one of the CPUs in
3955  *     the hmp domain
3956  *   + when more than one CPU has the same load, the one which
3957  *     is least-recently-disturbed by an HMP migration will be
3958  *     selected
3959  *   + if all CPUs are equally loaded or idle and the times are
3960  *     all the same, the first in the set will be used
3961  *   + if affinity is not set, cpu_online_mask is used
3962  */
3963 static inline unsigned int hmp_domain_min_load(struct hmp_domain *hmpd,
3964                                                 int *min_cpu, struct cpumask *affinity)
3965 {
3966         int cpu;
3967         int min_cpu_runnable_temp = NR_CPUS;
3968         u64 min_target_last_migration = ULLONG_MAX;
3969         u64 curr_last_migration;
3970         unsigned long min_runnable_load = INT_MAX;
3971         unsigned long contrib;
3972         struct sched_avg *avg;
3973         struct cpumask temp_cpumask;
3974         /*
3975          * only look at CPUs allowed if specified,
3976          * otherwise look at all online CPUs in the
3977          * right HMP domain
3978          */
3979         cpumask_and(&temp_cpumask, &hmpd->cpus, affinity ? affinity : cpu_online_mask);
3980
3981         for_each_cpu_mask(cpu, temp_cpumask) {
3982                 avg = &cpu_rq(cpu)->avg;
3983                 /* used for both up and down migration */
3984                 curr_last_migration = avg->hmp_last_up_migration ?
3985                         avg->hmp_last_up_migration : avg->hmp_last_down_migration;
3986
3987                 contrib = avg->load_avg_ratio;
3988                 /*
3989                  * Consider a runqueue completely busy if there is any load
3990                  * on it. Definitely not the best for overall fairness, but
3991                  * does well in typical Android use cases.
3992                  */
3993                 if (contrib)
3994                         contrib = 1023;
3995
3996                 if ((contrib < min_runnable_load) ||
3997                         (contrib == min_runnable_load &&
3998                          curr_last_migration < min_target_last_migration)) {
3999                         /*
4000                          * if the load is the same target the CPU with
4001                          * the longest time since a migration.
4002                          * This is to spread migration load between
4003                          * members of a domain more evenly when the
4004                          * domain is fully loaded
4005                          */
4006                         min_runnable_load = contrib;
4007                         min_cpu_runnable_temp = cpu;
4008                         min_target_last_migration = curr_last_migration;
4009                 }
4010         }
4011
4012         if (min_cpu)
4013                 *min_cpu = min_cpu_runnable_temp;
4014
4015         return min_runnable_load;
4016 }
4017
4018 /*
4019  * Calculate the task starvation
4020  * This is the ratio of actually running time vs. runnable time.
4021  * If the two are equal the task is getting the cpu time it needs or
4022  * it is alone on the cpu and the cpu is fully utilized.
4023  */
4024 static inline unsigned int hmp_task_starvation(struct sched_entity *se)
4025 {
4026         u32 starvation;
4027
4028         starvation = se->avg.usage_avg_sum * scale_load_down(NICE_0_LOAD);
4029         starvation /= (se->avg.runnable_avg_sum + 1);
4030
4031         return scale_load(starvation);
4032 }
4033
4034 static inline unsigned int hmp_offload_down(int cpu, struct sched_entity *se)
4035 {
4036         int min_usage;
4037         int dest_cpu = NR_CPUS;
4038
4039         if (hmp_cpu_is_slowest(cpu))
4040                 return NR_CPUS;
4041
4042         /* Is there an idle CPU in the current domain */
4043         min_usage = hmp_domain_min_load(hmp_cpu_domain(cpu), NULL, NULL);
4044         if (min_usage == 0) {
4045                 trace_sched_hmp_offload_abort(cpu, min_usage, "load");
4046                 return NR_CPUS;
4047         }
4048
4049         /* Is the task alone on the cpu? */
4050         if (cpu_rq(cpu)->cfs.h_nr_running < 2) {
4051                 trace_sched_hmp_offload_abort(cpu,
4052                         cpu_rq(cpu)->cfs.h_nr_running, "nr_running");
4053                 return NR_CPUS;
4054         }
4055
4056         /* Is the task actually starving? */
4057         /* >=25% ratio running/runnable = starving */
4058         if (hmp_task_starvation(se) > 768) {
4059                 trace_sched_hmp_offload_abort(cpu, hmp_task_starvation(se),
4060                         "starvation");
4061                 return NR_CPUS;
4062         }
4063
4064         /* Does the slower domain have any idle CPUs? */
4065         min_usage = hmp_domain_min_load(hmp_slower_domain(cpu), &dest_cpu,
4066                         tsk_cpus_allowed(task_of(se)));
4067
4068         if (min_usage == 0) {
4069                 trace_sched_hmp_offload_succeed(cpu, dest_cpu);
4070                 return dest_cpu;
4071         } else
4072                 trace_sched_hmp_offload_abort(cpu,min_usage,"slowdomain");
4073         return NR_CPUS;
4074 }
4075 #endif /* CONFIG_SCHED_HMP */
4076
4077 /*
4078  * sched_balance_self: balance the current task (running on cpu) in domains
4079  * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
4080  * SD_BALANCE_EXEC.
4081  *
4082  * Balance, ie. select the least loaded group.
4083  *
4084  * Returns the target CPU number, or the same CPU if no balancing is needed.
4085  *
4086  * preempt must be disabled.
4087  */
4088 static int
4089 select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
4090 {
4091         struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
4092         int cpu = smp_processor_id();
4093         int prev_cpu = task_cpu(p);
4094         int new_cpu = cpu;
4095         int want_affine = 0;
4096         int sync = wake_flags & WF_SYNC;
4097
4098         if (p->nr_cpus_allowed == 1)
4099                 return prev_cpu;
4100
4101 #ifdef CONFIG_SCHED_HMP
4102         /* always put non-kernel forking tasks on a big domain */
4103         if (p->mm && (sd_flag & SD_BALANCE_FORK)) {
4104                 new_cpu = hmp_select_faster_cpu(p, prev_cpu);
4105                 if (new_cpu != NR_CPUS) {
4106                         hmp_next_up_delay(&p->se, new_cpu);
4107                         return new_cpu;
4108                 }
4109                 /* failed to perform HMP fork balance, use normal balance */
4110                 new_cpu = cpu;
4111         }
4112 #endif
4113
4114         if (sd_flag & SD_BALANCE_WAKE) {
4115                 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
4116                         want_affine = 1;
4117                 new_cpu = prev_cpu;
4118         }
4119
4120         rcu_read_lock();
4121         for_each_domain(cpu, tmp) {
4122                 if (!(tmp->flags & SD_LOAD_BALANCE))
4123                         continue;
4124
4125                 /*
4126                  * If both cpu and prev_cpu are part of this domain,
4127                  * cpu is a valid SD_WAKE_AFFINE target.
4128                  */
4129                 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
4130                     cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
4131                         affine_sd = tmp;
4132                         break;
4133                 }
4134
4135                 if (tmp->flags & sd_flag)
4136                         sd = tmp;
4137         }
4138
4139         if (affine_sd) {
4140                 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
4141                         prev_cpu = cpu;
4142
4143                 new_cpu = select_idle_sibling(p, prev_cpu);
4144                 goto unlock;
4145         }
4146
4147         while (sd) {
4148                 int load_idx = sd->forkexec_idx;
4149                 struct sched_group *group;
4150                 int weight;
4151
4152                 if (!(sd->flags & sd_flag)) {
4153                         sd = sd->child;
4154                         continue;
4155                 }
4156
4157                 if (sd_flag & SD_BALANCE_WAKE)
4158                         load_idx = sd->wake_idx;
4159
4160                 group = find_idlest_group(sd, p, cpu, load_idx);
4161                 if (!group) {
4162                         sd = sd->child;
4163                         continue;
4164                 }
4165
4166                 new_cpu = find_idlest_cpu(group, p, cpu);
4167                 if (new_cpu == -1 || new_cpu == cpu) {
4168                         /* Now try balancing at a lower domain level of cpu */
4169                         sd = sd->child;
4170                         continue;
4171                 }
4172
4173                 /* Now try balancing at a lower domain level of new_cpu */
4174                 cpu = new_cpu;
4175                 weight = sd->span_weight;
4176                 sd = NULL;
4177                 for_each_domain(cpu, tmp) {
4178                         if (weight <= tmp->span_weight)
4179                                 break;
4180                         if (tmp->flags & sd_flag)
4181                                 sd = tmp;
4182                 }
4183                 /* while loop will break here if sd == NULL */
4184         }
4185 unlock:
4186         rcu_read_unlock();
4187
4188 #ifdef CONFIG_SCHED_HMP
4189         prev_cpu = task_cpu(p);
4190
4191         if (hmp_up_migration(prev_cpu, &new_cpu, &p->se)) {
4192                 hmp_next_up_delay(&p->se, new_cpu);
4193                 trace_sched_hmp_migrate(p, new_cpu, HMP_MIGRATE_WAKEUP);
4194                 return new_cpu;
4195         }
4196         if (hmp_down_migration(prev_cpu, &p->se)) {
4197                 new_cpu = hmp_select_slower_cpu(p, prev_cpu);
4198                 hmp_next_down_delay(&p->se, new_cpu);
4199                 trace_sched_hmp_migrate(p, new_cpu, HMP_MIGRATE_WAKEUP);
4200                 return new_cpu;
4201         }
4202         /* Make sure that the task stays in its previous hmp domain */
4203         if (!cpumask_test_cpu(new_cpu, &hmp_cpu_domain(prev_cpu)->cpus))
4204                 return prev_cpu;
4205 #endif
4206
4207         return new_cpu;
4208 }
4209
4210 /*
4211  * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
4212  * removed when useful for applications beyond shares distribution (e.g.
4213  * load-balance).
4214  */
4215 #ifdef CONFIG_FAIR_GROUP_SCHED
4216 /*
4217  * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
4218  * cfs_rq_of(p) references at time of call are still valid and identify the
4219  * previous cpu.  However, the caller only guarantees p->pi_lock is held; no
4220  * other assumptions, including the state of rq->lock, should be made.
4221  */
4222 static void
4223 migrate_task_rq_fair(struct task_struct *p, int next_cpu)
4224 {
4225         struct sched_entity *se = &p->se;
4226         struct cfs_rq *cfs_rq = cfs_rq_of(se);
4227
4228         /*
4229          * Load tracking: accumulate removed load so that it can be processed
4230          * when we next update owning cfs_rq under rq->lock.  Tasks contribute
4231          * to blocked load iff they have a positive decay-count.  It can never
4232          * be negative here since on-rq tasks have decay-count == 0.
4233          */
4234         if (se->avg.decay_count) {
4235                 se->avg.decay_count = -__synchronize_entity_decay(se);
4236                 atomic64_add(se->avg.load_avg_contrib, &cfs_rq->removed_load);
4237         }
4238 }
4239 #endif
4240 #endif /* CONFIG_SMP */
4241
4242 static unsigned long
4243 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
4244 {
4245         unsigned long gran = sysctl_sched_wakeup_granularity;
4246
4247         /*
4248          * Since its curr running now, convert the gran from real-time
4249          * to virtual-time in his units.
4250          *
4251          * By using 'se' instead of 'curr' we penalize light tasks, so
4252          * they get preempted easier. That is, if 'se' < 'curr' then
4253          * the resulting gran will be larger, therefore penalizing the
4254          * lighter, if otoh 'se' > 'curr' then the resulting gran will
4255          * be smaller, again penalizing the lighter task.
4256          *
4257          * This is especially important for buddies when the leftmost
4258          * task is higher priority than the buddy.
4259          */
4260         return calc_delta_fair(gran, se);
4261 }
4262
4263 /*
4264  * Should 'se' preempt 'curr'.
4265  *
4266  *             |s1
4267  *        |s2
4268  *   |s3
4269  *         g
4270  *      |<--->|c
4271  *
4272  *  w(c, s1) = -1
4273  *  w(c, s2) =  0
4274  *  w(c, s3) =  1
4275  *
4276  */
4277 static int
4278 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
4279 {
4280         s64 gran, vdiff = curr->vruntime - se->vruntime;
4281
4282         if (vdiff <= 0)
4283                 return -1;
4284
4285         gran = wakeup_gran(curr, se);
4286         if (vdiff > gran)
4287                 return 1;
4288
4289         return 0;
4290 }
4291
4292 static void set_last_buddy(struct sched_entity *se)
4293 {
4294         if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4295                 return;
4296
4297         for_each_sched_entity(se)
4298                 cfs_rq_of(se)->last = se;
4299 }
4300
4301 static void set_next_buddy(struct sched_entity *se)
4302 {
4303         if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4304                 return;
4305
4306         for_each_sched_entity(se)
4307                 cfs_rq_of(se)->next = se;
4308 }
4309
4310 static void set_skip_buddy(struct sched_entity *se)
4311 {
4312         for_each_sched_entity(se)
4313                 cfs_rq_of(se)->skip = se;
4314 }
4315
4316 /*
4317  * Preempt the current task with a newly woken task if needed:
4318  */
4319 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
4320 {
4321         struct task_struct *curr = rq->curr;
4322         struct sched_entity *se = &curr->se, *pse = &p->se;
4323         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4324         int scale = cfs_rq->nr_running >= sched_nr_latency;
4325         int next_buddy_marked = 0;
4326
4327         if (unlikely(se == pse))
4328                 return;
4329
4330         /*
4331          * This is possible from callers such as move_task(), in which we
4332          * unconditionally check_prempt_curr() after an enqueue (which may have
4333          * lead to a throttle).  This both saves work and prevents false
4334          * next-buddy nomination below.
4335          */
4336         if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
4337                 return;
4338
4339         if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
4340                 set_next_buddy(pse);
4341                 next_buddy_marked = 1;
4342         }
4343
4344         /*
4345          * We can come here with TIF_NEED_RESCHED already set from new task
4346          * wake up path.
4347          *
4348          * Note: this also catches the edge-case of curr being in a throttled
4349          * group (e.g. via set_curr_task), since update_curr() (in the
4350          * enqueue of curr) will have resulted in resched being set.  This
4351          * prevents us from potentially nominating it as a false LAST_BUDDY
4352          * below.
4353          */
4354         if (test_tsk_need_resched(curr))
4355                 return;
4356
4357         /* Idle tasks are by definition preempted by non-idle tasks. */
4358         if (unlikely(curr->policy == SCHED_IDLE) &&
4359             likely(p->policy != SCHED_IDLE))
4360                 goto preempt;
4361
4362         /*
4363          * Batch and idle tasks do not preempt non-idle tasks (their preemption
4364          * is driven by the tick):
4365          */
4366         if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
4367                 return;
4368
4369         find_matching_se(&se, &pse);
4370         update_curr(cfs_rq_of(se));
4371         BUG_ON(!pse);
4372         if (wakeup_preempt_entity(se, pse) == 1) {
4373                 /*
4374                  * Bias pick_next to pick the sched entity that is
4375                  * triggering this preemption.
4376                  */
4377                 if (!next_buddy_marked)
4378                         set_next_buddy(pse);
4379                 goto preempt;
4380         }
4381
4382         return;
4383
4384 preempt:
4385         resched_task(curr);
4386         /*
4387          * Only set the backward buddy when the current task is still
4388          * on the rq. This can happen when a wakeup gets interleaved
4389          * with schedule on the ->pre_schedule() or idle_balance()
4390          * point, either of which can * drop the rq lock.
4391          *
4392          * Also, during early boot the idle thread is in the fair class,
4393          * for obvious reasons its a bad idea to schedule back to it.
4394          */
4395         if (unlikely(!se->on_rq || curr == rq->idle))
4396                 return;
4397
4398         if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
4399                 set_last_buddy(se);
4400 }
4401
4402 static struct task_struct *pick_next_task_fair(struct rq *rq)
4403 {
4404         struct task_struct *p;
4405         struct cfs_rq *cfs_rq = &rq->cfs;
4406         struct sched_entity *se;
4407
4408         if (!cfs_rq->nr_running)
4409                 return NULL;
4410
4411         do {
4412                 se = pick_next_entity(cfs_rq);
4413                 set_next_entity(cfs_rq, se);
4414                 cfs_rq = group_cfs_rq(se);
4415         } while (cfs_rq);
4416
4417         p = task_of(se);
4418         if (hrtick_enabled(rq))
4419                 hrtick_start_fair(rq, p);
4420
4421         return p;
4422 }
4423
4424 /*
4425  * Account for a descheduled task:
4426  */
4427 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
4428 {
4429         struct sched_entity *se = &prev->se;
4430         struct cfs_rq *cfs_rq;
4431
4432         for_each_sched_entity(se) {
4433                 cfs_rq = cfs_rq_of(se);
4434                 put_prev_entity(cfs_rq, se);
4435         }
4436 }
4437
4438 /*
4439  * sched_yield() is very simple
4440  *
4441  * The magic of dealing with the ->skip buddy is in pick_next_entity.
4442  */
4443 static void yield_task_fair(struct rq *rq)
4444 {
4445         struct task_struct *curr = rq->curr;
4446         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4447         struct sched_entity *se = &curr->se;
4448
4449         /*
4450          * Are we the only task in the tree?
4451          */
4452         if (unlikely(rq->nr_running == 1))
4453                 return;
4454
4455         clear_buddies(cfs_rq, se);
4456
4457         if (curr->policy != SCHED_BATCH) {
4458                 update_rq_clock(rq);
4459                 /*
4460                  * Update run-time statistics of the 'current'.
4461                  */
4462                 update_curr(cfs_rq);
4463                 /*
4464                  * Tell update_rq_clock() that we've just updated,
4465                  * so we don't do microscopic update in schedule()
4466                  * and double the fastpath cost.
4467                  */
4468                  rq->skip_clock_update = 1;
4469         }
4470
4471         set_skip_buddy(se);
4472 }
4473
4474 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
4475 {
4476         struct sched_entity *se = &p->se;
4477
4478         /* throttled hierarchies are not runnable */
4479         if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
4480                 return false;
4481
4482         /* Tell the scheduler that we'd really like pse to run next. */
4483         set_next_buddy(se);
4484
4485         yield_task_fair(rq);
4486
4487         return true;
4488 }
4489
4490 #ifdef CONFIG_SMP
4491 /**************************************************
4492  * Fair scheduling class load-balancing methods.
4493  *
4494  * BASICS
4495  *
4496  * The purpose of load-balancing is to achieve the same basic fairness the
4497  * per-cpu scheduler provides, namely provide a proportional amount of compute
4498  * time to each task. This is expressed in the following equation:
4499  *
4500  *   W_i,n/P_i == W_j,n/P_j for all i,j                               (1)
4501  *
4502  * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
4503  * W_i,0 is defined as:
4504  *
4505  *   W_i,0 = \Sum_j w_i,j                                             (2)
4506  *
4507  * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
4508  * is derived from the nice value as per prio_to_weight[].
4509  *
4510  * The weight average is an exponential decay average of the instantaneous
4511  * weight:
4512  *
4513  *   W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0               (3)
4514  *
4515  * P_i is the cpu power (or compute capacity) of cpu i, typically it is the
4516  * fraction of 'recent' time available for SCHED_OTHER task execution. But it
4517  * can also include other factors [XXX].
4518  *
4519  * To achieve this balance we define a measure of imbalance which follows
4520  * directly from (1):
4521  *
4522  *   imb_i,j = max{ avg(W/P), W_i/P_i } - min{ avg(W/P), W_j/P_j }    (4)
4523  *
4524  * We them move tasks around to minimize the imbalance. In the continuous
4525  * function space it is obvious this converges, in the discrete case we get
4526  * a few fun cases generally called infeasible weight scenarios.
4527  *
4528  * [XXX expand on:
4529  *     - infeasible weights;
4530  *     - local vs global optima in the discrete case. ]
4531  *
4532  *
4533  * SCHED DOMAINS
4534  *
4535  * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
4536  * for all i,j solution, we create a tree of cpus that follows the hardware
4537  * topology where each level pairs two lower groups (or better). This results
4538  * in O(log n) layers. Furthermore we reduce the number of cpus going up the
4539  * tree to only the first of the previous level and we decrease the frequency
4540  * of load-balance at each level inv. proportional to the number of cpus in
4541  * the groups.
4542  *
4543  * This yields:
4544  *
4545  *     log_2 n     1     n
4546  *   \Sum       { --- * --- * 2^i } = O(n)                            (5)
4547  *     i = 0      2^i   2^i
4548  *                               `- size of each group
4549  *         |         |     `- number of cpus doing load-balance
4550  *         |         `- freq
4551  *         `- sum over all levels
4552  *
4553  * Coupled with a limit on how many tasks we can migrate every balance pass,
4554  * this makes (5) the runtime complexity of the balancer.
4555  *
4556  * An important property here is that each CPU is still (indirectly) connected
4557  * to every other cpu in at most O(log n) steps:
4558  *
4559  * The adjacency matrix of the resulting graph is given by:
4560  *
4561  *             log_2 n     
4562  *   A_i,j = \Union     (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1)  (6)
4563  *             k = 0
4564  *
4565  * And you'll find that:
4566  *
4567  *   A^(log_2 n)_i,j != 0  for all i,j                                (7)
4568  *
4569  * Showing there's indeed a path between every cpu in at most O(log n) steps.
4570  * The task movement gives a factor of O(m), giving a convergence complexity
4571  * of:
4572  *
4573  *   O(nm log n),  n := nr_cpus, m := nr_tasks                        (8)
4574  *
4575  *
4576  * WORK CONSERVING
4577  *
4578  * In order to avoid CPUs going idle while there's still work to do, new idle
4579  * balancing is more aggressive and has the newly idle cpu iterate up the domain
4580  * tree itself instead of relying on other CPUs to bring it work.
4581  *
4582  * This adds some complexity to both (5) and (8) but it reduces the total idle
4583  * time.
4584  *
4585  * [XXX more?]
4586  *
4587  *
4588  * CGROUPS
4589  *
4590  * Cgroups make a horror show out of (2), instead of a simple sum we get:
4591  *
4592  *                                s_k,i
4593  *   W_i,0 = \Sum_j \Prod_k w_k * -----                               (9)
4594  *                                 S_k
4595  *
4596  * Where
4597  *
4598  *   s_k,i = \Sum_j w_i,j,k  and  S_k = \Sum_i s_k,i                 (10)
4599  *
4600  * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
4601  *
4602  * The big problem is S_k, its a global sum needed to compute a local (W_i)
4603  * property.
4604  *
4605  * [XXX write more on how we solve this.. _after_ merging pjt's patches that
4606  *      rewrite all of this once again.]
4607  */ 
4608
4609 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
4610
4611 #define LBF_ALL_PINNED  0x01
4612 #define LBF_NEED_BREAK  0x02
4613 #define LBF_SOME_PINNED 0x04
4614
4615 struct lb_env {
4616         struct sched_domain     *sd;
4617
4618         struct rq               *src_rq;
4619         int                     src_cpu;
4620
4621         int                     dst_cpu;
4622         struct rq               *dst_rq;
4623
4624         struct cpumask          *dst_grpmask;
4625         int                     new_dst_cpu;
4626         enum cpu_idle_type      idle;
4627         long                    imbalance;
4628         /* The set of CPUs under consideration for load-balancing */
4629         struct cpumask          *cpus;
4630
4631         unsigned int            flags;
4632
4633         unsigned int            loop;
4634         unsigned int            loop_break;
4635         unsigned int            loop_max;
4636 };
4637
4638 /*
4639  * move_task - move a task from one runqueue to another runqueue.
4640  * Both runqueues must be locked.
4641  */
4642 static void move_task(struct task_struct *p, struct lb_env *env)
4643 {
4644         deactivate_task(env->src_rq, p, 0);
4645         set_task_cpu(p, env->dst_cpu);
4646         activate_task(env->dst_rq, p, 0);
4647         check_preempt_curr(env->dst_rq, p, 0);
4648 }
4649
4650 /*
4651  * Is this task likely cache-hot:
4652  */
4653 static int
4654 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
4655 {
4656         s64 delta;
4657
4658         if (p->sched_class != &fair_sched_class)
4659                 return 0;
4660
4661         if (unlikely(p->policy == SCHED_IDLE))
4662                 return 0;
4663
4664         /*
4665          * Buddy candidates are cache hot:
4666          */
4667         if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
4668                         (&p->se == cfs_rq_of(&p->se)->next ||
4669                          &p->se == cfs_rq_of(&p->se)->last))
4670                 return 1;
4671
4672         if (sysctl_sched_migration_cost == -1)
4673                 return 1;
4674         if (sysctl_sched_migration_cost == 0)
4675                 return 0;
4676
4677         delta = now - p->se.exec_start;
4678
4679         return delta < (s64)sysctl_sched_migration_cost;
4680 }
4681
4682 /*
4683  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
4684  */
4685 static
4686 int can_migrate_task(struct task_struct *p, struct lb_env *env)
4687 {
4688         int tsk_cache_hot = 0;
4689         /*
4690          * We do not migrate tasks that are:
4691          * 1) throttled_lb_pair, or
4692          * 2) cannot be migrated to this CPU due to cpus_allowed, or
4693          * 3) running (obviously), or
4694          * 4) are cache-hot on their current CPU.
4695          */
4696         if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
4697                 return 0;
4698
4699         if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
4700                 int cpu;
4701
4702                 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
4703
4704                 /*
4705                  * Remember if this task can be migrated to any other cpu in
4706                  * our sched_group. We may want to revisit it if we couldn't
4707                  * meet load balance goals by pulling other tasks on src_cpu.
4708                  *
4709                  * Also avoid computing new_dst_cpu if we have already computed
4710                  * one in current iteration.
4711                  */
4712                 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
4713                         return 0;
4714
4715                 /* Prevent to re-select dst_cpu via env's cpus */
4716                 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
4717                         if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
4718                                 env->flags |= LBF_SOME_PINNED;
4719                                 env->new_dst_cpu = cpu;
4720                                 break;
4721                         }
4722                 }
4723
4724                 return 0;
4725         }
4726
4727         /* Record that we found atleast one task that could run on dst_cpu */
4728         env->flags &= ~LBF_ALL_PINNED;
4729
4730         if (task_running(env->src_rq, p)) {
4731                 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
4732                 return 0;
4733         }
4734
4735         /*
4736          * Aggressive migration if:
4737          * 1) task is cache cold, or
4738          * 2) too many balance attempts have failed.
4739          */
4740         tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
4741         if (!tsk_cache_hot ||
4742                 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
4743
4744                 if (tsk_cache_hot) {
4745                         schedstat_inc(env->sd, lb_hot_gained[env->idle]);
4746                         schedstat_inc(p, se.statistics.nr_forced_migrations);
4747                 }
4748
4749                 return 1;
4750         }
4751
4752         schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
4753         return 0;
4754 }
4755
4756 /*
4757  * move_one_task tries to move exactly one task from busiest to this_rq, as
4758  * part of active balancing operations within "domain".
4759  * Returns 1 if successful and 0 otherwise.
4760  *
4761  * Called with both runqueues locked.
4762  */
4763 static int move_one_task(struct lb_env *env)
4764 {
4765         struct task_struct *p, *n;
4766
4767         list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
4768                 if (!can_migrate_task(p, env))
4769                         continue;
4770
4771                 move_task(p, env);
4772                 /*
4773                  * Right now, this is only the second place move_task()
4774                  * is called, so we can safely collect move_task()
4775                  * stats here rather than inside move_task().
4776                  */
4777                 schedstat_inc(env->sd, lb_gained[env->idle]);
4778                 return 1;
4779         }
4780         return 0;
4781 }
4782
4783 static unsigned long task_h_load(struct task_struct *p);
4784
4785 static const unsigned int sched_nr_migrate_break = 32;
4786
4787 /*
4788  * move_tasks tries to move up to imbalance weighted load from busiest to
4789  * this_rq, as part of a balancing operation within domain "sd".
4790  * Returns 1 if successful and 0 otherwise.
4791  *
4792  * Called with both runqueues locked.
4793  */
4794 static int move_tasks(struct lb_env *env)
4795 {
4796         struct list_head *tasks = &env->src_rq->cfs_tasks;
4797         struct task_struct *p;
4798         unsigned long load;
4799         int pulled = 0;
4800
4801         if (env->imbalance <= 0)
4802                 return 0;
4803
4804         while (!list_empty(tasks)) {
4805                 p = list_first_entry(tasks, struct task_struct, se.group_node);
4806
4807                 env->loop++;
4808                 /* We've more or less seen every task there is, call it quits */
4809                 if (env->loop > env->loop_max)
4810                         break;
4811
4812                 /* take a breather every nr_migrate tasks */
4813                 if (env->loop > env->loop_break) {
4814                         env->loop_break += sched_nr_migrate_break;
4815                         env->flags |= LBF_NEED_BREAK;
4816                         break;
4817                 }
4818
4819                 if (!can_migrate_task(p, env))
4820                         goto next;
4821
4822                 load = task_h_load(p);
4823
4824                 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
4825                         goto next;
4826
4827                 if ((load / 2) > env->imbalance)
4828                         goto next;
4829
4830                 move_task(p, env);
4831                 pulled++;
4832                 env->imbalance -= load;
4833
4834 #ifdef CONFIG_PREEMPT
4835                 /*
4836                  * NEWIDLE balancing is a source of latency, so preemptible
4837                  * kernels will stop after the first task is pulled to minimize
4838                  * the critical section.
4839                  */
4840                 if (env->idle == CPU_NEWLY_IDLE)
4841                         break;
4842 #endif
4843
4844                 /*
4845                  * We only want to steal up to the prescribed amount of
4846                  * weighted load.
4847                  */
4848                 if (env->imbalance <= 0)
4849                         break;
4850
4851                 continue;
4852 next:
4853                 list_move_tail(&p->se.group_node, tasks);
4854         }
4855
4856         /*
4857          * Right now, this is one of only two places move_task() is called,
4858          * so we can safely collect move_task() stats here rather than
4859          * inside move_task().
4860          */
4861         schedstat_add(env->sd, lb_gained[env->idle], pulled);
4862
4863         return pulled;
4864 }
4865
4866 #ifdef CONFIG_FAIR_GROUP_SCHED
4867 /*
4868  * update tg->load_weight by folding this cpu's load_avg
4869  */
4870 static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
4871 {
4872         struct sched_entity *se = tg->se[cpu];
4873         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
4874
4875         /* throttled entities do not contribute to load */
4876         if (throttled_hierarchy(cfs_rq))
4877                 return;
4878
4879         update_cfs_rq_blocked_load(cfs_rq, 1);
4880
4881         if (se) {
4882                 update_entity_load_avg(se, 1);
4883                 /*
4884                  * We pivot on our runnable average having decayed to zero for
4885                  * list removal.  This generally implies that all our children
4886                  * have also been removed (modulo rounding error or bandwidth
4887                  * control); however, such cases are rare and we can fix these
4888                  * at enqueue.
4889                  *
4890                  * TODO: fix up out-of-order children on enqueue.
4891                  */
4892                 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
4893                         list_del_leaf_cfs_rq(cfs_rq);
4894         } else {
4895                 struct rq *rq = rq_of(cfs_rq);
4896                 update_rq_runnable_avg(rq, rq->nr_running);
4897         }
4898 }
4899
4900 static void update_blocked_averages(int cpu)
4901 {
4902         struct rq *rq = cpu_rq(cpu);
4903         struct cfs_rq *cfs_rq;
4904         unsigned long flags;
4905
4906         raw_spin_lock_irqsave(&rq->lock, flags);
4907         update_rq_clock(rq);
4908         /*
4909          * Iterates the task_group tree in a bottom up fashion, see
4910          * list_add_leaf_cfs_rq() for details.
4911          */
4912         for_each_leaf_cfs_rq(rq, cfs_rq) {
4913                 /*
4914                  * Note: We may want to consider periodically releasing
4915                  * rq->lock about these updates so that creating many task
4916                  * groups does not result in continually extending hold time.
4917                  */
4918                 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
4919         }
4920
4921         raw_spin_unlock_irqrestore(&rq->lock, flags);
4922 }
4923
4924 /*
4925  * Compute the cpu's hierarchical load factor for each task group.
4926  * This needs to be done in a top-down fashion because the load of a child
4927  * group is a fraction of its parents load.
4928  */
4929 static int tg_load_down(struct task_group *tg, void *data)
4930 {
4931         unsigned long load;
4932         long cpu = (long)data;
4933
4934         if (!tg->parent) {
4935                 load = cpu_rq(cpu)->load.weight;
4936         } else {
4937                 load = tg->parent->cfs_rq[cpu]->h_load;
4938                 load *= tg->se[cpu]->load.weight;
4939                 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
4940         }
4941
4942         tg->cfs_rq[cpu]->h_load = load;
4943
4944         return 0;
4945 }
4946
4947 static void update_h_load(long cpu)
4948 {
4949         struct rq *rq = cpu_rq(cpu);
4950         unsigned long now = jiffies;
4951
4952         if (rq->h_load_throttle == now)
4953                 return;
4954
4955         rq->h_load_throttle = now;
4956
4957         rcu_read_lock();
4958         walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
4959         rcu_read_unlock();
4960 }
4961
4962 static unsigned long task_h_load(struct task_struct *p)
4963 {
4964         struct cfs_rq *cfs_rq = task_cfs_rq(p);
4965         unsigned long load;
4966
4967         load = p->se.load.weight;
4968         load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
4969
4970         return load;
4971 }
4972 #else
4973 static inline void update_blocked_averages(int cpu)
4974 {
4975 }
4976
4977 static inline void update_h_load(long cpu)
4978 {
4979 }
4980
4981 static unsigned long task_h_load(struct task_struct *p)
4982 {
4983         return p->se.load.weight;
4984 }
4985 #endif
4986
4987 /********** Helpers for find_busiest_group ************************/
4988 /*
4989  * sd_lb_stats - Structure to store the statistics of a sched_domain
4990  *              during load balancing.
4991  */
4992 struct sd_lb_stats {
4993         struct sched_group *busiest; /* Busiest group in this sd */
4994         struct sched_group *this;  /* Local group in this sd */
4995         unsigned long total_load;  /* Total load of all groups in sd */
4996         unsigned long total_pwr;   /*   Total power of all groups in sd */
4997         unsigned long avg_load;    /* Average load across all groups in sd */
4998
4999         /** Statistics of this group */
5000         unsigned long this_load;
5001         unsigned long this_load_per_task;
5002         unsigned long this_nr_running;
5003         unsigned long this_has_capacity;
5004         unsigned int  this_idle_cpus;
5005
5006         /* Statistics of the busiest group */
5007         unsigned int  busiest_idle_cpus;
5008         unsigned long max_load;
5009         unsigned long busiest_load_per_task;
5010         unsigned long busiest_nr_running;
5011         unsigned long busiest_group_capacity;
5012         unsigned long busiest_has_capacity;
5013         unsigned int  busiest_group_weight;
5014
5015         int group_imb; /* Is there imbalance in this sd */
5016 };
5017
5018 /*
5019  * sg_lb_stats - stats of a sched_group required for load_balancing
5020  */
5021 struct sg_lb_stats {
5022         unsigned long avg_load; /*Avg load across the CPUs of the group */
5023         unsigned long group_load; /* Total load over the CPUs of the group */
5024         unsigned long sum_nr_running; /* Nr tasks running in the group */
5025         unsigned long sum_weighted_load; /* Weighted load of group's tasks */
5026         unsigned long group_capacity;
5027         unsigned long idle_cpus;
5028         unsigned long group_weight;
5029         int group_imb; /* Is there an imbalance in the group ? */
5030         int group_has_capacity; /* Is there extra capacity in the group? */
5031 };
5032
5033 /**
5034  * get_sd_load_idx - Obtain the load index for a given sched domain.
5035  * @sd: The sched_domain whose load_idx is to be obtained.
5036  * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
5037  */
5038 static inline int get_sd_load_idx(struct sched_domain *sd,
5039                                         enum cpu_idle_type idle)
5040 {
5041         int load_idx;
5042
5043         switch (idle) {
5044         case CPU_NOT_IDLE:
5045                 load_idx = sd->busy_idx;
5046                 break;
5047
5048         case CPU_NEWLY_IDLE:
5049                 load_idx = sd->newidle_idx;
5050                 break;
5051         default:
5052                 load_idx = sd->idle_idx;
5053                 break;
5054         }
5055
5056         return load_idx;
5057 }
5058
5059 static unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
5060 {
5061         return SCHED_POWER_SCALE;
5062 }
5063
5064 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
5065 {
5066         return default_scale_freq_power(sd, cpu);
5067 }
5068
5069 static unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
5070 {
5071         unsigned long weight = sd->span_weight;
5072         unsigned long smt_gain = sd->smt_gain;
5073
5074         smt_gain /= weight;
5075
5076         return smt_gain;
5077 }
5078
5079 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
5080 {
5081         return default_scale_smt_power(sd, cpu);
5082 }
5083
5084 static unsigned long scale_rt_power(int cpu)
5085 {
5086         struct rq *rq = cpu_rq(cpu);
5087         u64 total, available, age_stamp, avg;
5088
5089         /*
5090          * Since we're reading these variables without serialization make sure
5091          * we read them once before doing sanity checks on them.
5092          */
5093         age_stamp = ACCESS_ONCE(rq->age_stamp);
5094         avg = ACCESS_ONCE(rq->rt_avg);
5095
5096         total = sched_avg_period() + (rq->clock - age_stamp);
5097
5098         if (unlikely(total < avg)) {
5099                 /* Ensures that power won't end up being negative */
5100                 available = 0;
5101         } else {
5102                 available = total - avg;
5103         }
5104
5105         if (unlikely((s64)total < SCHED_POWER_SCALE))
5106                 total = SCHED_POWER_SCALE;
5107
5108         total >>= SCHED_POWER_SHIFT;
5109
5110         return div_u64(available, total);
5111 }
5112
5113 static void update_cpu_power(struct sched_domain *sd, int cpu)
5114 {
5115         unsigned long weight = sd->span_weight;
5116         unsigned long power = SCHED_POWER_SCALE;
5117         struct sched_group *sdg = sd->groups;
5118
5119         if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
5120                 if (sched_feat(ARCH_POWER))
5121                         power *= arch_scale_smt_power(sd, cpu);
5122                 else
5123                         power *= default_scale_smt_power(sd, cpu);
5124
5125                 power >>= SCHED_POWER_SHIFT;
5126         }
5127
5128         sdg->sgp->power_orig = power;
5129
5130         if (sched_feat(ARCH_POWER))
5131                 power *= arch_scale_freq_power(sd, cpu);
5132         else
5133                 power *= default_scale_freq_power(sd, cpu);
5134
5135         power >>= SCHED_POWER_SHIFT;
5136
5137         power *= scale_rt_power(cpu);
5138         power >>= SCHED_POWER_SHIFT;
5139
5140         if (!power)
5141                 power = 1;
5142
5143         cpu_rq(cpu)->cpu_power = power;
5144         sdg->sgp->power = power;
5145 }
5146
5147 void update_group_power(struct sched_domain *sd, int cpu)
5148 {
5149         struct sched_domain *child = sd->child;
5150         struct sched_group *group, *sdg = sd->groups;
5151         unsigned long power;
5152         unsigned long interval;
5153
5154         interval = msecs_to_jiffies(sd->balance_interval);
5155         interval = clamp(interval, 1UL, max_load_balance_interval);
5156         sdg->sgp->next_update = jiffies + interval;
5157
5158         if (!child) {
5159                 update_cpu_power(sd, cpu);
5160                 return;
5161         }
5162
5163         power = 0;
5164
5165         if (child->flags & SD_OVERLAP) {
5166                 /*
5167                  * SD_OVERLAP domains cannot assume that child groups
5168                  * span the current group.
5169                  */
5170
5171                 for_each_cpu(cpu, sched_group_cpus(sdg))
5172                         power += power_of(cpu);
5173         } else  {
5174                 /*
5175                  * !SD_OVERLAP domains can assume that child groups
5176                  * span the current group.
5177                  */ 
5178
5179                 group = child->groups;
5180                 do {
5181                         power += group->sgp->power;
5182                         group = group->next;
5183                 } while (group != child->groups);
5184         }
5185
5186         sdg->sgp->power_orig = sdg->sgp->power = power;
5187 }
5188
5189 /*
5190  * Try and fix up capacity for tiny siblings, this is needed when
5191  * things like SD_ASYM_PACKING need f_b_g to select another sibling
5192  * which on its own isn't powerful enough.
5193  *
5194  * See update_sd_pick_busiest() and check_asym_packing().
5195  */
5196 static inline int
5197 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
5198 {
5199         /*
5200          * Only siblings can have significantly less than SCHED_POWER_SCALE
5201          */
5202         if (!(sd->flags & SD_SHARE_CPUPOWER))
5203                 return 0;
5204
5205         /*
5206          * If ~90% of the cpu_power is still there, we're good.
5207          */
5208         if (group->sgp->power * 32 > group->sgp->power_orig * 29)
5209                 return 1;
5210
5211         return 0;
5212 }
5213
5214 /**
5215  * update_sg_lb_stats - Update sched_group's statistics for load balancing.
5216  * @env: The load balancing environment.
5217  * @group: sched_group whose statistics are to be updated.
5218  * @load_idx: Load index of sched_domain of this_cpu for load calc.
5219  * @local_group: Does group contain this_cpu.
5220  * @balance: Should we balance.
5221  * @sgs: variable to hold the statistics for this group.
5222  */
5223 static inline void update_sg_lb_stats(struct lb_env *env,
5224                         struct sched_group *group, int load_idx,
5225                         int local_group, int *balance, struct sg_lb_stats *sgs)
5226 {
5227         unsigned long nr_running, max_nr_running, min_nr_running;
5228         unsigned long load, max_cpu_load, min_cpu_load;
5229         unsigned int balance_cpu = -1, first_idle_cpu = 0;
5230         unsigned long avg_load_per_task = 0;
5231         int i;
5232
5233         if (local_group)
5234                 balance_cpu = group_balance_cpu(group);
5235
5236         /* Tally up the load of all CPUs in the group */
5237         max_cpu_load = 0;
5238         min_cpu_load = ~0UL;
5239         max_nr_running = 0;
5240         min_nr_running = ~0UL;
5241
5242         for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
5243                 struct rq *rq = cpu_rq(i);
5244
5245                 nr_running = rq->nr_running;
5246
5247                 /* Bias balancing toward cpus of our domain */
5248                 if (local_group) {
5249                         if (idle_cpu(i) && !first_idle_cpu &&
5250                                         cpumask_test_cpu(i, sched_group_mask(group))) {
5251                                 first_idle_cpu = 1;
5252                                 balance_cpu = i;
5253                         }
5254
5255                         load = target_load(i, load_idx);
5256                 } else {
5257                         load = source_load(i, load_idx);
5258                         if (load > max_cpu_load)
5259                                 max_cpu_load = load;
5260                         if (min_cpu_load > load)
5261                                 min_cpu_load = load;
5262
5263                         if (nr_running > max_nr_running)
5264                                 max_nr_running = nr_running;
5265                         if (min_nr_running > nr_running)
5266                                 min_nr_running = nr_running;
5267                 }
5268
5269                 sgs->group_load += load;
5270                 sgs->sum_nr_running += nr_running;
5271                 sgs->sum_weighted_load += weighted_cpuload(i);
5272                 if (idle_cpu(i))
5273                         sgs->idle_cpus++;
5274         }
5275
5276         /*
5277          * First idle cpu or the first cpu(busiest) in this sched group
5278          * is eligible for doing load balancing at this and above
5279          * domains. In the newly idle case, we will allow all the cpu's
5280          * to do the newly idle load balance.
5281          */
5282         if (local_group) {
5283                 if (env->idle != CPU_NEWLY_IDLE) {
5284                         if (balance_cpu != env->dst_cpu) {
5285                                 *balance = 0;
5286                                 return;
5287                         }
5288                         update_group_power(env->sd, env->dst_cpu);
5289                 } else if (time_after_eq(jiffies, group->sgp->next_update))
5290                         update_group_power(env->sd, env->dst_cpu);
5291         }
5292
5293         /* Adjust by relative CPU power of the group */
5294         sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
5295
5296         /*
5297          * Consider the group unbalanced when the imbalance is larger
5298          * than the average weight of a task.
5299          *
5300          * APZ: with cgroup the avg task weight can vary wildly and
5301          *      might not be a suitable number - should we keep a
5302          *      normalized nr_running number somewhere that negates
5303          *      the hierarchy?
5304          */
5305         if (sgs->sum_nr_running)
5306                 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
5307
5308         if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
5309             (max_nr_running - min_nr_running) > 1)
5310                 sgs->group_imb = 1;
5311
5312         sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
5313                                                 SCHED_POWER_SCALE);
5314         if (!sgs->group_capacity)
5315                 sgs->group_capacity = fix_small_capacity(env->sd, group);
5316         sgs->group_weight = group->group_weight;
5317
5318         if (sgs->group_capacity > sgs->sum_nr_running)
5319                 sgs->group_has_capacity = 1;
5320 }
5321
5322 /**
5323  * update_sd_pick_busiest - return 1 on busiest group
5324  * @env: The load balancing environment.
5325  * @sds: sched_domain statistics
5326  * @sg: sched_group candidate to be checked for being the busiest
5327  * @sgs: sched_group statistics
5328  *
5329  * Determine if @sg is a busier group than the previously selected
5330  * busiest group.
5331  */
5332 static bool update_sd_pick_busiest(struct lb_env *env,
5333                                    struct sd_lb_stats *sds,
5334                                    struct sched_group *sg,
5335                                    struct sg_lb_stats *sgs)
5336 {
5337         if (sgs->avg_load <= sds->max_load)
5338                 return false;
5339
5340         if (sgs->sum_nr_running > sgs->group_capacity)
5341                 return true;
5342
5343         if (sgs->group_imb)
5344                 return true;
5345
5346         /*
5347          * ASYM_PACKING needs to move all the work to the lowest
5348          * numbered CPUs in the group, therefore mark all groups
5349          * higher than ourself as busy.
5350          */
5351         if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
5352             env->dst_cpu < group_first_cpu(sg)) {
5353                 if (!sds->busiest)
5354                         return true;
5355
5356                 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
5357                         return true;
5358         }
5359
5360         return false;
5361 }
5362
5363 /**
5364  * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
5365  * @env: The load balancing environment.
5366  * @balance: Should we balance.
5367  * @sds: variable to hold the statistics for this sched_domain.
5368  */
5369 static inline void update_sd_lb_stats(struct lb_env *env,
5370                                         int *balance, struct sd_lb_stats *sds)
5371 {
5372         struct sched_domain *child = env->sd->child;
5373         struct sched_group *sg = env->sd->groups;
5374         struct sg_lb_stats sgs;
5375         int load_idx, prefer_sibling = 0;
5376
5377         if (child && child->flags & SD_PREFER_SIBLING)
5378                 prefer_sibling = 1;
5379
5380         load_idx = get_sd_load_idx(env->sd, env->idle);
5381
5382         do {
5383                 int local_group;
5384
5385                 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
5386                 memset(&sgs, 0, sizeof(sgs));
5387                 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
5388
5389                 if (local_group && !(*balance))
5390                         return;
5391
5392                 sds->total_load += sgs.group_load;
5393                 sds->total_pwr += sg->sgp->power;
5394
5395                 /*
5396                  * In case the child domain prefers tasks go to siblings
5397                  * first, lower the sg capacity to one so that we'll try
5398                  * and move all the excess tasks away. We lower the capacity
5399                  * of a group only if the local group has the capacity to fit
5400                  * these excess tasks, i.e. nr_running < group_capacity. The
5401                  * extra check prevents the case where you always pull from the
5402                  * heaviest group when it is already under-utilized (possible
5403                  * with a large weight task outweighs the tasks on the system).
5404                  */
5405                 if (prefer_sibling && !local_group && sds->this_has_capacity)
5406                         sgs.group_capacity = min(sgs.group_capacity, 1UL);
5407
5408                 if (local_group) {
5409                         sds->this_load = sgs.avg_load;
5410                         sds->this = sg;
5411                         sds->this_nr_running = sgs.sum_nr_running;
5412                         sds->this_load_per_task = sgs.sum_weighted_load;
5413                         sds->this_has_capacity = sgs.group_has_capacity;
5414                         sds->this_idle_cpus = sgs.idle_cpus;
5415                 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
5416                         sds->max_load = sgs.avg_load;
5417                         sds->busiest = sg;
5418                         sds->busiest_nr_running = sgs.sum_nr_running;
5419                         sds->busiest_idle_cpus = sgs.idle_cpus;
5420                         sds->busiest_group_capacity = sgs.group_capacity;
5421                         sds->busiest_load_per_task = sgs.sum_weighted_load;
5422                         sds->busiest_has_capacity = sgs.group_has_capacity;
5423                         sds->busiest_group_weight = sgs.group_weight;
5424                         sds->group_imb = sgs.group_imb;
5425                 }
5426
5427                 sg = sg->next;
5428         } while (sg != env->sd->groups);
5429 }
5430
5431 /**
5432  * check_asym_packing - Check to see if the group is packed into the
5433  *                      sched doman.
5434  *
5435  * This is primarily intended to used at the sibling level.  Some
5436  * cores like POWER7 prefer to use lower numbered SMT threads.  In the
5437  * case of POWER7, it can move to lower SMT modes only when higher
5438  * threads are idle.  When in lower SMT modes, the threads will
5439  * perform better since they share less core resources.  Hence when we
5440  * have idle threads, we want them to be the higher ones.
5441  *
5442  * This packing function is run on idle threads.  It checks to see if
5443  * the busiest CPU in this domain (core in the P7 case) has a higher
5444  * CPU number than the packing function is being run on.  Here we are
5445  * assuming lower CPU number will be equivalent to lower a SMT thread
5446  * number.
5447  *
5448  * Returns 1 when packing is required and a task should be moved to
5449  * this CPU.  The amount of the imbalance is returned in *imbalance.
5450  *
5451  * @env: The load balancing environment.
5452  * @sds: Statistics of the sched_domain which is to be packed
5453  */
5454 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
5455 {
5456         int busiest_cpu;
5457
5458         if (!(env->sd->flags & SD_ASYM_PACKING))
5459                 return 0;
5460
5461         if (!sds->busiest)
5462                 return 0;
5463
5464         busiest_cpu = group_first_cpu(sds->busiest);
5465         if (env->dst_cpu > busiest_cpu)
5466                 return 0;
5467
5468         env->imbalance = DIV_ROUND_CLOSEST(
5469                 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
5470
5471         return 1;
5472 }
5473
5474 /**
5475  * fix_small_imbalance - Calculate the minor imbalance that exists
5476  *                      amongst the groups of a sched_domain, during
5477  *                      load balancing.
5478  * @env: The load balancing environment.
5479  * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
5480  */
5481 static inline
5482 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
5483 {
5484         unsigned long tmp, pwr_now = 0, pwr_move = 0;
5485         unsigned int imbn = 2;
5486         unsigned long scaled_busy_load_per_task;
5487
5488         if (sds->this_nr_running) {
5489                 sds->this_load_per_task /= sds->this_nr_running;
5490                 if (sds->busiest_load_per_task >
5491                                 sds->this_load_per_task)
5492                         imbn = 1;
5493         } else {
5494                 sds->this_load_per_task =
5495                         cpu_avg_load_per_task(env->dst_cpu);
5496         }
5497
5498         scaled_busy_load_per_task = sds->busiest_load_per_task
5499                                          * SCHED_POWER_SCALE;
5500         scaled_busy_load_per_task /= sds->busiest->sgp->power;
5501
5502         if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
5503                         (scaled_busy_load_per_task * imbn)) {
5504                 env->imbalance = sds->busiest_load_per_task;
5505                 return;
5506         }
5507
5508         /*
5509          * OK, we don't have enough imbalance to justify moving tasks,
5510          * however we may be able to increase total CPU power used by
5511          * moving them.
5512          */
5513
5514         pwr_now += sds->busiest->sgp->power *
5515                         min(sds->busiest_load_per_task, sds->max_load);
5516         pwr_now += sds->this->sgp->power *
5517                         min(sds->this_load_per_task, sds->this_load);
5518         pwr_now /= SCHED_POWER_SCALE;
5519
5520         /* Amount of load we'd subtract */
5521         tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
5522                 sds->busiest->sgp->power;
5523         if (sds->max_load > tmp)
5524                 pwr_move += sds->busiest->sgp->power *
5525                         min(sds->busiest_load_per_task, sds->max_load - tmp);
5526
5527         /* Amount of load we'd add */
5528         if (sds->max_load * sds->busiest->sgp->power <
5529                 sds->busiest_load_per_task * SCHED_POWER_SCALE)
5530                 tmp = (sds->max_load * sds->busiest->sgp->power) /
5531                         sds->this->sgp->power;
5532         else
5533                 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
5534                         sds->this->sgp->power;
5535         pwr_move += sds->this->sgp->power *
5536                         min(sds->this_load_per_task, sds->this_load + tmp);
5537         pwr_move /= SCHED_POWER_SCALE;
5538
5539         /* Move if we gain throughput */
5540         if (pwr_move > pwr_now)
5541                 env->imbalance = sds->busiest_load_per_task;
5542 }
5543
5544 /**
5545  * calculate_imbalance - Calculate the amount of imbalance present within the
5546  *                       groups of a given sched_domain during load balance.
5547  * @env: load balance environment
5548  * @sds: statistics of the sched_domain whose imbalance is to be calculated.
5549  */
5550 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
5551 {
5552         unsigned long max_pull, load_above_capacity = ~0UL;
5553
5554         sds->busiest_load_per_task /= sds->busiest_nr_running;
5555         if (sds->group_imb) {
5556                 sds->busiest_load_per_task =
5557                         min(sds->busiest_load_per_task, sds->avg_load);
5558         }
5559
5560         /*
5561          * In the presence of smp nice balancing, certain scenarios can have
5562          * max load less than avg load(as we skip the groups at or below
5563          * its cpu_power, while calculating max_load..)
5564          */
5565         if (sds->max_load < sds->avg_load) {
5566                 env->imbalance = 0;
5567                 return fix_small_imbalance(env, sds);
5568         }
5569
5570         if (!sds->group_imb) {
5571                 /*
5572                  * Don't want to pull so many tasks that a group would go idle.
5573                  */
5574                 load_above_capacity = (sds->busiest_nr_running -
5575                                                 sds->busiest_group_capacity);
5576
5577                 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
5578
5579                 load_above_capacity /= sds->busiest->sgp->power;
5580         }
5581
5582         /*
5583          * We're trying to get all the cpus to the average_load, so we don't
5584          * want to push ourselves above the average load, nor do we wish to
5585          * reduce the max loaded cpu below the average load. At the same time,
5586          * we also don't want to reduce the group load below the group capacity
5587          * (so that we can implement power-savings policies etc). Thus we look
5588          * for the minimum possible imbalance.
5589          * Be careful of negative numbers as they'll appear as very large values
5590          * with unsigned longs.
5591          */
5592         max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
5593
5594         /* How much load to actually move to equalise the imbalance */
5595         env->imbalance = min(max_pull * sds->busiest->sgp->power,
5596                 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
5597                         / SCHED_POWER_SCALE;
5598
5599         /*
5600          * if *imbalance is less than the average load per runnable task
5601          * there is no guarantee that any tasks will be moved so we'll have
5602          * a think about bumping its value to force at least one task to be
5603          * moved
5604          */
5605         if (env->imbalance < sds->busiest_load_per_task)
5606                 return fix_small_imbalance(env, sds);
5607
5608 }
5609
5610 /******* find_busiest_group() helpers end here *********************/
5611
5612 /**
5613  * find_busiest_group - Returns the busiest group within the sched_domain
5614  * if there is an imbalance. If there isn't an imbalance, and
5615  * the user has opted for power-savings, it returns a group whose
5616  * CPUs can be put to idle by rebalancing those tasks elsewhere, if
5617  * such a group exists.
5618  *
5619  * Also calculates the amount of weighted load which should be moved
5620  * to restore balance.
5621  *
5622  * @env: The load balancing environment.
5623  * @balance: Pointer to a variable indicating if this_cpu
5624  *      is the appropriate cpu to perform load balancing at this_level.
5625  *
5626  * Returns:     - the busiest group if imbalance exists.
5627  *              - If no imbalance and user has opted for power-savings balance,
5628  *                 return the least loaded group whose CPUs can be
5629  *                 put to idle by rebalancing its tasks onto our group.
5630  */
5631 static struct sched_group *
5632 find_busiest_group(struct lb_env *env, int *balance)
5633 {
5634         struct sd_lb_stats sds;
5635
5636         memset(&sds, 0, sizeof(sds));
5637
5638         /*
5639          * Compute the various statistics relavent for load balancing at
5640          * this level.
5641          */
5642         update_sd_lb_stats(env, balance, &sds);
5643
5644         /*
5645          * this_cpu is not the appropriate cpu to perform load balancing at
5646          * this level.
5647          */
5648         if (!(*balance))
5649                 goto ret;
5650
5651         if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
5652             check_asym_packing(env, &sds))
5653                 return sds.busiest;
5654
5655         /* There is no busy sibling group to pull tasks from */
5656         if (!sds.busiest || sds.busiest_nr_running == 0)
5657                 goto out_balanced;
5658
5659         sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
5660
5661         /*
5662          * If the busiest group is imbalanced the below checks don't
5663          * work because they assumes all things are equal, which typically
5664          * isn't true due to cpus_allowed constraints and the like.
5665          */
5666         if (sds.group_imb)
5667                 goto force_balance;
5668
5669         /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
5670         if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
5671                         !sds.busiest_has_capacity)
5672                 goto force_balance;
5673
5674         /*
5675          * If the local group is more busy than the selected busiest group
5676          * don't try and pull any tasks.
5677          */
5678         if (sds.this_load >= sds.max_load)
5679                 goto out_balanced;
5680
5681         /*
5682          * Don't pull any tasks if this group is already above the domain
5683          * average load.
5684          */
5685         if (sds.this_load >= sds.avg_load)
5686                 goto out_balanced;
5687
5688         if (env->idle == CPU_IDLE) {
5689                 /*
5690                  * This cpu is idle. If the busiest group load doesn't
5691                  * have more tasks than the number of available cpu's and
5692                  * there is no imbalance between this and busiest group
5693                  * wrt to idle cpu's, it is balanced.
5694                  */
5695                 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
5696                     sds.busiest_nr_running <= sds.busiest_group_weight)
5697                         goto out_balanced;
5698         } else {
5699                 /*
5700                  * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
5701                  * imbalance_pct to be conservative.
5702                  */
5703                 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
5704                         goto out_balanced;
5705         }
5706
5707 force_balance:
5708         /* Looks like there is an imbalance. Compute it */
5709         calculate_imbalance(env, &sds);
5710         return sds.busiest;
5711
5712 out_balanced:
5713 ret:
5714         env->imbalance = 0;
5715         return NULL;
5716 }
5717
5718 /*
5719  * find_busiest_queue - find the busiest runqueue among the cpus in group.
5720  */
5721 static struct rq *find_busiest_queue(struct lb_env *env,
5722                                      struct sched_group *group)
5723 {
5724         struct rq *busiest = NULL, *rq;
5725         unsigned long max_load = 0;
5726         int i;
5727
5728         for_each_cpu(i, sched_group_cpus(group)) {
5729                 unsigned long power = power_of(i);
5730                 unsigned long capacity = DIV_ROUND_CLOSEST(power,
5731                                                            SCHED_POWER_SCALE);
5732                 unsigned long wl;
5733
5734                 if (!capacity)
5735                         capacity = fix_small_capacity(env->sd, group);
5736
5737                 if (!cpumask_test_cpu(i, env->cpus))
5738                         continue;
5739
5740                 rq = cpu_rq(i);
5741                 wl = weighted_cpuload(i);
5742
5743                 /*
5744                  * When comparing with imbalance, use weighted_cpuload()
5745                  * which is not scaled with the cpu power.
5746                  */
5747                 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
5748                         continue;
5749
5750                 /*
5751                  * For the load comparisons with the other cpu's, consider
5752                  * the weighted_cpuload() scaled with the cpu power, so that
5753                  * the load can be moved away from the cpu that is potentially
5754                  * running at a lower capacity.
5755                  */
5756                 wl = (wl * SCHED_POWER_SCALE) / power;
5757
5758                 if (wl > max_load) {
5759                         max_load = wl;
5760                         busiest = rq;
5761                 }
5762         }
5763
5764         return busiest;
5765 }
5766
5767 /*
5768  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
5769  * so long as it is large enough.
5770  */
5771 #define MAX_PINNED_INTERVAL     512
5772
5773 /* Working cpumask for load_balance and load_balance_newidle. */
5774 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5775
5776 static int need_active_balance(struct lb_env *env)
5777 {
5778         struct sched_domain *sd = env->sd;
5779
5780         if (env->idle == CPU_NEWLY_IDLE) {
5781
5782                 /*
5783                  * ASYM_PACKING needs to force migrate tasks from busy but
5784                  * higher numbered CPUs in order to pack all tasks in the
5785                  * lowest numbered CPUs.
5786                  */
5787                 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
5788                         return 1;
5789         }
5790
5791         return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
5792 }
5793
5794 static int active_load_balance_cpu_stop(void *data);
5795
5796 /*
5797  * Check this_cpu to ensure it is balanced within domain. Attempt to move
5798  * tasks if there is an imbalance.
5799  */
5800 static int load_balance(int this_cpu, struct rq *this_rq,
5801                         struct sched_domain *sd, enum cpu_idle_type idle,
5802                         int *balance)
5803 {
5804         int ld_moved, cur_ld_moved, active_balance = 0;
5805         struct sched_group *group;
5806         struct rq *busiest;
5807         unsigned long flags;
5808         struct cpumask *cpus = __get_cpu_var(load_balance_mask);
5809
5810         struct lb_env env = {
5811                 .sd             = sd,
5812                 .dst_cpu        = this_cpu,
5813                 .dst_rq         = this_rq,
5814                 .dst_grpmask    = sched_group_cpus(sd->groups),
5815                 .idle           = idle,
5816                 .loop_break     = sched_nr_migrate_break,
5817                 .cpus           = cpus,
5818         };
5819
5820         /*
5821          * For NEWLY_IDLE load_balancing, we don't need to consider
5822          * other cpus in our group
5823          */
5824         if (idle == CPU_NEWLY_IDLE)
5825                 env.dst_grpmask = NULL;
5826
5827         cpumask_copy(cpus, cpu_active_mask);
5828
5829         schedstat_inc(sd, lb_count[idle]);
5830
5831 redo:
5832         group = find_busiest_group(&env, balance);
5833
5834         if (*balance == 0)
5835                 goto out_balanced;
5836
5837         if (!group) {
5838                 schedstat_inc(sd, lb_nobusyg[idle]);
5839                 goto out_balanced;
5840         }
5841
5842         busiest = find_busiest_queue(&env, group);
5843         if (!busiest) {
5844                 schedstat_inc(sd, lb_nobusyq[idle]);
5845                 goto out_balanced;
5846         }
5847
5848         BUG_ON(busiest == env.dst_rq);
5849
5850         schedstat_add(sd, lb_imbalance[idle], env.imbalance);
5851
5852         ld_moved = 0;
5853         if (busiest->nr_running > 1) {
5854                 /*
5855                  * Attempt to move tasks. If find_busiest_group has found
5856                  * an imbalance but busiest->nr_running <= 1, the group is
5857                  * still unbalanced. ld_moved simply stays zero, so it is
5858                  * correctly treated as an imbalance.
5859                  */
5860                 env.flags |= LBF_ALL_PINNED;
5861                 env.src_cpu   = busiest->cpu;
5862                 env.src_rq    = busiest;
5863                 env.loop_max  = min(sysctl_sched_nr_migrate, busiest->nr_running);
5864
5865                 update_h_load(env.src_cpu);
5866 more_balance:
5867                 local_irq_save(flags);
5868                 double_rq_lock(env.dst_rq, busiest);
5869
5870                 /*
5871                  * cur_ld_moved - load moved in current iteration
5872                  * ld_moved     - cumulative load moved across iterations
5873                  */
5874                 cur_ld_moved = move_tasks(&env);
5875                 ld_moved += cur_ld_moved;
5876                 double_rq_unlock(env.dst_rq, busiest);
5877                 local_irq_restore(flags);
5878
5879                 /*
5880                  * some other cpu did the load balance for us.
5881                  */
5882                 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
5883                         resched_cpu(env.dst_cpu);
5884
5885                 if (env.flags & LBF_NEED_BREAK) {
5886                         env.flags &= ~LBF_NEED_BREAK;
5887                         goto more_balance;
5888                 }
5889
5890                 /*
5891                  * Revisit (affine) tasks on src_cpu that couldn't be moved to
5892                  * us and move them to an alternate dst_cpu in our sched_group
5893                  * where they can run. The upper limit on how many times we
5894                  * iterate on same src_cpu is dependent on number of cpus in our
5895                  * sched_group.
5896                  *
5897                  * This changes load balance semantics a bit on who can move
5898                  * load to a given_cpu. In addition to the given_cpu itself
5899                  * (or a ilb_cpu acting on its behalf where given_cpu is
5900                  * nohz-idle), we now have balance_cpu in a position to move
5901                  * load to given_cpu. In rare situations, this may cause
5902                  * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
5903                  * _independently_ and at _same_ time to move some load to
5904                  * given_cpu) causing exceess load to be moved to given_cpu.
5905                  * This however should not happen so much in practice and
5906                  * moreover subsequent load balance cycles should correct the
5907                  * excess load moved.
5908                  */
5909                 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) {
5910
5911                         env.dst_rq       = cpu_rq(env.new_dst_cpu);
5912                         env.dst_cpu      = env.new_dst_cpu;
5913                         env.flags       &= ~LBF_SOME_PINNED;
5914                         env.loop         = 0;
5915                         env.loop_break   = sched_nr_migrate_break;
5916
5917                         /* Prevent to re-select dst_cpu via env's cpus */
5918                         cpumask_clear_cpu(env.dst_cpu, env.cpus);
5919
5920                         /*
5921                          * Go back to "more_balance" rather than "redo" since we
5922                          * need to continue with same src_cpu.
5923                          */
5924                         goto more_balance;
5925                 }
5926
5927                 /* All tasks on this runqueue were pinned by CPU affinity */
5928                 if (unlikely(env.flags & LBF_ALL_PINNED)) {
5929                         cpumask_clear_cpu(cpu_of(busiest), cpus);
5930                         if (!cpumask_empty(cpus)) {
5931                                 env.loop = 0;
5932                                 env.loop_break = sched_nr_migrate_break;
5933                                 goto redo;
5934                         }
5935                         goto out_balanced;
5936                 }
5937         }
5938
5939         if (!ld_moved) {
5940                 schedstat_inc(sd, lb_failed[idle]);
5941                 /*
5942                  * Increment the failure counter only on periodic balance.
5943                  * We do not want newidle balance, which can be very
5944                  * frequent, pollute the failure counter causing
5945                  * excessive cache_hot migrations and active balances.
5946                  */
5947                 if (idle != CPU_NEWLY_IDLE)
5948                         sd->nr_balance_failed++;
5949
5950                 if (need_active_balance(&env)) {
5951                         raw_spin_lock_irqsave(&busiest->lock, flags);
5952
5953                         /* don't kick the active_load_balance_cpu_stop,
5954                          * if the curr task on busiest cpu can't be
5955                          * moved to this_cpu
5956                          */
5957                         if (!cpumask_test_cpu(this_cpu,
5958                                         tsk_cpus_allowed(busiest->curr))) {
5959                                 raw_spin_unlock_irqrestore(&busiest->lock,
5960                                                             flags);
5961                                 env.flags |= LBF_ALL_PINNED;
5962                                 goto out_one_pinned;
5963                         }
5964
5965                         /*
5966                          * ->active_balance synchronizes accesses to
5967                          * ->active_balance_work.  Once set, it's cleared
5968                          * only after active load balance is finished.
5969                          */
5970                         if (!busiest->active_balance) {
5971                                 busiest->active_balance = 1;
5972                                 busiest->push_cpu = this_cpu;
5973                                 active_balance = 1;
5974                         }
5975                         raw_spin_unlock_irqrestore(&busiest->lock, flags);
5976
5977                         if (active_balance) {
5978                                 stop_one_cpu_nowait(cpu_of(busiest),
5979                                         active_load_balance_cpu_stop, busiest,
5980                                         &busiest->active_balance_work);
5981                         }
5982
5983                         /*
5984                          * We've kicked active balancing, reset the failure
5985                          * counter.
5986                          */
5987                         sd->nr_balance_failed = sd->cache_nice_tries+1;
5988                 }
5989         } else
5990                 sd->nr_balance_failed = 0;
5991
5992         if (likely(!active_balance)) {
5993                 /* We were unbalanced, so reset the balancing interval */
5994                 sd->balance_interval = sd->min_interval;
5995         } else {
5996                 /*
5997                  * If we've begun active balancing, start to back off. This
5998                  * case may not be covered by the all_pinned logic if there
5999                  * is only 1 task on the busy runqueue (because we don't call
6000                  * move_tasks).
6001                  */
6002                 if (sd->balance_interval < sd->max_interval)
6003                         sd->balance_interval *= 2;
6004         }
6005
6006         goto out;
6007
6008 out_balanced:
6009         schedstat_inc(sd, lb_balanced[idle]);
6010
6011         sd->nr_balance_failed = 0;
6012
6013 out_one_pinned:
6014         /* tune up the balancing interval */
6015         if (((env.flags & LBF_ALL_PINNED) &&
6016                         sd->balance_interval < MAX_PINNED_INTERVAL) ||
6017                         (sd->balance_interval < sd->max_interval))
6018                 sd->balance_interval *= 2;
6019
6020         ld_moved = 0;
6021 out:
6022         return ld_moved;
6023 }
6024 #ifdef CONFIG_SCHED_HMP
6025 static unsigned int hmp_idle_pull(int this_cpu);
6026 #endif
6027 /*
6028  * idle_balance is called by schedule() if this_cpu is about to become
6029  * idle. Attempts to pull tasks from other CPUs.
6030  */
6031 void idle_balance(int this_cpu, struct rq *this_rq)
6032 {
6033         struct sched_domain *sd;
6034         int pulled_task = 0;
6035         unsigned long next_balance = jiffies + HZ;
6036
6037         this_rq->idle_stamp = this_rq->clock;
6038
6039         if (this_rq->avg_idle < sysctl_sched_migration_cost)
6040                 return;
6041
6042         /*
6043          * Drop the rq->lock, but keep IRQ/preempt disabled.
6044          */
6045         raw_spin_unlock(&this_rq->lock);
6046
6047         update_blocked_averages(this_cpu);
6048         rcu_read_lock();
6049         for_each_domain(this_cpu, sd) {
6050                 unsigned long interval;
6051                 int balance = 1;
6052
6053                 if (!(sd->flags & SD_LOAD_BALANCE))
6054                         continue;
6055
6056                 if (sd->flags & SD_BALANCE_NEWIDLE) {
6057                         /* If we've pulled tasks over stop searching: */
6058                         pulled_task = load_balance(this_cpu, this_rq,
6059                                                    sd, CPU_NEWLY_IDLE, &balance);
6060                 }
6061
6062                 interval = msecs_to_jiffies(sd->balance_interval);
6063                 if (time_after(next_balance, sd->last_balance + interval))
6064                         next_balance = sd->last_balance + interval;
6065                 if (pulled_task) {
6066                         this_rq->idle_stamp = 0;
6067                         break;
6068                 }
6069         }
6070         rcu_read_unlock();
6071 #ifdef CONFIG_SCHED_HMP
6072         if (!pulled_task)
6073                 pulled_task = hmp_idle_pull(this_cpu);
6074 #endif
6075         raw_spin_lock(&this_rq->lock);
6076
6077         if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
6078                 /*
6079                  * We are going idle. next_balance may be set based on
6080                  * a busy processor. So reset next_balance.
6081                  */
6082                 this_rq->next_balance = next_balance;
6083         }
6084 }
6085
6086 /*
6087  * active_load_balance_cpu_stop is run by cpu stopper. It pushes
6088  * running tasks off the busiest CPU onto idle CPUs. It requires at
6089  * least 1 task to be running on each physical CPU where possible, and
6090  * avoids physical / logical imbalances.
6091  */
6092 static int active_load_balance_cpu_stop(void *data)
6093 {
6094         struct rq *busiest_rq = data;
6095         int busiest_cpu = cpu_of(busiest_rq);
6096         int target_cpu = busiest_rq->push_cpu;
6097         struct rq *target_rq = cpu_rq(target_cpu);
6098         struct sched_domain *sd;
6099
6100         raw_spin_lock_irq(&busiest_rq->lock);
6101
6102         /* make sure the requested cpu hasn't gone down in the meantime */
6103         if (unlikely(busiest_cpu != smp_processor_id() ||
6104                      !busiest_rq->active_balance))
6105                 goto out_unlock;
6106
6107         /* Is there any task to move? */
6108         if (busiest_rq->nr_running <= 1)
6109                 goto out_unlock;
6110
6111         /*
6112          * This condition is "impossible", if it occurs
6113          * we need to fix it. Originally reported by
6114          * Bjorn Helgaas on a 128-cpu setup.
6115          */
6116         BUG_ON(busiest_rq == target_rq);
6117
6118         /* move a task from busiest_rq to target_rq */
6119         double_lock_balance(busiest_rq, target_rq);
6120
6121         /* Search for an sd spanning us and the target CPU. */
6122         rcu_read_lock();
6123         for_each_domain(target_cpu, sd) {
6124                 if ((sd->flags & SD_LOAD_BALANCE) &&
6125                     cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6126                                 break;
6127         }
6128
6129         if (likely(sd)) {
6130                 struct lb_env env = {
6131                         .sd             = sd,
6132                         .dst_cpu        = target_cpu,
6133                         .dst_rq         = target_rq,
6134                         .src_cpu        = busiest_rq->cpu,
6135                         .src_rq         = busiest_rq,
6136                         .idle           = CPU_IDLE,
6137                 };
6138
6139                 schedstat_inc(sd, alb_count);
6140
6141                 if (move_one_task(&env))
6142                         schedstat_inc(sd, alb_pushed);
6143                 else
6144                         schedstat_inc(sd, alb_failed);
6145         }
6146         rcu_read_unlock();
6147         double_unlock_balance(busiest_rq, target_rq);
6148 out_unlock:
6149         busiest_rq->active_balance = 0;
6150         raw_spin_unlock_irq(&busiest_rq->lock);
6151         return 0;
6152 }
6153
6154 #ifdef CONFIG_NO_HZ_COMMON
6155 /*
6156  * idle load balancing details
6157  * - When one of the busy CPUs notice that there may be an idle rebalancing
6158  *   needed, they will kick the idle load balancer, which then does idle
6159  *   load balancing for all the idle CPUs.
6160  */
6161 static struct {
6162         cpumask_var_t idle_cpus_mask;
6163         atomic_t nr_cpus;
6164         unsigned long next_balance;     /* in jiffy units */
6165 } nohz ____cacheline_aligned;
6166
6167 static inline int find_new_ilb(int call_cpu)
6168 {
6169         int ilb = cpumask_first(nohz.idle_cpus_mask);
6170 #ifdef CONFIG_SCHED_HMP
6171         /* restrict nohz balancing to occur in the same hmp domain */
6172         ilb = cpumask_first_and(nohz.idle_cpus_mask,
6173                         &((struct hmp_domain *)hmp_cpu_domain(call_cpu))->cpus);
6174 #endif
6175         if (ilb < nr_cpu_ids && idle_cpu(ilb))
6176                 return ilb;
6177
6178         return nr_cpu_ids;
6179 }
6180
6181 /*
6182  * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
6183  * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
6184  * CPU (if there is one).
6185  */
6186 static void nohz_balancer_kick(int cpu)
6187 {
6188         int ilb_cpu;
6189
6190         nohz.next_balance++;
6191
6192         ilb_cpu = find_new_ilb(cpu);
6193
6194         if (ilb_cpu >= nr_cpu_ids)
6195                 return;
6196
6197         if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
6198                 return;
6199         /*
6200          * Use smp_send_reschedule() instead of resched_cpu().
6201          * This way we generate a sched IPI on the target cpu which
6202          * is idle. And the softirq performing nohz idle load balance
6203          * will be run before returning from the IPI.
6204          */
6205         smp_send_reschedule(ilb_cpu);
6206         return;
6207 }
6208
6209 static inline void nohz_balance_exit_idle(int cpu)
6210 {
6211         if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
6212                 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
6213                 atomic_dec(&nohz.nr_cpus);
6214                 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
6215         }
6216 }
6217
6218 static inline void set_cpu_sd_state_busy(void)
6219 {
6220         struct sched_domain *sd;
6221         int cpu = smp_processor_id();
6222
6223         rcu_read_lock();
6224         sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
6225
6226         if (!sd || !sd->nohz_idle)
6227                 goto unlock;
6228         sd->nohz_idle = 0;
6229
6230         for (; sd; sd = sd->parent)
6231                 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
6232 unlock:
6233         rcu_read_unlock();
6234 }
6235
6236 void set_cpu_sd_state_idle(void)
6237 {
6238         struct sched_domain *sd;
6239         int cpu = smp_processor_id();
6240
6241         rcu_read_lock();
6242         sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
6243
6244         if (!sd || sd->nohz_idle)
6245                 goto unlock;
6246         sd->nohz_idle = 1;
6247
6248         for (; sd; sd = sd->parent)
6249                 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
6250 unlock:
6251         rcu_read_unlock();
6252 }
6253
6254 /*
6255  * This routine will record that the cpu is going idle with tick stopped.
6256  * This info will be used in performing idle load balancing in the future.
6257  */
6258 void nohz_balance_enter_idle(int cpu)
6259 {
6260         /*
6261          * If this cpu is going down, then nothing needs to be done.
6262          */
6263         if (!cpu_active(cpu))
6264                 return;
6265
6266         if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
6267                 return;
6268
6269         cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
6270         atomic_inc(&nohz.nr_cpus);
6271         set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
6272 }
6273
6274 static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
6275                                         unsigned long action, void *hcpu)
6276 {
6277         switch (action & ~CPU_TASKS_FROZEN) {
6278         case CPU_DYING:
6279                 nohz_balance_exit_idle(smp_processor_id());
6280                 return NOTIFY_OK;
6281         default:
6282                 return NOTIFY_DONE;
6283         }
6284 }
6285 #endif
6286
6287 static DEFINE_SPINLOCK(balancing);
6288
6289 /*
6290  * Scale the max load_balance interval with the number of CPUs in the system.
6291  * This trades load-balance latency on larger machines for less cross talk.
6292  */
6293 void update_max_interval(void)
6294 {
6295         max_load_balance_interval = HZ*num_online_cpus()/10;
6296 }
6297
6298 /*
6299  * It checks each scheduling domain to see if it is due to be balanced,
6300  * and initiates a balancing operation if so.
6301  *
6302  * Balancing parameters are set up in init_sched_domains.
6303  */
6304 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
6305 {
6306         int balance = 1;
6307         struct rq *rq = cpu_rq(cpu);
6308         unsigned long interval;
6309         struct sched_domain *sd;
6310         /* Earliest time when we have to do rebalance again */
6311         unsigned long next_balance = jiffies + 60*HZ;
6312         int update_next_balance = 0;
6313         int need_serialize;
6314
6315         update_blocked_averages(cpu);
6316
6317         rcu_read_lock();
6318         for_each_domain(cpu, sd) {
6319                 if (!(sd->flags & SD_LOAD_BALANCE))
6320                         continue;
6321
6322                 interval = sd->balance_interval;
6323                 if (idle != CPU_IDLE)
6324                         interval *= sd->busy_factor;
6325
6326                 /* scale ms to jiffies */
6327                 interval = msecs_to_jiffies(interval);
6328                 interval = clamp(interval, 1UL, max_load_balance_interval);
6329
6330                 need_serialize = sd->flags & SD_SERIALIZE;
6331
6332                 if (need_serialize) {
6333                         if (!spin_trylock(&balancing))
6334                                 goto out;
6335                 }
6336
6337                 if (time_after_eq(jiffies, sd->last_balance + interval)) {
6338                         if (load_balance(cpu, rq, sd, idle, &balance)) {
6339                                 /*
6340                                  * The LBF_SOME_PINNED logic could have changed
6341                                  * env->dst_cpu, so we can't know our idle
6342                                  * state even if we migrated tasks. Update it.
6343                                  */
6344                                 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
6345                         }
6346                         sd->last_balance = jiffies;
6347                 }
6348                 if (need_serialize)
6349                         spin_unlock(&balancing);
6350 out:
6351                 if (time_after(next_balance, sd->last_balance + interval)) {
6352                         next_balance = sd->last_balance + interval;
6353                         update_next_balance = 1;
6354                 }
6355
6356                 /*
6357                  * Stop the load balance at this level. There is another
6358                  * CPU in our sched group which is doing load balancing more
6359                  * actively.
6360                  */
6361                 if (!balance)
6362                         break;
6363         }
6364         rcu_read_unlock();
6365
6366         /*
6367          * next_balance will be updated only when there is a need.
6368          * When the cpu is attached to null domain for ex, it will not be
6369          * updated.
6370          */
6371         if (likely(update_next_balance))
6372                 rq->next_balance = next_balance;
6373 }
6374
6375 #ifdef CONFIG_NO_HZ_COMMON
6376 /*
6377  * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
6378  * rebalancing for all the cpus for whom scheduler ticks are stopped.
6379  */
6380 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
6381 {
6382         struct rq *this_rq = cpu_rq(this_cpu);
6383         struct rq *rq;
6384         int balance_cpu;
6385
6386         if (idle != CPU_IDLE ||
6387             !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
6388                 goto end;
6389
6390         for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
6391                 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
6392                         continue;
6393
6394                 /*
6395                  * If this cpu gets work to do, stop the load balancing
6396                  * work being done for other cpus. Next load
6397                  * balancing owner will pick it up.
6398                  */
6399                 if (need_resched())
6400                         break;
6401
6402                 rq = cpu_rq(balance_cpu);
6403
6404                 raw_spin_lock_irq(&rq->lock);
6405                 update_rq_clock(rq);
6406                 update_idle_cpu_load(rq);
6407                 raw_spin_unlock_irq(&rq->lock);
6408
6409                 rebalance_domains(balance_cpu, CPU_IDLE);
6410
6411                 if (time_after(this_rq->next_balance, rq->next_balance))
6412                         this_rq->next_balance = rq->next_balance;
6413         }
6414         nohz.next_balance = this_rq->next_balance;
6415 end:
6416         clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
6417 }
6418
6419 /*
6420  * Current heuristic for kicking the idle load balancer in the presence
6421  * of an idle cpu is the system.
6422  *   - This rq has more than one task.
6423  *   - At any scheduler domain level, this cpu's scheduler group has multiple
6424  *     busy cpu's exceeding the group's power.
6425  *   - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
6426  *     domain span are idle.
6427  */
6428 static inline int nohz_kick_needed(struct rq *rq, int cpu)
6429 {
6430         unsigned long now = jiffies;
6431         struct sched_domain *sd;
6432
6433         if (unlikely(idle_cpu(cpu)))
6434                 return 0;
6435
6436        /*
6437         * We may be recently in ticked or tickless idle mode. At the first
6438         * busy tick after returning from idle, we will update the busy stats.
6439         */
6440         set_cpu_sd_state_busy();
6441         nohz_balance_exit_idle(cpu);
6442
6443         /*
6444          * None are in tickless mode and hence no need for NOHZ idle load
6445          * balancing.
6446          */
6447         if (likely(!atomic_read(&nohz.nr_cpus)))
6448                 return 0;
6449
6450         if (time_before(now, nohz.next_balance))
6451                 return 0;
6452
6453 #ifdef CONFIG_SCHED_HMP
6454         /*
6455          * Bail out if there are no nohz CPUs in our
6456          * HMP domain, since we will move tasks between
6457          * domains through wakeup and force balancing
6458          * as necessary based upon task load.
6459          */
6460         if (cpumask_first_and(nohz.idle_cpus_mask,
6461                         &((struct hmp_domain *)hmp_cpu_domain(cpu))->cpus) >= nr_cpu_ids)
6462                 return 0;
6463 #endif
6464
6465         if (rq->nr_running >= 2)
6466                 goto need_kick;
6467
6468         rcu_read_lock();
6469         for_each_domain(cpu, sd) {
6470                 struct sched_group *sg = sd->groups;
6471                 struct sched_group_power *sgp = sg->sgp;
6472                 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
6473
6474                 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
6475                         goto need_kick_unlock;
6476
6477                 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
6478                     && (cpumask_first_and(nohz.idle_cpus_mask,
6479                                           sched_domain_span(sd)) < cpu))
6480                         goto need_kick_unlock;
6481
6482                 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
6483                         break;
6484         }
6485         rcu_read_unlock();
6486         return 0;
6487
6488 need_kick_unlock:
6489         rcu_read_unlock();
6490 need_kick:
6491         return 1;
6492 }
6493 #else
6494 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
6495 #endif
6496
6497 #ifdef CONFIG_SCHED_HMP
6498 /* Check if task should migrate to a faster cpu */
6499 static unsigned int hmp_up_migration(int cpu, int *target_cpu, struct sched_entity *se)
6500 {
6501         struct task_struct *p = task_of(se);
6502         int temp_target_cpu;
6503         u64 now;
6504
6505         if (hmp_cpu_is_fastest(cpu))
6506                 return 0;
6507
6508 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
6509         /* Filter by task priority */
6510         if (p->prio >= hmp_up_prio)
6511                 return 0;
6512 #endif
6513         if (se->avg.load_avg_ratio < hmp_up_threshold)
6514                 return 0;
6515
6516         /* Let the task load settle before doing another up migration */
6517         /* hack - always use clock from first online CPU */
6518         now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
6519         if (((now - se->avg.hmp_last_up_migration) >> 10)
6520                                         < hmp_next_up_threshold)
6521                 return 0;
6522
6523         /* hmp_domain_min_load only returns 0 for an
6524          * idle CPU or 1023 for any partly-busy one.
6525          * Be explicit about requirement for an idle CPU.
6526          */
6527         if (hmp_domain_min_load(hmp_faster_domain(cpu), &temp_target_cpu,
6528                         tsk_cpus_allowed(p)) == 0 && temp_target_cpu != NR_CPUS) {
6529                 if(target_cpu)
6530                         *target_cpu = temp_target_cpu;
6531                 return 1;
6532         }
6533         return 0;
6534 }
6535
6536 /* Check if task should migrate to a slower cpu */
6537 static unsigned int hmp_down_migration(int cpu, struct sched_entity *se)
6538 {
6539         struct task_struct *p = task_of(se);
6540         u64 now;
6541
6542         if (hmp_cpu_is_slowest(cpu))
6543                 return 0;
6544
6545 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
6546         /* Filter by task priority */
6547         if ((p->prio >= hmp_up_prio) &&
6548                 cpumask_intersects(&hmp_slower_domain(cpu)->cpus,
6549                                         tsk_cpus_allowed(p))) {
6550                 return 1;
6551         }
6552 #endif
6553
6554         /* Let the task load settle before doing another down migration */
6555         /* hack - always use clock from first online CPU */
6556         now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
6557         if (((now - se->avg.hmp_last_down_migration) >> 10)
6558                                         < hmp_next_down_threshold)
6559                 return 0;
6560
6561         if (cpumask_intersects(&hmp_slower_domain(cpu)->cpus,
6562                                         tsk_cpus_allowed(p))
6563                 && se->avg.load_avg_ratio < hmp_down_threshold) {
6564                 return 1;
6565         }
6566         return 0;
6567 }
6568
6569 /*
6570  * hmp_can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
6571  * Ideally this function should be merged with can_migrate_task() to avoid
6572  * redundant code.
6573  */
6574 static int hmp_can_migrate_task(struct task_struct *p, struct lb_env *env)
6575 {
6576         int tsk_cache_hot = 0;
6577
6578         /*
6579          * We do not migrate tasks that are:
6580          * 1) running (obviously), or
6581          * 2) cannot be migrated to this CPU due to cpus_allowed
6582          */
6583         if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
6584                 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
6585                 return 0;
6586         }
6587         env->flags &= ~LBF_ALL_PINNED;
6588
6589         if (task_running(env->src_rq, p)) {
6590                 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
6591                 return 0;
6592         }
6593
6594         /*
6595          * Aggressive migration if:
6596          * 1) task is cache cold, or
6597          * 2) too many balance attempts have failed.
6598          */
6599
6600         tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
6601         if (!tsk_cache_hot ||
6602                 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
6603 #ifdef CONFIG_SCHEDSTATS
6604                 if (tsk_cache_hot) {
6605                         schedstat_inc(env->sd, lb_hot_gained[env->idle]);
6606                         schedstat_inc(p, se.statistics.nr_forced_migrations);
6607                 }
6608 #endif
6609                 return 1;
6610         }
6611
6612         return 1;
6613 }
6614
6615 /*
6616  * move_specific_task tries to move a specific task.
6617  * Returns 1 if successful and 0 otherwise.
6618  * Called with both runqueues locked.
6619  */
6620 static int move_specific_task(struct lb_env *env, struct task_struct *pm)
6621 {
6622         struct task_struct *p, *n;
6623
6624         list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
6625         if (throttled_lb_pair(task_group(p), env->src_rq->cpu,
6626                                 env->dst_cpu))
6627                 continue;
6628
6629                 if (!hmp_can_migrate_task(p, env))
6630                         continue;
6631                 /* Check if we found the right task */
6632                 if (p != pm)
6633                         continue;
6634
6635                 move_task(p, env);
6636                 /*
6637                  * Right now, this is only the third place move_task()
6638                  * is called, so we can safely collect move_task()
6639                  * stats here rather than inside move_task().
6640                  */
6641                 schedstat_inc(env->sd, lb_gained[env->idle]);
6642                 return 1;
6643         }
6644         return 0;
6645 }
6646
6647 /*
6648  * hmp_active_task_migration_cpu_stop is run by cpu stopper and used to
6649  * migrate a specific task from one runqueue to another.
6650  * hmp_force_up_migration uses this to push a currently running task
6651  * off a runqueue.
6652  * Based on active_load_balance_stop_cpu and can potentially be merged.
6653  */
6654 static int hmp_active_task_migration_cpu_stop(void *data)
6655 {
6656         struct rq *busiest_rq = data;
6657         struct task_struct *p = busiest_rq->migrate_task;
6658         int busiest_cpu = cpu_of(busiest_rq);
6659         int target_cpu = busiest_rq->push_cpu;
6660         struct rq *target_rq = cpu_rq(target_cpu);
6661         struct sched_domain *sd;
6662
6663         raw_spin_lock_irq(&busiest_rq->lock);
6664         /* make sure the requested cpu hasn't gone down in the meantime */
6665         if (unlikely(busiest_cpu != smp_processor_id() ||
6666                 !busiest_rq->active_balance)) {
6667                 goto out_unlock;
6668         }
6669         /* Is there any task to move? */
6670         if (busiest_rq->nr_running <= 1)
6671                 goto out_unlock;
6672         /* Task has migrated meanwhile, abort forced migration */
6673         if (task_rq(p) != busiest_rq)
6674                 goto out_unlock;
6675         /*
6676          * This condition is "impossible", if it occurs
6677          * we need to fix it. Originally reported by
6678          * Bjorn Helgaas on a 128-cpu setup.
6679          */
6680         BUG_ON(busiest_rq == target_rq);
6681
6682         /* move a task from busiest_rq to target_rq */
6683         double_lock_balance(busiest_rq, target_rq);
6684
6685         /* Search for an sd spanning us and the target CPU. */
6686         rcu_read_lock();
6687         for_each_domain(target_cpu, sd) {
6688                 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6689                         break;
6690         }
6691
6692         if (likely(sd)) {
6693                 struct lb_env env = {
6694                         .sd             = sd,
6695                         .dst_cpu        = target_cpu,
6696                         .dst_rq         = target_rq,
6697                         .src_cpu        = busiest_rq->cpu,
6698                         .src_rq         = busiest_rq,
6699                         .idle           = CPU_IDLE,
6700                 };
6701
6702                 schedstat_inc(sd, alb_count);
6703
6704                 if (move_specific_task(&env, p))
6705                         schedstat_inc(sd, alb_pushed);
6706                 else
6707                         schedstat_inc(sd, alb_failed);
6708         }
6709         rcu_read_unlock();
6710         double_unlock_balance(busiest_rq, target_rq);
6711 out_unlock:
6712         put_task_struct(p);
6713         busiest_rq->active_balance = 0;
6714         raw_spin_unlock_irq(&busiest_rq->lock);
6715         return 0;
6716 }
6717
6718 /*
6719  * hmp_idle_pull_cpu_stop is run by cpu stopper and used to
6720  * migrate a specific task from one runqueue to another.
6721  * hmp_idle_pull uses this to push a currently running task
6722  * off a runqueue to a faster CPU.
6723  * Locking is slightly different than usual.
6724  * Based on active_load_balance_stop_cpu and can potentially be merged.
6725  */
6726 static int hmp_idle_pull_cpu_stop(void *data)
6727 {
6728         struct rq *busiest_rq = data;
6729         struct task_struct *p = busiest_rq->migrate_task;
6730         int busiest_cpu = cpu_of(busiest_rq);
6731         int target_cpu = busiest_rq->push_cpu;
6732         struct rq *target_rq = cpu_rq(target_cpu);
6733         struct sched_domain *sd;
6734
6735         raw_spin_lock_irq(&busiest_rq->lock);
6736
6737         /* make sure the requested cpu hasn't gone down in the meantime */
6738         if (unlikely(busiest_cpu != smp_processor_id() ||
6739                 !busiest_rq->active_balance))
6740                 goto out_unlock;
6741
6742         /* Is there any task to move? */
6743         if (busiest_rq->nr_running <= 1)
6744                 goto out_unlock;
6745
6746         /* Task has migrated meanwhile, abort forced migration */
6747         if (task_rq(p) != busiest_rq)
6748                 goto out_unlock;
6749
6750         /*
6751          * This condition is "impossible", if it occurs
6752          * we need to fix it. Originally reported by
6753          * Bjorn Helgaas on a 128-cpu setup.
6754          */
6755         BUG_ON(busiest_rq == target_rq);
6756
6757         /* move a task from busiest_rq to target_rq */
6758         double_lock_balance(busiest_rq, target_rq);
6759
6760         /* Search for an sd spanning us and the target CPU. */
6761         rcu_read_lock();
6762         for_each_domain(target_cpu, sd) {
6763                 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6764                         break;
6765         }
6766         if (likely(sd)) {
6767                 struct lb_env env = {
6768                         .sd             = sd,
6769                         .dst_cpu        = target_cpu,
6770                         .dst_rq         = target_rq,
6771                         .src_cpu        = busiest_rq->cpu,
6772                         .src_rq         = busiest_rq,
6773                         .idle           = CPU_IDLE,
6774                 };
6775
6776                 schedstat_inc(sd, alb_count);
6777
6778                 if (move_specific_task(&env, p))
6779                         schedstat_inc(sd, alb_pushed);
6780                 else
6781                         schedstat_inc(sd, alb_failed);
6782         }
6783         rcu_read_unlock();
6784         double_unlock_balance(busiest_rq, target_rq);
6785 out_unlock:
6786         put_task_struct(p);
6787         busiest_rq->active_balance = 0;
6788         raw_spin_unlock_irq(&busiest_rq->lock);
6789         return 0;
6790 }
6791
6792 static DEFINE_SPINLOCK(hmp_force_migration);
6793
6794 /*
6795  * hmp_force_up_migration checks runqueues for tasks that need to
6796  * be actively migrated to a faster cpu.
6797  */
6798 static void hmp_force_up_migration(int this_cpu)
6799 {
6800         int cpu, target_cpu;
6801         struct sched_entity *curr, *orig;
6802         struct rq *target;
6803         unsigned long flags;
6804         unsigned int force;
6805         struct task_struct *p;
6806
6807         if (!spin_trylock(&hmp_force_migration))
6808                 return;
6809         for_each_online_cpu(cpu) {
6810                 force = 0;
6811                 target = cpu_rq(cpu);
6812                 raw_spin_lock_irqsave(&target->lock, flags);
6813                 curr = target->cfs.curr;
6814                 if (!curr) {
6815                         raw_spin_unlock_irqrestore(&target->lock, flags);
6816                         continue;
6817                 }
6818                 if (!entity_is_task(curr)) {
6819                         struct cfs_rq *cfs_rq;
6820
6821                         cfs_rq = group_cfs_rq(curr);
6822                         while (cfs_rq) {
6823                                 curr = cfs_rq->curr;
6824                                 cfs_rq = group_cfs_rq(curr);
6825                         }
6826                 }
6827                 orig = curr;
6828                 curr = hmp_get_heaviest_task(curr, 1);
6829                 p = task_of(curr);
6830                 if (hmp_up_migration(cpu, &target_cpu, curr)) {
6831                         if (!target->active_balance) {
6832                                 get_task_struct(p);
6833                                 target->active_balance = 1;
6834                                 target->push_cpu = target_cpu;
6835                                 target->migrate_task = p;
6836                                 force = 1;
6837                                 trace_sched_hmp_migrate(p, target->push_cpu, HMP_MIGRATE_FORCE);
6838                                 hmp_next_up_delay(&p->se, target->push_cpu);
6839                         }
6840                 }
6841                 if (!force && !target->active_balance) {
6842                         /*
6843                          * For now we just check the currently running task.
6844                          * Selecting the lightest task for offloading will
6845                          * require extensive book keeping.
6846                          */
6847                         curr = hmp_get_lightest_task(orig, 1);
6848                         p = task_of(curr);
6849                         target->push_cpu = hmp_offload_down(cpu, curr);
6850                         if (target->push_cpu < NR_CPUS) {
6851                                 get_task_struct(p);
6852                                 target->active_balance = 1;
6853                                 target->migrate_task = p;
6854                                 force = 1;
6855                                 trace_sched_hmp_migrate(p, target->push_cpu, HMP_MIGRATE_OFFLOAD);
6856                                 hmp_next_down_delay(&p->se, target->push_cpu);
6857                         }
6858                 }
6859                 raw_spin_unlock_irqrestore(&target->lock, flags);
6860                 if (force)
6861                         stop_one_cpu_nowait(cpu_of(target),
6862                                 hmp_active_task_migration_cpu_stop,
6863                                 target, &target->active_balance_work);
6864         }
6865         spin_unlock(&hmp_force_migration);
6866 }
6867 /*
6868  * hmp_idle_pull looks at little domain runqueues to see
6869  * if a task should be pulled.
6870  *
6871  * Reuses hmp_force_migration spinlock.
6872  *
6873  */
6874 static unsigned int hmp_idle_pull(int this_cpu)
6875 {
6876         int cpu;
6877         struct sched_entity *curr, *orig;
6878         struct hmp_domain *hmp_domain = NULL;
6879         struct rq *target, *rq;
6880         unsigned long flags, ratio = 0;
6881         unsigned int force = 0;
6882         struct task_struct *p = NULL;
6883
6884         if (!hmp_cpu_is_slowest(this_cpu))
6885                 hmp_domain = hmp_slower_domain(this_cpu);
6886         if (!hmp_domain)
6887                 return 0;
6888
6889         if (!spin_trylock(&hmp_force_migration))
6890                 return 0;
6891
6892         /* first select a task */
6893         for_each_cpu(cpu, &hmp_domain->cpus) {
6894                 rq = cpu_rq(cpu);
6895                 raw_spin_lock_irqsave(&rq->lock, flags);
6896                 curr = rq->cfs.curr;
6897                 if (!curr) {
6898                         raw_spin_unlock_irqrestore(&rq->lock, flags);
6899                         continue;
6900                 }
6901                 if (!entity_is_task(curr)) {
6902                         struct cfs_rq *cfs_rq;
6903
6904                         cfs_rq = group_cfs_rq(curr);
6905                         while (cfs_rq) {
6906                                 curr = cfs_rq->curr;
6907                                 if (!entity_is_task(curr))
6908                                         cfs_rq = group_cfs_rq(curr);
6909                                 else
6910                                         cfs_rq = NULL;
6911                         }
6912                 }
6913                 orig = curr;
6914                 curr = hmp_get_heaviest_task(curr, 1);
6915                 if (curr->avg.load_avg_ratio > hmp_up_threshold &&
6916                         curr->avg.load_avg_ratio > ratio) {
6917                         p = task_of(curr);
6918                         target = rq;
6919                         ratio = curr->avg.load_avg_ratio;
6920                 }
6921                 raw_spin_unlock_irqrestore(&rq->lock, flags);
6922         }
6923
6924         if (!p)
6925                 goto done;
6926
6927         /* now we have a candidate */
6928         raw_spin_lock_irqsave(&target->lock, flags);
6929         if (!target->active_balance && task_rq(p) == target) {
6930                 get_task_struct(p);
6931                 target->active_balance = 1;
6932                 target->push_cpu = this_cpu;
6933                 target->migrate_task = p;
6934                 force = 1;
6935                 trace_sched_hmp_migrate(p, target->push_cpu, HMP_MIGRATE_IDLE_PULL);
6936                 hmp_next_up_delay(&p->se, target->push_cpu);
6937         }
6938         raw_spin_unlock_irqrestore(&target->lock, flags);
6939         if (force) {
6940                 stop_one_cpu_nowait(cpu_of(target),
6941                         hmp_idle_pull_cpu_stop,
6942                         target, &target->active_balance_work);
6943         }
6944 done:
6945         spin_unlock(&hmp_force_migration);
6946         return force;
6947 }
6948 #else
6949 static void hmp_force_up_migration(int this_cpu) { }
6950 #endif /* CONFIG_SCHED_HMP */
6951
6952 /*
6953  * run_rebalance_domains is triggered when needed from the scheduler tick.
6954  * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
6955  */
6956 static void run_rebalance_domains(struct softirq_action *h)
6957 {
6958         int this_cpu = smp_processor_id();
6959         struct rq *this_rq = cpu_rq(this_cpu);
6960         enum cpu_idle_type idle = this_rq->idle_balance ?
6961                                                 CPU_IDLE : CPU_NOT_IDLE;
6962
6963         hmp_force_up_migration(this_cpu);
6964
6965         rebalance_domains(this_cpu, idle);
6966
6967         /*
6968          * If this cpu has a pending nohz_balance_kick, then do the
6969          * balancing on behalf of the other idle cpus whose ticks are
6970          * stopped.
6971          */
6972         nohz_idle_balance(this_cpu, idle);
6973 }
6974
6975 static inline int on_null_domain(int cpu)
6976 {
6977         return !rcu_dereference_sched(cpu_rq(cpu)->sd);
6978 }
6979
6980 /*
6981  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
6982  */
6983 void trigger_load_balance(struct rq *rq, int cpu)
6984 {
6985         /* Don't need to rebalance while attached to NULL domain */
6986         if (time_after_eq(jiffies, rq->next_balance) &&
6987             likely(!on_null_domain(cpu)))
6988                 raise_softirq(SCHED_SOFTIRQ);
6989 #ifdef CONFIG_NO_HZ_COMMON
6990         if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
6991                 nohz_balancer_kick(cpu);
6992 #endif
6993 }
6994
6995 static void rq_online_fair(struct rq *rq)
6996 {
6997 #ifdef CONFIG_SCHED_HMP
6998         hmp_online_cpu(rq->cpu);
6999 #endif
7000         update_sysctl();
7001 }
7002
7003 static void rq_offline_fair(struct rq *rq)
7004 {
7005 #ifdef CONFIG_SCHED_HMP
7006         hmp_offline_cpu(rq->cpu);
7007 #endif
7008         update_sysctl();
7009
7010         /* Ensure any throttled groups are reachable by pick_next_task */
7011         unthrottle_offline_cfs_rqs(rq);
7012 }
7013
7014 #endif /* CONFIG_SMP */
7015
7016 /*
7017  * scheduler tick hitting a task of our scheduling class:
7018  */
7019 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
7020 {
7021         struct cfs_rq *cfs_rq;
7022         struct sched_entity *se = &curr->se;
7023
7024         for_each_sched_entity(se) {
7025                 cfs_rq = cfs_rq_of(se);
7026                 entity_tick(cfs_rq, se, queued);
7027         }
7028
7029         if (sched_feat_numa(NUMA))
7030                 task_tick_numa(rq, curr);
7031
7032         update_rq_runnable_avg(rq, 1);
7033 }
7034
7035 /*
7036  * called on fork with the child task as argument from the parent's context
7037  *  - child not yet on the tasklist
7038  *  - preemption disabled
7039  */
7040 static void task_fork_fair(struct task_struct *p)
7041 {
7042         struct cfs_rq *cfs_rq;
7043         struct sched_entity *se = &p->se, *curr;
7044         int this_cpu = smp_processor_id();
7045         struct rq *rq = this_rq();
7046         unsigned long flags;
7047
7048         raw_spin_lock_irqsave(&rq->lock, flags);
7049
7050         update_rq_clock(rq);
7051
7052         cfs_rq = task_cfs_rq(current);
7053         curr = cfs_rq->curr;
7054
7055         if (unlikely(task_cpu(p) != this_cpu)) {
7056                 rcu_read_lock();
7057                 __set_task_cpu(p, this_cpu);
7058                 rcu_read_unlock();
7059         }
7060
7061         update_curr(cfs_rq);
7062
7063         if (curr)
7064                 se->vruntime = curr->vruntime;
7065         place_entity(cfs_rq, se, 1);
7066
7067         if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
7068                 /*
7069                  * Upon rescheduling, sched_class::put_prev_task() will place
7070                  * 'current' within the tree based on its new key value.
7071                  */
7072                 swap(curr->vruntime, se->vruntime);
7073                 resched_task(rq->curr);
7074         }
7075
7076         se->vruntime -= cfs_rq->min_vruntime;
7077
7078         raw_spin_unlock_irqrestore(&rq->lock, flags);
7079 }
7080
7081 /*
7082  * Priority of the task has changed. Check to see if we preempt
7083  * the current task.
7084  */
7085 static void
7086 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
7087 {
7088         if (!p->se.on_rq)
7089                 return;
7090
7091         /*
7092          * Reschedule if we are currently running on this runqueue and
7093          * our priority decreased, or if we are not currently running on
7094          * this runqueue and our priority is higher than the current's
7095          */
7096         if (rq->curr == p) {
7097                 if (p->prio > oldprio)
7098                         resched_task(rq->curr);
7099         } else
7100                 check_preempt_curr(rq, p, 0);
7101 }
7102
7103 static void switched_from_fair(struct rq *rq, struct task_struct *p)
7104 {
7105         struct sched_entity *se = &p->se;
7106         struct cfs_rq *cfs_rq = cfs_rq_of(se);
7107
7108         /*
7109          * Ensure the task's vruntime is normalized, so that when its
7110          * switched back to the fair class the enqueue_entity(.flags=0) will
7111          * do the right thing.
7112          *
7113          * If it was on_rq, then the dequeue_entity(.flags=0) will already
7114          * have normalized the vruntime, if it was !on_rq, then only when
7115          * the task is sleeping will it still have non-normalized vruntime.
7116          */
7117         if (!se->on_rq && p->state != TASK_RUNNING) {
7118                 /*
7119                  * Fix up our vruntime so that the current sleep doesn't
7120                  * cause 'unlimited' sleep bonus.
7121                  */
7122                 place_entity(cfs_rq, se, 0);
7123                 se->vruntime -= cfs_rq->min_vruntime;
7124         }
7125
7126 #if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
7127         /*
7128         * Remove our load from contribution when we leave sched_fair
7129         * and ensure we don't carry in an old decay_count if we
7130         * switch back.
7131         */
7132         if (p->se.avg.decay_count) {
7133                 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
7134                 __synchronize_entity_decay(&p->se);
7135                 subtract_blocked_load_contrib(cfs_rq,
7136                                 p->se.avg.load_avg_contrib);
7137         }
7138 #endif
7139 }
7140
7141 /*
7142  * We switched to the sched_fair class.
7143  */
7144 static void switched_to_fair(struct rq *rq, struct task_struct *p)
7145 {
7146         if (!p->se.on_rq)
7147                 return;
7148
7149         /*
7150          * We were most likely switched from sched_rt, so
7151          * kick off the schedule if running, otherwise just see
7152          * if we can still preempt the current task.
7153          */
7154         if (rq->curr == p)
7155                 resched_task(rq->curr);
7156         else
7157                 check_preempt_curr(rq, p, 0);
7158 }
7159
7160 /* Account for a task changing its policy or group.
7161  *
7162  * This routine is mostly called to set cfs_rq->curr field when a task
7163  * migrates between groups/classes.
7164  */
7165 static void set_curr_task_fair(struct rq *rq)
7166 {
7167         struct sched_entity *se = &rq->curr->se;
7168
7169         for_each_sched_entity(se) {
7170                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7171
7172                 set_next_entity(cfs_rq, se);
7173                 /* ensure bandwidth has been allocated on our new cfs_rq */
7174                 account_cfs_rq_runtime(cfs_rq, 0);
7175         }
7176 }
7177
7178 void init_cfs_rq(struct cfs_rq *cfs_rq)
7179 {
7180         cfs_rq->tasks_timeline = RB_ROOT;
7181         cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7182 #ifndef CONFIG_64BIT
7183         cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7184 #endif
7185 #if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
7186         atomic64_set(&cfs_rq->decay_counter, 1);
7187         atomic64_set(&cfs_rq->removed_load, 0);
7188 #endif
7189 }
7190
7191 #ifdef CONFIG_FAIR_GROUP_SCHED
7192 static void task_move_group_fair(struct task_struct *p, int on_rq)
7193 {
7194         struct cfs_rq *cfs_rq;
7195         /*
7196          * If the task was not on the rq at the time of this cgroup movement
7197          * it must have been asleep, sleeping tasks keep their ->vruntime
7198          * absolute on their old rq until wakeup (needed for the fair sleeper
7199          * bonus in place_entity()).
7200          *
7201          * If it was on the rq, we've just 'preempted' it, which does convert
7202          * ->vruntime to a relative base.
7203          *
7204          * Make sure both cases convert their relative position when migrating
7205          * to another cgroup's rq. This does somewhat interfere with the
7206          * fair sleeper stuff for the first placement, but who cares.
7207          */
7208         /*
7209          * When !on_rq, vruntime of the task has usually NOT been normalized.
7210          * But there are some cases where it has already been normalized:
7211          *
7212          * - Moving a forked child which is waiting for being woken up by
7213          *   wake_up_new_task().
7214          * - Moving a task which has been woken up by try_to_wake_up() and
7215          *   waiting for actually being woken up by sched_ttwu_pending().
7216          *
7217          * To prevent boost or penalty in the new cfs_rq caused by delta
7218          * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
7219          */
7220         if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
7221                 on_rq = 1;
7222
7223         if (!on_rq)
7224                 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
7225         set_task_rq(p, task_cpu(p));
7226         if (!on_rq) {
7227                 cfs_rq = cfs_rq_of(&p->se);
7228                 p->se.vruntime += cfs_rq->min_vruntime;
7229 #ifdef CONFIG_SMP
7230                 /*
7231                  * migrate_task_rq_fair() will have removed our previous
7232                  * contribution, but we must synchronize for ongoing future
7233                  * decay.
7234                  */
7235                 p->se.avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
7236                 cfs_rq->blocked_load_avg += p->se.avg.load_avg_contrib;
7237 #endif
7238         }
7239 }
7240
7241 void free_fair_sched_group(struct task_group *tg)
7242 {
7243         int i;
7244
7245         destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
7246
7247         for_each_possible_cpu(i) {
7248                 if (tg->cfs_rq)
7249                         kfree(tg->cfs_rq[i]);
7250                 if (tg->se)
7251                         kfree(tg->se[i]);
7252         }
7253
7254         kfree(tg->cfs_rq);
7255         kfree(tg->se);
7256 }
7257
7258 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7259 {
7260         struct cfs_rq *cfs_rq;
7261         struct sched_entity *se;
7262         int i;
7263
7264         tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7265         if (!tg->cfs_rq)
7266                 goto err;
7267         tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7268         if (!tg->se)
7269                 goto err;
7270
7271         tg->shares = NICE_0_LOAD;
7272
7273         init_cfs_bandwidth(tg_cfs_bandwidth(tg));
7274
7275         for_each_possible_cpu(i) {
7276                 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
7277                                       GFP_KERNEL, cpu_to_node(i));
7278                 if (!cfs_rq)
7279                         goto err;
7280
7281                 se = kzalloc_node(sizeof(struct sched_entity),
7282                                   GFP_KERNEL, cpu_to_node(i));
7283                 if (!se)
7284                         goto err_free_rq;
7285
7286                 init_cfs_rq(cfs_rq);
7287                 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
7288         }
7289
7290         return 1;
7291
7292 err_free_rq:
7293         kfree(cfs_rq);
7294 err:
7295         return 0;
7296 }
7297
7298 void unregister_fair_sched_group(struct task_group *tg, int cpu)
7299 {
7300         struct rq *rq = cpu_rq(cpu);
7301         unsigned long flags;
7302
7303         /*
7304         * Only empty task groups can be destroyed; so we can speculatively
7305         * check on_list without danger of it being re-added.
7306         */
7307         if (!tg->cfs_rq[cpu]->on_list)
7308                 return;
7309
7310         raw_spin_lock_irqsave(&rq->lock, flags);
7311         list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
7312         raw_spin_unlock_irqrestore(&rq->lock, flags);
7313 }
7314
7315 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7316                         struct sched_entity *se, int cpu,
7317                         struct sched_entity *parent)
7318 {
7319         struct rq *rq = cpu_rq(cpu);
7320
7321         cfs_rq->tg = tg;
7322         cfs_rq->rq = rq;
7323         init_cfs_rq_runtime(cfs_rq);
7324
7325         tg->cfs_rq[cpu] = cfs_rq;
7326         tg->se[cpu] = se;
7327
7328         /* se could be NULL for root_task_group */
7329         if (!se)
7330                 return;
7331
7332         if (!parent)
7333                 se->cfs_rq = &rq->cfs;
7334         else
7335                 se->cfs_rq = parent->my_q;
7336
7337         se->my_q = cfs_rq;
7338         update_load_set(&se->load, 0);
7339         se->parent = parent;
7340 }
7341
7342 static DEFINE_MUTEX(shares_mutex);
7343
7344 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7345 {
7346         int i;
7347         unsigned long flags;
7348
7349         /*
7350          * We can't change the weight of the root cgroup.
7351          */
7352         if (!tg->se[0])
7353                 return -EINVAL;
7354
7355         shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
7356
7357         mutex_lock(&shares_mutex);
7358         if (tg->shares == shares)
7359                 goto done;
7360
7361         tg->shares = shares;
7362         for_each_possible_cpu(i) {
7363                 struct rq *rq = cpu_rq(i);
7364                 struct sched_entity *se;
7365
7366                 se = tg->se[i];
7367                 /* Propagate contribution to hierarchy */
7368                 raw_spin_lock_irqsave(&rq->lock, flags);
7369                 for_each_sched_entity(se)
7370                         update_cfs_shares(group_cfs_rq(se));
7371                 raw_spin_unlock_irqrestore(&rq->lock, flags);
7372         }
7373
7374 done:
7375         mutex_unlock(&shares_mutex);
7376         return 0;
7377 }
7378 #else /* CONFIG_FAIR_GROUP_SCHED */
7379
7380 void free_fair_sched_group(struct task_group *tg) { }
7381
7382 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7383 {
7384         return 1;
7385 }
7386
7387 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
7388
7389 #endif /* CONFIG_FAIR_GROUP_SCHED */
7390
7391
7392 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
7393 {
7394         struct sched_entity *se = &task->se;
7395         unsigned int rr_interval = 0;
7396
7397         /*
7398          * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
7399          * idle runqueue:
7400          */
7401         if (rq->cfs.load.weight)
7402                 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
7403
7404         return rr_interval;
7405 }
7406
7407 /*
7408  * All the scheduling class methods:
7409  */
7410 const struct sched_class fair_sched_class = {
7411         .next                   = &idle_sched_class,
7412         .enqueue_task           = enqueue_task_fair,
7413         .dequeue_task           = dequeue_task_fair,
7414         .yield_task             = yield_task_fair,
7415         .yield_to_task          = yield_to_task_fair,
7416
7417         .check_preempt_curr     = check_preempt_wakeup,
7418
7419         .pick_next_task         = pick_next_task_fair,
7420         .put_prev_task          = put_prev_task_fair,
7421
7422 #ifdef CONFIG_SMP
7423         .select_task_rq         = select_task_rq_fair,
7424 #ifdef CONFIG_FAIR_GROUP_SCHED
7425         .migrate_task_rq        = migrate_task_rq_fair,
7426 #endif
7427         .rq_online              = rq_online_fair,
7428         .rq_offline             = rq_offline_fair,
7429
7430         .task_waking            = task_waking_fair,
7431 #endif
7432
7433         .set_curr_task          = set_curr_task_fair,
7434         .task_tick              = task_tick_fair,
7435         .task_fork              = task_fork_fair,
7436
7437         .prio_changed           = prio_changed_fair,
7438         .switched_from          = switched_from_fair,
7439         .switched_to            = switched_to_fair,
7440
7441         .get_rr_interval        = get_rr_interval_fair,
7442
7443 #ifdef CONFIG_FAIR_GROUP_SCHED
7444         .task_move_group        = task_move_group_fair,
7445 #endif
7446 };
7447
7448 #ifdef CONFIG_SCHED_DEBUG
7449 void print_cfs_stats(struct seq_file *m, int cpu)
7450 {
7451         struct cfs_rq *cfs_rq;
7452
7453         rcu_read_lock();
7454         for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
7455                 print_cfs_rq(m, cpu, cfs_rq);
7456         rcu_read_unlock();
7457 }
7458 #endif
7459
7460 __init void init_sched_fair_class(void)
7461 {
7462 #ifdef CONFIG_SMP
7463         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7464
7465 #ifdef CONFIG_NO_HZ_COMMON
7466         nohz.next_balance = jiffies;
7467         zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
7468         cpu_notifier(sched_ilb_notifier, 0);
7469 #endif
7470
7471 #ifdef CONFIG_SCHED_HMP
7472         hmp_cpu_mask_setup();
7473 #endif
7474 #endif /* SMP */
7475
7476 }
7477
7478 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
7479 static u32 cpufreq_calc_scale(u32 min, u32 max, u32 curr)
7480 {
7481         u32 result = curr / max;
7482         return result;
7483 }
7484
7485 /* Called when the CPU Frequency is changed.
7486  * Once for each CPU.
7487  */
7488 static int cpufreq_callback(struct notifier_block *nb,
7489                                         unsigned long val, void *data)
7490 {
7491         struct cpufreq_freqs *freq = data;
7492         int cpu = freq->cpu;
7493         struct cpufreq_extents *extents;
7494
7495         if (freq->flags & CPUFREQ_CONST_LOOPS)
7496                 return NOTIFY_OK;
7497
7498         if (val != CPUFREQ_POSTCHANGE)
7499                 return NOTIFY_OK;
7500
7501         /* if dynamic load scale is disabled, set the load scale to 1.0 */
7502         if (!hmp_data.freqinvar_load_scale_enabled) {
7503                 freq_scale[cpu].curr_scale = 1024;
7504                 return NOTIFY_OK;
7505         }
7506
7507         extents = &freq_scale[cpu];
7508         if (extents->flags & SCHED_LOAD_FREQINVAR_SINGLEFREQ) {
7509                 /* If our governor was recognised as a single-freq governor,
7510                  * use 1.0
7511                  */
7512                 extents->curr_scale = 1024;
7513         } else {
7514                 extents->curr_scale = cpufreq_calc_scale(extents->min,
7515                                 extents->max, freq->new);
7516         }
7517
7518         return NOTIFY_OK;
7519 }
7520
7521 /* Called when the CPUFreq governor is changed.
7522  * Only called for the CPUs which are actually changed by the
7523  * userspace.
7524  */
7525 static int cpufreq_policy_callback(struct notifier_block *nb,
7526                                        unsigned long event, void *data)
7527 {
7528         struct cpufreq_policy *policy = data;
7529         struct cpufreq_extents *extents;
7530         int cpu, singleFreq = 0;
7531         static const char performance_governor[] = "performance";
7532         static const char powersave_governor[] = "powersave";
7533
7534         if (event == CPUFREQ_START)
7535                 return 0;
7536
7537         if (event != CPUFREQ_INCOMPATIBLE)
7538                 return 0;
7539
7540         /* CPUFreq governors do not accurately report the range of
7541          * CPU Frequencies they will choose from.
7542          * We recognise performance and powersave governors as
7543          * single-frequency only.
7544          */
7545         if (!strncmp(policy->governor->name, performance_governor,
7546                         strlen(performance_governor)) ||
7547                 !strncmp(policy->governor->name, powersave_governor,
7548                                 strlen(powersave_governor)))
7549                 singleFreq = 1;
7550
7551         /* Make sure that all CPUs impacted by this policy are
7552          * updated since we will only get a notification when the
7553          * user explicitly changes the policy on a CPU.
7554          */
7555         for_each_cpu(cpu, policy->cpus) {
7556                 extents = &freq_scale[cpu];
7557                 extents->max = policy->max >> SCHED_FREQSCALE_SHIFT;
7558                 extents->min = policy->min >> SCHED_FREQSCALE_SHIFT;
7559                 if (!hmp_data.freqinvar_load_scale_enabled) {
7560                         extents->curr_scale = 1024;
7561                 } else if (singleFreq) {
7562                         extents->flags |= SCHED_LOAD_FREQINVAR_SINGLEFREQ;
7563                         extents->curr_scale = 1024;
7564                 } else {
7565                         extents->flags &= ~SCHED_LOAD_FREQINVAR_SINGLEFREQ;
7566                         extents->curr_scale = cpufreq_calc_scale(extents->min,
7567                                         extents->max, policy->cur);
7568                 }
7569         }
7570
7571         return 0;
7572 }
7573
7574 static struct notifier_block cpufreq_notifier = {
7575         .notifier_call  = cpufreq_callback,
7576 };
7577 static struct notifier_block cpufreq_policy_notifier = {
7578         .notifier_call  = cpufreq_policy_callback,
7579 };
7580
7581 static int __init register_sched_cpufreq_notifier(void)
7582 {
7583         int ret = 0;
7584
7585         /* init safe defaults since there are no policies at registration */
7586         for (ret = 0; ret < CONFIG_NR_CPUS; ret++) {
7587                 /* safe defaults */
7588                 freq_scale[ret].max = 1024;
7589                 freq_scale[ret].min = 1024;
7590                 freq_scale[ret].curr_scale = 1024;
7591         }
7592
7593         pr_info("sched: registering cpufreq notifiers for scale-invariant loads\n");
7594         ret = cpufreq_register_notifier(&cpufreq_policy_notifier,
7595                         CPUFREQ_POLICY_NOTIFIER);
7596
7597         if (ret != -EINVAL)
7598                 ret = cpufreq_register_notifier(&cpufreq_notifier,
7599                         CPUFREQ_TRANSITION_NOTIFIER);
7600
7601         return ret;
7602 }
7603
7604 core_initcall(register_sched_cpufreq_notifier);
7605 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */