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