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