]> git.proxmox.com Git - mirror_ubuntu-kernels.git/blame - kernel/sched/fair.c
sched: Make __update_entity_runnable_avg() fast
[mirror_ubuntu-kernels.git] / kernel / sched / fair.c
CommitLineData
bf0f6f24
IM
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>
21805085
PZ
18 *
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
bf0f6f24
IM
21 */
22
9745512c 23#include <linux/latencytop.h>
1983a922 24#include <linux/sched.h>
3436ae12 25#include <linux/cpumask.h>
029632fb
PZ
26#include <linux/slab.h>
27#include <linux/profile.h>
28#include <linux/interrupt.h>
29
30#include <trace/events/sched.h>
31
32#include "sched.h"
9745512c 33
bf0f6f24 34/*
21805085 35 * Targeted preemption latency for CPU-bound tasks:
864616ee 36 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24 37 *
21805085 38 * NOTE: this latency value is not the same as the concept of
d274a4ce
IM
39 * 'timeslice length' - timeslices in CFS are of variable length
40 * and have no persistent notion like in traditional, time-slice
41 * based scheduling concepts.
bf0f6f24 42 *
d274a4ce
IM
43 * (to see the precise effective timeslice length of your workload,
44 * run vmstat and monitor the context-switches (cs) field)
bf0f6f24 45 */
21406928
MG
46unsigned int sysctl_sched_latency = 6000000ULL;
47unsigned int normalized_sysctl_sched_latency = 6000000ULL;
2bd8e6d4 48
1983a922
CE
49/*
50 * The initial- and re-scaling of tunables is configurable
51 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
52 *
53 * Options are:
54 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
55 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
56 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
57 */
58enum sched_tunable_scaling sysctl_sched_tunable_scaling
59 = SCHED_TUNABLESCALING_LOG;
60
2bd8e6d4 61/*
b2be5e96 62 * Minimal preemption granularity for CPU-bound tasks:
864616ee 63 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
2bd8e6d4 64 */
0bf377bb
IM
65unsigned int sysctl_sched_min_granularity = 750000ULL;
66unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
21805085
PZ
67
68/*
b2be5e96
PZ
69 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
70 */
0bf377bb 71static unsigned int sched_nr_latency = 8;
b2be5e96
PZ
72
73/*
2bba22c5 74 * After fork, child runs first. If set to 0 (default) then
b2be5e96 75 * parent will (try to) run first.
21805085 76 */
2bba22c5 77unsigned int sysctl_sched_child_runs_first __read_mostly;
bf0f6f24 78
bf0f6f24
IM
79/*
80 * SCHED_OTHER wake-up granularity.
172e082a 81 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24
IM
82 *
83 * This option delays the preemption effects of decoupled workloads
84 * and reduces their over-scheduling. Synchronous workloads will still
85 * have immediate wakeup/sleep latencies.
86 */
172e082a 87unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
0bcdcf28 88unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
bf0f6f24 89
da84d961
IM
90const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
91
a7a4f8a7
PT
92/*
93 * The exponential sliding window over which load is averaged for shares
94 * distribution.
95 * (default: 10msec)
96 */
97unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
98
ec12cb7f
PT
99#ifdef CONFIG_CFS_BANDWIDTH
100/*
101 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
102 * each time a cfs_rq requests quota.
103 *
104 * Note: in the case that the slice exceeds the runtime remaining (either due
105 * to consumption or the quota being specified to be smaller than the slice)
106 * we will always only issue the remaining available time.
107 *
108 * default: 5 msec, units: microseconds
109 */
110unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
111#endif
112
029632fb
PZ
113/*
114 * Increase the granularity value when there are more CPUs,
115 * because with more CPUs the 'effective latency' as visible
116 * to users decreases. But the relationship is not linear,
117 * so pick a second-best guess by going with the log2 of the
118 * number of CPUs.
119 *
120 * This idea comes from the SD scheduler of Con Kolivas:
121 */
122static int get_update_sysctl_factor(void)
123{
124 unsigned int cpus = min_t(int, num_online_cpus(), 8);
125 unsigned int factor;
126
127 switch (sysctl_sched_tunable_scaling) {
128 case SCHED_TUNABLESCALING_NONE:
129 factor = 1;
130 break;
131 case SCHED_TUNABLESCALING_LINEAR:
132 factor = cpus;
133 break;
134 case SCHED_TUNABLESCALING_LOG:
135 default:
136 factor = 1 + ilog2(cpus);
137 break;
138 }
139
140 return factor;
141}
142
143static void update_sysctl(void)
144{
145 unsigned int factor = get_update_sysctl_factor();
146
147#define SET_SYSCTL(name) \
148 (sysctl_##name = (factor) * normalized_sysctl_##name)
149 SET_SYSCTL(sched_min_granularity);
150 SET_SYSCTL(sched_latency);
151 SET_SYSCTL(sched_wakeup_granularity);
152#undef SET_SYSCTL
153}
154
155void sched_init_granularity(void)
156{
157 update_sysctl();
158}
159
160#if BITS_PER_LONG == 32
161# define WMULT_CONST (~0UL)
162#else
163# define WMULT_CONST (1UL << 32)
164#endif
165
166#define WMULT_SHIFT 32
167
168/*
169 * Shift right and round:
170 */
171#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
172
173/*
174 * delta *= weight / lw
175 */
176static unsigned long
177calc_delta_mine(unsigned long delta_exec, unsigned long weight,
178 struct load_weight *lw)
179{
180 u64 tmp;
181
182 /*
183 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
184 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
185 * 2^SCHED_LOAD_RESOLUTION.
186 */
187 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
188 tmp = (u64)delta_exec * scale_load_down(weight);
189 else
190 tmp = (u64)delta_exec;
191
192 if (!lw->inv_weight) {
193 unsigned long w = scale_load_down(lw->weight);
194
195 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
196 lw->inv_weight = 1;
197 else if (unlikely(!w))
198 lw->inv_weight = WMULT_CONST;
199 else
200 lw->inv_weight = WMULT_CONST / w;
201 }
202
203 /*
204 * Check whether we'd overflow the 64-bit multiplication:
205 */
206 if (unlikely(tmp > WMULT_CONST))
207 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
208 WMULT_SHIFT/2);
209 else
210 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
211
212 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
213}
214
215
216const struct sched_class fair_sched_class;
a4c2f00f 217
bf0f6f24
IM
218/**************************************************************
219 * CFS operations on generic schedulable entities:
220 */
221
62160e3f 222#ifdef CONFIG_FAIR_GROUP_SCHED
bf0f6f24 223
62160e3f 224/* cpu runqueue to which this cfs_rq is attached */
bf0f6f24
IM
225static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
226{
62160e3f 227 return cfs_rq->rq;
bf0f6f24
IM
228}
229
62160e3f
IM
230/* An entity is a task if it doesn't "own" a runqueue */
231#define entity_is_task(se) (!se->my_q)
bf0f6f24 232
8f48894f
PZ
233static inline struct task_struct *task_of(struct sched_entity *se)
234{
235#ifdef CONFIG_SCHED_DEBUG
236 WARN_ON_ONCE(!entity_is_task(se));
237#endif
238 return container_of(se, struct task_struct, se);
239}
240
b758149c
PZ
241/* Walk up scheduling entities hierarchy */
242#define for_each_sched_entity(se) \
243 for (; se; se = se->parent)
244
245static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
246{
247 return p->se.cfs_rq;
248}
249
250/* runqueue on which this entity is (to be) queued */
251static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
252{
253 return se->cfs_rq;
254}
255
256/* runqueue "owned" by this group */
257static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
258{
259 return grp->my_q;
260}
261
aff3e498
PT
262static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
263 int force_update);
9ee474f5 264
3d4b47b4
PZ
265static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
266{
267 if (!cfs_rq->on_list) {
67e86250
PT
268 /*
269 * Ensure we either appear before our parent (if already
270 * enqueued) or force our parent to appear after us when it is
271 * enqueued. The fact that we always enqueue bottom-up
272 * reduces this to two cases.
273 */
274 if (cfs_rq->tg->parent &&
275 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
276 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
277 &rq_of(cfs_rq)->leaf_cfs_rq_list);
278 } else {
279 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
3d4b47b4 280 &rq_of(cfs_rq)->leaf_cfs_rq_list);
67e86250 281 }
3d4b47b4
PZ
282
283 cfs_rq->on_list = 1;
9ee474f5 284 /* We should have no load, but we need to update last_decay. */
aff3e498 285 update_cfs_rq_blocked_load(cfs_rq, 0);
3d4b47b4
PZ
286 }
287}
288
289static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
290{
291 if (cfs_rq->on_list) {
292 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
293 cfs_rq->on_list = 0;
294 }
295}
296
b758149c
PZ
297/* Iterate thr' all leaf cfs_rq's on a runqueue */
298#define for_each_leaf_cfs_rq(rq, cfs_rq) \
299 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
300
301/* Do the two (enqueued) entities belong to the same group ? */
302static inline int
303is_same_group(struct sched_entity *se, struct sched_entity *pse)
304{
305 if (se->cfs_rq == pse->cfs_rq)
306 return 1;
307
308 return 0;
309}
310
311static inline struct sched_entity *parent_entity(struct sched_entity *se)
312{
313 return se->parent;
314}
315
464b7527
PZ
316/* return depth at which a sched entity is present in the hierarchy */
317static inline int depth_se(struct sched_entity *se)
318{
319 int depth = 0;
320
321 for_each_sched_entity(se)
322 depth++;
323
324 return depth;
325}
326
327static void
328find_matching_se(struct sched_entity **se, struct sched_entity **pse)
329{
330 int se_depth, pse_depth;
331
332 /*
333 * preemption test can be made between sibling entities who are in the
334 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
335 * both tasks until we find their ancestors who are siblings of common
336 * parent.
337 */
338
339 /* First walk up until both entities are at same depth */
340 se_depth = depth_se(*se);
341 pse_depth = depth_se(*pse);
342
343 while (se_depth > pse_depth) {
344 se_depth--;
345 *se = parent_entity(*se);
346 }
347
348 while (pse_depth > se_depth) {
349 pse_depth--;
350 *pse = parent_entity(*pse);
351 }
352
353 while (!is_same_group(*se, *pse)) {
354 *se = parent_entity(*se);
355 *pse = parent_entity(*pse);
356 }
357}
358
8f48894f
PZ
359#else /* !CONFIG_FAIR_GROUP_SCHED */
360
361static inline struct task_struct *task_of(struct sched_entity *se)
362{
363 return container_of(se, struct task_struct, se);
364}
bf0f6f24 365
62160e3f
IM
366static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
367{
368 return container_of(cfs_rq, struct rq, cfs);
bf0f6f24
IM
369}
370
371#define entity_is_task(se) 1
372
b758149c
PZ
373#define for_each_sched_entity(se) \
374 for (; se; se = NULL)
bf0f6f24 375
b758149c 376static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
bf0f6f24 377{
b758149c 378 return &task_rq(p)->cfs;
bf0f6f24
IM
379}
380
b758149c
PZ
381static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
382{
383 struct task_struct *p = task_of(se);
384 struct rq *rq = task_rq(p);
385
386 return &rq->cfs;
387}
388
389/* runqueue "owned" by this group */
390static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
391{
392 return NULL;
393}
394
3d4b47b4
PZ
395static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
396{
397}
398
399static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
400{
401}
402
b758149c
PZ
403#define for_each_leaf_cfs_rq(rq, cfs_rq) \
404 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
405
406static inline int
407is_same_group(struct sched_entity *se, struct sched_entity *pse)
408{
409 return 1;
410}
411
412static inline struct sched_entity *parent_entity(struct sched_entity *se)
413{
414 return NULL;
415}
416
464b7527
PZ
417static inline void
418find_matching_se(struct sched_entity **se, struct sched_entity **pse)
419{
420}
421
b758149c
PZ
422#endif /* CONFIG_FAIR_GROUP_SCHED */
423
6c16a6dc
PZ
424static __always_inline
425void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
bf0f6f24
IM
426
427/**************************************************************
428 * Scheduling class tree data structure manipulation methods:
429 */
430
0702e3eb 431static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
02e0431a 432{
368059a9
PZ
433 s64 delta = (s64)(vruntime - min_vruntime);
434 if (delta > 0)
02e0431a
PZ
435 min_vruntime = vruntime;
436
437 return min_vruntime;
438}
439
0702e3eb 440static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
b0ffd246
PZ
441{
442 s64 delta = (s64)(vruntime - min_vruntime);
443 if (delta < 0)
444 min_vruntime = vruntime;
445
446 return min_vruntime;
447}
448
54fdc581
FC
449static inline int entity_before(struct sched_entity *a,
450 struct sched_entity *b)
451{
452 return (s64)(a->vruntime - b->vruntime) < 0;
453}
454
1af5f730
PZ
455static void update_min_vruntime(struct cfs_rq *cfs_rq)
456{
457 u64 vruntime = cfs_rq->min_vruntime;
458
459 if (cfs_rq->curr)
460 vruntime = cfs_rq->curr->vruntime;
461
462 if (cfs_rq->rb_leftmost) {
463 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
464 struct sched_entity,
465 run_node);
466
e17036da 467 if (!cfs_rq->curr)
1af5f730
PZ
468 vruntime = se->vruntime;
469 else
470 vruntime = min_vruntime(vruntime, se->vruntime);
471 }
472
473 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
3fe1698b
PZ
474#ifndef CONFIG_64BIT
475 smp_wmb();
476 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
477#endif
1af5f730
PZ
478}
479
bf0f6f24
IM
480/*
481 * Enqueue an entity into the rb-tree:
482 */
0702e3eb 483static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
484{
485 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
486 struct rb_node *parent = NULL;
487 struct sched_entity *entry;
bf0f6f24
IM
488 int leftmost = 1;
489
490 /*
491 * Find the right place in the rbtree:
492 */
493 while (*link) {
494 parent = *link;
495 entry = rb_entry(parent, struct sched_entity, run_node);
496 /*
497 * We dont care about collisions. Nodes with
498 * the same key stay together.
499 */
2bd2d6f2 500 if (entity_before(se, entry)) {
bf0f6f24
IM
501 link = &parent->rb_left;
502 } else {
503 link = &parent->rb_right;
504 leftmost = 0;
505 }
506 }
507
508 /*
509 * Maintain a cache of leftmost tree entries (it is frequently
510 * used):
511 */
1af5f730 512 if (leftmost)
57cb499d 513 cfs_rq->rb_leftmost = &se->run_node;
bf0f6f24
IM
514
515 rb_link_node(&se->run_node, parent, link);
516 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
517}
518
0702e3eb 519static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 520{
3fe69747
PZ
521 if (cfs_rq->rb_leftmost == &se->run_node) {
522 struct rb_node *next_node;
3fe69747
PZ
523
524 next_node = rb_next(&se->run_node);
525 cfs_rq->rb_leftmost = next_node;
3fe69747 526 }
e9acbff6 527
bf0f6f24 528 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
529}
530
029632fb 531struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
bf0f6f24 532{
f4b6755f
PZ
533 struct rb_node *left = cfs_rq->rb_leftmost;
534
535 if (!left)
536 return NULL;
537
538 return rb_entry(left, struct sched_entity, run_node);
bf0f6f24
IM
539}
540
ac53db59
RR
541static struct sched_entity *__pick_next_entity(struct sched_entity *se)
542{
543 struct rb_node *next = rb_next(&se->run_node);
544
545 if (!next)
546 return NULL;
547
548 return rb_entry(next, struct sched_entity, run_node);
549}
550
551#ifdef CONFIG_SCHED_DEBUG
029632fb 552struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
aeb73b04 553{
7eee3e67 554 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
aeb73b04 555
70eee74b
BS
556 if (!last)
557 return NULL;
7eee3e67
IM
558
559 return rb_entry(last, struct sched_entity, run_node);
aeb73b04
PZ
560}
561
bf0f6f24
IM
562/**************************************************************
563 * Scheduling class statistics methods:
564 */
565
acb4a848 566int sched_proc_update_handler(struct ctl_table *table, int write,
8d65af78 567 void __user *buffer, size_t *lenp,
b2be5e96
PZ
568 loff_t *ppos)
569{
8d65af78 570 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
acb4a848 571 int factor = get_update_sysctl_factor();
b2be5e96
PZ
572
573 if (ret || !write)
574 return ret;
575
576 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
577 sysctl_sched_min_granularity);
578
acb4a848
CE
579#define WRT_SYSCTL(name) \
580 (normalized_sysctl_##name = sysctl_##name / (factor))
581 WRT_SYSCTL(sched_min_granularity);
582 WRT_SYSCTL(sched_latency);
583 WRT_SYSCTL(sched_wakeup_granularity);
acb4a848
CE
584#undef WRT_SYSCTL
585
b2be5e96
PZ
586 return 0;
587}
588#endif
647e7cac 589
a7be37ac 590/*
f9c0b095 591 * delta /= w
a7be37ac
PZ
592 */
593static inline unsigned long
594calc_delta_fair(unsigned long delta, struct sched_entity *se)
595{
f9c0b095
PZ
596 if (unlikely(se->load.weight != NICE_0_LOAD))
597 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
a7be37ac
PZ
598
599 return delta;
600}
601
647e7cac
IM
602/*
603 * The idea is to set a period in which each task runs once.
604 *
532b1858 605 * When there are too many tasks (sched_nr_latency) we have to stretch
647e7cac
IM
606 * this period because otherwise the slices get too small.
607 *
608 * p = (nr <= nl) ? l : l*nr/nl
609 */
4d78e7b6
PZ
610static u64 __sched_period(unsigned long nr_running)
611{
612 u64 period = sysctl_sched_latency;
b2be5e96 613 unsigned long nr_latency = sched_nr_latency;
4d78e7b6
PZ
614
615 if (unlikely(nr_running > nr_latency)) {
4bf0b771 616 period = sysctl_sched_min_granularity;
4d78e7b6 617 period *= nr_running;
4d78e7b6
PZ
618 }
619
620 return period;
621}
622
647e7cac
IM
623/*
624 * We calculate the wall-time slice from the period by taking a part
625 * proportional to the weight.
626 *
f9c0b095 627 * s = p*P[w/rw]
647e7cac 628 */
6d0f0ebd 629static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
21805085 630{
0a582440 631 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
f9c0b095 632
0a582440 633 for_each_sched_entity(se) {
6272d68c 634 struct load_weight *load;
3104bf03 635 struct load_weight lw;
6272d68c
LM
636
637 cfs_rq = cfs_rq_of(se);
638 load = &cfs_rq->load;
f9c0b095 639
0a582440 640 if (unlikely(!se->on_rq)) {
3104bf03 641 lw = cfs_rq->load;
0a582440
MG
642
643 update_load_add(&lw, se->load.weight);
644 load = &lw;
645 }
646 slice = calc_delta_mine(slice, se->load.weight, load);
647 }
648 return slice;
bf0f6f24
IM
649}
650
647e7cac 651/*
ac884dec 652 * We calculate the vruntime slice of a to be inserted task
647e7cac 653 *
f9c0b095 654 * vs = s/w
647e7cac 655 */
f9c0b095 656static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
67e9fb2a 657{
f9c0b095 658 return calc_delta_fair(sched_slice(cfs_rq, se), se);
a7be37ac
PZ
659}
660
bf0f6f24
IM
661/*
662 * Update the current task's runtime statistics. Skip current tasks that
663 * are not in our scheduling class.
664 */
665static inline void
8ebc91d9
IM
666__update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
667 unsigned long delta_exec)
bf0f6f24 668{
bbdba7c0 669 unsigned long delta_exec_weighted;
bf0f6f24 670
41acab88
LDM
671 schedstat_set(curr->statistics.exec_max,
672 max((u64)delta_exec, curr->statistics.exec_max));
bf0f6f24
IM
673
674 curr->sum_exec_runtime += delta_exec;
7a62eabc 675 schedstat_add(cfs_rq, exec_clock, delta_exec);
a7be37ac 676 delta_exec_weighted = calc_delta_fair(delta_exec, curr);
88ec22d3 677
e9acbff6 678 curr->vruntime += delta_exec_weighted;
1af5f730 679 update_min_vruntime(cfs_rq);
bf0f6f24
IM
680}
681
b7cc0896 682static void update_curr(struct cfs_rq *cfs_rq)
bf0f6f24 683{
429d43bc 684 struct sched_entity *curr = cfs_rq->curr;
305e6835 685 u64 now = rq_of(cfs_rq)->clock_task;
bf0f6f24
IM
686 unsigned long delta_exec;
687
688 if (unlikely(!curr))
689 return;
690
691 /*
692 * Get the amount of time the current task was running
693 * since the last time we changed load (this cannot
694 * overflow on 32 bits):
695 */
8ebc91d9 696 delta_exec = (unsigned long)(now - curr->exec_start);
34f28ecd
PZ
697 if (!delta_exec)
698 return;
bf0f6f24 699
8ebc91d9
IM
700 __update_curr(cfs_rq, curr, delta_exec);
701 curr->exec_start = now;
d842de87
SV
702
703 if (entity_is_task(curr)) {
704 struct task_struct *curtask = task_of(curr);
705
f977bb49 706 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
d842de87 707 cpuacct_charge(curtask, delta_exec);
f06febc9 708 account_group_exec_runtime(curtask, delta_exec);
d842de87 709 }
ec12cb7f
PT
710
711 account_cfs_rq_runtime(cfs_rq, delta_exec);
bf0f6f24
IM
712}
713
714static inline void
5870db5b 715update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 716{
41acab88 717 schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
bf0f6f24
IM
718}
719
bf0f6f24
IM
720/*
721 * Task is being enqueued - update stats:
722 */
d2417e5a 723static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 724{
bf0f6f24
IM
725 /*
726 * Are we enqueueing a waiting task? (for current tasks
727 * a dequeue/enqueue event is a NOP)
728 */
429d43bc 729 if (se != cfs_rq->curr)
5870db5b 730 update_stats_wait_start(cfs_rq, se);
bf0f6f24
IM
731}
732
bf0f6f24 733static void
9ef0a961 734update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 735{
41acab88
LDM
736 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
737 rq_of(cfs_rq)->clock - se->statistics.wait_start));
738 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
739 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
740 rq_of(cfs_rq)->clock - se->statistics.wait_start);
768d0c27
PZ
741#ifdef CONFIG_SCHEDSTATS
742 if (entity_is_task(se)) {
743 trace_sched_stat_wait(task_of(se),
41acab88 744 rq_of(cfs_rq)->clock - se->statistics.wait_start);
768d0c27
PZ
745 }
746#endif
41acab88 747 schedstat_set(se->statistics.wait_start, 0);
bf0f6f24
IM
748}
749
750static inline void
19b6a2e3 751update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 752{
bf0f6f24
IM
753 /*
754 * Mark the end of the wait period if dequeueing a
755 * waiting task:
756 */
429d43bc 757 if (se != cfs_rq->curr)
9ef0a961 758 update_stats_wait_end(cfs_rq, se);
bf0f6f24
IM
759}
760
761/*
762 * We are picking a new current task - update its stats:
763 */
764static inline void
79303e9e 765update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
766{
767 /*
768 * We are starting a new run period:
769 */
305e6835 770 se->exec_start = rq_of(cfs_rq)->clock_task;
bf0f6f24
IM
771}
772
bf0f6f24
IM
773/**************************************************
774 * Scheduling class queueing methods:
775 */
776
30cfdcfc
DA
777static void
778account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
779{
780 update_load_add(&cfs_rq->load, se->load.weight);
c09595f6 781 if (!parent_entity(se))
029632fb 782 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
367456c7
PZ
783#ifdef CONFIG_SMP
784 if (entity_is_task(se))
eb95308e 785 list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
367456c7 786#endif
30cfdcfc 787 cfs_rq->nr_running++;
30cfdcfc
DA
788}
789
790static void
791account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
792{
793 update_load_sub(&cfs_rq->load, se->load.weight);
c09595f6 794 if (!parent_entity(se))
029632fb 795 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
367456c7 796 if (entity_is_task(se))
b87f1724 797 list_del_init(&se->group_node);
30cfdcfc 798 cfs_rq->nr_running--;
30cfdcfc
DA
799}
800
3ff6dcac
YZ
801#ifdef CONFIG_FAIR_GROUP_SCHED
802# ifdef CONFIG_SMP
cf5f0acf
PZ
803static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
804{
805 long tg_weight;
806
807 /*
808 * Use this CPU's actual weight instead of the last load_contribution
809 * to gain a more accurate current total weight. See
810 * update_cfs_rq_load_contribution().
811 */
82958366
PT
812 tg_weight = atomic64_read(&tg->load_avg);
813 tg_weight -= cfs_rq->tg_load_contrib;
cf5f0acf
PZ
814 tg_weight += cfs_rq->load.weight;
815
816 return tg_weight;
817}
818
6d5ab293 819static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
3ff6dcac 820{
cf5f0acf 821 long tg_weight, load, shares;
3ff6dcac 822
cf5f0acf 823 tg_weight = calc_tg_weight(tg, cfs_rq);
6d5ab293 824 load = cfs_rq->load.weight;
3ff6dcac 825
3ff6dcac 826 shares = (tg->shares * load);
cf5f0acf
PZ
827 if (tg_weight)
828 shares /= tg_weight;
3ff6dcac
YZ
829
830 if (shares < MIN_SHARES)
831 shares = MIN_SHARES;
832 if (shares > tg->shares)
833 shares = tg->shares;
834
835 return shares;
836}
3ff6dcac 837# else /* CONFIG_SMP */
6d5ab293 838static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
3ff6dcac
YZ
839{
840 return tg->shares;
841}
3ff6dcac 842# endif /* CONFIG_SMP */
2069dd75
PZ
843static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
844 unsigned long weight)
845{
19e5eebb
PT
846 if (se->on_rq) {
847 /* commit outstanding execution time */
848 if (cfs_rq->curr == se)
849 update_curr(cfs_rq);
2069dd75 850 account_entity_dequeue(cfs_rq, se);
19e5eebb 851 }
2069dd75
PZ
852
853 update_load_set(&se->load, weight);
854
855 if (se->on_rq)
856 account_entity_enqueue(cfs_rq, se);
857}
858
82958366
PT
859static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
860
6d5ab293 861static void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
862{
863 struct task_group *tg;
864 struct sched_entity *se;
3ff6dcac 865 long shares;
2069dd75 866
2069dd75
PZ
867 tg = cfs_rq->tg;
868 se = tg->se[cpu_of(rq_of(cfs_rq))];
64660c86 869 if (!se || throttled_hierarchy(cfs_rq))
2069dd75 870 return;
3ff6dcac
YZ
871#ifndef CONFIG_SMP
872 if (likely(se->load.weight == tg->shares))
873 return;
874#endif
6d5ab293 875 shares = calc_cfs_shares(cfs_rq, tg);
2069dd75
PZ
876
877 reweight_entity(cfs_rq_of(se), se, shares);
878}
879#else /* CONFIG_FAIR_GROUP_SCHED */
6d5ab293 880static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
881{
882}
883#endif /* CONFIG_FAIR_GROUP_SCHED */
884
9d85f21c 885#ifdef CONFIG_SMP
5b51f2f8
PT
886/*
887 * We choose a half-life close to 1 scheduling period.
888 * Note: The tables below are dependent on this value.
889 */
890#define LOAD_AVG_PERIOD 32
891#define LOAD_AVG_MAX 47742 /* maximum possible load avg */
892#define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
893
894/* Precomputed fixed inverse multiplies for multiplication by y^n */
895static const u32 runnable_avg_yN_inv[] = {
896 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
897 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
898 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
899 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
900 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
901 0x85aac367, 0x82cd8698,
902};
903
904/*
905 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
906 * over-estimates when re-combining.
907 */
908static const u32 runnable_avg_yN_sum[] = {
909 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
910 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
911 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
912};
913
9d85f21c
PT
914/*
915 * Approximate:
916 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
917 */
918static __always_inline u64 decay_load(u64 val, u64 n)
919{
5b51f2f8
PT
920 unsigned int local_n;
921
922 if (!n)
923 return val;
924 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
925 return 0;
926
927 /* after bounds checking we can collapse to 32-bit */
928 local_n = n;
929
930 /*
931 * As y^PERIOD = 1/2, we can combine
932 * y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
933 * With a look-up table which covers k^n (n<PERIOD)
934 *
935 * To achieve constant time decay_load.
936 */
937 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
938 val >>= local_n / LOAD_AVG_PERIOD;
939 local_n %= LOAD_AVG_PERIOD;
9d85f21c
PT
940 }
941
5b51f2f8
PT
942 val *= runnable_avg_yN_inv[local_n];
943 /* We don't use SRR here since we always want to round down. */
944 return val >> 32;
945}
946
947/*
948 * For updates fully spanning n periods, the contribution to runnable
949 * average will be: \Sum 1024*y^n
950 *
951 * We can compute this reasonably efficiently by combining:
952 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
953 */
954static u32 __compute_runnable_contrib(u64 n)
955{
956 u32 contrib = 0;
957
958 if (likely(n <= LOAD_AVG_PERIOD))
959 return runnable_avg_yN_sum[n];
960 else if (unlikely(n >= LOAD_AVG_MAX_N))
961 return LOAD_AVG_MAX;
962
963 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
964 do {
965 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
966 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
967
968 n -= LOAD_AVG_PERIOD;
969 } while (n > LOAD_AVG_PERIOD);
970
971 contrib = decay_load(contrib, n);
972 return contrib + runnable_avg_yN_sum[n];
9d85f21c
PT
973}
974
975/*
976 * We can represent the historical contribution to runnable average as the
977 * coefficients of a geometric series. To do this we sub-divide our runnable
978 * history into segments of approximately 1ms (1024us); label the segment that
979 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
980 *
981 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
982 * p0 p1 p2
983 * (now) (~1ms ago) (~2ms ago)
984 *
985 * Let u_i denote the fraction of p_i that the entity was runnable.
986 *
987 * We then designate the fractions u_i as our co-efficients, yielding the
988 * following representation of historical load:
989 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
990 *
991 * We choose y based on the with of a reasonably scheduling period, fixing:
992 * y^32 = 0.5
993 *
994 * This means that the contribution to load ~32ms ago (u_32) will be weighted
995 * approximately half as much as the contribution to load within the last ms
996 * (u_0).
997 *
998 * When a period "rolls over" and we have new u_0`, multiplying the previous
999 * sum again by y is sufficient to update:
1000 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
1001 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
1002 */
1003static __always_inline int __update_entity_runnable_avg(u64 now,
1004 struct sched_avg *sa,
1005 int runnable)
1006{
5b51f2f8
PT
1007 u64 delta, periods;
1008 u32 runnable_contrib;
9d85f21c
PT
1009 int delta_w, decayed = 0;
1010
1011 delta = now - sa->last_runnable_update;
1012 /*
1013 * This should only happen when time goes backwards, which it
1014 * unfortunately does during sched clock init when we swap over to TSC.
1015 */
1016 if ((s64)delta < 0) {
1017 sa->last_runnable_update = now;
1018 return 0;
1019 }
1020
1021 /*
1022 * Use 1024ns as the unit of measurement since it's a reasonable
1023 * approximation of 1us and fast to compute.
1024 */
1025 delta >>= 10;
1026 if (!delta)
1027 return 0;
1028 sa->last_runnable_update = now;
1029
1030 /* delta_w is the amount already accumulated against our next period */
1031 delta_w = sa->runnable_avg_period % 1024;
1032 if (delta + delta_w >= 1024) {
1033 /* period roll-over */
1034 decayed = 1;
1035
1036 /*
1037 * Now that we know we're crossing a period boundary, figure
1038 * out how much from delta we need to complete the current
1039 * period and accrue it.
1040 */
1041 delta_w = 1024 - delta_w;
5b51f2f8
PT
1042 if (runnable)
1043 sa->runnable_avg_sum += delta_w;
1044 sa->runnable_avg_period += delta_w;
1045
1046 delta -= delta_w;
1047
1048 /* Figure out how many additional periods this update spans */
1049 periods = delta / 1024;
1050 delta %= 1024;
1051
1052 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
1053 periods + 1);
1054 sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
1055 periods + 1);
1056
1057 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
1058 runnable_contrib = __compute_runnable_contrib(periods);
1059 if (runnable)
1060 sa->runnable_avg_sum += runnable_contrib;
1061 sa->runnable_avg_period += runnable_contrib;
9d85f21c
PT
1062 }
1063
1064 /* Remainder of delta accrued against u_0` */
1065 if (runnable)
1066 sa->runnable_avg_sum += delta;
1067 sa->runnable_avg_period += delta;
1068
1069 return decayed;
1070}
1071
9ee474f5 1072/* Synchronize an entity's decay with its parenting cfs_rq.*/
aff3e498 1073static inline u64 __synchronize_entity_decay(struct sched_entity *se)
9ee474f5
PT
1074{
1075 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1076 u64 decays = atomic64_read(&cfs_rq->decay_counter);
1077
1078 decays -= se->avg.decay_count;
1079 if (!decays)
aff3e498 1080 return 0;
9ee474f5
PT
1081
1082 se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
1083 se->avg.decay_count = 0;
aff3e498
PT
1084
1085 return decays;
9ee474f5
PT
1086}
1087
c566e8e9
PT
1088#ifdef CONFIG_FAIR_GROUP_SCHED
1089static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1090 int force_update)
1091{
1092 struct task_group *tg = cfs_rq->tg;
1093 s64 tg_contrib;
1094
1095 tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
1096 tg_contrib -= cfs_rq->tg_load_contrib;
1097
1098 if (force_update || abs64(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
1099 atomic64_add(tg_contrib, &tg->load_avg);
1100 cfs_rq->tg_load_contrib += tg_contrib;
1101 }
1102}
8165e145 1103
bb17f655
PT
1104/*
1105 * Aggregate cfs_rq runnable averages into an equivalent task_group
1106 * representation for computing load contributions.
1107 */
1108static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1109 struct cfs_rq *cfs_rq)
1110{
1111 struct task_group *tg = cfs_rq->tg;
1112 long contrib;
1113
1114 /* The fraction of a cpu used by this cfs_rq */
1115 contrib = div_u64(sa->runnable_avg_sum << NICE_0_SHIFT,
1116 sa->runnable_avg_period + 1);
1117 contrib -= cfs_rq->tg_runnable_contrib;
1118
1119 if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) {
1120 atomic_add(contrib, &tg->runnable_avg);
1121 cfs_rq->tg_runnable_contrib += contrib;
1122 }
1123}
1124
8165e145
PT
1125static inline void __update_group_entity_contrib(struct sched_entity *se)
1126{
1127 struct cfs_rq *cfs_rq = group_cfs_rq(se);
1128 struct task_group *tg = cfs_rq->tg;
bb17f655
PT
1129 int runnable_avg;
1130
8165e145
PT
1131 u64 contrib;
1132
1133 contrib = cfs_rq->tg_load_contrib * tg->shares;
1134 se->avg.load_avg_contrib = div64_u64(contrib,
1135 atomic64_read(&tg->load_avg) + 1);
bb17f655
PT
1136
1137 /*
1138 * For group entities we need to compute a correction term in the case
1139 * that they are consuming <1 cpu so that we would contribute the same
1140 * load as a task of equal weight.
1141 *
1142 * Explicitly co-ordinating this measurement would be expensive, but
1143 * fortunately the sum of each cpus contribution forms a usable
1144 * lower-bound on the true value.
1145 *
1146 * Consider the aggregate of 2 contributions. Either they are disjoint
1147 * (and the sum represents true value) or they are disjoint and we are
1148 * understating by the aggregate of their overlap.
1149 *
1150 * Extending this to N cpus, for a given overlap, the maximum amount we
1151 * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
1152 * cpus that overlap for this interval and w_i is the interval width.
1153 *
1154 * On a small machine; the first term is well-bounded which bounds the
1155 * total error since w_i is a subset of the period. Whereas on a
1156 * larger machine, while this first term can be larger, if w_i is the
1157 * of consequential size guaranteed to see n_i*w_i quickly converge to
1158 * our upper bound of 1-cpu.
1159 */
1160 runnable_avg = atomic_read(&tg->runnable_avg);
1161 if (runnable_avg < NICE_0_LOAD) {
1162 se->avg.load_avg_contrib *= runnable_avg;
1163 se->avg.load_avg_contrib >>= NICE_0_SHIFT;
1164 }
8165e145 1165}
c566e8e9
PT
1166#else
1167static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1168 int force_update) {}
bb17f655
PT
1169static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1170 struct cfs_rq *cfs_rq) {}
8165e145 1171static inline void __update_group_entity_contrib(struct sched_entity *se) {}
c566e8e9
PT
1172#endif
1173
8165e145
PT
1174static inline void __update_task_entity_contrib(struct sched_entity *se)
1175{
1176 u32 contrib;
1177
1178 /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
1179 contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
1180 contrib /= (se->avg.runnable_avg_period + 1);
1181 se->avg.load_avg_contrib = scale_load(contrib);
1182}
1183
2dac754e
PT
1184/* Compute the current contribution to load_avg by se, return any delta */
1185static long __update_entity_load_avg_contrib(struct sched_entity *se)
1186{
1187 long old_contrib = se->avg.load_avg_contrib;
1188
8165e145
PT
1189 if (entity_is_task(se)) {
1190 __update_task_entity_contrib(se);
1191 } else {
bb17f655 1192 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
8165e145
PT
1193 __update_group_entity_contrib(se);
1194 }
2dac754e
PT
1195
1196 return se->avg.load_avg_contrib - old_contrib;
1197}
1198
9ee474f5
PT
1199static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
1200 long load_contrib)
1201{
1202 if (likely(load_contrib < cfs_rq->blocked_load_avg))
1203 cfs_rq->blocked_load_avg -= load_contrib;
1204 else
1205 cfs_rq->blocked_load_avg = 0;
1206}
1207
f1b17280
PT
1208static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
1209
9d85f21c 1210/* Update a sched_entity's runnable average */
9ee474f5
PT
1211static inline void update_entity_load_avg(struct sched_entity *se,
1212 int update_cfs_rq)
9d85f21c 1213{
2dac754e
PT
1214 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1215 long contrib_delta;
f1b17280 1216 u64 now;
2dac754e 1217
f1b17280
PT
1218 /*
1219 * For a group entity we need to use their owned cfs_rq_clock_task() in
1220 * case they are the parent of a throttled hierarchy.
1221 */
1222 if (entity_is_task(se))
1223 now = cfs_rq_clock_task(cfs_rq);
1224 else
1225 now = cfs_rq_clock_task(group_cfs_rq(se));
1226
1227 if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq))
2dac754e
PT
1228 return;
1229
1230 contrib_delta = __update_entity_load_avg_contrib(se);
9ee474f5
PT
1231
1232 if (!update_cfs_rq)
1233 return;
1234
2dac754e
PT
1235 if (se->on_rq)
1236 cfs_rq->runnable_load_avg += contrib_delta;
9ee474f5
PT
1237 else
1238 subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
1239}
1240
1241/*
1242 * Decay the load contributed by all blocked children and account this so that
1243 * their contribution may appropriately discounted when they wake up.
1244 */
aff3e498 1245static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
9ee474f5 1246{
f1b17280 1247 u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
9ee474f5
PT
1248 u64 decays;
1249
1250 decays = now - cfs_rq->last_decay;
aff3e498 1251 if (!decays && !force_update)
9ee474f5
PT
1252 return;
1253
aff3e498
PT
1254 if (atomic64_read(&cfs_rq->removed_load)) {
1255 u64 removed_load = atomic64_xchg(&cfs_rq->removed_load, 0);
1256 subtract_blocked_load_contrib(cfs_rq, removed_load);
1257 }
9ee474f5 1258
aff3e498
PT
1259 if (decays) {
1260 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
1261 decays);
1262 atomic64_add(decays, &cfs_rq->decay_counter);
1263 cfs_rq->last_decay = now;
1264 }
c566e8e9
PT
1265
1266 __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
f269ae04 1267 update_cfs_shares(cfs_rq);
9d85f21c 1268}
18bf2805
BS
1269
1270static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
1271{
1272 __update_entity_runnable_avg(rq->clock_task, &rq->avg, runnable);
bb17f655 1273 __update_tg_runnable_avg(&rq->avg, &rq->cfs);
18bf2805 1274}
2dac754e
PT
1275
1276/* Add the load generated by se into cfs_rq's child load-average */
1277static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
1278 struct sched_entity *se,
1279 int wakeup)
2dac754e 1280{
aff3e498
PT
1281 /*
1282 * We track migrations using entity decay_count <= 0, on a wake-up
1283 * migration we use a negative decay count to track the remote decays
1284 * accumulated while sleeping.
1285 */
1286 if (unlikely(se->avg.decay_count <= 0)) {
9ee474f5 1287 se->avg.last_runnable_update = rq_of(cfs_rq)->clock_task;
aff3e498
PT
1288 if (se->avg.decay_count) {
1289 /*
1290 * In a wake-up migration we have to approximate the
1291 * time sleeping. This is because we can't synchronize
1292 * clock_task between the two cpus, and it is not
1293 * guaranteed to be read-safe. Instead, we can
1294 * approximate this using our carried decays, which are
1295 * explicitly atomically readable.
1296 */
1297 se->avg.last_runnable_update -= (-se->avg.decay_count)
1298 << 20;
1299 update_entity_load_avg(se, 0);
1300 /* Indicate that we're now synchronized and on-rq */
1301 se->avg.decay_count = 0;
1302 }
9ee474f5
PT
1303 wakeup = 0;
1304 } else {
1305 __synchronize_entity_decay(se);
1306 }
1307
aff3e498
PT
1308 /* migrated tasks did not contribute to our blocked load */
1309 if (wakeup) {
9ee474f5 1310 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
aff3e498
PT
1311 update_entity_load_avg(se, 0);
1312 }
9ee474f5 1313
2dac754e 1314 cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
aff3e498
PT
1315 /* we force update consideration on load-balancer moves */
1316 update_cfs_rq_blocked_load(cfs_rq, !wakeup);
2dac754e
PT
1317}
1318
9ee474f5
PT
1319/*
1320 * Remove se's load from this cfs_rq child load-average, if the entity is
1321 * transitioning to a blocked state we track its projected decay using
1322 * blocked_load_avg.
1323 */
2dac754e 1324static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
1325 struct sched_entity *se,
1326 int sleep)
2dac754e 1327{
9ee474f5 1328 update_entity_load_avg(se, 1);
aff3e498
PT
1329 /* we force update consideration on load-balancer moves */
1330 update_cfs_rq_blocked_load(cfs_rq, !sleep);
9ee474f5 1331
2dac754e 1332 cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
9ee474f5
PT
1333 if (sleep) {
1334 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
1335 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
1336 } /* migrations, e.g. sleep=0 leave decay_count == 0 */
2dac754e 1337}
9d85f21c 1338#else
9ee474f5
PT
1339static inline void update_entity_load_avg(struct sched_entity *se,
1340 int update_cfs_rq) {}
18bf2805 1341static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
2dac754e 1342static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
1343 struct sched_entity *se,
1344 int wakeup) {}
2dac754e 1345static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
1346 struct sched_entity *se,
1347 int sleep) {}
aff3e498
PT
1348static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
1349 int force_update) {}
9d85f21c
PT
1350#endif
1351
2396af69 1352static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 1353{
bf0f6f24 1354#ifdef CONFIG_SCHEDSTATS
e414314c
PZ
1355 struct task_struct *tsk = NULL;
1356
1357 if (entity_is_task(se))
1358 tsk = task_of(se);
1359
41acab88
LDM
1360 if (se->statistics.sleep_start) {
1361 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
bf0f6f24
IM
1362
1363 if ((s64)delta < 0)
1364 delta = 0;
1365
41acab88
LDM
1366 if (unlikely(delta > se->statistics.sleep_max))
1367 se->statistics.sleep_max = delta;
bf0f6f24 1368
8c79a045 1369 se->statistics.sleep_start = 0;
41acab88 1370 se->statistics.sum_sleep_runtime += delta;
9745512c 1371
768d0c27 1372 if (tsk) {
e414314c 1373 account_scheduler_latency(tsk, delta >> 10, 1);
768d0c27
PZ
1374 trace_sched_stat_sleep(tsk, delta);
1375 }
bf0f6f24 1376 }
41acab88
LDM
1377 if (se->statistics.block_start) {
1378 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
bf0f6f24
IM
1379
1380 if ((s64)delta < 0)
1381 delta = 0;
1382
41acab88
LDM
1383 if (unlikely(delta > se->statistics.block_max))
1384 se->statistics.block_max = delta;
bf0f6f24 1385
8c79a045 1386 se->statistics.block_start = 0;
41acab88 1387 se->statistics.sum_sleep_runtime += delta;
30084fbd 1388
e414314c 1389 if (tsk) {
8f0dfc34 1390 if (tsk->in_iowait) {
41acab88
LDM
1391 se->statistics.iowait_sum += delta;
1392 se->statistics.iowait_count++;
768d0c27 1393 trace_sched_stat_iowait(tsk, delta);
8f0dfc34
AV
1394 }
1395
b781a602
AV
1396 trace_sched_stat_blocked(tsk, delta);
1397
e414314c
PZ
1398 /*
1399 * Blocking time is in units of nanosecs, so shift by
1400 * 20 to get a milliseconds-range estimation of the
1401 * amount of time that the task spent sleeping:
1402 */
1403 if (unlikely(prof_on == SLEEP_PROFILING)) {
1404 profile_hits(SLEEP_PROFILING,
1405 (void *)get_wchan(tsk),
1406 delta >> 20);
1407 }
1408 account_scheduler_latency(tsk, delta >> 10, 0);
30084fbd 1409 }
bf0f6f24
IM
1410 }
1411#endif
1412}
1413
ddc97297
PZ
1414static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1415{
1416#ifdef CONFIG_SCHED_DEBUG
1417 s64 d = se->vruntime - cfs_rq->min_vruntime;
1418
1419 if (d < 0)
1420 d = -d;
1421
1422 if (d > 3*sysctl_sched_latency)
1423 schedstat_inc(cfs_rq, nr_spread_over);
1424#endif
1425}
1426
aeb73b04
PZ
1427static void
1428place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1429{
1af5f730 1430 u64 vruntime = cfs_rq->min_vruntime;
94dfb5e7 1431
2cb8600e
PZ
1432 /*
1433 * The 'current' period is already promised to the current tasks,
1434 * however the extra weight of the new task will slow them down a
1435 * little, place the new task so that it fits in the slot that
1436 * stays open at the end.
1437 */
94dfb5e7 1438 if (initial && sched_feat(START_DEBIT))
f9c0b095 1439 vruntime += sched_vslice(cfs_rq, se);
aeb73b04 1440
a2e7a7eb 1441 /* sleeps up to a single latency don't count. */
5ca9880c 1442 if (!initial) {
a2e7a7eb 1443 unsigned long thresh = sysctl_sched_latency;
a7be37ac 1444
a2e7a7eb
MG
1445 /*
1446 * Halve their sleep time's effect, to allow
1447 * for a gentler effect of sleepers:
1448 */
1449 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1450 thresh >>= 1;
51e0304c 1451
a2e7a7eb 1452 vruntime -= thresh;
aeb73b04
PZ
1453 }
1454
b5d9d734
MG
1455 /* ensure we never gain time by being placed backwards. */
1456 vruntime = max_vruntime(se->vruntime, vruntime);
1457
67e9fb2a 1458 se->vruntime = vruntime;
aeb73b04
PZ
1459}
1460
d3d9dc33
PT
1461static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1462
bf0f6f24 1463static void
88ec22d3 1464enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 1465{
88ec22d3
PZ
1466 /*
1467 * Update the normalized vruntime before updating min_vruntime
1468 * through callig update_curr().
1469 */
371fd7e7 1470 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
88ec22d3
PZ
1471 se->vruntime += cfs_rq->min_vruntime;
1472
bf0f6f24 1473 /*
a2a2d680 1474 * Update run-time statistics of the 'current'.
bf0f6f24 1475 */
b7cc0896 1476 update_curr(cfs_rq);
a992241d 1477 account_entity_enqueue(cfs_rq, se);
f269ae04 1478 enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
bf0f6f24 1479
88ec22d3 1480 if (flags & ENQUEUE_WAKEUP) {
aeb73b04 1481 place_entity(cfs_rq, se, 0);
2396af69 1482 enqueue_sleeper(cfs_rq, se);
e9acbff6 1483 }
bf0f6f24 1484
d2417e5a 1485 update_stats_enqueue(cfs_rq, se);
ddc97297 1486 check_spread(cfs_rq, se);
83b699ed
SV
1487 if (se != cfs_rq->curr)
1488 __enqueue_entity(cfs_rq, se);
2069dd75 1489 se->on_rq = 1;
3d4b47b4 1490
d3d9dc33 1491 if (cfs_rq->nr_running == 1) {
3d4b47b4 1492 list_add_leaf_cfs_rq(cfs_rq);
d3d9dc33
PT
1493 check_enqueue_throttle(cfs_rq);
1494 }
bf0f6f24
IM
1495}
1496
2c13c919 1497static void __clear_buddies_last(struct sched_entity *se)
2002c695 1498{
2c13c919
RR
1499 for_each_sched_entity(se) {
1500 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1501 if (cfs_rq->last == se)
1502 cfs_rq->last = NULL;
1503 else
1504 break;
1505 }
1506}
2002c695 1507
2c13c919
RR
1508static void __clear_buddies_next(struct sched_entity *se)
1509{
1510 for_each_sched_entity(se) {
1511 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1512 if (cfs_rq->next == se)
1513 cfs_rq->next = NULL;
1514 else
1515 break;
1516 }
2002c695
PZ
1517}
1518
ac53db59
RR
1519static void __clear_buddies_skip(struct sched_entity *se)
1520{
1521 for_each_sched_entity(se) {
1522 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1523 if (cfs_rq->skip == se)
1524 cfs_rq->skip = NULL;
1525 else
1526 break;
1527 }
1528}
1529
a571bbea
PZ
1530static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1531{
2c13c919
RR
1532 if (cfs_rq->last == se)
1533 __clear_buddies_last(se);
1534
1535 if (cfs_rq->next == se)
1536 __clear_buddies_next(se);
ac53db59
RR
1537
1538 if (cfs_rq->skip == se)
1539 __clear_buddies_skip(se);
a571bbea
PZ
1540}
1541
6c16a6dc 1542static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d8b4986d 1543
bf0f6f24 1544static void
371fd7e7 1545dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 1546{
a2a2d680
DA
1547 /*
1548 * Update run-time statistics of the 'current'.
1549 */
1550 update_curr(cfs_rq);
1551
19b6a2e3 1552 update_stats_dequeue(cfs_rq, se);
371fd7e7 1553 if (flags & DEQUEUE_SLEEP) {
67e9fb2a 1554#ifdef CONFIG_SCHEDSTATS
bf0f6f24
IM
1555 if (entity_is_task(se)) {
1556 struct task_struct *tsk = task_of(se);
1557
1558 if (tsk->state & TASK_INTERRUPTIBLE)
41acab88 1559 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
bf0f6f24 1560 if (tsk->state & TASK_UNINTERRUPTIBLE)
41acab88 1561 se->statistics.block_start = rq_of(cfs_rq)->clock;
bf0f6f24 1562 }
db36cc7d 1563#endif
67e9fb2a
PZ
1564 }
1565
2002c695 1566 clear_buddies(cfs_rq, se);
4793241b 1567
83b699ed 1568 if (se != cfs_rq->curr)
30cfdcfc
DA
1569 __dequeue_entity(cfs_rq, se);
1570 account_entity_dequeue(cfs_rq, se);
f269ae04 1571 dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
88ec22d3
PZ
1572
1573 /*
1574 * Normalize the entity after updating the min_vruntime because the
1575 * update can refer to the ->curr item and we need to reflect this
1576 * movement in our normalized position.
1577 */
371fd7e7 1578 if (!(flags & DEQUEUE_SLEEP))
88ec22d3 1579 se->vruntime -= cfs_rq->min_vruntime;
1e876231 1580
d8b4986d
PT
1581 /* return excess runtime on last dequeue */
1582 return_cfs_rq_runtime(cfs_rq);
1583
1e876231 1584 update_min_vruntime(cfs_rq);
f269ae04 1585 se->on_rq = 0;
bf0f6f24
IM
1586}
1587
1588/*
1589 * Preempt the current task with a newly woken task if needed:
1590 */
7c92e54f 1591static void
2e09bf55 1592check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
bf0f6f24 1593{
11697830 1594 unsigned long ideal_runtime, delta_exec;
f4cfb33e
WX
1595 struct sched_entity *se;
1596 s64 delta;
11697830 1597
6d0f0ebd 1598 ideal_runtime = sched_slice(cfs_rq, curr);
11697830 1599 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
a9f3e2b5 1600 if (delta_exec > ideal_runtime) {
bf0f6f24 1601 resched_task(rq_of(cfs_rq)->curr);
a9f3e2b5
MG
1602 /*
1603 * The current task ran long enough, ensure it doesn't get
1604 * re-elected due to buddy favours.
1605 */
1606 clear_buddies(cfs_rq, curr);
f685ceac
MG
1607 return;
1608 }
1609
1610 /*
1611 * Ensure that a task that missed wakeup preemption by a
1612 * narrow margin doesn't have to wait for a full slice.
1613 * This also mitigates buddy induced latencies under load.
1614 */
f685ceac
MG
1615 if (delta_exec < sysctl_sched_min_granularity)
1616 return;
1617
f4cfb33e
WX
1618 se = __pick_first_entity(cfs_rq);
1619 delta = curr->vruntime - se->vruntime;
f685ceac 1620
f4cfb33e
WX
1621 if (delta < 0)
1622 return;
d7d82944 1623
f4cfb33e
WX
1624 if (delta > ideal_runtime)
1625 resched_task(rq_of(cfs_rq)->curr);
bf0f6f24
IM
1626}
1627
83b699ed 1628static void
8494f412 1629set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 1630{
83b699ed
SV
1631 /* 'current' is not kept within the tree. */
1632 if (se->on_rq) {
1633 /*
1634 * Any task has to be enqueued before it get to execute on
1635 * a CPU. So account for the time it spent waiting on the
1636 * runqueue.
1637 */
1638 update_stats_wait_end(cfs_rq, se);
1639 __dequeue_entity(cfs_rq, se);
1640 }
1641
79303e9e 1642 update_stats_curr_start(cfs_rq, se);
429d43bc 1643 cfs_rq->curr = se;
eba1ed4b
IM
1644#ifdef CONFIG_SCHEDSTATS
1645 /*
1646 * Track our maximum slice length, if the CPU's load is at
1647 * least twice that of our own weight (i.e. dont track it
1648 * when there are only lesser-weight tasks around):
1649 */
495eca49 1650 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
41acab88 1651 se->statistics.slice_max = max(se->statistics.slice_max,
eba1ed4b
IM
1652 se->sum_exec_runtime - se->prev_sum_exec_runtime);
1653 }
1654#endif
4a55b450 1655 se->prev_sum_exec_runtime = se->sum_exec_runtime;
bf0f6f24
IM
1656}
1657
3f3a4904
PZ
1658static int
1659wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
1660
ac53db59
RR
1661/*
1662 * Pick the next process, keeping these things in mind, in this order:
1663 * 1) keep things fair between processes/task groups
1664 * 2) pick the "next" process, since someone really wants that to run
1665 * 3) pick the "last" process, for cache locality
1666 * 4) do not run the "skip" process, if something else is available
1667 */
f4b6755f 1668static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
aa2ac252 1669{
ac53db59 1670 struct sched_entity *se = __pick_first_entity(cfs_rq);
f685ceac 1671 struct sched_entity *left = se;
f4b6755f 1672
ac53db59
RR
1673 /*
1674 * Avoid running the skip buddy, if running something else can
1675 * be done without getting too unfair.
1676 */
1677 if (cfs_rq->skip == se) {
1678 struct sched_entity *second = __pick_next_entity(se);
1679 if (second && wakeup_preempt_entity(second, left) < 1)
1680 se = second;
1681 }
aa2ac252 1682
f685ceac
MG
1683 /*
1684 * Prefer last buddy, try to return the CPU to a preempted task.
1685 */
1686 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
1687 se = cfs_rq->last;
1688
ac53db59
RR
1689 /*
1690 * Someone really wants this to run. If it's not unfair, run it.
1691 */
1692 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
1693 se = cfs_rq->next;
1694
f685ceac 1695 clear_buddies(cfs_rq, se);
4793241b
PZ
1696
1697 return se;
aa2ac252
PZ
1698}
1699
d3d9dc33
PT
1700static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1701
ab6cde26 1702static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
bf0f6f24
IM
1703{
1704 /*
1705 * If still on the runqueue then deactivate_task()
1706 * was not called and update_curr() has to be done:
1707 */
1708 if (prev->on_rq)
b7cc0896 1709 update_curr(cfs_rq);
bf0f6f24 1710
d3d9dc33
PT
1711 /* throttle cfs_rqs exceeding runtime */
1712 check_cfs_rq_runtime(cfs_rq);
1713
ddc97297 1714 check_spread(cfs_rq, prev);
30cfdcfc 1715 if (prev->on_rq) {
5870db5b 1716 update_stats_wait_start(cfs_rq, prev);
30cfdcfc
DA
1717 /* Put 'current' back into the tree. */
1718 __enqueue_entity(cfs_rq, prev);
9d85f21c 1719 /* in !on_rq case, update occurred at dequeue */
9ee474f5 1720 update_entity_load_avg(prev, 1);
30cfdcfc 1721 }
429d43bc 1722 cfs_rq->curr = NULL;
bf0f6f24
IM
1723}
1724
8f4d37ec
PZ
1725static void
1726entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
bf0f6f24 1727{
bf0f6f24 1728 /*
30cfdcfc 1729 * Update run-time statistics of the 'current'.
bf0f6f24 1730 */
30cfdcfc 1731 update_curr(cfs_rq);
bf0f6f24 1732
9d85f21c
PT
1733 /*
1734 * Ensure that runnable average is periodically updated.
1735 */
9ee474f5 1736 update_entity_load_avg(curr, 1);
aff3e498 1737 update_cfs_rq_blocked_load(cfs_rq, 1);
9d85f21c 1738
8f4d37ec
PZ
1739#ifdef CONFIG_SCHED_HRTICK
1740 /*
1741 * queued ticks are scheduled to match the slice, so don't bother
1742 * validating it and just reschedule.
1743 */
983ed7a6
HH
1744 if (queued) {
1745 resched_task(rq_of(cfs_rq)->curr);
1746 return;
1747 }
8f4d37ec
PZ
1748 /*
1749 * don't let the period tick interfere with the hrtick preemption
1750 */
1751 if (!sched_feat(DOUBLE_TICK) &&
1752 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
1753 return;
1754#endif
1755
2c2efaed 1756 if (cfs_rq->nr_running > 1)
2e09bf55 1757 check_preempt_tick(cfs_rq, curr);
bf0f6f24
IM
1758}
1759
ab84d31e
PT
1760
1761/**************************************************
1762 * CFS bandwidth control machinery
1763 */
1764
1765#ifdef CONFIG_CFS_BANDWIDTH
029632fb
PZ
1766
1767#ifdef HAVE_JUMP_LABEL
c5905afb 1768static struct static_key __cfs_bandwidth_used;
029632fb
PZ
1769
1770static inline bool cfs_bandwidth_used(void)
1771{
c5905afb 1772 return static_key_false(&__cfs_bandwidth_used);
029632fb
PZ
1773}
1774
1775void account_cfs_bandwidth_used(int enabled, int was_enabled)
1776{
1777 /* only need to count groups transitioning between enabled/!enabled */
1778 if (enabled && !was_enabled)
c5905afb 1779 static_key_slow_inc(&__cfs_bandwidth_used);
029632fb 1780 else if (!enabled && was_enabled)
c5905afb 1781 static_key_slow_dec(&__cfs_bandwidth_used);
029632fb
PZ
1782}
1783#else /* HAVE_JUMP_LABEL */
1784static bool cfs_bandwidth_used(void)
1785{
1786 return true;
1787}
1788
1789void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
1790#endif /* HAVE_JUMP_LABEL */
1791
ab84d31e
PT
1792/*
1793 * default period for cfs group bandwidth.
1794 * default: 0.1s, units: nanoseconds
1795 */
1796static inline u64 default_cfs_period(void)
1797{
1798 return 100000000ULL;
1799}
ec12cb7f
PT
1800
1801static inline u64 sched_cfs_bandwidth_slice(void)
1802{
1803 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
1804}
1805
a9cf55b2
PT
1806/*
1807 * Replenish runtime according to assigned quota and update expiration time.
1808 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
1809 * additional synchronization around rq->lock.
1810 *
1811 * requires cfs_b->lock
1812 */
029632fb 1813void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
a9cf55b2
PT
1814{
1815 u64 now;
1816
1817 if (cfs_b->quota == RUNTIME_INF)
1818 return;
1819
1820 now = sched_clock_cpu(smp_processor_id());
1821 cfs_b->runtime = cfs_b->quota;
1822 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
1823}
1824
029632fb
PZ
1825static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
1826{
1827 return &tg->cfs_bandwidth;
1828}
1829
f1b17280
PT
1830/* rq->task_clock normalized against any time this cfs_rq has spent throttled */
1831static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
1832{
1833 if (unlikely(cfs_rq->throttle_count))
1834 return cfs_rq->throttled_clock_task;
1835
1836 return rq_of(cfs_rq)->clock_task - cfs_rq->throttled_clock_task_time;
1837}
1838
85dac906
PT
1839/* returns 0 on failure to allocate runtime */
1840static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f
PT
1841{
1842 struct task_group *tg = cfs_rq->tg;
1843 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
a9cf55b2 1844 u64 amount = 0, min_amount, expires;
ec12cb7f
PT
1845
1846 /* note: this is a positive sum as runtime_remaining <= 0 */
1847 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
1848
1849 raw_spin_lock(&cfs_b->lock);
1850 if (cfs_b->quota == RUNTIME_INF)
1851 amount = min_amount;
58088ad0 1852 else {
a9cf55b2
PT
1853 /*
1854 * If the bandwidth pool has become inactive, then at least one
1855 * period must have elapsed since the last consumption.
1856 * Refresh the global state and ensure bandwidth timer becomes
1857 * active.
1858 */
1859 if (!cfs_b->timer_active) {
1860 __refill_cfs_bandwidth_runtime(cfs_b);
58088ad0 1861 __start_cfs_bandwidth(cfs_b);
a9cf55b2 1862 }
58088ad0
PT
1863
1864 if (cfs_b->runtime > 0) {
1865 amount = min(cfs_b->runtime, min_amount);
1866 cfs_b->runtime -= amount;
1867 cfs_b->idle = 0;
1868 }
ec12cb7f 1869 }
a9cf55b2 1870 expires = cfs_b->runtime_expires;
ec12cb7f
PT
1871 raw_spin_unlock(&cfs_b->lock);
1872
1873 cfs_rq->runtime_remaining += amount;
a9cf55b2
PT
1874 /*
1875 * we may have advanced our local expiration to account for allowed
1876 * spread between our sched_clock and the one on which runtime was
1877 * issued.
1878 */
1879 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
1880 cfs_rq->runtime_expires = expires;
85dac906
PT
1881
1882 return cfs_rq->runtime_remaining > 0;
ec12cb7f
PT
1883}
1884
a9cf55b2
PT
1885/*
1886 * Note: This depends on the synchronization provided by sched_clock and the
1887 * fact that rq->clock snapshots this value.
1888 */
1889static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f 1890{
a9cf55b2
PT
1891 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1892 struct rq *rq = rq_of(cfs_rq);
1893
1894 /* if the deadline is ahead of our clock, nothing to do */
1895 if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
ec12cb7f
PT
1896 return;
1897
a9cf55b2
PT
1898 if (cfs_rq->runtime_remaining < 0)
1899 return;
1900
1901 /*
1902 * If the local deadline has passed we have to consider the
1903 * possibility that our sched_clock is 'fast' and the global deadline
1904 * has not truly expired.
1905 *
1906 * Fortunately we can check determine whether this the case by checking
1907 * whether the global deadline has advanced.
1908 */
1909
1910 if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
1911 /* extend local deadline, drift is bounded above by 2 ticks */
1912 cfs_rq->runtime_expires += TICK_NSEC;
1913 } else {
1914 /* global deadline is ahead, expiration has passed */
1915 cfs_rq->runtime_remaining = 0;
1916 }
1917}
1918
1919static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
1920 unsigned long delta_exec)
1921{
1922 /* dock delta_exec before expiring quota (as it could span periods) */
ec12cb7f 1923 cfs_rq->runtime_remaining -= delta_exec;
a9cf55b2
PT
1924 expire_cfs_rq_runtime(cfs_rq);
1925
1926 if (likely(cfs_rq->runtime_remaining > 0))
ec12cb7f
PT
1927 return;
1928
85dac906
PT
1929 /*
1930 * if we're unable to extend our runtime we resched so that the active
1931 * hierarchy can be throttled
1932 */
1933 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
1934 resched_task(rq_of(cfs_rq)->curr);
ec12cb7f
PT
1935}
1936
6c16a6dc
PZ
1937static __always_inline
1938void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
ec12cb7f 1939{
56f570e5 1940 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
ec12cb7f
PT
1941 return;
1942
1943 __account_cfs_rq_runtime(cfs_rq, delta_exec);
1944}
1945
85dac906
PT
1946static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
1947{
56f570e5 1948 return cfs_bandwidth_used() && cfs_rq->throttled;
85dac906
PT
1949}
1950
64660c86
PT
1951/* check whether cfs_rq, or any parent, is throttled */
1952static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
1953{
56f570e5 1954 return cfs_bandwidth_used() && cfs_rq->throttle_count;
64660c86
PT
1955}
1956
1957/*
1958 * Ensure that neither of the group entities corresponding to src_cpu or
1959 * dest_cpu are members of a throttled hierarchy when performing group
1960 * load-balance operations.
1961 */
1962static inline int throttled_lb_pair(struct task_group *tg,
1963 int src_cpu, int dest_cpu)
1964{
1965 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
1966
1967 src_cfs_rq = tg->cfs_rq[src_cpu];
1968 dest_cfs_rq = tg->cfs_rq[dest_cpu];
1969
1970 return throttled_hierarchy(src_cfs_rq) ||
1971 throttled_hierarchy(dest_cfs_rq);
1972}
1973
1974/* updated child weight may affect parent so we have to do this bottom up */
1975static int tg_unthrottle_up(struct task_group *tg, void *data)
1976{
1977 struct rq *rq = data;
1978 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1979
1980 cfs_rq->throttle_count--;
1981#ifdef CONFIG_SMP
1982 if (!cfs_rq->throttle_count) {
f1b17280
PT
1983 /* adjust cfs_rq_clock_task() */
1984 cfs_rq->throttled_clock_task_time += rq->clock_task -
1985 cfs_rq->throttled_clock_task;
64660c86
PT
1986 }
1987#endif
1988
1989 return 0;
1990}
1991
1992static int tg_throttle_down(struct task_group *tg, void *data)
1993{
1994 struct rq *rq = data;
1995 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1996
82958366
PT
1997 /* group is entering throttled state, stop time */
1998 if (!cfs_rq->throttle_count)
f1b17280 1999 cfs_rq->throttled_clock_task = rq->clock_task;
64660c86
PT
2000 cfs_rq->throttle_count++;
2001
2002 return 0;
2003}
2004
d3d9dc33 2005static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
85dac906
PT
2006{
2007 struct rq *rq = rq_of(cfs_rq);
2008 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2009 struct sched_entity *se;
2010 long task_delta, dequeue = 1;
2011
2012 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2013
f1b17280 2014 /* freeze hierarchy runnable averages while throttled */
64660c86
PT
2015 rcu_read_lock();
2016 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
2017 rcu_read_unlock();
85dac906
PT
2018
2019 task_delta = cfs_rq->h_nr_running;
2020 for_each_sched_entity(se) {
2021 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
2022 /* throttled entity or throttle-on-deactivate */
2023 if (!se->on_rq)
2024 break;
2025
2026 if (dequeue)
2027 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
2028 qcfs_rq->h_nr_running -= task_delta;
2029
2030 if (qcfs_rq->load.weight)
2031 dequeue = 0;
2032 }
2033
2034 if (!se)
2035 rq->nr_running -= task_delta;
2036
2037 cfs_rq->throttled = 1;
f1b17280 2038 cfs_rq->throttled_clock = rq->clock;
85dac906
PT
2039 raw_spin_lock(&cfs_b->lock);
2040 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
2041 raw_spin_unlock(&cfs_b->lock);
2042}
2043
029632fb 2044void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
671fd9da
PT
2045{
2046 struct rq *rq = rq_of(cfs_rq);
2047 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2048 struct sched_entity *se;
2049 int enqueue = 1;
2050 long task_delta;
2051
2052 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2053
2054 cfs_rq->throttled = 0;
2055 raw_spin_lock(&cfs_b->lock);
f1b17280 2056 cfs_b->throttled_time += rq->clock - cfs_rq->throttled_clock;
671fd9da
PT
2057 list_del_rcu(&cfs_rq->throttled_list);
2058 raw_spin_unlock(&cfs_b->lock);
2059
64660c86
PT
2060 update_rq_clock(rq);
2061 /* update hierarchical throttle state */
2062 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
2063
671fd9da
PT
2064 if (!cfs_rq->load.weight)
2065 return;
2066
2067 task_delta = cfs_rq->h_nr_running;
2068 for_each_sched_entity(se) {
2069 if (se->on_rq)
2070 enqueue = 0;
2071
2072 cfs_rq = cfs_rq_of(se);
2073 if (enqueue)
2074 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
2075 cfs_rq->h_nr_running += task_delta;
2076
2077 if (cfs_rq_throttled(cfs_rq))
2078 break;
2079 }
2080
2081 if (!se)
2082 rq->nr_running += task_delta;
2083
2084 /* determine whether we need to wake up potentially idle cpu */
2085 if (rq->curr == rq->idle && rq->cfs.nr_running)
2086 resched_task(rq->curr);
2087}
2088
2089static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
2090 u64 remaining, u64 expires)
2091{
2092 struct cfs_rq *cfs_rq;
2093 u64 runtime = remaining;
2094
2095 rcu_read_lock();
2096 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
2097 throttled_list) {
2098 struct rq *rq = rq_of(cfs_rq);
2099
2100 raw_spin_lock(&rq->lock);
2101 if (!cfs_rq_throttled(cfs_rq))
2102 goto next;
2103
2104 runtime = -cfs_rq->runtime_remaining + 1;
2105 if (runtime > remaining)
2106 runtime = remaining;
2107 remaining -= runtime;
2108
2109 cfs_rq->runtime_remaining += runtime;
2110 cfs_rq->runtime_expires = expires;
2111
2112 /* we check whether we're throttled above */
2113 if (cfs_rq->runtime_remaining > 0)
2114 unthrottle_cfs_rq(cfs_rq);
2115
2116next:
2117 raw_spin_unlock(&rq->lock);
2118
2119 if (!remaining)
2120 break;
2121 }
2122 rcu_read_unlock();
2123
2124 return remaining;
2125}
2126
58088ad0
PT
2127/*
2128 * Responsible for refilling a task_group's bandwidth and unthrottling its
2129 * cfs_rqs as appropriate. If there has been no activity within the last
2130 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
2131 * used to track this state.
2132 */
2133static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
2134{
671fd9da
PT
2135 u64 runtime, runtime_expires;
2136 int idle = 1, throttled;
58088ad0
PT
2137
2138 raw_spin_lock(&cfs_b->lock);
2139 /* no need to continue the timer with no bandwidth constraint */
2140 if (cfs_b->quota == RUNTIME_INF)
2141 goto out_unlock;
2142
671fd9da
PT
2143 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2144 /* idle depends on !throttled (for the case of a large deficit) */
2145 idle = cfs_b->idle && !throttled;
e8da1b18 2146 cfs_b->nr_periods += overrun;
671fd9da 2147
a9cf55b2
PT
2148 /* if we're going inactive then everything else can be deferred */
2149 if (idle)
2150 goto out_unlock;
2151
2152 __refill_cfs_bandwidth_runtime(cfs_b);
2153
671fd9da
PT
2154 if (!throttled) {
2155 /* mark as potentially idle for the upcoming period */
2156 cfs_b->idle = 1;
2157 goto out_unlock;
2158 }
2159
e8da1b18
NR
2160 /* account preceding periods in which throttling occurred */
2161 cfs_b->nr_throttled += overrun;
2162
671fd9da
PT
2163 /*
2164 * There are throttled entities so we must first use the new bandwidth
2165 * to unthrottle them before making it generally available. This
2166 * ensures that all existing debts will be paid before a new cfs_rq is
2167 * allowed to run.
2168 */
2169 runtime = cfs_b->runtime;
2170 runtime_expires = cfs_b->runtime_expires;
2171 cfs_b->runtime = 0;
2172
2173 /*
2174 * This check is repeated as we are holding onto the new bandwidth
2175 * while we unthrottle. This can potentially race with an unthrottled
2176 * group trying to acquire new bandwidth from the global pool.
2177 */
2178 while (throttled && runtime > 0) {
2179 raw_spin_unlock(&cfs_b->lock);
2180 /* we can't nest cfs_b->lock while distributing bandwidth */
2181 runtime = distribute_cfs_runtime(cfs_b, runtime,
2182 runtime_expires);
2183 raw_spin_lock(&cfs_b->lock);
2184
2185 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2186 }
58088ad0 2187
671fd9da
PT
2188 /* return (any) remaining runtime */
2189 cfs_b->runtime = runtime;
2190 /*
2191 * While we are ensured activity in the period following an
2192 * unthrottle, this also covers the case in which the new bandwidth is
2193 * insufficient to cover the existing bandwidth deficit. (Forcing the
2194 * timer to remain active while there are any throttled entities.)
2195 */
2196 cfs_b->idle = 0;
58088ad0
PT
2197out_unlock:
2198 if (idle)
2199 cfs_b->timer_active = 0;
2200 raw_spin_unlock(&cfs_b->lock);
2201
2202 return idle;
2203}
d3d9dc33 2204
d8b4986d
PT
2205/* a cfs_rq won't donate quota below this amount */
2206static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2207/* minimum remaining period time to redistribute slack quota */
2208static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2209/* how long we wait to gather additional slack before distributing */
2210static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2211
2212/* are we near the end of the current quota period? */
2213static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2214{
2215 struct hrtimer *refresh_timer = &cfs_b->period_timer;
2216 u64 remaining;
2217
2218 /* if the call-back is running a quota refresh is already occurring */
2219 if (hrtimer_callback_running(refresh_timer))
2220 return 1;
2221
2222 /* is a quota refresh about to occur? */
2223 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2224 if (remaining < min_expire)
2225 return 1;
2226
2227 return 0;
2228}
2229
2230static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2231{
2232 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2233
2234 /* if there's a quota refresh soon don't bother with slack */
2235 if (runtime_refresh_within(cfs_b, min_left))
2236 return;
2237
2238 start_bandwidth_timer(&cfs_b->slack_timer,
2239 ns_to_ktime(cfs_bandwidth_slack_period));
2240}
2241
2242/* we know any runtime found here is valid as update_curr() precedes return */
2243static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2244{
2245 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2246 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2247
2248 if (slack_runtime <= 0)
2249 return;
2250
2251 raw_spin_lock(&cfs_b->lock);
2252 if (cfs_b->quota != RUNTIME_INF &&
2253 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2254 cfs_b->runtime += slack_runtime;
2255
2256 /* we are under rq->lock, defer unthrottling using a timer */
2257 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2258 !list_empty(&cfs_b->throttled_cfs_rq))
2259 start_cfs_slack_bandwidth(cfs_b);
2260 }
2261 raw_spin_unlock(&cfs_b->lock);
2262
2263 /* even if it's not valid for return we don't want to try again */
2264 cfs_rq->runtime_remaining -= slack_runtime;
2265}
2266
2267static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2268{
56f570e5
PT
2269 if (!cfs_bandwidth_used())
2270 return;
2271
fccfdc6f 2272 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
d8b4986d
PT
2273 return;
2274
2275 __return_cfs_rq_runtime(cfs_rq);
2276}
2277
2278/*
2279 * This is done with a timer (instead of inline with bandwidth return) since
2280 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2281 */
2282static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2283{
2284 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2285 u64 expires;
2286
2287 /* confirm we're still not at a refresh boundary */
2288 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2289 return;
2290
2291 raw_spin_lock(&cfs_b->lock);
2292 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2293 runtime = cfs_b->runtime;
2294 cfs_b->runtime = 0;
2295 }
2296 expires = cfs_b->runtime_expires;
2297 raw_spin_unlock(&cfs_b->lock);
2298
2299 if (!runtime)
2300 return;
2301
2302 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2303
2304 raw_spin_lock(&cfs_b->lock);
2305 if (expires == cfs_b->runtime_expires)
2306 cfs_b->runtime = runtime;
2307 raw_spin_unlock(&cfs_b->lock);
2308}
2309
d3d9dc33
PT
2310/*
2311 * When a group wakes up we want to make sure that its quota is not already
2312 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2313 * runtime as update_curr() throttling can not not trigger until it's on-rq.
2314 */
2315static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2316{
56f570e5
PT
2317 if (!cfs_bandwidth_used())
2318 return;
2319
d3d9dc33
PT
2320 /* an active group must be handled by the update_curr()->put() path */
2321 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2322 return;
2323
2324 /* ensure the group is not already throttled */
2325 if (cfs_rq_throttled(cfs_rq))
2326 return;
2327
2328 /* update runtime allocation */
2329 account_cfs_rq_runtime(cfs_rq, 0);
2330 if (cfs_rq->runtime_remaining <= 0)
2331 throttle_cfs_rq(cfs_rq);
2332}
2333
2334/* conditionally throttle active cfs_rq's from put_prev_entity() */
2335static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2336{
56f570e5
PT
2337 if (!cfs_bandwidth_used())
2338 return;
2339
d3d9dc33
PT
2340 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2341 return;
2342
2343 /*
2344 * it's possible for a throttled entity to be forced into a running
2345 * state (e.g. set_curr_task), in this case we're finished.
2346 */
2347 if (cfs_rq_throttled(cfs_rq))
2348 return;
2349
2350 throttle_cfs_rq(cfs_rq);
2351}
029632fb
PZ
2352
2353static inline u64 default_cfs_period(void);
2354static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2355static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2356
2357static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2358{
2359 struct cfs_bandwidth *cfs_b =
2360 container_of(timer, struct cfs_bandwidth, slack_timer);
2361 do_sched_cfs_slack_timer(cfs_b);
2362
2363 return HRTIMER_NORESTART;
2364}
2365
2366static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2367{
2368 struct cfs_bandwidth *cfs_b =
2369 container_of(timer, struct cfs_bandwidth, period_timer);
2370 ktime_t now;
2371 int overrun;
2372 int idle = 0;
2373
2374 for (;;) {
2375 now = hrtimer_cb_get_time(timer);
2376 overrun = hrtimer_forward(timer, now, cfs_b->period);
2377
2378 if (!overrun)
2379 break;
2380
2381 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2382 }
2383
2384 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2385}
2386
2387void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2388{
2389 raw_spin_lock_init(&cfs_b->lock);
2390 cfs_b->runtime = 0;
2391 cfs_b->quota = RUNTIME_INF;
2392 cfs_b->period = ns_to_ktime(default_cfs_period());
2393
2394 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2395 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2396 cfs_b->period_timer.function = sched_cfs_period_timer;
2397 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2398 cfs_b->slack_timer.function = sched_cfs_slack_timer;
2399}
2400
2401static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2402{
2403 cfs_rq->runtime_enabled = 0;
2404 INIT_LIST_HEAD(&cfs_rq->throttled_list);
2405}
2406
2407/* requires cfs_b->lock, may release to reprogram timer */
2408void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2409{
2410 /*
2411 * The timer may be active because we're trying to set a new bandwidth
2412 * period or because we're racing with the tear-down path
2413 * (timer_active==0 becomes visible before the hrtimer call-back
2414 * terminates). In either case we ensure that it's re-programmed
2415 */
2416 while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2417 raw_spin_unlock(&cfs_b->lock);
2418 /* ensure cfs_b->lock is available while we wait */
2419 hrtimer_cancel(&cfs_b->period_timer);
2420
2421 raw_spin_lock(&cfs_b->lock);
2422 /* if someone else restarted the timer then we're done */
2423 if (cfs_b->timer_active)
2424 return;
2425 }
2426
2427 cfs_b->timer_active = 1;
2428 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2429}
2430
2431static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2432{
2433 hrtimer_cancel(&cfs_b->period_timer);
2434 hrtimer_cancel(&cfs_b->slack_timer);
2435}
2436
a4c96ae3 2437static void unthrottle_offline_cfs_rqs(struct rq *rq)
029632fb
PZ
2438{
2439 struct cfs_rq *cfs_rq;
2440
2441 for_each_leaf_cfs_rq(rq, cfs_rq) {
2442 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2443
2444 if (!cfs_rq->runtime_enabled)
2445 continue;
2446
2447 /*
2448 * clock_task is not advancing so we just need to make sure
2449 * there's some valid quota amount
2450 */
2451 cfs_rq->runtime_remaining = cfs_b->quota;
2452 if (cfs_rq_throttled(cfs_rq))
2453 unthrottle_cfs_rq(cfs_rq);
2454 }
2455}
2456
2457#else /* CONFIG_CFS_BANDWIDTH */
f1b17280
PT
2458static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
2459{
2460 return rq_of(cfs_rq)->clock_task;
2461}
2462
2463static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
2464 unsigned long delta_exec) {}
d3d9dc33
PT
2465static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2466static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6c16a6dc 2467static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
85dac906
PT
2468
2469static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2470{
2471 return 0;
2472}
64660c86
PT
2473
2474static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2475{
2476 return 0;
2477}
2478
2479static inline int throttled_lb_pair(struct task_group *tg,
2480 int src_cpu, int dest_cpu)
2481{
2482 return 0;
2483}
029632fb
PZ
2484
2485void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2486
2487#ifdef CONFIG_FAIR_GROUP_SCHED
2488static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
ab84d31e
PT
2489#endif
2490
029632fb
PZ
2491static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2492{
2493 return NULL;
2494}
2495static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
a4c96ae3 2496static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
029632fb
PZ
2497
2498#endif /* CONFIG_CFS_BANDWIDTH */
2499
bf0f6f24
IM
2500/**************************************************
2501 * CFS operations on tasks:
2502 */
2503
8f4d37ec
PZ
2504#ifdef CONFIG_SCHED_HRTICK
2505static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2506{
8f4d37ec
PZ
2507 struct sched_entity *se = &p->se;
2508 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2509
2510 WARN_ON(task_rq(p) != rq);
2511
b39e66ea 2512 if (cfs_rq->nr_running > 1) {
8f4d37ec
PZ
2513 u64 slice = sched_slice(cfs_rq, se);
2514 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2515 s64 delta = slice - ran;
2516
2517 if (delta < 0) {
2518 if (rq->curr == p)
2519 resched_task(p);
2520 return;
2521 }
2522
2523 /*
2524 * Don't schedule slices shorter than 10000ns, that just
2525 * doesn't make sense. Rely on vruntime for fairness.
2526 */
31656519 2527 if (rq->curr != p)
157124c1 2528 delta = max_t(s64, 10000LL, delta);
8f4d37ec 2529
31656519 2530 hrtick_start(rq, delta);
8f4d37ec
PZ
2531 }
2532}
a4c2f00f
PZ
2533
2534/*
2535 * called from enqueue/dequeue and updates the hrtick when the
2536 * current task is from our class and nr_running is low enough
2537 * to matter.
2538 */
2539static void hrtick_update(struct rq *rq)
2540{
2541 struct task_struct *curr = rq->curr;
2542
b39e66ea 2543 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
a4c2f00f
PZ
2544 return;
2545
2546 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2547 hrtick_start_fair(rq, curr);
2548}
55e12e5e 2549#else /* !CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
2550static inline void
2551hrtick_start_fair(struct rq *rq, struct task_struct *p)
2552{
2553}
a4c2f00f
PZ
2554
2555static inline void hrtick_update(struct rq *rq)
2556{
2557}
8f4d37ec
PZ
2558#endif
2559
bf0f6f24
IM
2560/*
2561 * The enqueue_task method is called before nr_running is
2562 * increased. Here we update the fair scheduling stats and
2563 * then put the task into the rbtree:
2564 */
ea87bb78 2565static void
371fd7e7 2566enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
2567{
2568 struct cfs_rq *cfs_rq;
62fb1851 2569 struct sched_entity *se = &p->se;
bf0f6f24
IM
2570
2571 for_each_sched_entity(se) {
62fb1851 2572 if (se->on_rq)
bf0f6f24
IM
2573 break;
2574 cfs_rq = cfs_rq_of(se);
88ec22d3 2575 enqueue_entity(cfs_rq, se, flags);
85dac906
PT
2576
2577 /*
2578 * end evaluation on encountering a throttled cfs_rq
2579 *
2580 * note: in the case of encountering a throttled cfs_rq we will
2581 * post the final h_nr_running increment below.
2582 */
2583 if (cfs_rq_throttled(cfs_rq))
2584 break;
953bfcd1 2585 cfs_rq->h_nr_running++;
85dac906 2586
88ec22d3 2587 flags = ENQUEUE_WAKEUP;
bf0f6f24 2588 }
8f4d37ec 2589
2069dd75 2590 for_each_sched_entity(se) {
0f317143 2591 cfs_rq = cfs_rq_of(se);
953bfcd1 2592 cfs_rq->h_nr_running++;
2069dd75 2593
85dac906
PT
2594 if (cfs_rq_throttled(cfs_rq))
2595 break;
2596
9ee474f5 2597 update_entity_load_avg(se, 1);
f269ae04 2598 update_cfs_rq_blocked_load(cfs_rq, 0);
2069dd75
PZ
2599 }
2600
18bf2805
BS
2601 if (!se) {
2602 update_rq_runnable_avg(rq, rq->nr_running);
85dac906 2603 inc_nr_running(rq);
18bf2805 2604 }
a4c2f00f 2605 hrtick_update(rq);
bf0f6f24
IM
2606}
2607
2f36825b
VP
2608static void set_next_buddy(struct sched_entity *se);
2609
bf0f6f24
IM
2610/*
2611 * The dequeue_task method is called before nr_running is
2612 * decreased. We remove the task from the rbtree and
2613 * update the fair scheduling stats:
2614 */
371fd7e7 2615static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
2616{
2617 struct cfs_rq *cfs_rq;
62fb1851 2618 struct sched_entity *se = &p->se;
2f36825b 2619 int task_sleep = flags & DEQUEUE_SLEEP;
bf0f6f24
IM
2620
2621 for_each_sched_entity(se) {
2622 cfs_rq = cfs_rq_of(se);
371fd7e7 2623 dequeue_entity(cfs_rq, se, flags);
85dac906
PT
2624
2625 /*
2626 * end evaluation on encountering a throttled cfs_rq
2627 *
2628 * note: in the case of encountering a throttled cfs_rq we will
2629 * post the final h_nr_running decrement below.
2630 */
2631 if (cfs_rq_throttled(cfs_rq))
2632 break;
953bfcd1 2633 cfs_rq->h_nr_running--;
2069dd75 2634
bf0f6f24 2635 /* Don't dequeue parent if it has other entities besides us */
2f36825b
VP
2636 if (cfs_rq->load.weight) {
2637 /*
2638 * Bias pick_next to pick a task from this cfs_rq, as
2639 * p is sleeping when it is within its sched_slice.
2640 */
2641 if (task_sleep && parent_entity(se))
2642 set_next_buddy(parent_entity(se));
9598c82d
PT
2643
2644 /* avoid re-evaluating load for this entity */
2645 se = parent_entity(se);
bf0f6f24 2646 break;
2f36825b 2647 }
371fd7e7 2648 flags |= DEQUEUE_SLEEP;
bf0f6f24 2649 }
8f4d37ec 2650
2069dd75 2651 for_each_sched_entity(se) {
0f317143 2652 cfs_rq = cfs_rq_of(se);
953bfcd1 2653 cfs_rq->h_nr_running--;
2069dd75 2654
85dac906
PT
2655 if (cfs_rq_throttled(cfs_rq))
2656 break;
2657
9ee474f5 2658 update_entity_load_avg(se, 1);
f269ae04 2659 update_cfs_rq_blocked_load(cfs_rq, 0);
2069dd75
PZ
2660 }
2661
18bf2805 2662 if (!se) {
85dac906 2663 dec_nr_running(rq);
18bf2805
BS
2664 update_rq_runnable_avg(rq, 1);
2665 }
a4c2f00f 2666 hrtick_update(rq);
bf0f6f24
IM
2667}
2668
e7693a36 2669#ifdef CONFIG_SMP
029632fb
PZ
2670/* Used instead of source_load when we know the type == 0 */
2671static unsigned long weighted_cpuload(const int cpu)
2672{
2673 return cpu_rq(cpu)->load.weight;
2674}
2675
2676/*
2677 * Return a low guess at the load of a migration-source cpu weighted
2678 * according to the scheduling class and "nice" value.
2679 *
2680 * We want to under-estimate the load of migration sources, to
2681 * balance conservatively.
2682 */
2683static unsigned long source_load(int cpu, int type)
2684{
2685 struct rq *rq = cpu_rq(cpu);
2686 unsigned long total = weighted_cpuload(cpu);
2687
2688 if (type == 0 || !sched_feat(LB_BIAS))
2689 return total;
2690
2691 return min(rq->cpu_load[type-1], total);
2692}
2693
2694/*
2695 * Return a high guess at the load of a migration-target cpu weighted
2696 * according to the scheduling class and "nice" value.
2697 */
2698static unsigned long target_load(int cpu, int type)
2699{
2700 struct rq *rq = cpu_rq(cpu);
2701 unsigned long total = weighted_cpuload(cpu);
2702
2703 if (type == 0 || !sched_feat(LB_BIAS))
2704 return total;
2705
2706 return max(rq->cpu_load[type-1], total);
2707}
2708
2709static unsigned long power_of(int cpu)
2710{
2711 return cpu_rq(cpu)->cpu_power;
2712}
2713
2714static unsigned long cpu_avg_load_per_task(int cpu)
2715{
2716 struct rq *rq = cpu_rq(cpu);
2717 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
2718
2719 if (nr_running)
2720 return rq->load.weight / nr_running;
2721
2722 return 0;
2723}
2724
098fb9db 2725
74f8e4b2 2726static void task_waking_fair(struct task_struct *p)
88ec22d3
PZ
2727{
2728 struct sched_entity *se = &p->se;
2729 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3fe1698b
PZ
2730 u64 min_vruntime;
2731
2732#ifndef CONFIG_64BIT
2733 u64 min_vruntime_copy;
88ec22d3 2734
3fe1698b
PZ
2735 do {
2736 min_vruntime_copy = cfs_rq->min_vruntime_copy;
2737 smp_rmb();
2738 min_vruntime = cfs_rq->min_vruntime;
2739 } while (min_vruntime != min_vruntime_copy);
2740#else
2741 min_vruntime = cfs_rq->min_vruntime;
2742#endif
88ec22d3 2743
3fe1698b 2744 se->vruntime -= min_vruntime;
88ec22d3
PZ
2745}
2746
bb3469ac 2747#ifdef CONFIG_FAIR_GROUP_SCHED
f5bfb7d9
PZ
2748/*
2749 * effective_load() calculates the load change as seen from the root_task_group
2750 *
2751 * Adding load to a group doesn't make a group heavier, but can cause movement
2752 * of group shares between cpus. Assuming the shares were perfectly aligned one
2753 * can calculate the shift in shares.
cf5f0acf
PZ
2754 *
2755 * Calculate the effective load difference if @wl is added (subtracted) to @tg
2756 * on this @cpu and results in a total addition (subtraction) of @wg to the
2757 * total group weight.
2758 *
2759 * Given a runqueue weight distribution (rw_i) we can compute a shares
2760 * distribution (s_i) using:
2761 *
2762 * s_i = rw_i / \Sum rw_j (1)
2763 *
2764 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
2765 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
2766 * shares distribution (s_i):
2767 *
2768 * rw_i = { 2, 4, 1, 0 }
2769 * s_i = { 2/7, 4/7, 1/7, 0 }
2770 *
2771 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
2772 * task used to run on and the CPU the waker is running on), we need to
2773 * compute the effect of waking a task on either CPU and, in case of a sync
2774 * wakeup, compute the effect of the current task going to sleep.
2775 *
2776 * So for a change of @wl to the local @cpu with an overall group weight change
2777 * of @wl we can compute the new shares distribution (s'_i) using:
2778 *
2779 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
2780 *
2781 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
2782 * differences in waking a task to CPU 0. The additional task changes the
2783 * weight and shares distributions like:
2784 *
2785 * rw'_i = { 3, 4, 1, 0 }
2786 * s'_i = { 3/8, 4/8, 1/8, 0 }
2787 *
2788 * We can then compute the difference in effective weight by using:
2789 *
2790 * dw_i = S * (s'_i - s_i) (3)
2791 *
2792 * Where 'S' is the group weight as seen by its parent.
2793 *
2794 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
2795 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
2796 * 4/7) times the weight of the group.
f5bfb7d9 2797 */
2069dd75 2798static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
bb3469ac 2799{
4be9daaa 2800 struct sched_entity *se = tg->se[cpu];
f1d239f7 2801
cf5f0acf 2802 if (!tg->parent) /* the trivial, non-cgroup case */
f1d239f7
PZ
2803 return wl;
2804
4be9daaa 2805 for_each_sched_entity(se) {
cf5f0acf 2806 long w, W;
4be9daaa 2807
977dda7c 2808 tg = se->my_q->tg;
bb3469ac 2809
cf5f0acf
PZ
2810 /*
2811 * W = @wg + \Sum rw_j
2812 */
2813 W = wg + calc_tg_weight(tg, se->my_q);
4be9daaa 2814
cf5f0acf
PZ
2815 /*
2816 * w = rw_i + @wl
2817 */
2818 w = se->my_q->load.weight + wl;
940959e9 2819
cf5f0acf
PZ
2820 /*
2821 * wl = S * s'_i; see (2)
2822 */
2823 if (W > 0 && w < W)
2824 wl = (w * tg->shares) / W;
977dda7c
PT
2825 else
2826 wl = tg->shares;
940959e9 2827
cf5f0acf
PZ
2828 /*
2829 * Per the above, wl is the new se->load.weight value; since
2830 * those are clipped to [MIN_SHARES, ...) do so now. See
2831 * calc_cfs_shares().
2832 */
977dda7c
PT
2833 if (wl < MIN_SHARES)
2834 wl = MIN_SHARES;
cf5f0acf
PZ
2835
2836 /*
2837 * wl = dw_i = S * (s'_i - s_i); see (3)
2838 */
977dda7c 2839 wl -= se->load.weight;
cf5f0acf
PZ
2840
2841 /*
2842 * Recursively apply this logic to all parent groups to compute
2843 * the final effective load change on the root group. Since
2844 * only the @tg group gets extra weight, all parent groups can
2845 * only redistribute existing shares. @wl is the shift in shares
2846 * resulting from this level per the above.
2847 */
4be9daaa 2848 wg = 0;
4be9daaa 2849 }
bb3469ac 2850
4be9daaa 2851 return wl;
bb3469ac
PZ
2852}
2853#else
4be9daaa 2854
83378269
PZ
2855static inline unsigned long effective_load(struct task_group *tg, int cpu,
2856 unsigned long wl, unsigned long wg)
4be9daaa 2857{
83378269 2858 return wl;
bb3469ac 2859}
4be9daaa 2860
bb3469ac
PZ
2861#endif
2862
c88d5910 2863static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
098fb9db 2864{
e37b6a7b 2865 s64 this_load, load;
c88d5910 2866 int idx, this_cpu, prev_cpu;
098fb9db 2867 unsigned long tl_per_task;
c88d5910 2868 struct task_group *tg;
83378269 2869 unsigned long weight;
b3137bc8 2870 int balanced;
098fb9db 2871
c88d5910
PZ
2872 idx = sd->wake_idx;
2873 this_cpu = smp_processor_id();
2874 prev_cpu = task_cpu(p);
2875 load = source_load(prev_cpu, idx);
2876 this_load = target_load(this_cpu, idx);
098fb9db 2877
b3137bc8
MG
2878 /*
2879 * If sync wakeup then subtract the (maximum possible)
2880 * effect of the currently running task from the load
2881 * of the current CPU:
2882 */
83378269
PZ
2883 if (sync) {
2884 tg = task_group(current);
2885 weight = current->se.load.weight;
2886
c88d5910 2887 this_load += effective_load(tg, this_cpu, -weight, -weight);
83378269
PZ
2888 load += effective_load(tg, prev_cpu, 0, -weight);
2889 }
b3137bc8 2890
83378269
PZ
2891 tg = task_group(p);
2892 weight = p->se.load.weight;
b3137bc8 2893
71a29aa7
PZ
2894 /*
2895 * In low-load situations, where prev_cpu is idle and this_cpu is idle
c88d5910
PZ
2896 * due to the sync cause above having dropped this_load to 0, we'll
2897 * always have an imbalance, but there's really nothing you can do
2898 * about that, so that's good too.
71a29aa7
PZ
2899 *
2900 * Otherwise check if either cpus are near enough in load to allow this
2901 * task to be woken on this_cpu.
2902 */
e37b6a7b
PT
2903 if (this_load > 0) {
2904 s64 this_eff_load, prev_eff_load;
e51fd5e2
PZ
2905
2906 this_eff_load = 100;
2907 this_eff_load *= power_of(prev_cpu);
2908 this_eff_load *= this_load +
2909 effective_load(tg, this_cpu, weight, weight);
2910
2911 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
2912 prev_eff_load *= power_of(this_cpu);
2913 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
2914
2915 balanced = this_eff_load <= prev_eff_load;
2916 } else
2917 balanced = true;
b3137bc8 2918
098fb9db 2919 /*
4ae7d5ce
IM
2920 * If the currently running task will sleep within
2921 * a reasonable amount of time then attract this newly
2922 * woken task:
098fb9db 2923 */
2fb7635c
PZ
2924 if (sync && balanced)
2925 return 1;
098fb9db 2926
41acab88 2927 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
098fb9db
IM
2928 tl_per_task = cpu_avg_load_per_task(this_cpu);
2929
c88d5910
PZ
2930 if (balanced ||
2931 (this_load <= load &&
2932 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
098fb9db
IM
2933 /*
2934 * This domain has SD_WAKE_AFFINE and
2935 * p is cache cold in this domain, and
2936 * there is no bad imbalance.
2937 */
c88d5910 2938 schedstat_inc(sd, ttwu_move_affine);
41acab88 2939 schedstat_inc(p, se.statistics.nr_wakeups_affine);
098fb9db
IM
2940
2941 return 1;
2942 }
2943 return 0;
2944}
2945
aaee1203
PZ
2946/*
2947 * find_idlest_group finds and returns the least busy CPU group within the
2948 * domain.
2949 */
2950static struct sched_group *
78e7ed53 2951find_idlest_group(struct sched_domain *sd, struct task_struct *p,
5158f4e4 2952 int this_cpu, int load_idx)
e7693a36 2953{
b3bd3de6 2954 struct sched_group *idlest = NULL, *group = sd->groups;
aaee1203 2955 unsigned long min_load = ULONG_MAX, this_load = 0;
aaee1203 2956 int imbalance = 100 + (sd->imbalance_pct-100)/2;
e7693a36 2957
aaee1203
PZ
2958 do {
2959 unsigned long load, avg_load;
2960 int local_group;
2961 int i;
e7693a36 2962
aaee1203
PZ
2963 /* Skip over this group if it has no CPUs allowed */
2964 if (!cpumask_intersects(sched_group_cpus(group),
fa17b507 2965 tsk_cpus_allowed(p)))
aaee1203
PZ
2966 continue;
2967
2968 local_group = cpumask_test_cpu(this_cpu,
2969 sched_group_cpus(group));
2970
2971 /* Tally up the load of all CPUs in the group */
2972 avg_load = 0;
2973
2974 for_each_cpu(i, sched_group_cpus(group)) {
2975 /* Bias balancing toward cpus of our domain */
2976 if (local_group)
2977 load = source_load(i, load_idx);
2978 else
2979 load = target_load(i, load_idx);
2980
2981 avg_load += load;
2982 }
2983
2984 /* Adjust by relative CPU power of the group */
9c3f75cb 2985 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
aaee1203
PZ
2986
2987 if (local_group) {
2988 this_load = avg_load;
aaee1203
PZ
2989 } else if (avg_load < min_load) {
2990 min_load = avg_load;
2991 idlest = group;
2992 }
2993 } while (group = group->next, group != sd->groups);
2994
2995 if (!idlest || 100*this_load < imbalance*min_load)
2996 return NULL;
2997 return idlest;
2998}
2999
3000/*
3001 * find_idlest_cpu - find the idlest cpu among the cpus in group.
3002 */
3003static int
3004find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
3005{
3006 unsigned long load, min_load = ULONG_MAX;
3007 int idlest = -1;
3008 int i;
3009
3010 /* Traverse only the allowed CPUs */
fa17b507 3011 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
aaee1203
PZ
3012 load = weighted_cpuload(i);
3013
3014 if (load < min_load || (load == min_load && i == this_cpu)) {
3015 min_load = load;
3016 idlest = i;
e7693a36
GH
3017 }
3018 }
3019
aaee1203
PZ
3020 return idlest;
3021}
e7693a36 3022
a50bde51
PZ
3023/*
3024 * Try and locate an idle CPU in the sched_domain.
3025 */
99bd5e2f 3026static int select_idle_sibling(struct task_struct *p, int target)
a50bde51
PZ
3027{
3028 int cpu = smp_processor_id();
3029 int prev_cpu = task_cpu(p);
99bd5e2f 3030 struct sched_domain *sd;
37407ea7
LT
3031 struct sched_group *sg;
3032 int i;
a50bde51
PZ
3033
3034 /*
99bd5e2f
SS
3035 * If the task is going to be woken-up on this cpu and if it is
3036 * already idle, then it is the right target.
a50bde51 3037 */
99bd5e2f
SS
3038 if (target == cpu && idle_cpu(cpu))
3039 return cpu;
3040
3041 /*
3042 * If the task is going to be woken-up on the cpu where it previously
3043 * ran and if it is currently idle, then it the right target.
3044 */
3045 if (target == prev_cpu && idle_cpu(prev_cpu))
fe3bcfe1 3046 return prev_cpu;
a50bde51
PZ
3047
3048 /*
37407ea7 3049 * Otherwise, iterate the domains and find an elegible idle cpu.
a50bde51 3050 */
518cd623 3051 sd = rcu_dereference(per_cpu(sd_llc, target));
970e1789 3052 for_each_lower_domain(sd) {
37407ea7
LT
3053 sg = sd->groups;
3054 do {
3055 if (!cpumask_intersects(sched_group_cpus(sg),
3056 tsk_cpus_allowed(p)))
3057 goto next;
3058
3059 for_each_cpu(i, sched_group_cpus(sg)) {
3060 if (!idle_cpu(i))
3061 goto next;
3062 }
970e1789 3063
37407ea7
LT
3064 target = cpumask_first_and(sched_group_cpus(sg),
3065 tsk_cpus_allowed(p));
3066 goto done;
3067next:
3068 sg = sg->next;
3069 } while (sg != sd->groups);
3070 }
3071done:
a50bde51
PZ
3072 return target;
3073}
3074
aaee1203
PZ
3075/*
3076 * sched_balance_self: balance the current task (running on cpu) in domains
3077 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
3078 * SD_BALANCE_EXEC.
3079 *
3080 * Balance, ie. select the least loaded group.
3081 *
3082 * Returns the target CPU number, or the same CPU if no balancing is needed.
3083 *
3084 * preempt must be disabled.
3085 */
0017d735 3086static int
7608dec2 3087select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
aaee1203 3088{
29cd8bae 3089 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
c88d5910
PZ
3090 int cpu = smp_processor_id();
3091 int prev_cpu = task_cpu(p);
3092 int new_cpu = cpu;
99bd5e2f 3093 int want_affine = 0;
5158f4e4 3094 int sync = wake_flags & WF_SYNC;
c88d5910 3095
29baa747 3096 if (p->nr_cpus_allowed == 1)
76854c7e
MG
3097 return prev_cpu;
3098
0763a660 3099 if (sd_flag & SD_BALANCE_WAKE) {
fa17b507 3100 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
c88d5910
PZ
3101 want_affine = 1;
3102 new_cpu = prev_cpu;
3103 }
aaee1203 3104
dce840a0 3105 rcu_read_lock();
aaee1203 3106 for_each_domain(cpu, tmp) {
e4f42888
PZ
3107 if (!(tmp->flags & SD_LOAD_BALANCE))
3108 continue;
3109
fe3bcfe1 3110 /*
99bd5e2f
SS
3111 * If both cpu and prev_cpu are part of this domain,
3112 * cpu is a valid SD_WAKE_AFFINE target.
fe3bcfe1 3113 */
99bd5e2f
SS
3114 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
3115 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
3116 affine_sd = tmp;
29cd8bae 3117 break;
f03542a7 3118 }
29cd8bae 3119
f03542a7 3120 if (tmp->flags & sd_flag)
29cd8bae
PZ
3121 sd = tmp;
3122 }
3123
8b911acd 3124 if (affine_sd) {
f03542a7 3125 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
dce840a0
PZ
3126 prev_cpu = cpu;
3127
3128 new_cpu = select_idle_sibling(p, prev_cpu);
3129 goto unlock;
8b911acd 3130 }
e7693a36 3131
aaee1203 3132 while (sd) {
5158f4e4 3133 int load_idx = sd->forkexec_idx;
aaee1203 3134 struct sched_group *group;
c88d5910 3135 int weight;
098fb9db 3136
0763a660 3137 if (!(sd->flags & sd_flag)) {
aaee1203
PZ
3138 sd = sd->child;
3139 continue;
3140 }
098fb9db 3141
5158f4e4
PZ
3142 if (sd_flag & SD_BALANCE_WAKE)
3143 load_idx = sd->wake_idx;
098fb9db 3144
5158f4e4 3145 group = find_idlest_group(sd, p, cpu, load_idx);
aaee1203
PZ
3146 if (!group) {
3147 sd = sd->child;
3148 continue;
3149 }
4ae7d5ce 3150
d7c33c49 3151 new_cpu = find_idlest_cpu(group, p, cpu);
aaee1203
PZ
3152 if (new_cpu == -1 || new_cpu == cpu) {
3153 /* Now try balancing at a lower domain level of cpu */
3154 sd = sd->child;
3155 continue;
e7693a36 3156 }
aaee1203
PZ
3157
3158 /* Now try balancing at a lower domain level of new_cpu */
3159 cpu = new_cpu;
669c55e9 3160 weight = sd->span_weight;
aaee1203
PZ
3161 sd = NULL;
3162 for_each_domain(cpu, tmp) {
669c55e9 3163 if (weight <= tmp->span_weight)
aaee1203 3164 break;
0763a660 3165 if (tmp->flags & sd_flag)
aaee1203
PZ
3166 sd = tmp;
3167 }
3168 /* while loop will break here if sd == NULL */
e7693a36 3169 }
dce840a0
PZ
3170unlock:
3171 rcu_read_unlock();
e7693a36 3172
c88d5910 3173 return new_cpu;
e7693a36 3174}
0a74bef8
PT
3175
3176/*
3177 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
3178 * cfs_rq_of(p) references at time of call are still valid and identify the
3179 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
3180 * other assumptions, including the state of rq->lock, should be made.
3181 */
3182static void
3183migrate_task_rq_fair(struct task_struct *p, int next_cpu)
3184{
aff3e498
PT
3185 struct sched_entity *se = &p->se;
3186 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3187
3188 /*
3189 * Load tracking: accumulate removed load so that it can be processed
3190 * when we next update owning cfs_rq under rq->lock. Tasks contribute
3191 * to blocked load iff they have a positive decay-count. It can never
3192 * be negative here since on-rq tasks have decay-count == 0.
3193 */
3194 if (se->avg.decay_count) {
3195 se->avg.decay_count = -__synchronize_entity_decay(se);
3196 atomic64_add(se->avg.load_avg_contrib, &cfs_rq->removed_load);
3197 }
0a74bef8 3198}
e7693a36
GH
3199#endif /* CONFIG_SMP */
3200
e52fb7c0
PZ
3201static unsigned long
3202wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
0bbd3336
PZ
3203{
3204 unsigned long gran = sysctl_sched_wakeup_granularity;
3205
3206 /*
e52fb7c0
PZ
3207 * Since its curr running now, convert the gran from real-time
3208 * to virtual-time in his units.
13814d42
MG
3209 *
3210 * By using 'se' instead of 'curr' we penalize light tasks, so
3211 * they get preempted easier. That is, if 'se' < 'curr' then
3212 * the resulting gran will be larger, therefore penalizing the
3213 * lighter, if otoh 'se' > 'curr' then the resulting gran will
3214 * be smaller, again penalizing the lighter task.
3215 *
3216 * This is especially important for buddies when the leftmost
3217 * task is higher priority than the buddy.
0bbd3336 3218 */
f4ad9bd2 3219 return calc_delta_fair(gran, se);
0bbd3336
PZ
3220}
3221
464b7527
PZ
3222/*
3223 * Should 'se' preempt 'curr'.
3224 *
3225 * |s1
3226 * |s2
3227 * |s3
3228 * g
3229 * |<--->|c
3230 *
3231 * w(c, s1) = -1
3232 * w(c, s2) = 0
3233 * w(c, s3) = 1
3234 *
3235 */
3236static int
3237wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
3238{
3239 s64 gran, vdiff = curr->vruntime - se->vruntime;
3240
3241 if (vdiff <= 0)
3242 return -1;
3243
e52fb7c0 3244 gran = wakeup_gran(curr, se);
464b7527
PZ
3245 if (vdiff > gran)
3246 return 1;
3247
3248 return 0;
3249}
3250
02479099
PZ
3251static void set_last_buddy(struct sched_entity *se)
3252{
69c80f3e
VP
3253 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3254 return;
3255
3256 for_each_sched_entity(se)
3257 cfs_rq_of(se)->last = se;
02479099
PZ
3258}
3259
3260static void set_next_buddy(struct sched_entity *se)
3261{
69c80f3e
VP
3262 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3263 return;
3264
3265 for_each_sched_entity(se)
3266 cfs_rq_of(se)->next = se;
02479099
PZ
3267}
3268
ac53db59
RR
3269static void set_skip_buddy(struct sched_entity *se)
3270{
69c80f3e
VP
3271 for_each_sched_entity(se)
3272 cfs_rq_of(se)->skip = se;
ac53db59
RR
3273}
3274
bf0f6f24
IM
3275/*
3276 * Preempt the current task with a newly woken task if needed:
3277 */
5a9b86f6 3278static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
bf0f6f24
IM
3279{
3280 struct task_struct *curr = rq->curr;
8651a86c 3281 struct sched_entity *se = &curr->se, *pse = &p->se;
03e89e45 3282 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
f685ceac 3283 int scale = cfs_rq->nr_running >= sched_nr_latency;
2f36825b 3284 int next_buddy_marked = 0;
bf0f6f24 3285
4ae7d5ce
IM
3286 if (unlikely(se == pse))
3287 return;
3288
5238cdd3 3289 /*
ddcdf6e7 3290 * This is possible from callers such as move_task(), in which we
5238cdd3
PT
3291 * unconditionally check_prempt_curr() after an enqueue (which may have
3292 * lead to a throttle). This both saves work and prevents false
3293 * next-buddy nomination below.
3294 */
3295 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
3296 return;
3297
2f36825b 3298 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3cb63d52 3299 set_next_buddy(pse);
2f36825b
VP
3300 next_buddy_marked = 1;
3301 }
57fdc26d 3302
aec0a514
BR
3303 /*
3304 * We can come here with TIF_NEED_RESCHED already set from new task
3305 * wake up path.
5238cdd3
PT
3306 *
3307 * Note: this also catches the edge-case of curr being in a throttled
3308 * group (e.g. via set_curr_task), since update_curr() (in the
3309 * enqueue of curr) will have resulted in resched being set. This
3310 * prevents us from potentially nominating it as a false LAST_BUDDY
3311 * below.
aec0a514
BR
3312 */
3313 if (test_tsk_need_resched(curr))
3314 return;
3315
a2f5c9ab
DH
3316 /* Idle tasks are by definition preempted by non-idle tasks. */
3317 if (unlikely(curr->policy == SCHED_IDLE) &&
3318 likely(p->policy != SCHED_IDLE))
3319 goto preempt;
3320
91c234b4 3321 /*
a2f5c9ab
DH
3322 * Batch and idle tasks do not preempt non-idle tasks (their preemption
3323 * is driven by the tick):
91c234b4 3324 */
6bc912b7 3325 if (unlikely(p->policy != SCHED_NORMAL))
91c234b4 3326 return;
bf0f6f24 3327
464b7527 3328 find_matching_se(&se, &pse);
9bbd7374 3329 update_curr(cfs_rq_of(se));
002f128b 3330 BUG_ON(!pse);
2f36825b
VP
3331 if (wakeup_preempt_entity(se, pse) == 1) {
3332 /*
3333 * Bias pick_next to pick the sched entity that is
3334 * triggering this preemption.
3335 */
3336 if (!next_buddy_marked)
3337 set_next_buddy(pse);
3a7e73a2 3338 goto preempt;
2f36825b 3339 }
464b7527 3340
3a7e73a2 3341 return;
a65ac745 3342
3a7e73a2
PZ
3343preempt:
3344 resched_task(curr);
3345 /*
3346 * Only set the backward buddy when the current task is still
3347 * on the rq. This can happen when a wakeup gets interleaved
3348 * with schedule on the ->pre_schedule() or idle_balance()
3349 * point, either of which can * drop the rq lock.
3350 *
3351 * Also, during early boot the idle thread is in the fair class,
3352 * for obvious reasons its a bad idea to schedule back to it.
3353 */
3354 if (unlikely(!se->on_rq || curr == rq->idle))
3355 return;
3356
3357 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
3358 set_last_buddy(se);
bf0f6f24
IM
3359}
3360
fb8d4724 3361static struct task_struct *pick_next_task_fair(struct rq *rq)
bf0f6f24 3362{
8f4d37ec 3363 struct task_struct *p;
bf0f6f24
IM
3364 struct cfs_rq *cfs_rq = &rq->cfs;
3365 struct sched_entity *se;
3366
36ace27e 3367 if (!cfs_rq->nr_running)
bf0f6f24
IM
3368 return NULL;
3369
3370 do {
9948f4b2 3371 se = pick_next_entity(cfs_rq);
f4b6755f 3372 set_next_entity(cfs_rq, se);
bf0f6f24
IM
3373 cfs_rq = group_cfs_rq(se);
3374 } while (cfs_rq);
3375
8f4d37ec 3376 p = task_of(se);
b39e66ea
MG
3377 if (hrtick_enabled(rq))
3378 hrtick_start_fair(rq, p);
8f4d37ec
PZ
3379
3380 return p;
bf0f6f24
IM
3381}
3382
3383/*
3384 * Account for a descheduled task:
3385 */
31ee529c 3386static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
bf0f6f24
IM
3387{
3388 struct sched_entity *se = &prev->se;
3389 struct cfs_rq *cfs_rq;
3390
3391 for_each_sched_entity(se) {
3392 cfs_rq = cfs_rq_of(se);
ab6cde26 3393 put_prev_entity(cfs_rq, se);
bf0f6f24
IM
3394 }
3395}
3396
ac53db59
RR
3397/*
3398 * sched_yield() is very simple
3399 *
3400 * The magic of dealing with the ->skip buddy is in pick_next_entity.
3401 */
3402static void yield_task_fair(struct rq *rq)
3403{
3404 struct task_struct *curr = rq->curr;
3405 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3406 struct sched_entity *se = &curr->se;
3407
3408 /*
3409 * Are we the only task in the tree?
3410 */
3411 if (unlikely(rq->nr_running == 1))
3412 return;
3413
3414 clear_buddies(cfs_rq, se);
3415
3416 if (curr->policy != SCHED_BATCH) {
3417 update_rq_clock(rq);
3418 /*
3419 * Update run-time statistics of the 'current'.
3420 */
3421 update_curr(cfs_rq);
916671c0
MG
3422 /*
3423 * Tell update_rq_clock() that we've just updated,
3424 * so we don't do microscopic update in schedule()
3425 * and double the fastpath cost.
3426 */
3427 rq->skip_clock_update = 1;
ac53db59
RR
3428 }
3429
3430 set_skip_buddy(se);
3431}
3432
d95f4122
MG
3433static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
3434{
3435 struct sched_entity *se = &p->se;
3436
5238cdd3
PT
3437 /* throttled hierarchies are not runnable */
3438 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
d95f4122
MG
3439 return false;
3440
3441 /* Tell the scheduler that we'd really like pse to run next. */
3442 set_next_buddy(se);
3443
d95f4122
MG
3444 yield_task_fair(rq);
3445
3446 return true;
3447}
3448
681f3e68 3449#ifdef CONFIG_SMP
bf0f6f24
IM
3450/**************************************************
3451 * Fair scheduling class load-balancing methods:
3452 */
3453
ed387b78
HS
3454static unsigned long __read_mostly max_load_balance_interval = HZ/10;
3455
ddcdf6e7 3456#define LBF_ALL_PINNED 0x01
367456c7 3457#define LBF_NEED_BREAK 0x02
88b8dac0 3458#define LBF_SOME_PINNED 0x04
ddcdf6e7
PZ
3459
3460struct lb_env {
3461 struct sched_domain *sd;
3462
ddcdf6e7 3463 struct rq *src_rq;
85c1e7da 3464 int src_cpu;
ddcdf6e7
PZ
3465
3466 int dst_cpu;
3467 struct rq *dst_rq;
3468
88b8dac0
SV
3469 struct cpumask *dst_grpmask;
3470 int new_dst_cpu;
ddcdf6e7 3471 enum cpu_idle_type idle;
bd939f45 3472 long imbalance;
b9403130
MW
3473 /* The set of CPUs under consideration for load-balancing */
3474 struct cpumask *cpus;
3475
ddcdf6e7 3476 unsigned int flags;
367456c7
PZ
3477
3478 unsigned int loop;
3479 unsigned int loop_break;
3480 unsigned int loop_max;
ddcdf6e7
PZ
3481};
3482
1e3c88bd 3483/*
ddcdf6e7 3484 * move_task - move a task from one runqueue to another runqueue.
1e3c88bd
PZ
3485 * Both runqueues must be locked.
3486 */
ddcdf6e7 3487static void move_task(struct task_struct *p, struct lb_env *env)
1e3c88bd 3488{
ddcdf6e7
PZ
3489 deactivate_task(env->src_rq, p, 0);
3490 set_task_cpu(p, env->dst_cpu);
3491 activate_task(env->dst_rq, p, 0);
3492 check_preempt_curr(env->dst_rq, p, 0);
1e3c88bd
PZ
3493}
3494
029632fb
PZ
3495/*
3496 * Is this task likely cache-hot:
3497 */
3498static int
3499task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
3500{
3501 s64 delta;
3502
3503 if (p->sched_class != &fair_sched_class)
3504 return 0;
3505
3506 if (unlikely(p->policy == SCHED_IDLE))
3507 return 0;
3508
3509 /*
3510 * Buddy candidates are cache hot:
3511 */
3512 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
3513 (&p->se == cfs_rq_of(&p->se)->next ||
3514 &p->se == cfs_rq_of(&p->se)->last))
3515 return 1;
3516
3517 if (sysctl_sched_migration_cost == -1)
3518 return 1;
3519 if (sysctl_sched_migration_cost == 0)
3520 return 0;
3521
3522 delta = now - p->se.exec_start;
3523
3524 return delta < (s64)sysctl_sched_migration_cost;
3525}
3526
1e3c88bd
PZ
3527/*
3528 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3529 */
3530static
8e45cb54 3531int can_migrate_task(struct task_struct *p, struct lb_env *env)
1e3c88bd
PZ
3532{
3533 int tsk_cache_hot = 0;
3534 /*
3535 * We do not migrate tasks that are:
3536 * 1) running (obviously), or
3537 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3538 * 3) are cache-hot on their current CPU.
3539 */
ddcdf6e7 3540 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
88b8dac0
SV
3541 int new_dst_cpu;
3542
41acab88 3543 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
88b8dac0
SV
3544
3545 /*
3546 * Remember if this task can be migrated to any other cpu in
3547 * our sched_group. We may want to revisit it if we couldn't
3548 * meet load balance goals by pulling other tasks on src_cpu.
3549 *
3550 * Also avoid computing new_dst_cpu if we have already computed
3551 * one in current iteration.
3552 */
3553 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
3554 return 0;
3555
3556 new_dst_cpu = cpumask_first_and(env->dst_grpmask,
3557 tsk_cpus_allowed(p));
3558 if (new_dst_cpu < nr_cpu_ids) {
3559 env->flags |= LBF_SOME_PINNED;
3560 env->new_dst_cpu = new_dst_cpu;
3561 }
1e3c88bd
PZ
3562 return 0;
3563 }
88b8dac0
SV
3564
3565 /* Record that we found atleast one task that could run on dst_cpu */
8e45cb54 3566 env->flags &= ~LBF_ALL_PINNED;
1e3c88bd 3567
ddcdf6e7 3568 if (task_running(env->src_rq, p)) {
41acab88 3569 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
1e3c88bd
PZ
3570 return 0;
3571 }
3572
3573 /*
3574 * Aggressive migration if:
3575 * 1) task is cache cold, or
3576 * 2) too many balance attempts have failed.
3577 */
3578
ddcdf6e7 3579 tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
1e3c88bd 3580 if (!tsk_cache_hot ||
8e45cb54 3581 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
1e3c88bd
PZ
3582#ifdef CONFIG_SCHEDSTATS
3583 if (tsk_cache_hot) {
8e45cb54 3584 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
41acab88 3585 schedstat_inc(p, se.statistics.nr_forced_migrations);
1e3c88bd
PZ
3586 }
3587#endif
3588 return 1;
3589 }
3590
3591 if (tsk_cache_hot) {
41acab88 3592 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
1e3c88bd
PZ
3593 return 0;
3594 }
3595 return 1;
3596}
3597
897c395f
PZ
3598/*
3599 * move_one_task tries to move exactly one task from busiest to this_rq, as
3600 * part of active balancing operations within "domain".
3601 * Returns 1 if successful and 0 otherwise.
3602 *
3603 * Called with both runqueues locked.
3604 */
8e45cb54 3605static int move_one_task(struct lb_env *env)
897c395f
PZ
3606{
3607 struct task_struct *p, *n;
897c395f 3608
367456c7
PZ
3609 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
3610 if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
3611 continue;
897c395f 3612
367456c7
PZ
3613 if (!can_migrate_task(p, env))
3614 continue;
897c395f 3615
367456c7
PZ
3616 move_task(p, env);
3617 /*
3618 * Right now, this is only the second place move_task()
3619 * is called, so we can safely collect move_task()
3620 * stats here rather than inside move_task().
3621 */
3622 schedstat_inc(env->sd, lb_gained[env->idle]);
3623 return 1;
897c395f 3624 }
897c395f
PZ
3625 return 0;
3626}
3627
367456c7
PZ
3628static unsigned long task_h_load(struct task_struct *p);
3629
eb95308e
PZ
3630static const unsigned int sched_nr_migrate_break = 32;
3631
5d6523eb 3632/*
bd939f45 3633 * move_tasks tries to move up to imbalance weighted load from busiest to
5d6523eb
PZ
3634 * this_rq, as part of a balancing operation within domain "sd".
3635 * Returns 1 if successful and 0 otherwise.
3636 *
3637 * Called with both runqueues locked.
3638 */
3639static int move_tasks(struct lb_env *env)
1e3c88bd 3640{
5d6523eb
PZ
3641 struct list_head *tasks = &env->src_rq->cfs_tasks;
3642 struct task_struct *p;
367456c7
PZ
3643 unsigned long load;
3644 int pulled = 0;
1e3c88bd 3645
bd939f45 3646 if (env->imbalance <= 0)
5d6523eb 3647 return 0;
1e3c88bd 3648
5d6523eb
PZ
3649 while (!list_empty(tasks)) {
3650 p = list_first_entry(tasks, struct task_struct, se.group_node);
1e3c88bd 3651
367456c7
PZ
3652 env->loop++;
3653 /* We've more or less seen every task there is, call it quits */
5d6523eb 3654 if (env->loop > env->loop_max)
367456c7 3655 break;
5d6523eb
PZ
3656
3657 /* take a breather every nr_migrate tasks */
367456c7 3658 if (env->loop > env->loop_break) {
eb95308e 3659 env->loop_break += sched_nr_migrate_break;
8e45cb54 3660 env->flags |= LBF_NEED_BREAK;
ee00e66f 3661 break;
a195f004 3662 }
1e3c88bd 3663
5d6523eb 3664 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
367456c7
PZ
3665 goto next;
3666
3667 load = task_h_load(p);
5d6523eb 3668
eb95308e 3669 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
367456c7
PZ
3670 goto next;
3671
bd939f45 3672 if ((load / 2) > env->imbalance)
367456c7 3673 goto next;
1e3c88bd 3674
367456c7
PZ
3675 if (!can_migrate_task(p, env))
3676 goto next;
1e3c88bd 3677
ddcdf6e7 3678 move_task(p, env);
ee00e66f 3679 pulled++;
bd939f45 3680 env->imbalance -= load;
1e3c88bd
PZ
3681
3682#ifdef CONFIG_PREEMPT
ee00e66f
PZ
3683 /*
3684 * NEWIDLE balancing is a source of latency, so preemptible
3685 * kernels will stop after the first task is pulled to minimize
3686 * the critical section.
3687 */
5d6523eb 3688 if (env->idle == CPU_NEWLY_IDLE)
ee00e66f 3689 break;
1e3c88bd
PZ
3690#endif
3691
ee00e66f
PZ
3692 /*
3693 * We only want to steal up to the prescribed amount of
3694 * weighted load.
3695 */
bd939f45 3696 if (env->imbalance <= 0)
ee00e66f 3697 break;
367456c7
PZ
3698
3699 continue;
3700next:
5d6523eb 3701 list_move_tail(&p->se.group_node, tasks);
1e3c88bd 3702 }
5d6523eb 3703
1e3c88bd 3704 /*
ddcdf6e7
PZ
3705 * Right now, this is one of only two places move_task() is called,
3706 * so we can safely collect move_task() stats here rather than
3707 * inside move_task().
1e3c88bd 3708 */
8e45cb54 3709 schedstat_add(env->sd, lb_gained[env->idle], pulled);
1e3c88bd 3710
5d6523eb 3711 return pulled;
1e3c88bd
PZ
3712}
3713
230059de 3714#ifdef CONFIG_FAIR_GROUP_SCHED
9e3081ca
PZ
3715/*
3716 * update tg->load_weight by folding this cpu's load_avg
3717 */
48a16753 3718static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
9e3081ca 3719{
48a16753
PT
3720 struct sched_entity *se = tg->se[cpu];
3721 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
9e3081ca 3722
48a16753
PT
3723 /* throttled entities do not contribute to load */
3724 if (throttled_hierarchy(cfs_rq))
3725 return;
9e3081ca 3726
aff3e498 3727 update_cfs_rq_blocked_load(cfs_rq, 1);
9e3081ca 3728
82958366
PT
3729 if (se) {
3730 update_entity_load_avg(se, 1);
3731 /*
3732 * We pivot on our runnable average having decayed to zero for
3733 * list removal. This generally implies that all our children
3734 * have also been removed (modulo rounding error or bandwidth
3735 * control); however, such cases are rare and we can fix these
3736 * at enqueue.
3737 *
3738 * TODO: fix up out-of-order children on enqueue.
3739 */
3740 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
3741 list_del_leaf_cfs_rq(cfs_rq);
3742 } else {
48a16753 3743 struct rq *rq = rq_of(cfs_rq);
82958366
PT
3744 update_rq_runnable_avg(rq, rq->nr_running);
3745 }
9e3081ca
PZ
3746}
3747
48a16753 3748static void update_blocked_averages(int cpu)
9e3081ca 3749{
9e3081ca 3750 struct rq *rq = cpu_rq(cpu);
48a16753
PT
3751 struct cfs_rq *cfs_rq;
3752 unsigned long flags;
9e3081ca 3753
48a16753
PT
3754 raw_spin_lock_irqsave(&rq->lock, flags);
3755 update_rq_clock(rq);
9763b67f
PZ
3756 /*
3757 * Iterates the task_group tree in a bottom up fashion, see
3758 * list_add_leaf_cfs_rq() for details.
3759 */
64660c86 3760 for_each_leaf_cfs_rq(rq, cfs_rq) {
48a16753
PT
3761 /*
3762 * Note: We may want to consider periodically releasing
3763 * rq->lock about these updates so that creating many task
3764 * groups does not result in continually extending hold time.
3765 */
3766 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
64660c86 3767 }
48a16753
PT
3768
3769 raw_spin_unlock_irqrestore(&rq->lock, flags);
9e3081ca
PZ
3770}
3771
9763b67f
PZ
3772/*
3773 * Compute the cpu's hierarchical load factor for each task group.
3774 * This needs to be done in a top-down fashion because the load of a child
3775 * group is a fraction of its parents load.
3776 */
3777static int tg_load_down(struct task_group *tg, void *data)
3778{
3779 unsigned long load;
3780 long cpu = (long)data;
3781
3782 if (!tg->parent) {
3783 load = cpu_rq(cpu)->load.weight;
3784 } else {
3785 load = tg->parent->cfs_rq[cpu]->h_load;
3786 load *= tg->se[cpu]->load.weight;
3787 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
3788 }
3789
3790 tg->cfs_rq[cpu]->h_load = load;
3791
3792 return 0;
3793}
3794
3795static void update_h_load(long cpu)
3796{
a35b6466
PZ
3797 struct rq *rq = cpu_rq(cpu);
3798 unsigned long now = jiffies;
3799
3800 if (rq->h_load_throttle == now)
3801 return;
3802
3803 rq->h_load_throttle = now;
3804
367456c7 3805 rcu_read_lock();
9763b67f 3806 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
367456c7 3807 rcu_read_unlock();
9763b67f
PZ
3808}
3809
367456c7 3810static unsigned long task_h_load(struct task_struct *p)
230059de 3811{
367456c7
PZ
3812 struct cfs_rq *cfs_rq = task_cfs_rq(p);
3813 unsigned long load;
230059de 3814
367456c7
PZ
3815 load = p->se.load.weight;
3816 load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
230059de 3817
367456c7 3818 return load;
230059de
PZ
3819}
3820#else
48a16753 3821static inline void update_blocked_averages(int cpu)
9e3081ca
PZ
3822{
3823}
3824
367456c7 3825static inline void update_h_load(long cpu)
230059de 3826{
230059de 3827}
230059de 3828
367456c7 3829static unsigned long task_h_load(struct task_struct *p)
1e3c88bd 3830{
367456c7 3831 return p->se.load.weight;
1e3c88bd 3832}
230059de 3833#endif
1e3c88bd 3834
1e3c88bd
PZ
3835/********** Helpers for find_busiest_group ************************/
3836/*
3837 * sd_lb_stats - Structure to store the statistics of a sched_domain
3838 * during load balancing.
3839 */
3840struct sd_lb_stats {
3841 struct sched_group *busiest; /* Busiest group in this sd */
3842 struct sched_group *this; /* Local group in this sd */
3843 unsigned long total_load; /* Total load of all groups in sd */
3844 unsigned long total_pwr; /* Total power of all groups in sd */
3845 unsigned long avg_load; /* Average load across all groups in sd */
3846
3847 /** Statistics of this group */
3848 unsigned long this_load;
3849 unsigned long this_load_per_task;
3850 unsigned long this_nr_running;
fab47622 3851 unsigned long this_has_capacity;
aae6d3dd 3852 unsigned int this_idle_cpus;
1e3c88bd
PZ
3853
3854 /* Statistics of the busiest group */
aae6d3dd 3855 unsigned int busiest_idle_cpus;
1e3c88bd
PZ
3856 unsigned long max_load;
3857 unsigned long busiest_load_per_task;
3858 unsigned long busiest_nr_running;
dd5feea1 3859 unsigned long busiest_group_capacity;
fab47622 3860 unsigned long busiest_has_capacity;
aae6d3dd 3861 unsigned int busiest_group_weight;
1e3c88bd
PZ
3862
3863 int group_imb; /* Is there imbalance in this sd */
1e3c88bd
PZ
3864};
3865
3866/*
3867 * sg_lb_stats - stats of a sched_group required for load_balancing
3868 */
3869struct sg_lb_stats {
3870 unsigned long avg_load; /*Avg load across the CPUs of the group */
3871 unsigned long group_load; /* Total load over the CPUs of the group */
3872 unsigned long sum_nr_running; /* Nr tasks running in the group */
3873 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3874 unsigned long group_capacity;
aae6d3dd
SS
3875 unsigned long idle_cpus;
3876 unsigned long group_weight;
1e3c88bd 3877 int group_imb; /* Is there an imbalance in the group ? */
fab47622 3878 int group_has_capacity; /* Is there extra capacity in the group? */
1e3c88bd
PZ
3879};
3880
1e3c88bd
PZ
3881/**
3882 * get_sd_load_idx - Obtain the load index for a given sched domain.
3883 * @sd: The sched_domain whose load_idx is to be obtained.
3884 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3885 */
3886static inline int get_sd_load_idx(struct sched_domain *sd,
3887 enum cpu_idle_type idle)
3888{
3889 int load_idx;
3890
3891 switch (idle) {
3892 case CPU_NOT_IDLE:
3893 load_idx = sd->busy_idx;
3894 break;
3895
3896 case CPU_NEWLY_IDLE:
3897 load_idx = sd->newidle_idx;
3898 break;
3899 default:
3900 load_idx = sd->idle_idx;
3901 break;
3902 }
3903
3904 return load_idx;
3905}
3906
1e3c88bd
PZ
3907unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3908{
1399fa78 3909 return SCHED_POWER_SCALE;
1e3c88bd
PZ
3910}
3911
3912unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3913{
3914 return default_scale_freq_power(sd, cpu);
3915}
3916
3917unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3918{
669c55e9 3919 unsigned long weight = sd->span_weight;
1e3c88bd
PZ
3920 unsigned long smt_gain = sd->smt_gain;
3921
3922 smt_gain /= weight;
3923
3924 return smt_gain;
3925}
3926
3927unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3928{
3929 return default_scale_smt_power(sd, cpu);
3930}
3931
3932unsigned long scale_rt_power(int cpu)
3933{
3934 struct rq *rq = cpu_rq(cpu);
b654f7de 3935 u64 total, available, age_stamp, avg;
1e3c88bd 3936
b654f7de
PZ
3937 /*
3938 * Since we're reading these variables without serialization make sure
3939 * we read them once before doing sanity checks on them.
3940 */
3941 age_stamp = ACCESS_ONCE(rq->age_stamp);
3942 avg = ACCESS_ONCE(rq->rt_avg);
3943
3944 total = sched_avg_period() + (rq->clock - age_stamp);
aa483808 3945
b654f7de 3946 if (unlikely(total < avg)) {
aa483808
VP
3947 /* Ensures that power won't end up being negative */
3948 available = 0;
3949 } else {
b654f7de 3950 available = total - avg;
aa483808 3951 }
1e3c88bd 3952
1399fa78
NR
3953 if (unlikely((s64)total < SCHED_POWER_SCALE))
3954 total = SCHED_POWER_SCALE;
1e3c88bd 3955
1399fa78 3956 total >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
3957
3958 return div_u64(available, total);
3959}
3960
3961static void update_cpu_power(struct sched_domain *sd, int cpu)
3962{
669c55e9 3963 unsigned long weight = sd->span_weight;
1399fa78 3964 unsigned long power = SCHED_POWER_SCALE;
1e3c88bd
PZ
3965 struct sched_group *sdg = sd->groups;
3966
1e3c88bd
PZ
3967 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
3968 if (sched_feat(ARCH_POWER))
3969 power *= arch_scale_smt_power(sd, cpu);
3970 else
3971 power *= default_scale_smt_power(sd, cpu);
3972
1399fa78 3973 power >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
3974 }
3975
9c3f75cb 3976 sdg->sgp->power_orig = power;
9d5efe05
SV
3977
3978 if (sched_feat(ARCH_POWER))
3979 power *= arch_scale_freq_power(sd, cpu);
3980 else
3981 power *= default_scale_freq_power(sd, cpu);
3982
1399fa78 3983 power >>= SCHED_POWER_SHIFT;
9d5efe05 3984
1e3c88bd 3985 power *= scale_rt_power(cpu);
1399fa78 3986 power >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
3987
3988 if (!power)
3989 power = 1;
3990
e51fd5e2 3991 cpu_rq(cpu)->cpu_power = power;
9c3f75cb 3992 sdg->sgp->power = power;
1e3c88bd
PZ
3993}
3994
029632fb 3995void update_group_power(struct sched_domain *sd, int cpu)
1e3c88bd
PZ
3996{
3997 struct sched_domain *child = sd->child;
3998 struct sched_group *group, *sdg = sd->groups;
3999 unsigned long power;
4ec4412e
VG
4000 unsigned long interval;
4001
4002 interval = msecs_to_jiffies(sd->balance_interval);
4003 interval = clamp(interval, 1UL, max_load_balance_interval);
4004 sdg->sgp->next_update = jiffies + interval;
1e3c88bd
PZ
4005
4006 if (!child) {
4007 update_cpu_power(sd, cpu);
4008 return;
4009 }
4010
4011 power = 0;
4012
74a5ce20
PZ
4013 if (child->flags & SD_OVERLAP) {
4014 /*
4015 * SD_OVERLAP domains cannot assume that child groups
4016 * span the current group.
4017 */
4018
4019 for_each_cpu(cpu, sched_group_cpus(sdg))
4020 power += power_of(cpu);
4021 } else {
4022 /*
4023 * !SD_OVERLAP domains can assume that child groups
4024 * span the current group.
4025 */
4026
4027 group = child->groups;
4028 do {
4029 power += group->sgp->power;
4030 group = group->next;
4031 } while (group != child->groups);
4032 }
1e3c88bd 4033
c3decf0d 4034 sdg->sgp->power_orig = sdg->sgp->power = power;
1e3c88bd
PZ
4035}
4036
9d5efe05
SV
4037/*
4038 * Try and fix up capacity for tiny siblings, this is needed when
4039 * things like SD_ASYM_PACKING need f_b_g to select another sibling
4040 * which on its own isn't powerful enough.
4041 *
4042 * See update_sd_pick_busiest() and check_asym_packing().
4043 */
4044static inline int
4045fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
4046{
4047 /*
1399fa78 4048 * Only siblings can have significantly less than SCHED_POWER_SCALE
9d5efe05 4049 */
a6c75f2f 4050 if (!(sd->flags & SD_SHARE_CPUPOWER))
9d5efe05
SV
4051 return 0;
4052
4053 /*
4054 * If ~90% of the cpu_power is still there, we're good.
4055 */
9c3f75cb 4056 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
9d5efe05
SV
4057 return 1;
4058
4059 return 0;
4060}
4061
1e3c88bd
PZ
4062/**
4063 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
cd96891d 4064 * @env: The load balancing environment.
1e3c88bd 4065 * @group: sched_group whose statistics are to be updated.
1e3c88bd 4066 * @load_idx: Load index of sched_domain of this_cpu for load calc.
1e3c88bd 4067 * @local_group: Does group contain this_cpu.
1e3c88bd
PZ
4068 * @balance: Should we balance.
4069 * @sgs: variable to hold the statistics for this group.
4070 */
bd939f45
PZ
4071static inline void update_sg_lb_stats(struct lb_env *env,
4072 struct sched_group *group, int load_idx,
b9403130 4073 int local_group, int *balance, struct sg_lb_stats *sgs)
1e3c88bd 4074{
e44bc5c5
PZ
4075 unsigned long nr_running, max_nr_running, min_nr_running;
4076 unsigned long load, max_cpu_load, min_cpu_load;
04f733b4 4077 unsigned int balance_cpu = -1, first_idle_cpu = 0;
dd5feea1 4078 unsigned long avg_load_per_task = 0;
bd939f45 4079 int i;
1e3c88bd 4080
871e35bc 4081 if (local_group)
c1174876 4082 balance_cpu = group_balance_cpu(group);
1e3c88bd
PZ
4083
4084 /* Tally up the load of all CPUs in the group */
1e3c88bd
PZ
4085 max_cpu_load = 0;
4086 min_cpu_load = ~0UL;
2582f0eb 4087 max_nr_running = 0;
e44bc5c5 4088 min_nr_running = ~0UL;
1e3c88bd 4089
b9403130 4090 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
1e3c88bd
PZ
4091 struct rq *rq = cpu_rq(i);
4092
e44bc5c5
PZ
4093 nr_running = rq->nr_running;
4094
1e3c88bd
PZ
4095 /* Bias balancing toward cpus of our domain */
4096 if (local_group) {
c1174876
PZ
4097 if (idle_cpu(i) && !first_idle_cpu &&
4098 cpumask_test_cpu(i, sched_group_mask(group))) {
04f733b4 4099 first_idle_cpu = 1;
1e3c88bd
PZ
4100 balance_cpu = i;
4101 }
04f733b4
PZ
4102
4103 load = target_load(i, load_idx);
1e3c88bd
PZ
4104 } else {
4105 load = source_load(i, load_idx);
e44bc5c5 4106 if (load > max_cpu_load)
1e3c88bd
PZ
4107 max_cpu_load = load;
4108 if (min_cpu_load > load)
4109 min_cpu_load = load;
e44bc5c5
PZ
4110
4111 if (nr_running > max_nr_running)
4112 max_nr_running = nr_running;
4113 if (min_nr_running > nr_running)
4114 min_nr_running = nr_running;
1e3c88bd
PZ
4115 }
4116
4117 sgs->group_load += load;
e44bc5c5 4118 sgs->sum_nr_running += nr_running;
1e3c88bd 4119 sgs->sum_weighted_load += weighted_cpuload(i);
aae6d3dd
SS
4120 if (idle_cpu(i))
4121 sgs->idle_cpus++;
1e3c88bd
PZ
4122 }
4123
4124 /*
4125 * First idle cpu or the first cpu(busiest) in this sched group
4126 * is eligible for doing load balancing at this and above
4127 * domains. In the newly idle case, we will allow all the cpu's
4128 * to do the newly idle load balance.
4129 */
4ec4412e 4130 if (local_group) {
bd939f45 4131 if (env->idle != CPU_NEWLY_IDLE) {
04f733b4 4132 if (balance_cpu != env->dst_cpu) {
4ec4412e
VG
4133 *balance = 0;
4134 return;
4135 }
bd939f45 4136 update_group_power(env->sd, env->dst_cpu);
4ec4412e 4137 } else if (time_after_eq(jiffies, group->sgp->next_update))
bd939f45 4138 update_group_power(env->sd, env->dst_cpu);
1e3c88bd
PZ
4139 }
4140
4141 /* Adjust by relative CPU power of the group */
9c3f75cb 4142 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
1e3c88bd 4143
1e3c88bd
PZ
4144 /*
4145 * Consider the group unbalanced when the imbalance is larger
866ab43e 4146 * than the average weight of a task.
1e3c88bd
PZ
4147 *
4148 * APZ: with cgroup the avg task weight can vary wildly and
4149 * might not be a suitable number - should we keep a
4150 * normalized nr_running number somewhere that negates
4151 * the hierarchy?
4152 */
dd5feea1
SS
4153 if (sgs->sum_nr_running)
4154 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
1e3c88bd 4155
e44bc5c5
PZ
4156 if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
4157 (max_nr_running - min_nr_running) > 1)
1e3c88bd
PZ
4158 sgs->group_imb = 1;
4159
9c3f75cb 4160 sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
1399fa78 4161 SCHED_POWER_SCALE);
9d5efe05 4162 if (!sgs->group_capacity)
bd939f45 4163 sgs->group_capacity = fix_small_capacity(env->sd, group);
aae6d3dd 4164 sgs->group_weight = group->group_weight;
fab47622
NR
4165
4166 if (sgs->group_capacity > sgs->sum_nr_running)
4167 sgs->group_has_capacity = 1;
1e3c88bd
PZ
4168}
4169
532cb4c4
MN
4170/**
4171 * update_sd_pick_busiest - return 1 on busiest group
cd96891d 4172 * @env: The load balancing environment.
532cb4c4
MN
4173 * @sds: sched_domain statistics
4174 * @sg: sched_group candidate to be checked for being the busiest
b6b12294 4175 * @sgs: sched_group statistics
532cb4c4
MN
4176 *
4177 * Determine if @sg is a busier group than the previously selected
4178 * busiest group.
4179 */
bd939f45 4180static bool update_sd_pick_busiest(struct lb_env *env,
532cb4c4
MN
4181 struct sd_lb_stats *sds,
4182 struct sched_group *sg,
bd939f45 4183 struct sg_lb_stats *sgs)
532cb4c4
MN
4184{
4185 if (sgs->avg_load <= sds->max_load)
4186 return false;
4187
4188 if (sgs->sum_nr_running > sgs->group_capacity)
4189 return true;
4190
4191 if (sgs->group_imb)
4192 return true;
4193
4194 /*
4195 * ASYM_PACKING needs to move all the work to the lowest
4196 * numbered CPUs in the group, therefore mark all groups
4197 * higher than ourself as busy.
4198 */
bd939f45
PZ
4199 if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
4200 env->dst_cpu < group_first_cpu(sg)) {
532cb4c4
MN
4201 if (!sds->busiest)
4202 return true;
4203
4204 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
4205 return true;
4206 }
4207
4208 return false;
4209}
4210
1e3c88bd 4211/**
461819ac 4212 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
cd96891d 4213 * @env: The load balancing environment.
1e3c88bd
PZ
4214 * @balance: Should we balance.
4215 * @sds: variable to hold the statistics for this sched_domain.
4216 */
bd939f45 4217static inline void update_sd_lb_stats(struct lb_env *env,
b9403130 4218 int *balance, struct sd_lb_stats *sds)
1e3c88bd 4219{
bd939f45
PZ
4220 struct sched_domain *child = env->sd->child;
4221 struct sched_group *sg = env->sd->groups;
1e3c88bd
PZ
4222 struct sg_lb_stats sgs;
4223 int load_idx, prefer_sibling = 0;
4224
4225 if (child && child->flags & SD_PREFER_SIBLING)
4226 prefer_sibling = 1;
4227
bd939f45 4228 load_idx = get_sd_load_idx(env->sd, env->idle);
1e3c88bd
PZ
4229
4230 do {
4231 int local_group;
4232
bd939f45 4233 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
1e3c88bd 4234 memset(&sgs, 0, sizeof(sgs));
b9403130 4235 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
1e3c88bd 4236
8f190fb3 4237 if (local_group && !(*balance))
1e3c88bd
PZ
4238 return;
4239
4240 sds->total_load += sgs.group_load;
9c3f75cb 4241 sds->total_pwr += sg->sgp->power;
1e3c88bd
PZ
4242
4243 /*
4244 * In case the child domain prefers tasks go to siblings
532cb4c4 4245 * first, lower the sg capacity to one so that we'll try
75dd321d
NR
4246 * and move all the excess tasks away. We lower the capacity
4247 * of a group only if the local group has the capacity to fit
4248 * these excess tasks, i.e. nr_running < group_capacity. The
4249 * extra check prevents the case where you always pull from the
4250 * heaviest group when it is already under-utilized (possible
4251 * with a large weight task outweighs the tasks on the system).
1e3c88bd 4252 */
75dd321d 4253 if (prefer_sibling && !local_group && sds->this_has_capacity)
1e3c88bd
PZ
4254 sgs.group_capacity = min(sgs.group_capacity, 1UL);
4255
4256 if (local_group) {
4257 sds->this_load = sgs.avg_load;
532cb4c4 4258 sds->this = sg;
1e3c88bd
PZ
4259 sds->this_nr_running = sgs.sum_nr_running;
4260 sds->this_load_per_task = sgs.sum_weighted_load;
fab47622 4261 sds->this_has_capacity = sgs.group_has_capacity;
aae6d3dd 4262 sds->this_idle_cpus = sgs.idle_cpus;
bd939f45 4263 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
1e3c88bd 4264 sds->max_load = sgs.avg_load;
532cb4c4 4265 sds->busiest = sg;
1e3c88bd 4266 sds->busiest_nr_running = sgs.sum_nr_running;
aae6d3dd 4267 sds->busiest_idle_cpus = sgs.idle_cpus;
dd5feea1 4268 sds->busiest_group_capacity = sgs.group_capacity;
1e3c88bd 4269 sds->busiest_load_per_task = sgs.sum_weighted_load;
fab47622 4270 sds->busiest_has_capacity = sgs.group_has_capacity;
aae6d3dd 4271 sds->busiest_group_weight = sgs.group_weight;
1e3c88bd
PZ
4272 sds->group_imb = sgs.group_imb;
4273 }
4274
532cb4c4 4275 sg = sg->next;
bd939f45 4276 } while (sg != env->sd->groups);
532cb4c4
MN
4277}
4278
532cb4c4
MN
4279/**
4280 * check_asym_packing - Check to see if the group is packed into the
4281 * sched doman.
4282 *
4283 * This is primarily intended to used at the sibling level. Some
4284 * cores like POWER7 prefer to use lower numbered SMT threads. In the
4285 * case of POWER7, it can move to lower SMT modes only when higher
4286 * threads are idle. When in lower SMT modes, the threads will
4287 * perform better since they share less core resources. Hence when we
4288 * have idle threads, we want them to be the higher ones.
4289 *
4290 * This packing function is run on idle threads. It checks to see if
4291 * the busiest CPU in this domain (core in the P7 case) has a higher
4292 * CPU number than the packing function is being run on. Here we are
4293 * assuming lower CPU number will be equivalent to lower a SMT thread
4294 * number.
4295 *
b6b12294
MN
4296 * Returns 1 when packing is required and a task should be moved to
4297 * this CPU. The amount of the imbalance is returned in *imbalance.
4298 *
cd96891d 4299 * @env: The load balancing environment.
532cb4c4 4300 * @sds: Statistics of the sched_domain which is to be packed
532cb4c4 4301 */
bd939f45 4302static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
532cb4c4
MN
4303{
4304 int busiest_cpu;
4305
bd939f45 4306 if (!(env->sd->flags & SD_ASYM_PACKING))
532cb4c4
MN
4307 return 0;
4308
4309 if (!sds->busiest)
4310 return 0;
4311
4312 busiest_cpu = group_first_cpu(sds->busiest);
bd939f45 4313 if (env->dst_cpu > busiest_cpu)
532cb4c4
MN
4314 return 0;
4315
bd939f45
PZ
4316 env->imbalance = DIV_ROUND_CLOSEST(
4317 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
4318
532cb4c4 4319 return 1;
1e3c88bd
PZ
4320}
4321
4322/**
4323 * fix_small_imbalance - Calculate the minor imbalance that exists
4324 * amongst the groups of a sched_domain, during
4325 * load balancing.
cd96891d 4326 * @env: The load balancing environment.
1e3c88bd 4327 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 4328 */
bd939f45
PZ
4329static inline
4330void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd
PZ
4331{
4332 unsigned long tmp, pwr_now = 0, pwr_move = 0;
4333 unsigned int imbn = 2;
dd5feea1 4334 unsigned long scaled_busy_load_per_task;
1e3c88bd
PZ
4335
4336 if (sds->this_nr_running) {
4337 sds->this_load_per_task /= sds->this_nr_running;
4338 if (sds->busiest_load_per_task >
4339 sds->this_load_per_task)
4340 imbn = 1;
bd939f45 4341 } else {
1e3c88bd 4342 sds->this_load_per_task =
bd939f45
PZ
4343 cpu_avg_load_per_task(env->dst_cpu);
4344 }
1e3c88bd 4345
dd5feea1 4346 scaled_busy_load_per_task = sds->busiest_load_per_task
1399fa78 4347 * SCHED_POWER_SCALE;
9c3f75cb 4348 scaled_busy_load_per_task /= sds->busiest->sgp->power;
dd5feea1
SS
4349
4350 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
4351 (scaled_busy_load_per_task * imbn)) {
bd939f45 4352 env->imbalance = sds->busiest_load_per_task;
1e3c88bd
PZ
4353 return;
4354 }
4355
4356 /*
4357 * OK, we don't have enough imbalance to justify moving tasks,
4358 * however we may be able to increase total CPU power used by
4359 * moving them.
4360 */
4361
9c3f75cb 4362 pwr_now += sds->busiest->sgp->power *
1e3c88bd 4363 min(sds->busiest_load_per_task, sds->max_load);
9c3f75cb 4364 pwr_now += sds->this->sgp->power *
1e3c88bd 4365 min(sds->this_load_per_task, sds->this_load);
1399fa78 4366 pwr_now /= SCHED_POWER_SCALE;
1e3c88bd
PZ
4367
4368 /* Amount of load we'd subtract */
1399fa78 4369 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
9c3f75cb 4370 sds->busiest->sgp->power;
1e3c88bd 4371 if (sds->max_load > tmp)
9c3f75cb 4372 pwr_move += sds->busiest->sgp->power *
1e3c88bd
PZ
4373 min(sds->busiest_load_per_task, sds->max_load - tmp);
4374
4375 /* Amount of load we'd add */
9c3f75cb 4376 if (sds->max_load * sds->busiest->sgp->power <
1399fa78 4377 sds->busiest_load_per_task * SCHED_POWER_SCALE)
9c3f75cb
PZ
4378 tmp = (sds->max_load * sds->busiest->sgp->power) /
4379 sds->this->sgp->power;
1e3c88bd 4380 else
1399fa78 4381 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
9c3f75cb
PZ
4382 sds->this->sgp->power;
4383 pwr_move += sds->this->sgp->power *
1e3c88bd 4384 min(sds->this_load_per_task, sds->this_load + tmp);
1399fa78 4385 pwr_move /= SCHED_POWER_SCALE;
1e3c88bd
PZ
4386
4387 /* Move if we gain throughput */
4388 if (pwr_move > pwr_now)
bd939f45 4389 env->imbalance = sds->busiest_load_per_task;
1e3c88bd
PZ
4390}
4391
4392/**
4393 * calculate_imbalance - Calculate the amount of imbalance present within the
4394 * groups of a given sched_domain during load balance.
bd939f45 4395 * @env: load balance environment
1e3c88bd 4396 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 4397 */
bd939f45 4398static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 4399{
dd5feea1
SS
4400 unsigned long max_pull, load_above_capacity = ~0UL;
4401
4402 sds->busiest_load_per_task /= sds->busiest_nr_running;
4403 if (sds->group_imb) {
4404 sds->busiest_load_per_task =
4405 min(sds->busiest_load_per_task, sds->avg_load);
4406 }
4407
1e3c88bd
PZ
4408 /*
4409 * In the presence of smp nice balancing, certain scenarios can have
4410 * max load less than avg load(as we skip the groups at or below
4411 * its cpu_power, while calculating max_load..)
4412 */
4413 if (sds->max_load < sds->avg_load) {
bd939f45
PZ
4414 env->imbalance = 0;
4415 return fix_small_imbalance(env, sds);
1e3c88bd
PZ
4416 }
4417
dd5feea1
SS
4418 if (!sds->group_imb) {
4419 /*
4420 * Don't want to pull so many tasks that a group would go idle.
4421 */
4422 load_above_capacity = (sds->busiest_nr_running -
4423 sds->busiest_group_capacity);
4424
1399fa78 4425 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
dd5feea1 4426
9c3f75cb 4427 load_above_capacity /= sds->busiest->sgp->power;
dd5feea1
SS
4428 }
4429
4430 /*
4431 * We're trying to get all the cpus to the average_load, so we don't
4432 * want to push ourselves above the average load, nor do we wish to
4433 * reduce the max loaded cpu below the average load. At the same time,
4434 * we also don't want to reduce the group load below the group capacity
4435 * (so that we can implement power-savings policies etc). Thus we look
4436 * for the minimum possible imbalance.
4437 * Be careful of negative numbers as they'll appear as very large values
4438 * with unsigned longs.
4439 */
4440 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
1e3c88bd
PZ
4441
4442 /* How much load to actually move to equalise the imbalance */
bd939f45 4443 env->imbalance = min(max_pull * sds->busiest->sgp->power,
9c3f75cb 4444 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
1399fa78 4445 / SCHED_POWER_SCALE;
1e3c88bd
PZ
4446
4447 /*
4448 * if *imbalance is less than the average load per runnable task
25985edc 4449 * there is no guarantee that any tasks will be moved so we'll have
1e3c88bd
PZ
4450 * a think about bumping its value to force at least one task to be
4451 * moved
4452 */
bd939f45
PZ
4453 if (env->imbalance < sds->busiest_load_per_task)
4454 return fix_small_imbalance(env, sds);
1e3c88bd
PZ
4455
4456}
fab47622 4457
1e3c88bd
PZ
4458/******* find_busiest_group() helpers end here *********************/
4459
4460/**
4461 * find_busiest_group - Returns the busiest group within the sched_domain
4462 * if there is an imbalance. If there isn't an imbalance, and
4463 * the user has opted for power-savings, it returns a group whose
4464 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4465 * such a group exists.
4466 *
4467 * Also calculates the amount of weighted load which should be moved
4468 * to restore balance.
4469 *
cd96891d 4470 * @env: The load balancing environment.
1e3c88bd
PZ
4471 * @balance: Pointer to a variable indicating if this_cpu
4472 * is the appropriate cpu to perform load balancing at this_level.
4473 *
4474 * Returns: - the busiest group if imbalance exists.
4475 * - If no imbalance and user has opted for power-savings balance,
4476 * return the least loaded group whose CPUs can be
4477 * put to idle by rebalancing its tasks onto our group.
4478 */
4479static struct sched_group *
b9403130 4480find_busiest_group(struct lb_env *env, int *balance)
1e3c88bd
PZ
4481{
4482 struct sd_lb_stats sds;
4483
4484 memset(&sds, 0, sizeof(sds));
4485
4486 /*
4487 * Compute the various statistics relavent for load balancing at
4488 * this level.
4489 */
b9403130 4490 update_sd_lb_stats(env, balance, &sds);
1e3c88bd 4491
cc57aa8f
PZ
4492 /*
4493 * this_cpu is not the appropriate cpu to perform load balancing at
4494 * this level.
1e3c88bd 4495 */
8f190fb3 4496 if (!(*balance))
1e3c88bd
PZ
4497 goto ret;
4498
bd939f45
PZ
4499 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
4500 check_asym_packing(env, &sds))
532cb4c4
MN
4501 return sds.busiest;
4502
cc57aa8f 4503 /* There is no busy sibling group to pull tasks from */
1e3c88bd
PZ
4504 if (!sds.busiest || sds.busiest_nr_running == 0)
4505 goto out_balanced;
4506
1399fa78 4507 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
b0432d8f 4508
866ab43e
PZ
4509 /*
4510 * If the busiest group is imbalanced the below checks don't
4511 * work because they assumes all things are equal, which typically
4512 * isn't true due to cpus_allowed constraints and the like.
4513 */
4514 if (sds.group_imb)
4515 goto force_balance;
4516
cc57aa8f 4517 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
bd939f45 4518 if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
fab47622
NR
4519 !sds.busiest_has_capacity)
4520 goto force_balance;
4521
cc57aa8f
PZ
4522 /*
4523 * If the local group is more busy than the selected busiest group
4524 * don't try and pull any tasks.
4525 */
1e3c88bd
PZ
4526 if (sds.this_load >= sds.max_load)
4527 goto out_balanced;
4528
cc57aa8f
PZ
4529 /*
4530 * Don't pull any tasks if this group is already above the domain
4531 * average load.
4532 */
1e3c88bd
PZ
4533 if (sds.this_load >= sds.avg_load)
4534 goto out_balanced;
4535
bd939f45 4536 if (env->idle == CPU_IDLE) {
aae6d3dd
SS
4537 /*
4538 * This cpu is idle. If the busiest group load doesn't
4539 * have more tasks than the number of available cpu's and
4540 * there is no imbalance between this and busiest group
4541 * wrt to idle cpu's, it is balanced.
4542 */
c186fafe 4543 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
aae6d3dd
SS
4544 sds.busiest_nr_running <= sds.busiest_group_weight)
4545 goto out_balanced;
c186fafe
PZ
4546 } else {
4547 /*
4548 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
4549 * imbalance_pct to be conservative.
4550 */
bd939f45 4551 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
c186fafe 4552 goto out_balanced;
aae6d3dd 4553 }
1e3c88bd 4554
fab47622 4555force_balance:
1e3c88bd 4556 /* Looks like there is an imbalance. Compute it */
bd939f45 4557 calculate_imbalance(env, &sds);
1e3c88bd
PZ
4558 return sds.busiest;
4559
4560out_balanced:
1e3c88bd 4561ret:
bd939f45 4562 env->imbalance = 0;
1e3c88bd
PZ
4563 return NULL;
4564}
4565
4566/*
4567 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4568 */
bd939f45 4569static struct rq *find_busiest_queue(struct lb_env *env,
b9403130 4570 struct sched_group *group)
1e3c88bd
PZ
4571{
4572 struct rq *busiest = NULL, *rq;
4573 unsigned long max_load = 0;
4574 int i;
4575
4576 for_each_cpu(i, sched_group_cpus(group)) {
4577 unsigned long power = power_of(i);
1399fa78
NR
4578 unsigned long capacity = DIV_ROUND_CLOSEST(power,
4579 SCHED_POWER_SCALE);
1e3c88bd
PZ
4580 unsigned long wl;
4581
9d5efe05 4582 if (!capacity)
bd939f45 4583 capacity = fix_small_capacity(env->sd, group);
9d5efe05 4584
b9403130 4585 if (!cpumask_test_cpu(i, env->cpus))
1e3c88bd
PZ
4586 continue;
4587
4588 rq = cpu_rq(i);
6e40f5bb 4589 wl = weighted_cpuload(i);
1e3c88bd 4590
6e40f5bb
TG
4591 /*
4592 * When comparing with imbalance, use weighted_cpuload()
4593 * which is not scaled with the cpu power.
4594 */
bd939f45 4595 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
1e3c88bd
PZ
4596 continue;
4597
6e40f5bb
TG
4598 /*
4599 * For the load comparisons with the other cpu's, consider
4600 * the weighted_cpuload() scaled with the cpu power, so that
4601 * the load can be moved away from the cpu that is potentially
4602 * running at a lower capacity.
4603 */
1399fa78 4604 wl = (wl * SCHED_POWER_SCALE) / power;
6e40f5bb 4605
1e3c88bd
PZ
4606 if (wl > max_load) {
4607 max_load = wl;
4608 busiest = rq;
4609 }
4610 }
4611
4612 return busiest;
4613}
4614
4615/*
4616 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4617 * so long as it is large enough.
4618 */
4619#define MAX_PINNED_INTERVAL 512
4620
4621/* Working cpumask for load_balance and load_balance_newidle. */
029632fb 4622DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
1e3c88bd 4623
bd939f45 4624static int need_active_balance(struct lb_env *env)
1af3ed3d 4625{
bd939f45
PZ
4626 struct sched_domain *sd = env->sd;
4627
4628 if (env->idle == CPU_NEWLY_IDLE) {
532cb4c4
MN
4629
4630 /*
4631 * ASYM_PACKING needs to force migrate tasks from busy but
4632 * higher numbered CPUs in order to pack all tasks in the
4633 * lowest numbered CPUs.
4634 */
bd939f45 4635 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
532cb4c4 4636 return 1;
1af3ed3d
PZ
4637 }
4638
4639 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
4640}
4641
969c7921
TH
4642static int active_load_balance_cpu_stop(void *data);
4643
1e3c88bd
PZ
4644/*
4645 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4646 * tasks if there is an imbalance.
4647 */
4648static int load_balance(int this_cpu, struct rq *this_rq,
4649 struct sched_domain *sd, enum cpu_idle_type idle,
4650 int *balance)
4651{
88b8dac0
SV
4652 int ld_moved, cur_ld_moved, active_balance = 0;
4653 int lb_iterations, max_lb_iterations;
1e3c88bd 4654 struct sched_group *group;
1e3c88bd
PZ
4655 struct rq *busiest;
4656 unsigned long flags;
4657 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4658
8e45cb54
PZ
4659 struct lb_env env = {
4660 .sd = sd,
ddcdf6e7
PZ
4661 .dst_cpu = this_cpu,
4662 .dst_rq = this_rq,
88b8dac0 4663 .dst_grpmask = sched_group_cpus(sd->groups),
8e45cb54 4664 .idle = idle,
eb95308e 4665 .loop_break = sched_nr_migrate_break,
b9403130 4666 .cpus = cpus,
8e45cb54
PZ
4667 };
4668
1e3c88bd 4669 cpumask_copy(cpus, cpu_active_mask);
88b8dac0 4670 max_lb_iterations = cpumask_weight(env.dst_grpmask);
1e3c88bd 4671
1e3c88bd
PZ
4672 schedstat_inc(sd, lb_count[idle]);
4673
4674redo:
b9403130 4675 group = find_busiest_group(&env, balance);
1e3c88bd
PZ
4676
4677 if (*balance == 0)
4678 goto out_balanced;
4679
4680 if (!group) {
4681 schedstat_inc(sd, lb_nobusyg[idle]);
4682 goto out_balanced;
4683 }
4684
b9403130 4685 busiest = find_busiest_queue(&env, group);
1e3c88bd
PZ
4686 if (!busiest) {
4687 schedstat_inc(sd, lb_nobusyq[idle]);
4688 goto out_balanced;
4689 }
4690
78feefc5 4691 BUG_ON(busiest == env.dst_rq);
1e3c88bd 4692
bd939f45 4693 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
1e3c88bd
PZ
4694
4695 ld_moved = 0;
88b8dac0 4696 lb_iterations = 1;
1e3c88bd
PZ
4697 if (busiest->nr_running > 1) {
4698 /*
4699 * Attempt to move tasks. If find_busiest_group has found
4700 * an imbalance but busiest->nr_running <= 1, the group is
4701 * still unbalanced. ld_moved simply stays zero, so it is
4702 * correctly treated as an imbalance.
4703 */
8e45cb54 4704 env.flags |= LBF_ALL_PINNED;
c82513e5
PZ
4705 env.src_cpu = busiest->cpu;
4706 env.src_rq = busiest;
4707 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
8e45cb54 4708
a35b6466 4709 update_h_load(env.src_cpu);
5d6523eb 4710more_balance:
1e3c88bd 4711 local_irq_save(flags);
78feefc5 4712 double_rq_lock(env.dst_rq, busiest);
88b8dac0
SV
4713
4714 /*
4715 * cur_ld_moved - load moved in current iteration
4716 * ld_moved - cumulative load moved across iterations
4717 */
4718 cur_ld_moved = move_tasks(&env);
4719 ld_moved += cur_ld_moved;
78feefc5 4720 double_rq_unlock(env.dst_rq, busiest);
1e3c88bd
PZ
4721 local_irq_restore(flags);
4722
5d6523eb
PZ
4723 if (env.flags & LBF_NEED_BREAK) {
4724 env.flags &= ~LBF_NEED_BREAK;
4725 goto more_balance;
4726 }
4727
1e3c88bd
PZ
4728 /*
4729 * some other cpu did the load balance for us.
4730 */
88b8dac0
SV
4731 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
4732 resched_cpu(env.dst_cpu);
4733
4734 /*
4735 * Revisit (affine) tasks on src_cpu that couldn't be moved to
4736 * us and move them to an alternate dst_cpu in our sched_group
4737 * where they can run. The upper limit on how many times we
4738 * iterate on same src_cpu is dependent on number of cpus in our
4739 * sched_group.
4740 *
4741 * This changes load balance semantics a bit on who can move
4742 * load to a given_cpu. In addition to the given_cpu itself
4743 * (or a ilb_cpu acting on its behalf where given_cpu is
4744 * nohz-idle), we now have balance_cpu in a position to move
4745 * load to given_cpu. In rare situations, this may cause
4746 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
4747 * _independently_ and at _same_ time to move some load to
4748 * given_cpu) causing exceess load to be moved to given_cpu.
4749 * This however should not happen so much in practice and
4750 * moreover subsequent load balance cycles should correct the
4751 * excess load moved.
4752 */
4753 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0 &&
4754 lb_iterations++ < max_lb_iterations) {
4755
78feefc5 4756 env.dst_rq = cpu_rq(env.new_dst_cpu);
88b8dac0
SV
4757 env.dst_cpu = env.new_dst_cpu;
4758 env.flags &= ~LBF_SOME_PINNED;
4759 env.loop = 0;
4760 env.loop_break = sched_nr_migrate_break;
4761 /*
4762 * Go back to "more_balance" rather than "redo" since we
4763 * need to continue with same src_cpu.
4764 */
4765 goto more_balance;
4766 }
1e3c88bd
PZ
4767
4768 /* All tasks on this runqueue were pinned by CPU affinity */
8e45cb54 4769 if (unlikely(env.flags & LBF_ALL_PINNED)) {
1e3c88bd 4770 cpumask_clear_cpu(cpu_of(busiest), cpus);
bbf18b19
PN
4771 if (!cpumask_empty(cpus)) {
4772 env.loop = 0;
4773 env.loop_break = sched_nr_migrate_break;
1e3c88bd 4774 goto redo;
bbf18b19 4775 }
1e3c88bd
PZ
4776 goto out_balanced;
4777 }
4778 }
4779
4780 if (!ld_moved) {
4781 schedstat_inc(sd, lb_failed[idle]);
58b26c4c
VP
4782 /*
4783 * Increment the failure counter only on periodic balance.
4784 * We do not want newidle balance, which can be very
4785 * frequent, pollute the failure counter causing
4786 * excessive cache_hot migrations and active balances.
4787 */
4788 if (idle != CPU_NEWLY_IDLE)
4789 sd->nr_balance_failed++;
1e3c88bd 4790
bd939f45 4791 if (need_active_balance(&env)) {
1e3c88bd
PZ
4792 raw_spin_lock_irqsave(&busiest->lock, flags);
4793
969c7921
TH
4794 /* don't kick the active_load_balance_cpu_stop,
4795 * if the curr task on busiest cpu can't be
4796 * moved to this_cpu
1e3c88bd
PZ
4797 */
4798 if (!cpumask_test_cpu(this_cpu,
fa17b507 4799 tsk_cpus_allowed(busiest->curr))) {
1e3c88bd
PZ
4800 raw_spin_unlock_irqrestore(&busiest->lock,
4801 flags);
8e45cb54 4802 env.flags |= LBF_ALL_PINNED;
1e3c88bd
PZ
4803 goto out_one_pinned;
4804 }
4805
969c7921
TH
4806 /*
4807 * ->active_balance synchronizes accesses to
4808 * ->active_balance_work. Once set, it's cleared
4809 * only after active load balance is finished.
4810 */
1e3c88bd
PZ
4811 if (!busiest->active_balance) {
4812 busiest->active_balance = 1;
4813 busiest->push_cpu = this_cpu;
4814 active_balance = 1;
4815 }
4816 raw_spin_unlock_irqrestore(&busiest->lock, flags);
969c7921 4817
bd939f45 4818 if (active_balance) {
969c7921
TH
4819 stop_one_cpu_nowait(cpu_of(busiest),
4820 active_load_balance_cpu_stop, busiest,
4821 &busiest->active_balance_work);
bd939f45 4822 }
1e3c88bd
PZ
4823
4824 /*
4825 * We've kicked active balancing, reset the failure
4826 * counter.
4827 */
4828 sd->nr_balance_failed = sd->cache_nice_tries+1;
4829 }
4830 } else
4831 sd->nr_balance_failed = 0;
4832
4833 if (likely(!active_balance)) {
4834 /* We were unbalanced, so reset the balancing interval */
4835 sd->balance_interval = sd->min_interval;
4836 } else {
4837 /*
4838 * If we've begun active balancing, start to back off. This
4839 * case may not be covered by the all_pinned logic if there
4840 * is only 1 task on the busy runqueue (because we don't call
4841 * move_tasks).
4842 */
4843 if (sd->balance_interval < sd->max_interval)
4844 sd->balance_interval *= 2;
4845 }
4846
1e3c88bd
PZ
4847 goto out;
4848
4849out_balanced:
4850 schedstat_inc(sd, lb_balanced[idle]);
4851
4852 sd->nr_balance_failed = 0;
4853
4854out_one_pinned:
4855 /* tune up the balancing interval */
8e45cb54 4856 if (((env.flags & LBF_ALL_PINNED) &&
5b54b56b 4857 sd->balance_interval < MAX_PINNED_INTERVAL) ||
1e3c88bd
PZ
4858 (sd->balance_interval < sd->max_interval))
4859 sd->balance_interval *= 2;
4860
46e49b38 4861 ld_moved = 0;
1e3c88bd 4862out:
1e3c88bd
PZ
4863 return ld_moved;
4864}
4865
1e3c88bd
PZ
4866/*
4867 * idle_balance is called by schedule() if this_cpu is about to become
4868 * idle. Attempts to pull tasks from other CPUs.
4869 */
029632fb 4870void idle_balance(int this_cpu, struct rq *this_rq)
1e3c88bd
PZ
4871{
4872 struct sched_domain *sd;
4873 int pulled_task = 0;
4874 unsigned long next_balance = jiffies + HZ;
4875
4876 this_rq->idle_stamp = this_rq->clock;
4877
4878 if (this_rq->avg_idle < sysctl_sched_migration_cost)
4879 return;
4880
18bf2805
BS
4881 update_rq_runnable_avg(this_rq, 1);
4882
f492e12e
PZ
4883 /*
4884 * Drop the rq->lock, but keep IRQ/preempt disabled.
4885 */
4886 raw_spin_unlock(&this_rq->lock);
4887
48a16753 4888 update_blocked_averages(this_cpu);
dce840a0 4889 rcu_read_lock();
1e3c88bd
PZ
4890 for_each_domain(this_cpu, sd) {
4891 unsigned long interval;
f492e12e 4892 int balance = 1;
1e3c88bd
PZ
4893
4894 if (!(sd->flags & SD_LOAD_BALANCE))
4895 continue;
4896
f492e12e 4897 if (sd->flags & SD_BALANCE_NEWIDLE) {
1e3c88bd 4898 /* If we've pulled tasks over stop searching: */
f492e12e
PZ
4899 pulled_task = load_balance(this_cpu, this_rq,
4900 sd, CPU_NEWLY_IDLE, &balance);
4901 }
1e3c88bd
PZ
4902
4903 interval = msecs_to_jiffies(sd->balance_interval);
4904 if (time_after(next_balance, sd->last_balance + interval))
4905 next_balance = sd->last_balance + interval;
d5ad140b
NR
4906 if (pulled_task) {
4907 this_rq->idle_stamp = 0;
1e3c88bd 4908 break;
d5ad140b 4909 }
1e3c88bd 4910 }
dce840a0 4911 rcu_read_unlock();
f492e12e
PZ
4912
4913 raw_spin_lock(&this_rq->lock);
4914
1e3c88bd
PZ
4915 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4916 /*
4917 * We are going idle. next_balance may be set based on
4918 * a busy processor. So reset next_balance.
4919 */
4920 this_rq->next_balance = next_balance;
4921 }
4922}
4923
4924/*
969c7921
TH
4925 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
4926 * running tasks off the busiest CPU onto idle CPUs. It requires at
4927 * least 1 task to be running on each physical CPU where possible, and
4928 * avoids physical / logical imbalances.
1e3c88bd 4929 */
969c7921 4930static int active_load_balance_cpu_stop(void *data)
1e3c88bd 4931{
969c7921
TH
4932 struct rq *busiest_rq = data;
4933 int busiest_cpu = cpu_of(busiest_rq);
1e3c88bd 4934 int target_cpu = busiest_rq->push_cpu;
969c7921 4935 struct rq *target_rq = cpu_rq(target_cpu);
1e3c88bd 4936 struct sched_domain *sd;
969c7921
TH
4937
4938 raw_spin_lock_irq(&busiest_rq->lock);
4939
4940 /* make sure the requested cpu hasn't gone down in the meantime */
4941 if (unlikely(busiest_cpu != smp_processor_id() ||
4942 !busiest_rq->active_balance))
4943 goto out_unlock;
1e3c88bd
PZ
4944
4945 /* Is there any task to move? */
4946 if (busiest_rq->nr_running <= 1)
969c7921 4947 goto out_unlock;
1e3c88bd
PZ
4948
4949 /*
4950 * This condition is "impossible", if it occurs
4951 * we need to fix it. Originally reported by
4952 * Bjorn Helgaas on a 128-cpu setup.
4953 */
4954 BUG_ON(busiest_rq == target_rq);
4955
4956 /* move a task from busiest_rq to target_rq */
4957 double_lock_balance(busiest_rq, target_rq);
1e3c88bd
PZ
4958
4959 /* Search for an sd spanning us and the target CPU. */
dce840a0 4960 rcu_read_lock();
1e3c88bd
PZ
4961 for_each_domain(target_cpu, sd) {
4962 if ((sd->flags & SD_LOAD_BALANCE) &&
4963 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4964 break;
4965 }
4966
4967 if (likely(sd)) {
8e45cb54
PZ
4968 struct lb_env env = {
4969 .sd = sd,
ddcdf6e7
PZ
4970 .dst_cpu = target_cpu,
4971 .dst_rq = target_rq,
4972 .src_cpu = busiest_rq->cpu,
4973 .src_rq = busiest_rq,
8e45cb54
PZ
4974 .idle = CPU_IDLE,
4975 };
4976
1e3c88bd
PZ
4977 schedstat_inc(sd, alb_count);
4978
8e45cb54 4979 if (move_one_task(&env))
1e3c88bd
PZ
4980 schedstat_inc(sd, alb_pushed);
4981 else
4982 schedstat_inc(sd, alb_failed);
4983 }
dce840a0 4984 rcu_read_unlock();
1e3c88bd 4985 double_unlock_balance(busiest_rq, target_rq);
969c7921
TH
4986out_unlock:
4987 busiest_rq->active_balance = 0;
4988 raw_spin_unlock_irq(&busiest_rq->lock);
4989 return 0;
1e3c88bd
PZ
4990}
4991
4992#ifdef CONFIG_NO_HZ
83cd4fe2
VP
4993/*
4994 * idle load balancing details
83cd4fe2
VP
4995 * - When one of the busy CPUs notice that there may be an idle rebalancing
4996 * needed, they will kick the idle load balancer, which then does idle
4997 * load balancing for all the idle CPUs.
4998 */
1e3c88bd 4999static struct {
83cd4fe2 5000 cpumask_var_t idle_cpus_mask;
0b005cf5 5001 atomic_t nr_cpus;
83cd4fe2
VP
5002 unsigned long next_balance; /* in jiffy units */
5003} nohz ____cacheline_aligned;
1e3c88bd 5004
8e7fbcbc 5005static inline int find_new_ilb(int call_cpu)
1e3c88bd 5006{
0b005cf5 5007 int ilb = cpumask_first(nohz.idle_cpus_mask);
1e3c88bd 5008
786d6dc7
SS
5009 if (ilb < nr_cpu_ids && idle_cpu(ilb))
5010 return ilb;
5011
5012 return nr_cpu_ids;
1e3c88bd 5013}
1e3c88bd 5014
83cd4fe2
VP
5015/*
5016 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
5017 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
5018 * CPU (if there is one).
5019 */
5020static void nohz_balancer_kick(int cpu)
5021{
5022 int ilb_cpu;
5023
5024 nohz.next_balance++;
5025
0b005cf5 5026 ilb_cpu = find_new_ilb(cpu);
83cd4fe2 5027
0b005cf5
SS
5028 if (ilb_cpu >= nr_cpu_ids)
5029 return;
83cd4fe2 5030
cd490c5b 5031 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
1c792db7
SS
5032 return;
5033 /*
5034 * Use smp_send_reschedule() instead of resched_cpu().
5035 * This way we generate a sched IPI on the target cpu which
5036 * is idle. And the softirq performing nohz idle load balance
5037 * will be run before returning from the IPI.
5038 */
5039 smp_send_reschedule(ilb_cpu);
83cd4fe2
VP
5040 return;
5041}
5042
c1cc017c 5043static inline void nohz_balance_exit_idle(int cpu)
71325960
SS
5044{
5045 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
5046 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
5047 atomic_dec(&nohz.nr_cpus);
5048 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5049 }
5050}
5051
69e1e811
SS
5052static inline void set_cpu_sd_state_busy(void)
5053{
5054 struct sched_domain *sd;
5055 int cpu = smp_processor_id();
5056
5057 if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5058 return;
5059 clear_bit(NOHZ_IDLE, nohz_flags(cpu));
5060
5061 rcu_read_lock();
5062 for_each_domain(cpu, sd)
5063 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
5064 rcu_read_unlock();
5065}
5066
5067void set_cpu_sd_state_idle(void)
5068{
5069 struct sched_domain *sd;
5070 int cpu = smp_processor_id();
5071
5072 if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5073 return;
5074 set_bit(NOHZ_IDLE, nohz_flags(cpu));
5075
5076 rcu_read_lock();
5077 for_each_domain(cpu, sd)
5078 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
5079 rcu_read_unlock();
5080}
5081
1e3c88bd 5082/*
c1cc017c 5083 * This routine will record that the cpu is going idle with tick stopped.
0b005cf5 5084 * This info will be used in performing idle load balancing in the future.
1e3c88bd 5085 */
c1cc017c 5086void nohz_balance_enter_idle(int cpu)
1e3c88bd 5087{
71325960
SS
5088 /*
5089 * If this cpu is going down, then nothing needs to be done.
5090 */
5091 if (!cpu_active(cpu))
5092 return;
5093
c1cc017c
AS
5094 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
5095 return;
1e3c88bd 5096
c1cc017c
AS
5097 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
5098 atomic_inc(&nohz.nr_cpus);
5099 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
1e3c88bd 5100}
71325960
SS
5101
5102static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
5103 unsigned long action, void *hcpu)
5104{
5105 switch (action & ~CPU_TASKS_FROZEN) {
5106 case CPU_DYING:
c1cc017c 5107 nohz_balance_exit_idle(smp_processor_id());
71325960
SS
5108 return NOTIFY_OK;
5109 default:
5110 return NOTIFY_DONE;
5111 }
5112}
1e3c88bd
PZ
5113#endif
5114
5115static DEFINE_SPINLOCK(balancing);
5116
49c022e6
PZ
5117/*
5118 * Scale the max load_balance interval with the number of CPUs in the system.
5119 * This trades load-balance latency on larger machines for less cross talk.
5120 */
029632fb 5121void update_max_interval(void)
49c022e6
PZ
5122{
5123 max_load_balance_interval = HZ*num_online_cpus()/10;
5124}
5125
1e3c88bd
PZ
5126/*
5127 * It checks each scheduling domain to see if it is due to be balanced,
5128 * and initiates a balancing operation if so.
5129 *
5130 * Balancing parameters are set up in arch_init_sched_domains.
5131 */
5132static void rebalance_domains(int cpu, enum cpu_idle_type idle)
5133{
5134 int balance = 1;
5135 struct rq *rq = cpu_rq(cpu);
5136 unsigned long interval;
04f733b4 5137 struct sched_domain *sd;
1e3c88bd
PZ
5138 /* Earliest time when we have to do rebalance again */
5139 unsigned long next_balance = jiffies + 60*HZ;
5140 int update_next_balance = 0;
5141 int need_serialize;
5142
48a16753 5143 update_blocked_averages(cpu);
2069dd75 5144
dce840a0 5145 rcu_read_lock();
1e3c88bd
PZ
5146 for_each_domain(cpu, sd) {
5147 if (!(sd->flags & SD_LOAD_BALANCE))
5148 continue;
5149
5150 interval = sd->balance_interval;
5151 if (idle != CPU_IDLE)
5152 interval *= sd->busy_factor;
5153
5154 /* scale ms to jiffies */
5155 interval = msecs_to_jiffies(interval);
49c022e6 5156 interval = clamp(interval, 1UL, max_load_balance_interval);
1e3c88bd
PZ
5157
5158 need_serialize = sd->flags & SD_SERIALIZE;
5159
5160 if (need_serialize) {
5161 if (!spin_trylock(&balancing))
5162 goto out;
5163 }
5164
5165 if (time_after_eq(jiffies, sd->last_balance + interval)) {
5166 if (load_balance(cpu, rq, sd, idle, &balance)) {
5167 /*
5168 * We've pulled tasks over so either we're no
c186fafe 5169 * longer idle.
1e3c88bd
PZ
5170 */
5171 idle = CPU_NOT_IDLE;
5172 }
5173 sd->last_balance = jiffies;
5174 }
5175 if (need_serialize)
5176 spin_unlock(&balancing);
5177out:
5178 if (time_after(next_balance, sd->last_balance + interval)) {
5179 next_balance = sd->last_balance + interval;
5180 update_next_balance = 1;
5181 }
5182
5183 /*
5184 * Stop the load balance at this level. There is another
5185 * CPU in our sched group which is doing load balancing more
5186 * actively.
5187 */
5188 if (!balance)
5189 break;
5190 }
dce840a0 5191 rcu_read_unlock();
1e3c88bd
PZ
5192
5193 /*
5194 * next_balance will be updated only when there is a need.
5195 * When the cpu is attached to null domain for ex, it will not be
5196 * updated.
5197 */
5198 if (likely(update_next_balance))
5199 rq->next_balance = next_balance;
5200}
5201
83cd4fe2 5202#ifdef CONFIG_NO_HZ
1e3c88bd 5203/*
83cd4fe2 5204 * In CONFIG_NO_HZ case, the idle balance kickee will do the
1e3c88bd
PZ
5205 * rebalancing for all the cpus for whom scheduler ticks are stopped.
5206 */
83cd4fe2
VP
5207static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
5208{
5209 struct rq *this_rq = cpu_rq(this_cpu);
5210 struct rq *rq;
5211 int balance_cpu;
5212
1c792db7
SS
5213 if (idle != CPU_IDLE ||
5214 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
5215 goto end;
83cd4fe2
VP
5216
5217 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
8a6d42d1 5218 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
83cd4fe2
VP
5219 continue;
5220
5221 /*
5222 * If this cpu gets work to do, stop the load balancing
5223 * work being done for other cpus. Next load
5224 * balancing owner will pick it up.
5225 */
1c792db7 5226 if (need_resched())
83cd4fe2 5227 break;
83cd4fe2 5228
5ed4f1d9
VG
5229 rq = cpu_rq(balance_cpu);
5230
5231 raw_spin_lock_irq(&rq->lock);
5232 update_rq_clock(rq);
5233 update_idle_cpu_load(rq);
5234 raw_spin_unlock_irq(&rq->lock);
83cd4fe2
VP
5235
5236 rebalance_domains(balance_cpu, CPU_IDLE);
5237
83cd4fe2
VP
5238 if (time_after(this_rq->next_balance, rq->next_balance))
5239 this_rq->next_balance = rq->next_balance;
5240 }
5241 nohz.next_balance = this_rq->next_balance;
1c792db7
SS
5242end:
5243 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
83cd4fe2
VP
5244}
5245
5246/*
0b005cf5
SS
5247 * Current heuristic for kicking the idle load balancer in the presence
5248 * of an idle cpu is the system.
5249 * - This rq has more than one task.
5250 * - At any scheduler domain level, this cpu's scheduler group has multiple
5251 * busy cpu's exceeding the group's power.
5252 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
5253 * domain span are idle.
83cd4fe2
VP
5254 */
5255static inline int nohz_kick_needed(struct rq *rq, int cpu)
5256{
5257 unsigned long now = jiffies;
0b005cf5 5258 struct sched_domain *sd;
83cd4fe2 5259
1c792db7 5260 if (unlikely(idle_cpu(cpu)))
83cd4fe2
VP
5261 return 0;
5262
1c792db7
SS
5263 /*
5264 * We may be recently in ticked or tickless idle mode. At the first
5265 * busy tick after returning from idle, we will update the busy stats.
5266 */
69e1e811 5267 set_cpu_sd_state_busy();
c1cc017c 5268 nohz_balance_exit_idle(cpu);
0b005cf5
SS
5269
5270 /*
5271 * None are in tickless mode and hence no need for NOHZ idle load
5272 * balancing.
5273 */
5274 if (likely(!atomic_read(&nohz.nr_cpus)))
5275 return 0;
1c792db7
SS
5276
5277 if (time_before(now, nohz.next_balance))
83cd4fe2
VP
5278 return 0;
5279
0b005cf5
SS
5280 if (rq->nr_running >= 2)
5281 goto need_kick;
83cd4fe2 5282
067491b7 5283 rcu_read_lock();
0b005cf5
SS
5284 for_each_domain(cpu, sd) {
5285 struct sched_group *sg = sd->groups;
5286 struct sched_group_power *sgp = sg->sgp;
5287 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
83cd4fe2 5288
0b005cf5 5289 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
067491b7 5290 goto need_kick_unlock;
0b005cf5
SS
5291
5292 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
5293 && (cpumask_first_and(nohz.idle_cpus_mask,
5294 sched_domain_span(sd)) < cpu))
067491b7 5295 goto need_kick_unlock;
0b005cf5
SS
5296
5297 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
5298 break;
83cd4fe2 5299 }
067491b7 5300 rcu_read_unlock();
83cd4fe2 5301 return 0;
067491b7
PZ
5302
5303need_kick_unlock:
5304 rcu_read_unlock();
0b005cf5
SS
5305need_kick:
5306 return 1;
83cd4fe2
VP
5307}
5308#else
5309static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
5310#endif
5311
5312/*
5313 * run_rebalance_domains is triggered when needed from the scheduler tick.
5314 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
5315 */
1e3c88bd
PZ
5316static void run_rebalance_domains(struct softirq_action *h)
5317{
5318 int this_cpu = smp_processor_id();
5319 struct rq *this_rq = cpu_rq(this_cpu);
6eb57e0d 5320 enum cpu_idle_type idle = this_rq->idle_balance ?
1e3c88bd
PZ
5321 CPU_IDLE : CPU_NOT_IDLE;
5322
5323 rebalance_domains(this_cpu, idle);
5324
1e3c88bd 5325 /*
83cd4fe2 5326 * If this cpu has a pending nohz_balance_kick, then do the
1e3c88bd
PZ
5327 * balancing on behalf of the other idle cpus whose ticks are
5328 * stopped.
5329 */
83cd4fe2 5330 nohz_idle_balance(this_cpu, idle);
1e3c88bd
PZ
5331}
5332
5333static inline int on_null_domain(int cpu)
5334{
90a6501f 5335 return !rcu_dereference_sched(cpu_rq(cpu)->sd);
1e3c88bd
PZ
5336}
5337
5338/*
5339 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
1e3c88bd 5340 */
029632fb 5341void trigger_load_balance(struct rq *rq, int cpu)
1e3c88bd 5342{
1e3c88bd
PZ
5343 /* Don't need to rebalance while attached to NULL domain */
5344 if (time_after_eq(jiffies, rq->next_balance) &&
5345 likely(!on_null_domain(cpu)))
5346 raise_softirq(SCHED_SOFTIRQ);
83cd4fe2 5347#ifdef CONFIG_NO_HZ
1c792db7 5348 if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
83cd4fe2
VP
5349 nohz_balancer_kick(cpu);
5350#endif
1e3c88bd
PZ
5351}
5352
0bcdcf28
CE
5353static void rq_online_fair(struct rq *rq)
5354{
5355 update_sysctl();
5356}
5357
5358static void rq_offline_fair(struct rq *rq)
5359{
5360 update_sysctl();
a4c96ae3
PB
5361
5362 /* Ensure any throttled groups are reachable by pick_next_task */
5363 unthrottle_offline_cfs_rqs(rq);
0bcdcf28
CE
5364}
5365
55e12e5e 5366#endif /* CONFIG_SMP */
e1d1484f 5367
bf0f6f24
IM
5368/*
5369 * scheduler tick hitting a task of our scheduling class:
5370 */
8f4d37ec 5371static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
bf0f6f24
IM
5372{
5373 struct cfs_rq *cfs_rq;
5374 struct sched_entity *se = &curr->se;
5375
5376 for_each_sched_entity(se) {
5377 cfs_rq = cfs_rq_of(se);
8f4d37ec 5378 entity_tick(cfs_rq, se, queued);
bf0f6f24 5379 }
18bf2805
BS
5380
5381 update_rq_runnable_avg(rq, 1);
bf0f6f24
IM
5382}
5383
5384/*
cd29fe6f
PZ
5385 * called on fork with the child task as argument from the parent's context
5386 * - child not yet on the tasklist
5387 * - preemption disabled
bf0f6f24 5388 */
cd29fe6f 5389static void task_fork_fair(struct task_struct *p)
bf0f6f24 5390{
4fc420c9
DN
5391 struct cfs_rq *cfs_rq;
5392 struct sched_entity *se = &p->se, *curr;
00bf7bfc 5393 int this_cpu = smp_processor_id();
cd29fe6f
PZ
5394 struct rq *rq = this_rq();
5395 unsigned long flags;
5396
05fa785c 5397 raw_spin_lock_irqsave(&rq->lock, flags);
bf0f6f24 5398
861d034e
PZ
5399 update_rq_clock(rq);
5400
4fc420c9
DN
5401 cfs_rq = task_cfs_rq(current);
5402 curr = cfs_rq->curr;
5403
b0a0f667
PM
5404 if (unlikely(task_cpu(p) != this_cpu)) {
5405 rcu_read_lock();
cd29fe6f 5406 __set_task_cpu(p, this_cpu);
b0a0f667
PM
5407 rcu_read_unlock();
5408 }
bf0f6f24 5409
7109c442 5410 update_curr(cfs_rq);
cd29fe6f 5411
b5d9d734
MG
5412 if (curr)
5413 se->vruntime = curr->vruntime;
aeb73b04 5414 place_entity(cfs_rq, se, 1);
4d78e7b6 5415
cd29fe6f 5416 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
87fefa38 5417 /*
edcb60a3
IM
5418 * Upon rescheduling, sched_class::put_prev_task() will place
5419 * 'current' within the tree based on its new key value.
5420 */
4d78e7b6 5421 swap(curr->vruntime, se->vruntime);
aec0a514 5422 resched_task(rq->curr);
4d78e7b6 5423 }
bf0f6f24 5424
88ec22d3
PZ
5425 se->vruntime -= cfs_rq->min_vruntime;
5426
05fa785c 5427 raw_spin_unlock_irqrestore(&rq->lock, flags);
bf0f6f24
IM
5428}
5429
cb469845
SR
5430/*
5431 * Priority of the task has changed. Check to see if we preempt
5432 * the current task.
5433 */
da7a735e
PZ
5434static void
5435prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
cb469845 5436{
da7a735e
PZ
5437 if (!p->se.on_rq)
5438 return;
5439
cb469845
SR
5440 /*
5441 * Reschedule if we are currently running on this runqueue and
5442 * our priority decreased, or if we are not currently running on
5443 * this runqueue and our priority is higher than the current's
5444 */
da7a735e 5445 if (rq->curr == p) {
cb469845
SR
5446 if (p->prio > oldprio)
5447 resched_task(rq->curr);
5448 } else
15afe09b 5449 check_preempt_curr(rq, p, 0);
cb469845
SR
5450}
5451
da7a735e
PZ
5452static void switched_from_fair(struct rq *rq, struct task_struct *p)
5453{
5454 struct sched_entity *se = &p->se;
5455 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5456
5457 /*
5458 * Ensure the task's vruntime is normalized, so that when its
5459 * switched back to the fair class the enqueue_entity(.flags=0) will
5460 * do the right thing.
5461 *
5462 * If it was on_rq, then the dequeue_entity(.flags=0) will already
5463 * have normalized the vruntime, if it was !on_rq, then only when
5464 * the task is sleeping will it still have non-normalized vruntime.
5465 */
5466 if (!se->on_rq && p->state != TASK_RUNNING) {
5467 /*
5468 * Fix up our vruntime so that the current sleep doesn't
5469 * cause 'unlimited' sleep bonus.
5470 */
5471 place_entity(cfs_rq, se, 0);
5472 se->vruntime -= cfs_rq->min_vruntime;
5473 }
9ee474f5
PT
5474
5475#if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
5476 /*
5477 * Remove our load from contribution when we leave sched_fair
5478 * and ensure we don't carry in an old decay_count if we
5479 * switch back.
5480 */
5481 if (p->se.avg.decay_count) {
5482 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
5483 __synchronize_entity_decay(&p->se);
5484 subtract_blocked_load_contrib(cfs_rq,
5485 p->se.avg.load_avg_contrib);
5486 }
5487#endif
da7a735e
PZ
5488}
5489
cb469845
SR
5490/*
5491 * We switched to the sched_fair class.
5492 */
da7a735e 5493static void switched_to_fair(struct rq *rq, struct task_struct *p)
cb469845 5494{
da7a735e
PZ
5495 if (!p->se.on_rq)
5496 return;
5497
cb469845
SR
5498 /*
5499 * We were most likely switched from sched_rt, so
5500 * kick off the schedule if running, otherwise just see
5501 * if we can still preempt the current task.
5502 */
da7a735e 5503 if (rq->curr == p)
cb469845
SR
5504 resched_task(rq->curr);
5505 else
15afe09b 5506 check_preempt_curr(rq, p, 0);
cb469845
SR
5507}
5508
83b699ed
SV
5509/* Account for a task changing its policy or group.
5510 *
5511 * This routine is mostly called to set cfs_rq->curr field when a task
5512 * migrates between groups/classes.
5513 */
5514static void set_curr_task_fair(struct rq *rq)
5515{
5516 struct sched_entity *se = &rq->curr->se;
5517
ec12cb7f
PT
5518 for_each_sched_entity(se) {
5519 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5520
5521 set_next_entity(cfs_rq, se);
5522 /* ensure bandwidth has been allocated on our new cfs_rq */
5523 account_cfs_rq_runtime(cfs_rq, 0);
5524 }
83b699ed
SV
5525}
5526
029632fb
PZ
5527void init_cfs_rq(struct cfs_rq *cfs_rq)
5528{
5529 cfs_rq->tasks_timeline = RB_ROOT;
029632fb
PZ
5530 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
5531#ifndef CONFIG_64BIT
5532 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
5533#endif
9ee474f5
PT
5534#if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
5535 atomic64_set(&cfs_rq->decay_counter, 1);
aff3e498 5536 atomic64_set(&cfs_rq->removed_load, 0);
9ee474f5 5537#endif
029632fb
PZ
5538}
5539
810b3817 5540#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02 5541static void task_move_group_fair(struct task_struct *p, int on_rq)
810b3817 5542{
aff3e498 5543 struct cfs_rq *cfs_rq;
b2b5ce02
PZ
5544 /*
5545 * If the task was not on the rq at the time of this cgroup movement
5546 * it must have been asleep, sleeping tasks keep their ->vruntime
5547 * absolute on their old rq until wakeup (needed for the fair sleeper
5548 * bonus in place_entity()).
5549 *
5550 * If it was on the rq, we've just 'preempted' it, which does convert
5551 * ->vruntime to a relative base.
5552 *
5553 * Make sure both cases convert their relative position when migrating
5554 * to another cgroup's rq. This does somewhat interfere with the
5555 * fair sleeper stuff for the first placement, but who cares.
5556 */
7ceff013
DN
5557 /*
5558 * When !on_rq, vruntime of the task has usually NOT been normalized.
5559 * But there are some cases where it has already been normalized:
5560 *
5561 * - Moving a forked child which is waiting for being woken up by
5562 * wake_up_new_task().
62af3783
DN
5563 * - Moving a task which has been woken up by try_to_wake_up() and
5564 * waiting for actually being woken up by sched_ttwu_pending().
7ceff013
DN
5565 *
5566 * To prevent boost or penalty in the new cfs_rq caused by delta
5567 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
5568 */
62af3783 5569 if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
7ceff013
DN
5570 on_rq = 1;
5571
b2b5ce02
PZ
5572 if (!on_rq)
5573 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
5574 set_task_rq(p, task_cpu(p));
aff3e498
PT
5575 if (!on_rq) {
5576 cfs_rq = cfs_rq_of(&p->se);
5577 p->se.vruntime += cfs_rq->min_vruntime;
5578#ifdef CONFIG_SMP
5579 /*
5580 * migrate_task_rq_fair() will have removed our previous
5581 * contribution, but we must synchronize for ongoing future
5582 * decay.
5583 */
5584 p->se.avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
5585 cfs_rq->blocked_load_avg += p->se.avg.load_avg_contrib;
5586#endif
5587 }
810b3817 5588}
029632fb
PZ
5589
5590void free_fair_sched_group(struct task_group *tg)
5591{
5592 int i;
5593
5594 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
5595
5596 for_each_possible_cpu(i) {
5597 if (tg->cfs_rq)
5598 kfree(tg->cfs_rq[i]);
5599 if (tg->se)
5600 kfree(tg->se[i]);
5601 }
5602
5603 kfree(tg->cfs_rq);
5604 kfree(tg->se);
5605}
5606
5607int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5608{
5609 struct cfs_rq *cfs_rq;
5610 struct sched_entity *se;
5611 int i;
5612
5613 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
5614 if (!tg->cfs_rq)
5615 goto err;
5616 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
5617 if (!tg->se)
5618 goto err;
5619
5620 tg->shares = NICE_0_LOAD;
5621
5622 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
5623
5624 for_each_possible_cpu(i) {
5625 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
5626 GFP_KERNEL, cpu_to_node(i));
5627 if (!cfs_rq)
5628 goto err;
5629
5630 se = kzalloc_node(sizeof(struct sched_entity),
5631 GFP_KERNEL, cpu_to_node(i));
5632 if (!se)
5633 goto err_free_rq;
5634
5635 init_cfs_rq(cfs_rq);
5636 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
5637 }
5638
5639 return 1;
5640
5641err_free_rq:
5642 kfree(cfs_rq);
5643err:
5644 return 0;
5645}
5646
5647void unregister_fair_sched_group(struct task_group *tg, int cpu)
5648{
5649 struct rq *rq = cpu_rq(cpu);
5650 unsigned long flags;
5651
5652 /*
5653 * Only empty task groups can be destroyed; so we can speculatively
5654 * check on_list without danger of it being re-added.
5655 */
5656 if (!tg->cfs_rq[cpu]->on_list)
5657 return;
5658
5659 raw_spin_lock_irqsave(&rq->lock, flags);
5660 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
5661 raw_spin_unlock_irqrestore(&rq->lock, flags);
5662}
5663
5664void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
5665 struct sched_entity *se, int cpu,
5666 struct sched_entity *parent)
5667{
5668 struct rq *rq = cpu_rq(cpu);
5669
5670 cfs_rq->tg = tg;
5671 cfs_rq->rq = rq;
029632fb
PZ
5672 init_cfs_rq_runtime(cfs_rq);
5673
5674 tg->cfs_rq[cpu] = cfs_rq;
5675 tg->se[cpu] = se;
5676
5677 /* se could be NULL for root_task_group */
5678 if (!se)
5679 return;
5680
5681 if (!parent)
5682 se->cfs_rq = &rq->cfs;
5683 else
5684 se->cfs_rq = parent->my_q;
5685
5686 se->my_q = cfs_rq;
5687 update_load_set(&se->load, 0);
5688 se->parent = parent;
5689}
5690
5691static DEFINE_MUTEX(shares_mutex);
5692
5693int sched_group_set_shares(struct task_group *tg, unsigned long shares)
5694{
5695 int i;
5696 unsigned long flags;
5697
5698 /*
5699 * We can't change the weight of the root cgroup.
5700 */
5701 if (!tg->se[0])
5702 return -EINVAL;
5703
5704 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
5705
5706 mutex_lock(&shares_mutex);
5707 if (tg->shares == shares)
5708 goto done;
5709
5710 tg->shares = shares;
5711 for_each_possible_cpu(i) {
5712 struct rq *rq = cpu_rq(i);
5713 struct sched_entity *se;
5714
5715 se = tg->se[i];
5716 /* Propagate contribution to hierarchy */
5717 raw_spin_lock_irqsave(&rq->lock, flags);
f269ae04 5718 for_each_sched_entity(se) {
029632fb 5719 update_cfs_shares(group_cfs_rq(se));
f269ae04
PT
5720 /* update contribution to parent */
5721 update_entity_load_avg(se, 1);
5722 }
029632fb
PZ
5723 raw_spin_unlock_irqrestore(&rq->lock, flags);
5724 }
5725
5726done:
5727 mutex_unlock(&shares_mutex);
5728 return 0;
5729}
5730#else /* CONFIG_FAIR_GROUP_SCHED */
5731
5732void free_fair_sched_group(struct task_group *tg) { }
5733
5734int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5735{
5736 return 1;
5737}
5738
5739void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
5740
5741#endif /* CONFIG_FAIR_GROUP_SCHED */
5742
810b3817 5743
6d686f45 5744static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
0d721cea
PW
5745{
5746 struct sched_entity *se = &task->se;
0d721cea
PW
5747 unsigned int rr_interval = 0;
5748
5749 /*
5750 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
5751 * idle runqueue:
5752 */
0d721cea
PW
5753 if (rq->cfs.load.weight)
5754 rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
0d721cea
PW
5755
5756 return rr_interval;
5757}
5758
bf0f6f24
IM
5759/*
5760 * All the scheduling class methods:
5761 */
029632fb 5762const struct sched_class fair_sched_class = {
5522d5d5 5763 .next = &idle_sched_class,
bf0f6f24
IM
5764 .enqueue_task = enqueue_task_fair,
5765 .dequeue_task = dequeue_task_fair,
5766 .yield_task = yield_task_fair,
d95f4122 5767 .yield_to_task = yield_to_task_fair,
bf0f6f24 5768
2e09bf55 5769 .check_preempt_curr = check_preempt_wakeup,
bf0f6f24
IM
5770
5771 .pick_next_task = pick_next_task_fair,
5772 .put_prev_task = put_prev_task_fair,
5773
681f3e68 5774#ifdef CONFIG_SMP
4ce72a2c 5775 .select_task_rq = select_task_rq_fair,
0a74bef8 5776 .migrate_task_rq = migrate_task_rq_fair,
4ce72a2c 5777
0bcdcf28
CE
5778 .rq_online = rq_online_fair,
5779 .rq_offline = rq_offline_fair,
88ec22d3
PZ
5780
5781 .task_waking = task_waking_fair,
681f3e68 5782#endif
bf0f6f24 5783
83b699ed 5784 .set_curr_task = set_curr_task_fair,
bf0f6f24 5785 .task_tick = task_tick_fair,
cd29fe6f 5786 .task_fork = task_fork_fair,
cb469845
SR
5787
5788 .prio_changed = prio_changed_fair,
da7a735e 5789 .switched_from = switched_from_fair,
cb469845 5790 .switched_to = switched_to_fair,
810b3817 5791
0d721cea
PW
5792 .get_rr_interval = get_rr_interval_fair,
5793
810b3817 5794#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02 5795 .task_move_group = task_move_group_fair,
810b3817 5796#endif
bf0f6f24
IM
5797};
5798
5799#ifdef CONFIG_SCHED_DEBUG
029632fb 5800void print_cfs_stats(struct seq_file *m, int cpu)
bf0f6f24 5801{
bf0f6f24
IM
5802 struct cfs_rq *cfs_rq;
5803
5973e5b9 5804 rcu_read_lock();
c3b64f1e 5805 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5cef9eca 5806 print_cfs_rq(m, cpu, cfs_rq);
5973e5b9 5807 rcu_read_unlock();
bf0f6f24
IM
5808}
5809#endif
029632fb
PZ
5810
5811__init void init_sched_fair_class(void)
5812{
5813#ifdef CONFIG_SMP
5814 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
5815
5816#ifdef CONFIG_NO_HZ
554cecaf 5817 nohz.next_balance = jiffies;
029632fb 5818 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
71325960 5819 cpu_notifier(sched_ilb_notifier, 0);
029632fb
PZ
5820#endif
5821#endif /* SMP */
5822
5823}