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