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