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