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