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