]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/sched/fair.c
sched: Clean up idle task SMP logic
[mirror_ubuntu-bionic-kernel.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>
cbee9f88 29#include <linux/mempolicy.h>
e14808b4 30#include <linux/migrate.h>
cbee9f88 31#include <linux/task_work.h>
029632fb
PZ
32
33#include <trace/events/sched.h>
34
35#include "sched.h"
9745512c 36
bf0f6f24 37/*
21805085 38 * Targeted preemption latency for CPU-bound tasks:
864616ee 39 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24 40 *
21805085 41 * NOTE: this latency value is not the same as the concept of
d274a4ce
IM
42 * 'timeslice length' - timeslices in CFS are of variable length
43 * and have no persistent notion like in traditional, time-slice
44 * based scheduling concepts.
bf0f6f24 45 *
d274a4ce
IM
46 * (to see the precise effective timeslice length of your workload,
47 * run vmstat and monitor the context-switches (cs) field)
bf0f6f24 48 */
21406928
MG
49unsigned int sysctl_sched_latency = 6000000ULL;
50unsigned int normalized_sysctl_sched_latency = 6000000ULL;
2bd8e6d4 51
1983a922
CE
52/*
53 * The initial- and re-scaling of tunables is configurable
54 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
55 *
56 * Options are:
57 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
58 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
59 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
60 */
61enum sched_tunable_scaling sysctl_sched_tunable_scaling
62 = SCHED_TUNABLESCALING_LOG;
63
2bd8e6d4 64/*
b2be5e96 65 * Minimal preemption granularity for CPU-bound tasks:
864616ee 66 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
2bd8e6d4 67 */
0bf377bb
IM
68unsigned int sysctl_sched_min_granularity = 750000ULL;
69unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
21805085
PZ
70
71/*
b2be5e96
PZ
72 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
73 */
0bf377bb 74static unsigned int sched_nr_latency = 8;
b2be5e96
PZ
75
76/*
2bba22c5 77 * After fork, child runs first. If set to 0 (default) then
b2be5e96 78 * parent will (try to) run first.
21805085 79 */
2bba22c5 80unsigned int sysctl_sched_child_runs_first __read_mostly;
bf0f6f24 81
bf0f6f24
IM
82/*
83 * SCHED_OTHER wake-up granularity.
172e082a 84 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24
IM
85 *
86 * This option delays the preemption effects of decoupled workloads
87 * and reduces their over-scheduling. Synchronous workloads will still
88 * have immediate wakeup/sleep latencies.
89 */
172e082a 90unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
0bcdcf28 91unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
bf0f6f24 92
da84d961
IM
93const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
94
a7a4f8a7
PT
95/*
96 * The exponential sliding window over which load is averaged for shares
97 * distribution.
98 * (default: 10msec)
99 */
100unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
101
ec12cb7f
PT
102#ifdef CONFIG_CFS_BANDWIDTH
103/*
104 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
105 * each time a cfs_rq requests quota.
106 *
107 * Note: in the case that the slice exceeds the runtime remaining (either due
108 * to consumption or the quota being specified to be smaller than the slice)
109 * we will always only issue the remaining available time.
110 *
111 * default: 5 msec, units: microseconds
112 */
113unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
114#endif
115
8527632d
PG
116static inline void update_load_add(struct load_weight *lw, unsigned long inc)
117{
118 lw->weight += inc;
119 lw->inv_weight = 0;
120}
121
122static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
123{
124 lw->weight -= dec;
125 lw->inv_weight = 0;
126}
127
128static inline void update_load_set(struct load_weight *lw, unsigned long w)
129{
130 lw->weight = w;
131 lw->inv_weight = 0;
132}
133
029632fb
PZ
134/*
135 * Increase the granularity value when there are more CPUs,
136 * because with more CPUs the 'effective latency' as visible
137 * to users decreases. But the relationship is not linear,
138 * so pick a second-best guess by going with the log2 of the
139 * number of CPUs.
140 *
141 * This idea comes from the SD scheduler of Con Kolivas:
142 */
143static int get_update_sysctl_factor(void)
144{
145 unsigned int cpus = min_t(int, num_online_cpus(), 8);
146 unsigned int factor;
147
148 switch (sysctl_sched_tunable_scaling) {
149 case SCHED_TUNABLESCALING_NONE:
150 factor = 1;
151 break;
152 case SCHED_TUNABLESCALING_LINEAR:
153 factor = cpus;
154 break;
155 case SCHED_TUNABLESCALING_LOG:
156 default:
157 factor = 1 + ilog2(cpus);
158 break;
159 }
160
161 return factor;
162}
163
164static void update_sysctl(void)
165{
166 unsigned int factor = get_update_sysctl_factor();
167
168#define SET_SYSCTL(name) \
169 (sysctl_##name = (factor) * normalized_sysctl_##name)
170 SET_SYSCTL(sched_min_granularity);
171 SET_SYSCTL(sched_latency);
172 SET_SYSCTL(sched_wakeup_granularity);
173#undef SET_SYSCTL
174}
175
176void sched_init_granularity(void)
177{
178 update_sysctl();
179}
180
9dbdb155 181#define WMULT_CONST (~0U)
029632fb
PZ
182#define WMULT_SHIFT 32
183
9dbdb155
PZ
184static void __update_inv_weight(struct load_weight *lw)
185{
186 unsigned long w;
187
188 if (likely(lw->inv_weight))
189 return;
190
191 w = scale_load_down(lw->weight);
192
193 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
194 lw->inv_weight = 1;
195 else if (unlikely(!w))
196 lw->inv_weight = WMULT_CONST;
197 else
198 lw->inv_weight = WMULT_CONST / w;
199}
029632fb
PZ
200
201/*
9dbdb155
PZ
202 * delta_exec * weight / lw.weight
203 * OR
204 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
205 *
206 * Either weight := NICE_0_LOAD and lw \e prio_to_wmult[], in which case
207 * we're guaranteed shift stays positive because inv_weight is guaranteed to
208 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
209 *
210 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
211 * weight/lw.weight <= 1, and therefore our shift will also be positive.
029632fb 212 */
9dbdb155 213static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
029632fb 214{
9dbdb155
PZ
215 u64 fact = scale_load_down(weight);
216 int shift = WMULT_SHIFT;
029632fb 217
9dbdb155 218 __update_inv_weight(lw);
029632fb 219
9dbdb155
PZ
220 if (unlikely(fact >> 32)) {
221 while (fact >> 32) {
222 fact >>= 1;
223 shift--;
224 }
029632fb
PZ
225 }
226
9dbdb155
PZ
227 /* hint to use a 32x32->64 mul */
228 fact = (u64)(u32)fact * lw->inv_weight;
029632fb 229
9dbdb155
PZ
230 while (fact >> 32) {
231 fact >>= 1;
232 shift--;
233 }
029632fb 234
9dbdb155 235 return mul_u64_u32_shr(delta_exec, fact, shift);
029632fb
PZ
236}
237
238
239const struct sched_class fair_sched_class;
a4c2f00f 240
bf0f6f24
IM
241/**************************************************************
242 * CFS operations on generic schedulable entities:
243 */
244
62160e3f 245#ifdef CONFIG_FAIR_GROUP_SCHED
bf0f6f24 246
62160e3f 247/* cpu runqueue to which this cfs_rq is attached */
bf0f6f24
IM
248static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
249{
62160e3f 250 return cfs_rq->rq;
bf0f6f24
IM
251}
252
62160e3f
IM
253/* An entity is a task if it doesn't "own" a runqueue */
254#define entity_is_task(se) (!se->my_q)
bf0f6f24 255
8f48894f
PZ
256static inline struct task_struct *task_of(struct sched_entity *se)
257{
258#ifdef CONFIG_SCHED_DEBUG
259 WARN_ON_ONCE(!entity_is_task(se));
260#endif
261 return container_of(se, struct task_struct, se);
262}
263
b758149c
PZ
264/* Walk up scheduling entities hierarchy */
265#define for_each_sched_entity(se) \
266 for (; se; se = se->parent)
267
268static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
269{
270 return p->se.cfs_rq;
271}
272
273/* runqueue on which this entity is (to be) queued */
274static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
275{
276 return se->cfs_rq;
277}
278
279/* runqueue "owned" by this group */
280static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
281{
282 return grp->my_q;
283}
284
aff3e498
PT
285static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
286 int force_update);
9ee474f5 287
3d4b47b4
PZ
288static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
289{
290 if (!cfs_rq->on_list) {
67e86250
PT
291 /*
292 * Ensure we either appear before our parent (if already
293 * enqueued) or force our parent to appear after us when it is
294 * enqueued. The fact that we always enqueue bottom-up
295 * reduces this to two cases.
296 */
297 if (cfs_rq->tg->parent &&
298 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
299 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
300 &rq_of(cfs_rq)->leaf_cfs_rq_list);
301 } else {
302 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
3d4b47b4 303 &rq_of(cfs_rq)->leaf_cfs_rq_list);
67e86250 304 }
3d4b47b4
PZ
305
306 cfs_rq->on_list = 1;
9ee474f5 307 /* We should have no load, but we need to update last_decay. */
aff3e498 308 update_cfs_rq_blocked_load(cfs_rq, 0);
3d4b47b4
PZ
309 }
310}
311
312static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
313{
314 if (cfs_rq->on_list) {
315 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
316 cfs_rq->on_list = 0;
317 }
318}
319
b758149c
PZ
320/* Iterate thr' all leaf cfs_rq's on a runqueue */
321#define for_each_leaf_cfs_rq(rq, cfs_rq) \
322 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
323
324/* Do the two (enqueued) entities belong to the same group ? */
fed14d45 325static inline struct cfs_rq *
b758149c
PZ
326is_same_group(struct sched_entity *se, struct sched_entity *pse)
327{
328 if (se->cfs_rq == pse->cfs_rq)
fed14d45 329 return se->cfs_rq;
b758149c 330
fed14d45 331 return NULL;
b758149c
PZ
332}
333
334static inline struct sched_entity *parent_entity(struct sched_entity *se)
335{
336 return se->parent;
337}
338
464b7527
PZ
339static void
340find_matching_se(struct sched_entity **se, struct sched_entity **pse)
341{
342 int se_depth, pse_depth;
343
344 /*
345 * preemption test can be made between sibling entities who are in the
346 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
347 * both tasks until we find their ancestors who are siblings of common
348 * parent.
349 */
350
351 /* First walk up until both entities are at same depth */
fed14d45
PZ
352 se_depth = (*se)->depth;
353 pse_depth = (*pse)->depth;
464b7527
PZ
354
355 while (se_depth > pse_depth) {
356 se_depth--;
357 *se = parent_entity(*se);
358 }
359
360 while (pse_depth > se_depth) {
361 pse_depth--;
362 *pse = parent_entity(*pse);
363 }
364
365 while (!is_same_group(*se, *pse)) {
366 *se = parent_entity(*se);
367 *pse = parent_entity(*pse);
368 }
369}
370
8f48894f
PZ
371#else /* !CONFIG_FAIR_GROUP_SCHED */
372
373static inline struct task_struct *task_of(struct sched_entity *se)
374{
375 return container_of(se, struct task_struct, se);
376}
bf0f6f24 377
62160e3f
IM
378static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
379{
380 return container_of(cfs_rq, struct rq, cfs);
bf0f6f24
IM
381}
382
383#define entity_is_task(se) 1
384
b758149c
PZ
385#define for_each_sched_entity(se) \
386 for (; se; se = NULL)
bf0f6f24 387
b758149c 388static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
bf0f6f24 389{
b758149c 390 return &task_rq(p)->cfs;
bf0f6f24
IM
391}
392
b758149c
PZ
393static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
394{
395 struct task_struct *p = task_of(se);
396 struct rq *rq = task_rq(p);
397
398 return &rq->cfs;
399}
400
401/* runqueue "owned" by this group */
402static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
403{
404 return NULL;
405}
406
3d4b47b4
PZ
407static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
408{
409}
410
411static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
412{
413}
414
b758149c
PZ
415#define for_each_leaf_cfs_rq(rq, cfs_rq) \
416 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
417
fed14d45 418static inline struct cfs_rq *
b758149c
PZ
419is_same_group(struct sched_entity *se, struct sched_entity *pse)
420{
fed14d45 421 return cfs_rq_of(se); /* always the same rq */
b758149c
PZ
422}
423
424static inline struct sched_entity *parent_entity(struct sched_entity *se)
425{
426 return NULL;
427}
428
464b7527
PZ
429static inline void
430find_matching_se(struct sched_entity **se, struct sched_entity **pse)
431{
432}
433
b758149c
PZ
434#endif /* CONFIG_FAIR_GROUP_SCHED */
435
6c16a6dc 436static __always_inline
9dbdb155 437void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
bf0f6f24
IM
438
439/**************************************************************
440 * Scheduling class tree data structure manipulation methods:
441 */
442
1bf08230 443static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
02e0431a 444{
1bf08230 445 s64 delta = (s64)(vruntime - max_vruntime);
368059a9 446 if (delta > 0)
1bf08230 447 max_vruntime = vruntime;
02e0431a 448
1bf08230 449 return max_vruntime;
02e0431a
PZ
450}
451
0702e3eb 452static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
b0ffd246
PZ
453{
454 s64 delta = (s64)(vruntime - min_vruntime);
455 if (delta < 0)
456 min_vruntime = vruntime;
457
458 return min_vruntime;
459}
460
54fdc581
FC
461static inline int entity_before(struct sched_entity *a,
462 struct sched_entity *b)
463{
464 return (s64)(a->vruntime - b->vruntime) < 0;
465}
466
1af5f730
PZ
467static void update_min_vruntime(struct cfs_rq *cfs_rq)
468{
469 u64 vruntime = cfs_rq->min_vruntime;
470
471 if (cfs_rq->curr)
472 vruntime = cfs_rq->curr->vruntime;
473
474 if (cfs_rq->rb_leftmost) {
475 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
476 struct sched_entity,
477 run_node);
478
e17036da 479 if (!cfs_rq->curr)
1af5f730
PZ
480 vruntime = se->vruntime;
481 else
482 vruntime = min_vruntime(vruntime, se->vruntime);
483 }
484
1bf08230 485 /* ensure we never gain time by being placed backwards. */
1af5f730 486 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
3fe1698b
PZ
487#ifndef CONFIG_64BIT
488 smp_wmb();
489 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
490#endif
1af5f730
PZ
491}
492
bf0f6f24
IM
493/*
494 * Enqueue an entity into the rb-tree:
495 */
0702e3eb 496static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
497{
498 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
499 struct rb_node *parent = NULL;
500 struct sched_entity *entry;
bf0f6f24
IM
501 int leftmost = 1;
502
503 /*
504 * Find the right place in the rbtree:
505 */
506 while (*link) {
507 parent = *link;
508 entry = rb_entry(parent, struct sched_entity, run_node);
509 /*
510 * We dont care about collisions. Nodes with
511 * the same key stay together.
512 */
2bd2d6f2 513 if (entity_before(se, entry)) {
bf0f6f24
IM
514 link = &parent->rb_left;
515 } else {
516 link = &parent->rb_right;
517 leftmost = 0;
518 }
519 }
520
521 /*
522 * Maintain a cache of leftmost tree entries (it is frequently
523 * used):
524 */
1af5f730 525 if (leftmost)
57cb499d 526 cfs_rq->rb_leftmost = &se->run_node;
bf0f6f24
IM
527
528 rb_link_node(&se->run_node, parent, link);
529 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
530}
531
0702e3eb 532static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 533{
3fe69747
PZ
534 if (cfs_rq->rb_leftmost == &se->run_node) {
535 struct rb_node *next_node;
3fe69747
PZ
536
537 next_node = rb_next(&se->run_node);
538 cfs_rq->rb_leftmost = next_node;
3fe69747 539 }
e9acbff6 540
bf0f6f24 541 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
542}
543
029632fb 544struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
bf0f6f24 545{
f4b6755f
PZ
546 struct rb_node *left = cfs_rq->rb_leftmost;
547
548 if (!left)
549 return NULL;
550
551 return rb_entry(left, struct sched_entity, run_node);
bf0f6f24
IM
552}
553
ac53db59
RR
554static struct sched_entity *__pick_next_entity(struct sched_entity *se)
555{
556 struct rb_node *next = rb_next(&se->run_node);
557
558 if (!next)
559 return NULL;
560
561 return rb_entry(next, struct sched_entity, run_node);
562}
563
564#ifdef CONFIG_SCHED_DEBUG
029632fb 565struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
aeb73b04 566{
7eee3e67 567 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
aeb73b04 568
70eee74b
BS
569 if (!last)
570 return NULL;
7eee3e67
IM
571
572 return rb_entry(last, struct sched_entity, run_node);
aeb73b04
PZ
573}
574
bf0f6f24
IM
575/**************************************************************
576 * Scheduling class statistics methods:
577 */
578
acb4a848 579int sched_proc_update_handler(struct ctl_table *table, int write,
8d65af78 580 void __user *buffer, size_t *lenp,
b2be5e96
PZ
581 loff_t *ppos)
582{
8d65af78 583 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
acb4a848 584 int factor = get_update_sysctl_factor();
b2be5e96
PZ
585
586 if (ret || !write)
587 return ret;
588
589 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
590 sysctl_sched_min_granularity);
591
acb4a848
CE
592#define WRT_SYSCTL(name) \
593 (normalized_sysctl_##name = sysctl_##name / (factor))
594 WRT_SYSCTL(sched_min_granularity);
595 WRT_SYSCTL(sched_latency);
596 WRT_SYSCTL(sched_wakeup_granularity);
acb4a848
CE
597#undef WRT_SYSCTL
598
b2be5e96
PZ
599 return 0;
600}
601#endif
647e7cac 602
a7be37ac 603/*
f9c0b095 604 * delta /= w
a7be37ac 605 */
9dbdb155 606static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
a7be37ac 607{
f9c0b095 608 if (unlikely(se->load.weight != NICE_0_LOAD))
9dbdb155 609 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
a7be37ac
PZ
610
611 return delta;
612}
613
647e7cac
IM
614/*
615 * The idea is to set a period in which each task runs once.
616 *
532b1858 617 * When there are too many tasks (sched_nr_latency) we have to stretch
647e7cac
IM
618 * this period because otherwise the slices get too small.
619 *
620 * p = (nr <= nl) ? l : l*nr/nl
621 */
4d78e7b6
PZ
622static u64 __sched_period(unsigned long nr_running)
623{
624 u64 period = sysctl_sched_latency;
b2be5e96 625 unsigned long nr_latency = sched_nr_latency;
4d78e7b6
PZ
626
627 if (unlikely(nr_running > nr_latency)) {
4bf0b771 628 period = sysctl_sched_min_granularity;
4d78e7b6 629 period *= nr_running;
4d78e7b6
PZ
630 }
631
632 return period;
633}
634
647e7cac
IM
635/*
636 * We calculate the wall-time slice from the period by taking a part
637 * proportional to the weight.
638 *
f9c0b095 639 * s = p*P[w/rw]
647e7cac 640 */
6d0f0ebd 641static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
21805085 642{
0a582440 643 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
f9c0b095 644
0a582440 645 for_each_sched_entity(se) {
6272d68c 646 struct load_weight *load;
3104bf03 647 struct load_weight lw;
6272d68c
LM
648
649 cfs_rq = cfs_rq_of(se);
650 load = &cfs_rq->load;
f9c0b095 651
0a582440 652 if (unlikely(!se->on_rq)) {
3104bf03 653 lw = cfs_rq->load;
0a582440
MG
654
655 update_load_add(&lw, se->load.weight);
656 load = &lw;
657 }
9dbdb155 658 slice = __calc_delta(slice, se->load.weight, load);
0a582440
MG
659 }
660 return slice;
bf0f6f24
IM
661}
662
647e7cac 663/*
660cc00f 664 * We calculate the vruntime slice of a to-be-inserted task.
647e7cac 665 *
f9c0b095 666 * vs = s/w
647e7cac 667 */
f9c0b095 668static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
67e9fb2a 669{
f9c0b095 670 return calc_delta_fair(sched_slice(cfs_rq, se), se);
a7be37ac
PZ
671}
672
a75cdaa9 673#ifdef CONFIG_SMP
fb13c7ee
MG
674static unsigned long task_h_load(struct task_struct *p);
675
a75cdaa9
AS
676static inline void __update_task_entity_contrib(struct sched_entity *se);
677
678/* Give new task start runnable values to heavy its load in infant time */
679void init_task_runnable_average(struct task_struct *p)
680{
681 u32 slice;
682
683 p->se.avg.decay_count = 0;
684 slice = sched_slice(task_cfs_rq(p), &p->se) >> 10;
685 p->se.avg.runnable_avg_sum = slice;
686 p->se.avg.runnable_avg_period = slice;
687 __update_task_entity_contrib(&p->se);
688}
689#else
690void init_task_runnable_average(struct task_struct *p)
691{
692}
693#endif
694
bf0f6f24 695/*
9dbdb155 696 * Update the current task's runtime statistics.
bf0f6f24 697 */
b7cc0896 698static void update_curr(struct cfs_rq *cfs_rq)
bf0f6f24 699{
429d43bc 700 struct sched_entity *curr = cfs_rq->curr;
78becc27 701 u64 now = rq_clock_task(rq_of(cfs_rq));
9dbdb155 702 u64 delta_exec;
bf0f6f24
IM
703
704 if (unlikely(!curr))
705 return;
706
9dbdb155
PZ
707 delta_exec = now - curr->exec_start;
708 if (unlikely((s64)delta_exec <= 0))
34f28ecd 709 return;
bf0f6f24 710
8ebc91d9 711 curr->exec_start = now;
d842de87 712
9dbdb155
PZ
713 schedstat_set(curr->statistics.exec_max,
714 max(delta_exec, curr->statistics.exec_max));
715
716 curr->sum_exec_runtime += delta_exec;
717 schedstat_add(cfs_rq, exec_clock, delta_exec);
718
719 curr->vruntime += calc_delta_fair(delta_exec, curr);
720 update_min_vruntime(cfs_rq);
721
d842de87
SV
722 if (entity_is_task(curr)) {
723 struct task_struct *curtask = task_of(curr);
724
f977bb49 725 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
d842de87 726 cpuacct_charge(curtask, delta_exec);
f06febc9 727 account_group_exec_runtime(curtask, delta_exec);
d842de87 728 }
ec12cb7f
PT
729
730 account_cfs_rq_runtime(cfs_rq, delta_exec);
bf0f6f24
IM
731}
732
733static inline void
5870db5b 734update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 735{
78becc27 736 schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq)));
bf0f6f24
IM
737}
738
bf0f6f24
IM
739/*
740 * Task is being enqueued - update stats:
741 */
d2417e5a 742static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 743{
bf0f6f24
IM
744 /*
745 * Are we enqueueing a waiting task? (for current tasks
746 * a dequeue/enqueue event is a NOP)
747 */
429d43bc 748 if (se != cfs_rq->curr)
5870db5b 749 update_stats_wait_start(cfs_rq, se);
bf0f6f24
IM
750}
751
bf0f6f24 752static void
9ef0a961 753update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 754{
41acab88 755 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
78becc27 756 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start));
41acab88
LDM
757 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
758 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
78becc27 759 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
768d0c27
PZ
760#ifdef CONFIG_SCHEDSTATS
761 if (entity_is_task(se)) {
762 trace_sched_stat_wait(task_of(se),
78becc27 763 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
768d0c27
PZ
764 }
765#endif
41acab88 766 schedstat_set(se->statistics.wait_start, 0);
bf0f6f24
IM
767}
768
769static inline void
19b6a2e3 770update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 771{
bf0f6f24
IM
772 /*
773 * Mark the end of the wait period if dequeueing a
774 * waiting task:
775 */
429d43bc 776 if (se != cfs_rq->curr)
9ef0a961 777 update_stats_wait_end(cfs_rq, se);
bf0f6f24
IM
778}
779
780/*
781 * We are picking a new current task - update its stats:
782 */
783static inline void
79303e9e 784update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
785{
786 /*
787 * We are starting a new run period:
788 */
78becc27 789 se->exec_start = rq_clock_task(rq_of(cfs_rq));
bf0f6f24
IM
790}
791
bf0f6f24
IM
792/**************************************************
793 * Scheduling class queueing methods:
794 */
795
cbee9f88
PZ
796#ifdef CONFIG_NUMA_BALANCING
797/*
598f0ec0
MG
798 * Approximate time to scan a full NUMA task in ms. The task scan period is
799 * calculated based on the tasks virtual memory size and
800 * numa_balancing_scan_size.
cbee9f88 801 */
598f0ec0
MG
802unsigned int sysctl_numa_balancing_scan_period_min = 1000;
803unsigned int sysctl_numa_balancing_scan_period_max = 60000;
6e5fb223
PZ
804
805/* Portion of address space to scan in MB */
806unsigned int sysctl_numa_balancing_scan_size = 256;
cbee9f88 807
4b96a29b
PZ
808/* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
809unsigned int sysctl_numa_balancing_scan_delay = 1000;
810
598f0ec0
MG
811static unsigned int task_nr_scan_windows(struct task_struct *p)
812{
813 unsigned long rss = 0;
814 unsigned long nr_scan_pages;
815
816 /*
817 * Calculations based on RSS as non-present and empty pages are skipped
818 * by the PTE scanner and NUMA hinting faults should be trapped based
819 * on resident pages
820 */
821 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
822 rss = get_mm_rss(p->mm);
823 if (!rss)
824 rss = nr_scan_pages;
825
826 rss = round_up(rss, nr_scan_pages);
827 return rss / nr_scan_pages;
828}
829
830/* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
831#define MAX_SCAN_WINDOW 2560
832
833static unsigned int task_scan_min(struct task_struct *p)
834{
835 unsigned int scan, floor;
836 unsigned int windows = 1;
837
838 if (sysctl_numa_balancing_scan_size < MAX_SCAN_WINDOW)
839 windows = MAX_SCAN_WINDOW / sysctl_numa_balancing_scan_size;
840 floor = 1000 / windows;
841
842 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
843 return max_t(unsigned int, floor, scan);
844}
845
846static unsigned int task_scan_max(struct task_struct *p)
847{
848 unsigned int smin = task_scan_min(p);
849 unsigned int smax;
850
851 /* Watch for min being lower than max due to floor calculations */
852 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
853 return max(smin, smax);
854}
855
0ec8aa00
PZ
856static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
857{
858 rq->nr_numa_running += (p->numa_preferred_nid != -1);
859 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
860}
861
862static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
863{
864 rq->nr_numa_running -= (p->numa_preferred_nid != -1);
865 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
866}
867
8c8a743c
PZ
868struct numa_group {
869 atomic_t refcount;
870
871 spinlock_t lock; /* nr_tasks, tasks */
872 int nr_tasks;
e29cf08b 873 pid_t gid;
8c8a743c
PZ
874 struct list_head task_list;
875
876 struct rcu_head rcu;
20e07dea 877 nodemask_t active_nodes;
989348b5 878 unsigned long total_faults;
7e2703e6
RR
879 /*
880 * Faults_cpu is used to decide whether memory should move
881 * towards the CPU. As a consequence, these stats are weighted
882 * more by CPU use than by memory faults.
883 */
50ec8a40 884 unsigned long *faults_cpu;
989348b5 885 unsigned long faults[0];
8c8a743c
PZ
886};
887
be1e4e76
RR
888/* Shared or private faults. */
889#define NR_NUMA_HINT_FAULT_TYPES 2
890
891/* Memory and CPU locality */
892#define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
893
894/* Averaged statistics, and temporary buffers. */
895#define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
896
e29cf08b
MG
897pid_t task_numa_group_id(struct task_struct *p)
898{
899 return p->numa_group ? p->numa_group->gid : 0;
900}
901
ac8e895b
MG
902static inline int task_faults_idx(int nid, int priv)
903{
be1e4e76 904 return NR_NUMA_HINT_FAULT_TYPES * nid + priv;
ac8e895b
MG
905}
906
907static inline unsigned long task_faults(struct task_struct *p, int nid)
908{
ff1df896 909 if (!p->numa_faults_memory)
ac8e895b
MG
910 return 0;
911
ff1df896
RR
912 return p->numa_faults_memory[task_faults_idx(nid, 0)] +
913 p->numa_faults_memory[task_faults_idx(nid, 1)];
ac8e895b
MG
914}
915
83e1d2cd
MG
916static inline unsigned long group_faults(struct task_struct *p, int nid)
917{
918 if (!p->numa_group)
919 return 0;
920
82897b4f
WL
921 return p->numa_group->faults[task_faults_idx(nid, 0)] +
922 p->numa_group->faults[task_faults_idx(nid, 1)];
83e1d2cd
MG
923}
924
20e07dea
RR
925static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
926{
927 return group->faults_cpu[task_faults_idx(nid, 0)] +
928 group->faults_cpu[task_faults_idx(nid, 1)];
929}
930
83e1d2cd
MG
931/*
932 * These return the fraction of accesses done by a particular task, or
933 * task group, on a particular numa node. The group weight is given a
934 * larger multiplier, in order to group tasks together that are almost
935 * evenly spread out between numa nodes.
936 */
937static inline unsigned long task_weight(struct task_struct *p, int nid)
938{
939 unsigned long total_faults;
940
ff1df896 941 if (!p->numa_faults_memory)
83e1d2cd
MG
942 return 0;
943
944 total_faults = p->total_numa_faults;
945
946 if (!total_faults)
947 return 0;
948
949 return 1000 * task_faults(p, nid) / total_faults;
950}
951
952static inline unsigned long group_weight(struct task_struct *p, int nid)
953{
989348b5 954 if (!p->numa_group || !p->numa_group->total_faults)
83e1d2cd
MG
955 return 0;
956
989348b5 957 return 1000 * group_faults(p, nid) / p->numa_group->total_faults;
83e1d2cd
MG
958}
959
10f39042
RR
960bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
961 int src_nid, int dst_cpu)
962{
963 struct numa_group *ng = p->numa_group;
964 int dst_nid = cpu_to_node(dst_cpu);
965 int last_cpupid, this_cpupid;
966
967 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
968
969 /*
970 * Multi-stage node selection is used in conjunction with a periodic
971 * migration fault to build a temporal task<->page relation. By using
972 * a two-stage filter we remove short/unlikely relations.
973 *
974 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
975 * a task's usage of a particular page (n_p) per total usage of this
976 * page (n_t) (in a given time-span) to a probability.
977 *
978 * Our periodic faults will sample this probability and getting the
979 * same result twice in a row, given these samples are fully
980 * independent, is then given by P(n)^2, provided our sample period
981 * is sufficiently short compared to the usage pattern.
982 *
983 * This quadric squishes small probabilities, making it less likely we
984 * act on an unlikely task<->page relation.
985 */
986 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
987 if (!cpupid_pid_unset(last_cpupid) &&
988 cpupid_to_nid(last_cpupid) != dst_nid)
989 return false;
990
991 /* Always allow migrate on private faults */
992 if (cpupid_match_pid(p, last_cpupid))
993 return true;
994
995 /* A shared fault, but p->numa_group has not been set up yet. */
996 if (!ng)
997 return true;
998
999 /*
1000 * Do not migrate if the destination is not a node that
1001 * is actively used by this numa group.
1002 */
1003 if (!node_isset(dst_nid, ng->active_nodes))
1004 return false;
1005
1006 /*
1007 * Source is a node that is not actively used by this
1008 * numa group, while the destination is. Migrate.
1009 */
1010 if (!node_isset(src_nid, ng->active_nodes))
1011 return true;
1012
1013 /*
1014 * Both source and destination are nodes in active
1015 * use by this numa group. Maximize memory bandwidth
1016 * by migrating from more heavily used groups, to less
1017 * heavily used ones, spreading the load around.
1018 * Use a 1/4 hysteresis to avoid spurious page movement.
1019 */
1020 return group_faults(p, dst_nid) < (group_faults(p, src_nid) * 3 / 4);
1021}
1022
e6628d5b 1023static unsigned long weighted_cpuload(const int cpu);
58d081b5
MG
1024static unsigned long source_load(int cpu, int type);
1025static unsigned long target_load(int cpu, int type);
1026static unsigned long power_of(int cpu);
1027static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
1028
fb13c7ee 1029/* Cached statistics for all CPUs within a node */
58d081b5 1030struct numa_stats {
fb13c7ee 1031 unsigned long nr_running;
58d081b5 1032 unsigned long load;
fb13c7ee
MG
1033
1034 /* Total compute capacity of CPUs on a node */
1035 unsigned long power;
1036
1037 /* Approximate capacity in terms of runnable tasks on a node */
1038 unsigned long capacity;
1039 int has_capacity;
58d081b5 1040};
e6628d5b 1041
fb13c7ee
MG
1042/*
1043 * XXX borrowed from update_sg_lb_stats
1044 */
1045static void update_numa_stats(struct numa_stats *ns, int nid)
1046{
5eca82a9 1047 int cpu, cpus = 0;
fb13c7ee
MG
1048
1049 memset(ns, 0, sizeof(*ns));
1050 for_each_cpu(cpu, cpumask_of_node(nid)) {
1051 struct rq *rq = cpu_rq(cpu);
1052
1053 ns->nr_running += rq->nr_running;
1054 ns->load += weighted_cpuload(cpu);
1055 ns->power += power_of(cpu);
5eca82a9
PZ
1056
1057 cpus++;
fb13c7ee
MG
1058 }
1059
5eca82a9
PZ
1060 /*
1061 * If we raced with hotplug and there are no CPUs left in our mask
1062 * the @ns structure is NULL'ed and task_numa_compare() will
1063 * not find this node attractive.
1064 *
1065 * We'll either bail at !has_capacity, or we'll detect a huge imbalance
1066 * and bail there.
1067 */
1068 if (!cpus)
1069 return;
1070
fb13c7ee
MG
1071 ns->load = (ns->load * SCHED_POWER_SCALE) / ns->power;
1072 ns->capacity = DIV_ROUND_CLOSEST(ns->power, SCHED_POWER_SCALE);
1073 ns->has_capacity = (ns->nr_running < ns->capacity);
1074}
1075
58d081b5
MG
1076struct task_numa_env {
1077 struct task_struct *p;
e6628d5b 1078
58d081b5
MG
1079 int src_cpu, src_nid;
1080 int dst_cpu, dst_nid;
e6628d5b 1081
58d081b5 1082 struct numa_stats src_stats, dst_stats;
e6628d5b 1083
40ea2b42 1084 int imbalance_pct;
fb13c7ee
MG
1085
1086 struct task_struct *best_task;
1087 long best_imp;
58d081b5
MG
1088 int best_cpu;
1089};
1090
fb13c7ee
MG
1091static void task_numa_assign(struct task_numa_env *env,
1092 struct task_struct *p, long imp)
1093{
1094 if (env->best_task)
1095 put_task_struct(env->best_task);
1096 if (p)
1097 get_task_struct(p);
1098
1099 env->best_task = p;
1100 env->best_imp = imp;
1101 env->best_cpu = env->dst_cpu;
1102}
1103
1104/*
1105 * This checks if the overall compute and NUMA accesses of the system would
1106 * be improved if the source tasks was migrated to the target dst_cpu taking
1107 * into account that it might be best if task running on the dst_cpu should
1108 * be exchanged with the source task
1109 */
887c290e
RR
1110static void task_numa_compare(struct task_numa_env *env,
1111 long taskimp, long groupimp)
fb13c7ee
MG
1112{
1113 struct rq *src_rq = cpu_rq(env->src_cpu);
1114 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1115 struct task_struct *cur;
1116 long dst_load, src_load;
1117 long load;
887c290e 1118 long imp = (groupimp > 0) ? groupimp : taskimp;
fb13c7ee
MG
1119
1120 rcu_read_lock();
1121 cur = ACCESS_ONCE(dst_rq->curr);
1122 if (cur->pid == 0) /* idle */
1123 cur = NULL;
1124
1125 /*
1126 * "imp" is the fault differential for the source task between the
1127 * source and destination node. Calculate the total differential for
1128 * the source task and potential destination task. The more negative
1129 * the value is, the more rmeote accesses that would be expected to
1130 * be incurred if the tasks were swapped.
1131 */
1132 if (cur) {
1133 /* Skip this swap candidate if cannot move to the source cpu */
1134 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
1135 goto unlock;
1136
887c290e
RR
1137 /*
1138 * If dst and source tasks are in the same NUMA group, or not
ca28aa53 1139 * in any group then look only at task weights.
887c290e 1140 */
ca28aa53 1141 if (cur->numa_group == env->p->numa_group) {
887c290e
RR
1142 imp = taskimp + task_weight(cur, env->src_nid) -
1143 task_weight(cur, env->dst_nid);
ca28aa53
RR
1144 /*
1145 * Add some hysteresis to prevent swapping the
1146 * tasks within a group over tiny differences.
1147 */
1148 if (cur->numa_group)
1149 imp -= imp/16;
887c290e 1150 } else {
ca28aa53
RR
1151 /*
1152 * Compare the group weights. If a task is all by
1153 * itself (not part of a group), use the task weight
1154 * instead.
1155 */
1156 if (env->p->numa_group)
1157 imp = groupimp;
1158 else
1159 imp = taskimp;
1160
1161 if (cur->numa_group)
1162 imp += group_weight(cur, env->src_nid) -
1163 group_weight(cur, env->dst_nid);
1164 else
1165 imp += task_weight(cur, env->src_nid) -
1166 task_weight(cur, env->dst_nid);
887c290e 1167 }
fb13c7ee
MG
1168 }
1169
1170 if (imp < env->best_imp)
1171 goto unlock;
1172
1173 if (!cur) {
1174 /* Is there capacity at our destination? */
1175 if (env->src_stats.has_capacity &&
1176 !env->dst_stats.has_capacity)
1177 goto unlock;
1178
1179 goto balance;
1180 }
1181
1182 /* Balance doesn't matter much if we're running a task per cpu */
1183 if (src_rq->nr_running == 1 && dst_rq->nr_running == 1)
1184 goto assign;
1185
1186 /*
1187 * In the overloaded case, try and keep the load balanced.
1188 */
1189balance:
1190 dst_load = env->dst_stats.load;
1191 src_load = env->src_stats.load;
1192
1193 /* XXX missing power terms */
1194 load = task_h_load(env->p);
1195 dst_load += load;
1196 src_load -= load;
1197
1198 if (cur) {
1199 load = task_h_load(cur);
1200 dst_load -= load;
1201 src_load += load;
1202 }
1203
1204 /* make src_load the smaller */
1205 if (dst_load < src_load)
1206 swap(dst_load, src_load);
1207
1208 if (src_load * env->imbalance_pct < dst_load * 100)
1209 goto unlock;
1210
1211assign:
1212 task_numa_assign(env, cur, imp);
1213unlock:
1214 rcu_read_unlock();
1215}
1216
887c290e
RR
1217static void task_numa_find_cpu(struct task_numa_env *env,
1218 long taskimp, long groupimp)
2c8a50aa
MG
1219{
1220 int cpu;
1221
1222 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1223 /* Skip this CPU if the source task cannot migrate */
1224 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
1225 continue;
1226
1227 env->dst_cpu = cpu;
887c290e 1228 task_numa_compare(env, taskimp, groupimp);
2c8a50aa
MG
1229 }
1230}
1231
58d081b5
MG
1232static int task_numa_migrate(struct task_struct *p)
1233{
58d081b5
MG
1234 struct task_numa_env env = {
1235 .p = p,
fb13c7ee 1236
58d081b5 1237 .src_cpu = task_cpu(p),
b32e86b4 1238 .src_nid = task_node(p),
fb13c7ee
MG
1239
1240 .imbalance_pct = 112,
1241
1242 .best_task = NULL,
1243 .best_imp = 0,
1244 .best_cpu = -1
58d081b5
MG
1245 };
1246 struct sched_domain *sd;
887c290e 1247 unsigned long taskweight, groupweight;
2c8a50aa 1248 int nid, ret;
887c290e 1249 long taskimp, groupimp;
e6628d5b 1250
58d081b5 1251 /*
fb13c7ee
MG
1252 * Pick the lowest SD_NUMA domain, as that would have the smallest
1253 * imbalance and would be the first to start moving tasks about.
1254 *
1255 * And we want to avoid any moving of tasks about, as that would create
1256 * random movement of tasks -- counter the numa conditions we're trying
1257 * to satisfy here.
58d081b5
MG
1258 */
1259 rcu_read_lock();
fb13c7ee 1260 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
46a73e8a
RR
1261 if (sd)
1262 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
e6628d5b
MG
1263 rcu_read_unlock();
1264
46a73e8a
RR
1265 /*
1266 * Cpusets can break the scheduler domain tree into smaller
1267 * balance domains, some of which do not cross NUMA boundaries.
1268 * Tasks that are "trapped" in such domains cannot be migrated
1269 * elsewhere, so there is no point in (re)trying.
1270 */
1271 if (unlikely(!sd)) {
de1b301a 1272 p->numa_preferred_nid = task_node(p);
46a73e8a
RR
1273 return -EINVAL;
1274 }
1275
887c290e
RR
1276 taskweight = task_weight(p, env.src_nid);
1277 groupweight = group_weight(p, env.src_nid);
fb13c7ee 1278 update_numa_stats(&env.src_stats, env.src_nid);
2c8a50aa 1279 env.dst_nid = p->numa_preferred_nid;
887c290e
RR
1280 taskimp = task_weight(p, env.dst_nid) - taskweight;
1281 groupimp = group_weight(p, env.dst_nid) - groupweight;
2c8a50aa 1282 update_numa_stats(&env.dst_stats, env.dst_nid);
58d081b5 1283
e1dda8a7
RR
1284 /* If the preferred nid has capacity, try to use it. */
1285 if (env.dst_stats.has_capacity)
887c290e 1286 task_numa_find_cpu(&env, taskimp, groupimp);
e1dda8a7
RR
1287
1288 /* No space available on the preferred nid. Look elsewhere. */
1289 if (env.best_cpu == -1) {
2c8a50aa
MG
1290 for_each_online_node(nid) {
1291 if (nid == env.src_nid || nid == p->numa_preferred_nid)
1292 continue;
58d081b5 1293
83e1d2cd 1294 /* Only consider nodes where both task and groups benefit */
887c290e
RR
1295 taskimp = task_weight(p, nid) - taskweight;
1296 groupimp = group_weight(p, nid) - groupweight;
1297 if (taskimp < 0 && groupimp < 0)
fb13c7ee
MG
1298 continue;
1299
2c8a50aa
MG
1300 env.dst_nid = nid;
1301 update_numa_stats(&env.dst_stats, env.dst_nid);
887c290e 1302 task_numa_find_cpu(&env, taskimp, groupimp);
58d081b5
MG
1303 }
1304 }
1305
fb13c7ee
MG
1306 /* No better CPU than the current one was found. */
1307 if (env.best_cpu == -1)
1308 return -EAGAIN;
1309
0ec8aa00
PZ
1310 sched_setnuma(p, env.dst_nid);
1311
04bb2f94
RR
1312 /*
1313 * Reset the scan period if the task is being rescheduled on an
1314 * alternative node to recheck if the tasks is now properly placed.
1315 */
1316 p->numa_scan_period = task_scan_min(p);
1317
fb13c7ee 1318 if (env.best_task == NULL) {
286549dc
MG
1319 ret = migrate_task_to(p, env.best_cpu);
1320 if (ret != 0)
1321 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
fb13c7ee
MG
1322 return ret;
1323 }
1324
1325 ret = migrate_swap(p, env.best_task);
286549dc
MG
1326 if (ret != 0)
1327 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
fb13c7ee
MG
1328 put_task_struct(env.best_task);
1329 return ret;
e6628d5b
MG
1330}
1331
6b9a7460
MG
1332/* Attempt to migrate a task to a CPU on the preferred node. */
1333static void numa_migrate_preferred(struct task_struct *p)
1334{
2739d3ee 1335 /* This task has no NUMA fault statistics yet */
ff1df896 1336 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults_memory))
6b9a7460
MG
1337 return;
1338
2739d3ee
RR
1339 /* Periodically retry migrating the task to the preferred node */
1340 p->numa_migrate_retry = jiffies + HZ;
1341
1342 /* Success if task is already running on preferred CPU */
de1b301a 1343 if (task_node(p) == p->numa_preferred_nid)
6b9a7460
MG
1344 return;
1345
1346 /* Otherwise, try migrate to a CPU on the preferred node */
2739d3ee 1347 task_numa_migrate(p);
6b9a7460
MG
1348}
1349
20e07dea
RR
1350/*
1351 * Find the nodes on which the workload is actively running. We do this by
1352 * tracking the nodes from which NUMA hinting faults are triggered. This can
1353 * be different from the set of nodes where the workload's memory is currently
1354 * located.
1355 *
1356 * The bitmask is used to make smarter decisions on when to do NUMA page
1357 * migrations, To prevent flip-flopping, and excessive page migrations, nodes
1358 * are added when they cause over 6/16 of the maximum number of faults, but
1359 * only removed when they drop below 3/16.
1360 */
1361static void update_numa_active_node_mask(struct numa_group *numa_group)
1362{
1363 unsigned long faults, max_faults = 0;
1364 int nid;
1365
1366 for_each_online_node(nid) {
1367 faults = group_faults_cpu(numa_group, nid);
1368 if (faults > max_faults)
1369 max_faults = faults;
1370 }
1371
1372 for_each_online_node(nid) {
1373 faults = group_faults_cpu(numa_group, nid);
1374 if (!node_isset(nid, numa_group->active_nodes)) {
1375 if (faults > max_faults * 6 / 16)
1376 node_set(nid, numa_group->active_nodes);
1377 } else if (faults < max_faults * 3 / 16)
1378 node_clear(nid, numa_group->active_nodes);
1379 }
1380}
1381
04bb2f94
RR
1382/*
1383 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1384 * increments. The more local the fault statistics are, the higher the scan
1385 * period will be for the next scan window. If local/remote ratio is below
1386 * NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) the
1387 * scan period will decrease
1388 */
1389#define NUMA_PERIOD_SLOTS 10
1390#define NUMA_PERIOD_THRESHOLD 3
1391
1392/*
1393 * Increase the scan period (slow down scanning) if the majority of
1394 * our memory is already on our local node, or if the majority of
1395 * the page accesses are shared with other processes.
1396 * Otherwise, decrease the scan period.
1397 */
1398static void update_task_scan_period(struct task_struct *p,
1399 unsigned long shared, unsigned long private)
1400{
1401 unsigned int period_slot;
1402 int ratio;
1403 int diff;
1404
1405 unsigned long remote = p->numa_faults_locality[0];
1406 unsigned long local = p->numa_faults_locality[1];
1407
1408 /*
1409 * If there were no record hinting faults then either the task is
1410 * completely idle or all activity is areas that are not of interest
1411 * to automatic numa balancing. Scan slower
1412 */
1413 if (local + shared == 0) {
1414 p->numa_scan_period = min(p->numa_scan_period_max,
1415 p->numa_scan_period << 1);
1416
1417 p->mm->numa_next_scan = jiffies +
1418 msecs_to_jiffies(p->numa_scan_period);
1419
1420 return;
1421 }
1422
1423 /*
1424 * Prepare to scale scan period relative to the current period.
1425 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1426 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1427 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1428 */
1429 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1430 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1431 if (ratio >= NUMA_PERIOD_THRESHOLD) {
1432 int slot = ratio - NUMA_PERIOD_THRESHOLD;
1433 if (!slot)
1434 slot = 1;
1435 diff = slot * period_slot;
1436 } else {
1437 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1438
1439 /*
1440 * Scale scan rate increases based on sharing. There is an
1441 * inverse relationship between the degree of sharing and
1442 * the adjustment made to the scanning period. Broadly
1443 * speaking the intent is that there is little point
1444 * scanning faster if shared accesses dominate as it may
1445 * simply bounce migrations uselessly
1446 */
04bb2f94
RR
1447 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared));
1448 diff = (diff * ratio) / NUMA_PERIOD_SLOTS;
1449 }
1450
1451 p->numa_scan_period = clamp(p->numa_scan_period + diff,
1452 task_scan_min(p), task_scan_max(p));
1453 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1454}
1455
7e2703e6
RR
1456/*
1457 * Get the fraction of time the task has been running since the last
1458 * NUMA placement cycle. The scheduler keeps similar statistics, but
1459 * decays those on a 32ms period, which is orders of magnitude off
1460 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1461 * stats only if the task is so new there are no NUMA statistics yet.
1462 */
1463static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1464{
1465 u64 runtime, delta, now;
1466 /* Use the start of this time slice to avoid calculations. */
1467 now = p->se.exec_start;
1468 runtime = p->se.sum_exec_runtime;
1469
1470 if (p->last_task_numa_placement) {
1471 delta = runtime - p->last_sum_exec_runtime;
1472 *period = now - p->last_task_numa_placement;
1473 } else {
1474 delta = p->se.avg.runnable_avg_sum;
1475 *period = p->se.avg.runnable_avg_period;
1476 }
1477
1478 p->last_sum_exec_runtime = runtime;
1479 p->last_task_numa_placement = now;
1480
1481 return delta;
1482}
1483
cbee9f88
PZ
1484static void task_numa_placement(struct task_struct *p)
1485{
83e1d2cd
MG
1486 int seq, nid, max_nid = -1, max_group_nid = -1;
1487 unsigned long max_faults = 0, max_group_faults = 0;
04bb2f94 1488 unsigned long fault_types[2] = { 0, 0 };
7e2703e6
RR
1489 unsigned long total_faults;
1490 u64 runtime, period;
7dbd13ed 1491 spinlock_t *group_lock = NULL;
cbee9f88 1492
2832bc19 1493 seq = ACCESS_ONCE(p->mm->numa_scan_seq);
cbee9f88
PZ
1494 if (p->numa_scan_seq == seq)
1495 return;
1496 p->numa_scan_seq = seq;
598f0ec0 1497 p->numa_scan_period_max = task_scan_max(p);
cbee9f88 1498
7e2703e6
RR
1499 total_faults = p->numa_faults_locality[0] +
1500 p->numa_faults_locality[1];
1501 runtime = numa_get_avg_runtime(p, &period);
1502
7dbd13ed
MG
1503 /* If the task is part of a group prevent parallel updates to group stats */
1504 if (p->numa_group) {
1505 group_lock = &p->numa_group->lock;
1506 spin_lock(group_lock);
1507 }
1508
688b7585
MG
1509 /* Find the node with the highest number of faults */
1510 for_each_online_node(nid) {
83e1d2cd 1511 unsigned long faults = 0, group_faults = 0;
ac8e895b 1512 int priv, i;
745d6147 1513
be1e4e76 1514 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
7e2703e6 1515 long diff, f_diff, f_weight;
8c8a743c 1516
ac8e895b 1517 i = task_faults_idx(nid, priv);
745d6147 1518
ac8e895b 1519 /* Decay existing window, copy faults since last scan */
35664fd4 1520 diff = p->numa_faults_buffer_memory[i] - p->numa_faults_memory[i] / 2;
ff1df896
RR
1521 fault_types[priv] += p->numa_faults_buffer_memory[i];
1522 p->numa_faults_buffer_memory[i] = 0;
fb13c7ee 1523
7e2703e6
RR
1524 /*
1525 * Normalize the faults_from, so all tasks in a group
1526 * count according to CPU use, instead of by the raw
1527 * number of faults. Tasks with little runtime have
1528 * little over-all impact on throughput, and thus their
1529 * faults are less important.
1530 */
1531 f_weight = div64_u64(runtime << 16, period + 1);
1532 f_weight = (f_weight * p->numa_faults_buffer_cpu[i]) /
1533 (total_faults + 1);
35664fd4 1534 f_diff = f_weight - p->numa_faults_cpu[i] / 2;
50ec8a40
RR
1535 p->numa_faults_buffer_cpu[i] = 0;
1536
35664fd4
RR
1537 p->numa_faults_memory[i] += diff;
1538 p->numa_faults_cpu[i] += f_diff;
ff1df896 1539 faults += p->numa_faults_memory[i];
83e1d2cd 1540 p->total_numa_faults += diff;
8c8a743c
PZ
1541 if (p->numa_group) {
1542 /* safe because we can only change our own group */
989348b5 1543 p->numa_group->faults[i] += diff;
50ec8a40 1544 p->numa_group->faults_cpu[i] += f_diff;
989348b5
MG
1545 p->numa_group->total_faults += diff;
1546 group_faults += p->numa_group->faults[i];
8c8a743c 1547 }
ac8e895b
MG
1548 }
1549
688b7585
MG
1550 if (faults > max_faults) {
1551 max_faults = faults;
1552 max_nid = nid;
1553 }
83e1d2cd
MG
1554
1555 if (group_faults > max_group_faults) {
1556 max_group_faults = group_faults;
1557 max_group_nid = nid;
1558 }
1559 }
1560
04bb2f94
RR
1561 update_task_scan_period(p, fault_types[0], fault_types[1]);
1562
7dbd13ed 1563 if (p->numa_group) {
20e07dea 1564 update_numa_active_node_mask(p->numa_group);
7dbd13ed
MG
1565 /*
1566 * If the preferred task and group nids are different,
1567 * iterate over the nodes again to find the best place.
1568 */
1569 if (max_nid != max_group_nid) {
1570 unsigned long weight, max_weight = 0;
1571
1572 for_each_online_node(nid) {
1573 weight = task_weight(p, nid) + group_weight(p, nid);
1574 if (weight > max_weight) {
1575 max_weight = weight;
1576 max_nid = nid;
1577 }
83e1d2cd
MG
1578 }
1579 }
7dbd13ed
MG
1580
1581 spin_unlock(group_lock);
688b7585
MG
1582 }
1583
6b9a7460 1584 /* Preferred node as the node with the most faults */
3a7053b3 1585 if (max_faults && max_nid != p->numa_preferred_nid) {
e6628d5b 1586 /* Update the preferred nid and migrate task if possible */
0ec8aa00 1587 sched_setnuma(p, max_nid);
6b9a7460 1588 numa_migrate_preferred(p);
3a7053b3 1589 }
cbee9f88
PZ
1590}
1591
8c8a743c
PZ
1592static inline int get_numa_group(struct numa_group *grp)
1593{
1594 return atomic_inc_not_zero(&grp->refcount);
1595}
1596
1597static inline void put_numa_group(struct numa_group *grp)
1598{
1599 if (atomic_dec_and_test(&grp->refcount))
1600 kfree_rcu(grp, rcu);
1601}
1602
3e6a9418
MG
1603static void task_numa_group(struct task_struct *p, int cpupid, int flags,
1604 int *priv)
8c8a743c
PZ
1605{
1606 struct numa_group *grp, *my_grp;
1607 struct task_struct *tsk;
1608 bool join = false;
1609 int cpu = cpupid_to_cpu(cpupid);
1610 int i;
1611
1612 if (unlikely(!p->numa_group)) {
1613 unsigned int size = sizeof(struct numa_group) +
50ec8a40 1614 4*nr_node_ids*sizeof(unsigned long);
8c8a743c
PZ
1615
1616 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
1617 if (!grp)
1618 return;
1619
1620 atomic_set(&grp->refcount, 1);
1621 spin_lock_init(&grp->lock);
1622 INIT_LIST_HEAD(&grp->task_list);
e29cf08b 1623 grp->gid = p->pid;
50ec8a40 1624 /* Second half of the array tracks nids where faults happen */
be1e4e76
RR
1625 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
1626 nr_node_ids;
8c8a743c 1627
20e07dea
RR
1628 node_set(task_node(current), grp->active_nodes);
1629
be1e4e76 1630 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
ff1df896 1631 grp->faults[i] = p->numa_faults_memory[i];
8c8a743c 1632
989348b5 1633 grp->total_faults = p->total_numa_faults;
83e1d2cd 1634
8c8a743c
PZ
1635 list_add(&p->numa_entry, &grp->task_list);
1636 grp->nr_tasks++;
1637 rcu_assign_pointer(p->numa_group, grp);
1638 }
1639
1640 rcu_read_lock();
1641 tsk = ACCESS_ONCE(cpu_rq(cpu)->curr);
1642
1643 if (!cpupid_match_pid(tsk, cpupid))
3354781a 1644 goto no_join;
8c8a743c
PZ
1645
1646 grp = rcu_dereference(tsk->numa_group);
1647 if (!grp)
3354781a 1648 goto no_join;
8c8a743c
PZ
1649
1650 my_grp = p->numa_group;
1651 if (grp == my_grp)
3354781a 1652 goto no_join;
8c8a743c
PZ
1653
1654 /*
1655 * Only join the other group if its bigger; if we're the bigger group,
1656 * the other task will join us.
1657 */
1658 if (my_grp->nr_tasks > grp->nr_tasks)
3354781a 1659 goto no_join;
8c8a743c
PZ
1660
1661 /*
1662 * Tie-break on the grp address.
1663 */
1664 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3354781a 1665 goto no_join;
8c8a743c 1666
dabe1d99
RR
1667 /* Always join threads in the same process. */
1668 if (tsk->mm == current->mm)
1669 join = true;
1670
1671 /* Simple filter to avoid false positives due to PID collisions */
1672 if (flags & TNF_SHARED)
1673 join = true;
8c8a743c 1674
3e6a9418
MG
1675 /* Update priv based on whether false sharing was detected */
1676 *priv = !join;
1677
dabe1d99 1678 if (join && !get_numa_group(grp))
3354781a 1679 goto no_join;
8c8a743c 1680
8c8a743c
PZ
1681 rcu_read_unlock();
1682
1683 if (!join)
1684 return;
1685
989348b5
MG
1686 double_lock(&my_grp->lock, &grp->lock);
1687
be1e4e76 1688 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
ff1df896
RR
1689 my_grp->faults[i] -= p->numa_faults_memory[i];
1690 grp->faults[i] += p->numa_faults_memory[i];
8c8a743c 1691 }
989348b5
MG
1692 my_grp->total_faults -= p->total_numa_faults;
1693 grp->total_faults += p->total_numa_faults;
8c8a743c
PZ
1694
1695 list_move(&p->numa_entry, &grp->task_list);
1696 my_grp->nr_tasks--;
1697 grp->nr_tasks++;
1698
1699 spin_unlock(&my_grp->lock);
1700 spin_unlock(&grp->lock);
1701
1702 rcu_assign_pointer(p->numa_group, grp);
1703
1704 put_numa_group(my_grp);
3354781a
PZ
1705 return;
1706
1707no_join:
1708 rcu_read_unlock();
1709 return;
8c8a743c
PZ
1710}
1711
1712void task_numa_free(struct task_struct *p)
1713{
1714 struct numa_group *grp = p->numa_group;
1715 int i;
ff1df896 1716 void *numa_faults = p->numa_faults_memory;
8c8a743c
PZ
1717
1718 if (grp) {
989348b5 1719 spin_lock(&grp->lock);
be1e4e76 1720 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
ff1df896 1721 grp->faults[i] -= p->numa_faults_memory[i];
989348b5 1722 grp->total_faults -= p->total_numa_faults;
83e1d2cd 1723
8c8a743c
PZ
1724 list_del(&p->numa_entry);
1725 grp->nr_tasks--;
1726 spin_unlock(&grp->lock);
1727 rcu_assign_pointer(p->numa_group, NULL);
1728 put_numa_group(grp);
1729 }
1730
ff1df896
RR
1731 p->numa_faults_memory = NULL;
1732 p->numa_faults_buffer_memory = NULL;
50ec8a40
RR
1733 p->numa_faults_cpu= NULL;
1734 p->numa_faults_buffer_cpu = NULL;
82727018 1735 kfree(numa_faults);
8c8a743c
PZ
1736}
1737
cbee9f88
PZ
1738/*
1739 * Got a PROT_NONE fault for a page on @node.
1740 */
58b46da3 1741void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
cbee9f88
PZ
1742{
1743 struct task_struct *p = current;
6688cc05 1744 bool migrated = flags & TNF_MIGRATED;
58b46da3 1745 int cpu_node = task_node(current);
ac8e895b 1746 int priv;
cbee9f88 1747
10e84b97 1748 if (!numabalancing_enabled)
1a687c2e
MG
1749 return;
1750
9ff1d9ff
MG
1751 /* for example, ksmd faulting in a user's mm */
1752 if (!p->mm)
1753 return;
1754
82727018
RR
1755 /* Do not worry about placement if exiting */
1756 if (p->state == TASK_DEAD)
1757 return;
1758
f809ca9a 1759 /* Allocate buffer to track faults on a per-node basis */
ff1df896 1760 if (unlikely(!p->numa_faults_memory)) {
be1e4e76
RR
1761 int size = sizeof(*p->numa_faults_memory) *
1762 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
f809ca9a 1763
be1e4e76 1764 p->numa_faults_memory = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
ff1df896 1765 if (!p->numa_faults_memory)
f809ca9a 1766 return;
745d6147 1767
ff1df896 1768 BUG_ON(p->numa_faults_buffer_memory);
be1e4e76
RR
1769 /*
1770 * The averaged statistics, shared & private, memory & cpu,
1771 * occupy the first half of the array. The second half of the
1772 * array is for current counters, which are averaged into the
1773 * first set by task_numa_placement.
1774 */
50ec8a40
RR
1775 p->numa_faults_cpu = p->numa_faults_memory + (2 * nr_node_ids);
1776 p->numa_faults_buffer_memory = p->numa_faults_memory + (4 * nr_node_ids);
1777 p->numa_faults_buffer_cpu = p->numa_faults_memory + (6 * nr_node_ids);
83e1d2cd 1778 p->total_numa_faults = 0;
04bb2f94 1779 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
f809ca9a 1780 }
cbee9f88 1781
8c8a743c
PZ
1782 /*
1783 * First accesses are treated as private, otherwise consider accesses
1784 * to be private if the accessing pid has not changed
1785 */
1786 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
1787 priv = 1;
1788 } else {
1789 priv = cpupid_match_pid(p, last_cpupid);
6688cc05 1790 if (!priv && !(flags & TNF_NO_GROUP))
3e6a9418 1791 task_numa_group(p, last_cpupid, flags, &priv);
8c8a743c
PZ
1792 }
1793
cbee9f88 1794 task_numa_placement(p);
f809ca9a 1795
2739d3ee
RR
1796 /*
1797 * Retry task to preferred node migration periodically, in case it
1798 * case it previously failed, or the scheduler moved us.
1799 */
1800 if (time_after(jiffies, p->numa_migrate_retry))
6b9a7460
MG
1801 numa_migrate_preferred(p);
1802
b32e86b4
IM
1803 if (migrated)
1804 p->numa_pages_migrated += pages;
1805
58b46da3
RR
1806 p->numa_faults_buffer_memory[task_faults_idx(mem_node, priv)] += pages;
1807 p->numa_faults_buffer_cpu[task_faults_idx(cpu_node, priv)] += pages;
04bb2f94 1808 p->numa_faults_locality[!!(flags & TNF_FAULT_LOCAL)] += pages;
cbee9f88
PZ
1809}
1810
6e5fb223
PZ
1811static void reset_ptenuma_scan(struct task_struct *p)
1812{
1813 ACCESS_ONCE(p->mm->numa_scan_seq)++;
1814 p->mm->numa_scan_offset = 0;
1815}
1816
cbee9f88
PZ
1817/*
1818 * The expensive part of numa migration is done from task_work context.
1819 * Triggered from task_tick_numa().
1820 */
1821void task_numa_work(struct callback_head *work)
1822{
1823 unsigned long migrate, next_scan, now = jiffies;
1824 struct task_struct *p = current;
1825 struct mm_struct *mm = p->mm;
6e5fb223 1826 struct vm_area_struct *vma;
9f40604c 1827 unsigned long start, end;
598f0ec0 1828 unsigned long nr_pte_updates = 0;
9f40604c 1829 long pages;
cbee9f88
PZ
1830
1831 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
1832
1833 work->next = work; /* protect against double add */
1834 /*
1835 * Who cares about NUMA placement when they're dying.
1836 *
1837 * NOTE: make sure not to dereference p->mm before this check,
1838 * exit_task_work() happens _after_ exit_mm() so we could be called
1839 * without p->mm even though we still had it when we enqueued this
1840 * work.
1841 */
1842 if (p->flags & PF_EXITING)
1843 return;
1844
930aa174 1845 if (!mm->numa_next_scan) {
7e8d16b6
MG
1846 mm->numa_next_scan = now +
1847 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
b8593bfd
MG
1848 }
1849
cbee9f88
PZ
1850 /*
1851 * Enforce maximal scan/migration frequency..
1852 */
1853 migrate = mm->numa_next_scan;
1854 if (time_before(now, migrate))
1855 return;
1856
598f0ec0
MG
1857 if (p->numa_scan_period == 0) {
1858 p->numa_scan_period_max = task_scan_max(p);
1859 p->numa_scan_period = task_scan_min(p);
1860 }
cbee9f88 1861
fb003b80 1862 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
cbee9f88
PZ
1863 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
1864 return;
1865
19a78d11
PZ
1866 /*
1867 * Delay this task enough that another task of this mm will likely win
1868 * the next time around.
1869 */
1870 p->node_stamp += 2 * TICK_NSEC;
1871
9f40604c
MG
1872 start = mm->numa_scan_offset;
1873 pages = sysctl_numa_balancing_scan_size;
1874 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
1875 if (!pages)
1876 return;
cbee9f88 1877
6e5fb223 1878 down_read(&mm->mmap_sem);
9f40604c 1879 vma = find_vma(mm, start);
6e5fb223
PZ
1880 if (!vma) {
1881 reset_ptenuma_scan(p);
9f40604c 1882 start = 0;
6e5fb223
PZ
1883 vma = mm->mmap;
1884 }
9f40604c 1885 for (; vma; vma = vma->vm_next) {
fc314724 1886 if (!vma_migratable(vma) || !vma_policy_mof(p, vma))
6e5fb223
PZ
1887 continue;
1888
4591ce4f
MG
1889 /*
1890 * Shared library pages mapped by multiple processes are not
1891 * migrated as it is expected they are cache replicated. Avoid
1892 * hinting faults in read-only file-backed mappings or the vdso
1893 * as migrating the pages will be of marginal benefit.
1894 */
1895 if (!vma->vm_mm ||
1896 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
1897 continue;
1898
3c67f474
MG
1899 /*
1900 * Skip inaccessible VMAs to avoid any confusion between
1901 * PROT_NONE and NUMA hinting ptes
1902 */
1903 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
1904 continue;
4591ce4f 1905
9f40604c
MG
1906 do {
1907 start = max(start, vma->vm_start);
1908 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
1909 end = min(end, vma->vm_end);
598f0ec0
MG
1910 nr_pte_updates += change_prot_numa(vma, start, end);
1911
1912 /*
1913 * Scan sysctl_numa_balancing_scan_size but ensure that
1914 * at least one PTE is updated so that unused virtual
1915 * address space is quickly skipped.
1916 */
1917 if (nr_pte_updates)
1918 pages -= (end - start) >> PAGE_SHIFT;
6e5fb223 1919
9f40604c
MG
1920 start = end;
1921 if (pages <= 0)
1922 goto out;
1923 } while (end != vma->vm_end);
cbee9f88 1924 }
6e5fb223 1925
9f40604c 1926out:
6e5fb223 1927 /*
c69307d5
PZ
1928 * It is possible to reach the end of the VMA list but the last few
1929 * VMAs are not guaranteed to the vma_migratable. If they are not, we
1930 * would find the !migratable VMA on the next scan but not reset the
1931 * scanner to the start so check it now.
6e5fb223
PZ
1932 */
1933 if (vma)
9f40604c 1934 mm->numa_scan_offset = start;
6e5fb223
PZ
1935 else
1936 reset_ptenuma_scan(p);
1937 up_read(&mm->mmap_sem);
cbee9f88
PZ
1938}
1939
1940/*
1941 * Drive the periodic memory faults..
1942 */
1943void task_tick_numa(struct rq *rq, struct task_struct *curr)
1944{
1945 struct callback_head *work = &curr->numa_work;
1946 u64 period, now;
1947
1948 /*
1949 * We don't care about NUMA placement if we don't have memory.
1950 */
1951 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
1952 return;
1953
1954 /*
1955 * Using runtime rather than walltime has the dual advantage that
1956 * we (mostly) drive the selection from busy threads and that the
1957 * task needs to have done some actual work before we bother with
1958 * NUMA placement.
1959 */
1960 now = curr->se.sum_exec_runtime;
1961 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
1962
1963 if (now - curr->node_stamp > period) {
4b96a29b 1964 if (!curr->node_stamp)
598f0ec0 1965 curr->numa_scan_period = task_scan_min(curr);
19a78d11 1966 curr->node_stamp += period;
cbee9f88
PZ
1967
1968 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
1969 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
1970 task_work_add(curr, work, true);
1971 }
1972 }
1973}
1974#else
1975static void task_tick_numa(struct rq *rq, struct task_struct *curr)
1976{
1977}
0ec8aa00
PZ
1978
1979static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1980{
1981}
1982
1983static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1984{
1985}
cbee9f88
PZ
1986#endif /* CONFIG_NUMA_BALANCING */
1987
30cfdcfc
DA
1988static void
1989account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1990{
1991 update_load_add(&cfs_rq->load, se->load.weight);
c09595f6 1992 if (!parent_entity(se))
029632fb 1993 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
367456c7 1994#ifdef CONFIG_SMP
0ec8aa00
PZ
1995 if (entity_is_task(se)) {
1996 struct rq *rq = rq_of(cfs_rq);
1997
1998 account_numa_enqueue(rq, task_of(se));
1999 list_add(&se->group_node, &rq->cfs_tasks);
2000 }
367456c7 2001#endif
30cfdcfc 2002 cfs_rq->nr_running++;
30cfdcfc
DA
2003}
2004
2005static void
2006account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2007{
2008 update_load_sub(&cfs_rq->load, se->load.weight);
c09595f6 2009 if (!parent_entity(se))
029632fb 2010 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
0ec8aa00
PZ
2011 if (entity_is_task(se)) {
2012 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
b87f1724 2013 list_del_init(&se->group_node);
0ec8aa00 2014 }
30cfdcfc 2015 cfs_rq->nr_running--;
30cfdcfc
DA
2016}
2017
3ff6dcac
YZ
2018#ifdef CONFIG_FAIR_GROUP_SCHED
2019# ifdef CONFIG_SMP
cf5f0acf
PZ
2020static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
2021{
2022 long tg_weight;
2023
2024 /*
2025 * Use this CPU's actual weight instead of the last load_contribution
2026 * to gain a more accurate current total weight. See
2027 * update_cfs_rq_load_contribution().
2028 */
bf5b986e 2029 tg_weight = atomic_long_read(&tg->load_avg);
82958366 2030 tg_weight -= cfs_rq->tg_load_contrib;
cf5f0acf
PZ
2031 tg_weight += cfs_rq->load.weight;
2032
2033 return tg_weight;
2034}
2035
6d5ab293 2036static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
3ff6dcac 2037{
cf5f0acf 2038 long tg_weight, load, shares;
3ff6dcac 2039
cf5f0acf 2040 tg_weight = calc_tg_weight(tg, cfs_rq);
6d5ab293 2041 load = cfs_rq->load.weight;
3ff6dcac 2042
3ff6dcac 2043 shares = (tg->shares * load);
cf5f0acf
PZ
2044 if (tg_weight)
2045 shares /= tg_weight;
3ff6dcac
YZ
2046
2047 if (shares < MIN_SHARES)
2048 shares = MIN_SHARES;
2049 if (shares > tg->shares)
2050 shares = tg->shares;
2051
2052 return shares;
2053}
3ff6dcac 2054# else /* CONFIG_SMP */
6d5ab293 2055static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
3ff6dcac
YZ
2056{
2057 return tg->shares;
2058}
3ff6dcac 2059# endif /* CONFIG_SMP */
2069dd75
PZ
2060static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2061 unsigned long weight)
2062{
19e5eebb
PT
2063 if (se->on_rq) {
2064 /* commit outstanding execution time */
2065 if (cfs_rq->curr == se)
2066 update_curr(cfs_rq);
2069dd75 2067 account_entity_dequeue(cfs_rq, se);
19e5eebb 2068 }
2069dd75
PZ
2069
2070 update_load_set(&se->load, weight);
2071
2072 if (se->on_rq)
2073 account_entity_enqueue(cfs_rq, se);
2074}
2075
82958366
PT
2076static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2077
6d5ab293 2078static void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
2079{
2080 struct task_group *tg;
2081 struct sched_entity *se;
3ff6dcac 2082 long shares;
2069dd75 2083
2069dd75
PZ
2084 tg = cfs_rq->tg;
2085 se = tg->se[cpu_of(rq_of(cfs_rq))];
64660c86 2086 if (!se || throttled_hierarchy(cfs_rq))
2069dd75 2087 return;
3ff6dcac
YZ
2088#ifndef CONFIG_SMP
2089 if (likely(se->load.weight == tg->shares))
2090 return;
2091#endif
6d5ab293 2092 shares = calc_cfs_shares(cfs_rq, tg);
2069dd75
PZ
2093
2094 reweight_entity(cfs_rq_of(se), se, shares);
2095}
2096#else /* CONFIG_FAIR_GROUP_SCHED */
6d5ab293 2097static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
2098{
2099}
2100#endif /* CONFIG_FAIR_GROUP_SCHED */
2101
141965c7 2102#ifdef CONFIG_SMP
5b51f2f8
PT
2103/*
2104 * We choose a half-life close to 1 scheduling period.
2105 * Note: The tables below are dependent on this value.
2106 */
2107#define LOAD_AVG_PERIOD 32
2108#define LOAD_AVG_MAX 47742 /* maximum possible load avg */
2109#define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
2110
2111/* Precomputed fixed inverse multiplies for multiplication by y^n */
2112static const u32 runnable_avg_yN_inv[] = {
2113 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2114 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2115 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2116 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2117 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2118 0x85aac367, 0x82cd8698,
2119};
2120
2121/*
2122 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2123 * over-estimates when re-combining.
2124 */
2125static const u32 runnable_avg_yN_sum[] = {
2126 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2127 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2128 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2129};
2130
9d85f21c
PT
2131/*
2132 * Approximate:
2133 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2134 */
2135static __always_inline u64 decay_load(u64 val, u64 n)
2136{
5b51f2f8
PT
2137 unsigned int local_n;
2138
2139 if (!n)
2140 return val;
2141 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2142 return 0;
2143
2144 /* after bounds checking we can collapse to 32-bit */
2145 local_n = n;
2146
2147 /*
2148 * As y^PERIOD = 1/2, we can combine
2149 * y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
2150 * With a look-up table which covers k^n (n<PERIOD)
2151 *
2152 * To achieve constant time decay_load.
2153 */
2154 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2155 val >>= local_n / LOAD_AVG_PERIOD;
2156 local_n %= LOAD_AVG_PERIOD;
9d85f21c
PT
2157 }
2158
5b51f2f8
PT
2159 val *= runnable_avg_yN_inv[local_n];
2160 /* We don't use SRR here since we always want to round down. */
2161 return val >> 32;
2162}
2163
2164/*
2165 * For updates fully spanning n periods, the contribution to runnable
2166 * average will be: \Sum 1024*y^n
2167 *
2168 * We can compute this reasonably efficiently by combining:
2169 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2170 */
2171static u32 __compute_runnable_contrib(u64 n)
2172{
2173 u32 contrib = 0;
2174
2175 if (likely(n <= LOAD_AVG_PERIOD))
2176 return runnable_avg_yN_sum[n];
2177 else if (unlikely(n >= LOAD_AVG_MAX_N))
2178 return LOAD_AVG_MAX;
2179
2180 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
2181 do {
2182 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
2183 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
2184
2185 n -= LOAD_AVG_PERIOD;
2186 } while (n > LOAD_AVG_PERIOD);
2187
2188 contrib = decay_load(contrib, n);
2189 return contrib + runnable_avg_yN_sum[n];
9d85f21c
PT
2190}
2191
2192/*
2193 * We can represent the historical contribution to runnable average as the
2194 * coefficients of a geometric series. To do this we sub-divide our runnable
2195 * history into segments of approximately 1ms (1024us); label the segment that
2196 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2197 *
2198 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2199 * p0 p1 p2
2200 * (now) (~1ms ago) (~2ms ago)
2201 *
2202 * Let u_i denote the fraction of p_i that the entity was runnable.
2203 *
2204 * We then designate the fractions u_i as our co-efficients, yielding the
2205 * following representation of historical load:
2206 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2207 *
2208 * We choose y based on the with of a reasonably scheduling period, fixing:
2209 * y^32 = 0.5
2210 *
2211 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2212 * approximately half as much as the contribution to load within the last ms
2213 * (u_0).
2214 *
2215 * When a period "rolls over" and we have new u_0`, multiplying the previous
2216 * sum again by y is sufficient to update:
2217 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2218 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2219 */
2220static __always_inline int __update_entity_runnable_avg(u64 now,
2221 struct sched_avg *sa,
2222 int runnable)
2223{
5b51f2f8
PT
2224 u64 delta, periods;
2225 u32 runnable_contrib;
9d85f21c
PT
2226 int delta_w, decayed = 0;
2227
2228 delta = now - sa->last_runnable_update;
2229 /*
2230 * This should only happen when time goes backwards, which it
2231 * unfortunately does during sched clock init when we swap over to TSC.
2232 */
2233 if ((s64)delta < 0) {
2234 sa->last_runnable_update = now;
2235 return 0;
2236 }
2237
2238 /*
2239 * Use 1024ns as the unit of measurement since it's a reasonable
2240 * approximation of 1us and fast to compute.
2241 */
2242 delta >>= 10;
2243 if (!delta)
2244 return 0;
2245 sa->last_runnable_update = now;
2246
2247 /* delta_w is the amount already accumulated against our next period */
2248 delta_w = sa->runnable_avg_period % 1024;
2249 if (delta + delta_w >= 1024) {
2250 /* period roll-over */
2251 decayed = 1;
2252
2253 /*
2254 * Now that we know we're crossing a period boundary, figure
2255 * out how much from delta we need to complete the current
2256 * period and accrue it.
2257 */
2258 delta_w = 1024 - delta_w;
5b51f2f8
PT
2259 if (runnable)
2260 sa->runnable_avg_sum += delta_w;
2261 sa->runnable_avg_period += delta_w;
2262
2263 delta -= delta_w;
2264
2265 /* Figure out how many additional periods this update spans */
2266 periods = delta / 1024;
2267 delta %= 1024;
2268
2269 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
2270 periods + 1);
2271 sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
2272 periods + 1);
2273
2274 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
2275 runnable_contrib = __compute_runnable_contrib(periods);
2276 if (runnable)
2277 sa->runnable_avg_sum += runnable_contrib;
2278 sa->runnable_avg_period += runnable_contrib;
9d85f21c
PT
2279 }
2280
2281 /* Remainder of delta accrued against u_0` */
2282 if (runnable)
2283 sa->runnable_avg_sum += delta;
2284 sa->runnable_avg_period += delta;
2285
2286 return decayed;
2287}
2288
9ee474f5 2289/* Synchronize an entity's decay with its parenting cfs_rq.*/
aff3e498 2290static inline u64 __synchronize_entity_decay(struct sched_entity *se)
9ee474f5
PT
2291{
2292 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2293 u64 decays = atomic64_read(&cfs_rq->decay_counter);
2294
2295 decays -= se->avg.decay_count;
2296 if (!decays)
aff3e498 2297 return 0;
9ee474f5
PT
2298
2299 se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
2300 se->avg.decay_count = 0;
aff3e498
PT
2301
2302 return decays;
9ee474f5
PT
2303}
2304
c566e8e9
PT
2305#ifdef CONFIG_FAIR_GROUP_SCHED
2306static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
2307 int force_update)
2308{
2309 struct task_group *tg = cfs_rq->tg;
bf5b986e 2310 long tg_contrib;
c566e8e9
PT
2311
2312 tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
2313 tg_contrib -= cfs_rq->tg_load_contrib;
2314
bf5b986e
AS
2315 if (force_update || abs(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
2316 atomic_long_add(tg_contrib, &tg->load_avg);
c566e8e9
PT
2317 cfs_rq->tg_load_contrib += tg_contrib;
2318 }
2319}
8165e145 2320
bb17f655
PT
2321/*
2322 * Aggregate cfs_rq runnable averages into an equivalent task_group
2323 * representation for computing load contributions.
2324 */
2325static inline void __update_tg_runnable_avg(struct sched_avg *sa,
2326 struct cfs_rq *cfs_rq)
2327{
2328 struct task_group *tg = cfs_rq->tg;
2329 long contrib;
2330
2331 /* The fraction of a cpu used by this cfs_rq */
85b088e9 2332 contrib = div_u64((u64)sa->runnable_avg_sum << NICE_0_SHIFT,
bb17f655
PT
2333 sa->runnable_avg_period + 1);
2334 contrib -= cfs_rq->tg_runnable_contrib;
2335
2336 if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) {
2337 atomic_add(contrib, &tg->runnable_avg);
2338 cfs_rq->tg_runnable_contrib += contrib;
2339 }
2340}
2341
8165e145
PT
2342static inline void __update_group_entity_contrib(struct sched_entity *se)
2343{
2344 struct cfs_rq *cfs_rq = group_cfs_rq(se);
2345 struct task_group *tg = cfs_rq->tg;
bb17f655
PT
2346 int runnable_avg;
2347
8165e145
PT
2348 u64 contrib;
2349
2350 contrib = cfs_rq->tg_load_contrib * tg->shares;
bf5b986e
AS
2351 se->avg.load_avg_contrib = div_u64(contrib,
2352 atomic_long_read(&tg->load_avg) + 1);
bb17f655
PT
2353
2354 /*
2355 * For group entities we need to compute a correction term in the case
2356 * that they are consuming <1 cpu so that we would contribute the same
2357 * load as a task of equal weight.
2358 *
2359 * Explicitly co-ordinating this measurement would be expensive, but
2360 * fortunately the sum of each cpus contribution forms a usable
2361 * lower-bound on the true value.
2362 *
2363 * Consider the aggregate of 2 contributions. Either they are disjoint
2364 * (and the sum represents true value) or they are disjoint and we are
2365 * understating by the aggregate of their overlap.
2366 *
2367 * Extending this to N cpus, for a given overlap, the maximum amount we
2368 * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
2369 * cpus that overlap for this interval and w_i is the interval width.
2370 *
2371 * On a small machine; the first term is well-bounded which bounds the
2372 * total error since w_i is a subset of the period. Whereas on a
2373 * larger machine, while this first term can be larger, if w_i is the
2374 * of consequential size guaranteed to see n_i*w_i quickly converge to
2375 * our upper bound of 1-cpu.
2376 */
2377 runnable_avg = atomic_read(&tg->runnable_avg);
2378 if (runnable_avg < NICE_0_LOAD) {
2379 se->avg.load_avg_contrib *= runnable_avg;
2380 se->avg.load_avg_contrib >>= NICE_0_SHIFT;
2381 }
8165e145 2382}
c566e8e9
PT
2383#else
2384static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
2385 int force_update) {}
bb17f655
PT
2386static inline void __update_tg_runnable_avg(struct sched_avg *sa,
2387 struct cfs_rq *cfs_rq) {}
8165e145 2388static inline void __update_group_entity_contrib(struct sched_entity *se) {}
c566e8e9
PT
2389#endif
2390
8165e145
PT
2391static inline void __update_task_entity_contrib(struct sched_entity *se)
2392{
2393 u32 contrib;
2394
2395 /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
2396 contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
2397 contrib /= (se->avg.runnable_avg_period + 1);
2398 se->avg.load_avg_contrib = scale_load(contrib);
2399}
2400
2dac754e
PT
2401/* Compute the current contribution to load_avg by se, return any delta */
2402static long __update_entity_load_avg_contrib(struct sched_entity *se)
2403{
2404 long old_contrib = se->avg.load_avg_contrib;
2405
8165e145
PT
2406 if (entity_is_task(se)) {
2407 __update_task_entity_contrib(se);
2408 } else {
bb17f655 2409 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
8165e145
PT
2410 __update_group_entity_contrib(se);
2411 }
2dac754e
PT
2412
2413 return se->avg.load_avg_contrib - old_contrib;
2414}
2415
9ee474f5
PT
2416static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
2417 long load_contrib)
2418{
2419 if (likely(load_contrib < cfs_rq->blocked_load_avg))
2420 cfs_rq->blocked_load_avg -= load_contrib;
2421 else
2422 cfs_rq->blocked_load_avg = 0;
2423}
2424
f1b17280
PT
2425static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
2426
9d85f21c 2427/* Update a sched_entity's runnable average */
9ee474f5
PT
2428static inline void update_entity_load_avg(struct sched_entity *se,
2429 int update_cfs_rq)
9d85f21c 2430{
2dac754e
PT
2431 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2432 long contrib_delta;
f1b17280 2433 u64 now;
2dac754e 2434
f1b17280
PT
2435 /*
2436 * For a group entity we need to use their owned cfs_rq_clock_task() in
2437 * case they are the parent of a throttled hierarchy.
2438 */
2439 if (entity_is_task(se))
2440 now = cfs_rq_clock_task(cfs_rq);
2441 else
2442 now = cfs_rq_clock_task(group_cfs_rq(se));
2443
2444 if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq))
2dac754e
PT
2445 return;
2446
2447 contrib_delta = __update_entity_load_avg_contrib(se);
9ee474f5
PT
2448
2449 if (!update_cfs_rq)
2450 return;
2451
2dac754e
PT
2452 if (se->on_rq)
2453 cfs_rq->runnable_load_avg += contrib_delta;
9ee474f5
PT
2454 else
2455 subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
2456}
2457
2458/*
2459 * Decay the load contributed by all blocked children and account this so that
2460 * their contribution may appropriately discounted when they wake up.
2461 */
aff3e498 2462static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
9ee474f5 2463{
f1b17280 2464 u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
9ee474f5
PT
2465 u64 decays;
2466
2467 decays = now - cfs_rq->last_decay;
aff3e498 2468 if (!decays && !force_update)
9ee474f5
PT
2469 return;
2470
2509940f
AS
2471 if (atomic_long_read(&cfs_rq->removed_load)) {
2472 unsigned long removed_load;
2473 removed_load = atomic_long_xchg(&cfs_rq->removed_load, 0);
aff3e498
PT
2474 subtract_blocked_load_contrib(cfs_rq, removed_load);
2475 }
9ee474f5 2476
aff3e498
PT
2477 if (decays) {
2478 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
2479 decays);
2480 atomic64_add(decays, &cfs_rq->decay_counter);
2481 cfs_rq->last_decay = now;
2482 }
c566e8e9
PT
2483
2484 __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
9d85f21c 2485}
18bf2805
BS
2486
2487static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
2488{
78becc27 2489 __update_entity_runnable_avg(rq_clock_task(rq), &rq->avg, runnable);
bb17f655 2490 __update_tg_runnable_avg(&rq->avg, &rq->cfs);
18bf2805 2491}
2dac754e
PT
2492
2493/* Add the load generated by se into cfs_rq's child load-average */
2494static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
2495 struct sched_entity *se,
2496 int wakeup)
2dac754e 2497{
aff3e498
PT
2498 /*
2499 * We track migrations using entity decay_count <= 0, on a wake-up
2500 * migration we use a negative decay count to track the remote decays
2501 * accumulated while sleeping.
a75cdaa9
AS
2502 *
2503 * Newly forked tasks are enqueued with se->avg.decay_count == 0, they
2504 * are seen by enqueue_entity_load_avg() as a migration with an already
2505 * constructed load_avg_contrib.
aff3e498
PT
2506 */
2507 if (unlikely(se->avg.decay_count <= 0)) {
78becc27 2508 se->avg.last_runnable_update = rq_clock_task(rq_of(cfs_rq));
aff3e498
PT
2509 if (se->avg.decay_count) {
2510 /*
2511 * In a wake-up migration we have to approximate the
2512 * time sleeping. This is because we can't synchronize
2513 * clock_task between the two cpus, and it is not
2514 * guaranteed to be read-safe. Instead, we can
2515 * approximate this using our carried decays, which are
2516 * explicitly atomically readable.
2517 */
2518 se->avg.last_runnable_update -= (-se->avg.decay_count)
2519 << 20;
2520 update_entity_load_avg(se, 0);
2521 /* Indicate that we're now synchronized and on-rq */
2522 se->avg.decay_count = 0;
2523 }
9ee474f5
PT
2524 wakeup = 0;
2525 } else {
9390675a 2526 __synchronize_entity_decay(se);
9ee474f5
PT
2527 }
2528
aff3e498
PT
2529 /* migrated tasks did not contribute to our blocked load */
2530 if (wakeup) {
9ee474f5 2531 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
aff3e498
PT
2532 update_entity_load_avg(se, 0);
2533 }
9ee474f5 2534
2dac754e 2535 cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
aff3e498
PT
2536 /* we force update consideration on load-balancer moves */
2537 update_cfs_rq_blocked_load(cfs_rq, !wakeup);
2dac754e
PT
2538}
2539
9ee474f5
PT
2540/*
2541 * Remove se's load from this cfs_rq child load-average, if the entity is
2542 * transitioning to a blocked state we track its projected decay using
2543 * blocked_load_avg.
2544 */
2dac754e 2545static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
2546 struct sched_entity *se,
2547 int sleep)
2dac754e 2548{
9ee474f5 2549 update_entity_load_avg(se, 1);
aff3e498
PT
2550 /* we force update consideration on load-balancer moves */
2551 update_cfs_rq_blocked_load(cfs_rq, !sleep);
9ee474f5 2552
2dac754e 2553 cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
9ee474f5
PT
2554 if (sleep) {
2555 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
2556 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
2557 } /* migrations, e.g. sleep=0 leave decay_count == 0 */
2dac754e 2558}
642dbc39
VG
2559
2560/*
2561 * Update the rq's load with the elapsed running time before entering
2562 * idle. if the last scheduled task is not a CFS task, idle_enter will
2563 * be the only way to update the runnable statistic.
2564 */
2565void idle_enter_fair(struct rq *this_rq)
2566{
2567 update_rq_runnable_avg(this_rq, 1);
2568}
2569
2570/*
2571 * Update the rq's load with the elapsed idle time before a task is
2572 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
2573 * be the only way to update the runnable statistic.
2574 */
2575void idle_exit_fair(struct rq *this_rq)
2576{
2577 update_rq_runnable_avg(this_rq, 0);
2578}
2579
9d85f21c 2580#else
9ee474f5
PT
2581static inline void update_entity_load_avg(struct sched_entity *se,
2582 int update_cfs_rq) {}
18bf2805 2583static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
2dac754e 2584static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
2585 struct sched_entity *se,
2586 int wakeup) {}
2dac754e 2587static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
9ee474f5
PT
2588 struct sched_entity *se,
2589 int sleep) {}
aff3e498
PT
2590static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
2591 int force_update) {}
9d85f21c
PT
2592#endif
2593
2396af69 2594static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 2595{
bf0f6f24 2596#ifdef CONFIG_SCHEDSTATS
e414314c
PZ
2597 struct task_struct *tsk = NULL;
2598
2599 if (entity_is_task(se))
2600 tsk = task_of(se);
2601
41acab88 2602 if (se->statistics.sleep_start) {
78becc27 2603 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
bf0f6f24
IM
2604
2605 if ((s64)delta < 0)
2606 delta = 0;
2607
41acab88
LDM
2608 if (unlikely(delta > se->statistics.sleep_max))
2609 se->statistics.sleep_max = delta;
bf0f6f24 2610
8c79a045 2611 se->statistics.sleep_start = 0;
41acab88 2612 se->statistics.sum_sleep_runtime += delta;
9745512c 2613
768d0c27 2614 if (tsk) {
e414314c 2615 account_scheduler_latency(tsk, delta >> 10, 1);
768d0c27
PZ
2616 trace_sched_stat_sleep(tsk, delta);
2617 }
bf0f6f24 2618 }
41acab88 2619 if (se->statistics.block_start) {
78becc27 2620 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
bf0f6f24
IM
2621
2622 if ((s64)delta < 0)
2623 delta = 0;
2624
41acab88
LDM
2625 if (unlikely(delta > se->statistics.block_max))
2626 se->statistics.block_max = delta;
bf0f6f24 2627
8c79a045 2628 se->statistics.block_start = 0;
41acab88 2629 se->statistics.sum_sleep_runtime += delta;
30084fbd 2630
e414314c 2631 if (tsk) {
8f0dfc34 2632 if (tsk->in_iowait) {
41acab88
LDM
2633 se->statistics.iowait_sum += delta;
2634 se->statistics.iowait_count++;
768d0c27 2635 trace_sched_stat_iowait(tsk, delta);
8f0dfc34
AV
2636 }
2637
b781a602
AV
2638 trace_sched_stat_blocked(tsk, delta);
2639
e414314c
PZ
2640 /*
2641 * Blocking time is in units of nanosecs, so shift by
2642 * 20 to get a milliseconds-range estimation of the
2643 * amount of time that the task spent sleeping:
2644 */
2645 if (unlikely(prof_on == SLEEP_PROFILING)) {
2646 profile_hits(SLEEP_PROFILING,
2647 (void *)get_wchan(tsk),
2648 delta >> 20);
2649 }
2650 account_scheduler_latency(tsk, delta >> 10, 0);
30084fbd 2651 }
bf0f6f24
IM
2652 }
2653#endif
2654}
2655
ddc97297
PZ
2656static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
2657{
2658#ifdef CONFIG_SCHED_DEBUG
2659 s64 d = se->vruntime - cfs_rq->min_vruntime;
2660
2661 if (d < 0)
2662 d = -d;
2663
2664 if (d > 3*sysctl_sched_latency)
2665 schedstat_inc(cfs_rq, nr_spread_over);
2666#endif
2667}
2668
aeb73b04
PZ
2669static void
2670place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
2671{
1af5f730 2672 u64 vruntime = cfs_rq->min_vruntime;
94dfb5e7 2673
2cb8600e
PZ
2674 /*
2675 * The 'current' period is already promised to the current tasks,
2676 * however the extra weight of the new task will slow them down a
2677 * little, place the new task so that it fits in the slot that
2678 * stays open at the end.
2679 */
94dfb5e7 2680 if (initial && sched_feat(START_DEBIT))
f9c0b095 2681 vruntime += sched_vslice(cfs_rq, se);
aeb73b04 2682
a2e7a7eb 2683 /* sleeps up to a single latency don't count. */
5ca9880c 2684 if (!initial) {
a2e7a7eb 2685 unsigned long thresh = sysctl_sched_latency;
a7be37ac 2686
a2e7a7eb
MG
2687 /*
2688 * Halve their sleep time's effect, to allow
2689 * for a gentler effect of sleepers:
2690 */
2691 if (sched_feat(GENTLE_FAIR_SLEEPERS))
2692 thresh >>= 1;
51e0304c 2693
a2e7a7eb 2694 vruntime -= thresh;
aeb73b04
PZ
2695 }
2696
b5d9d734 2697 /* ensure we never gain time by being placed backwards. */
16c8f1c7 2698 se->vruntime = max_vruntime(se->vruntime, vruntime);
aeb73b04
PZ
2699}
2700
d3d9dc33
PT
2701static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
2702
bf0f6f24 2703static void
88ec22d3 2704enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 2705{
88ec22d3
PZ
2706 /*
2707 * Update the normalized vruntime before updating min_vruntime
0fc576d5 2708 * through calling update_curr().
88ec22d3 2709 */
371fd7e7 2710 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
88ec22d3
PZ
2711 se->vruntime += cfs_rq->min_vruntime;
2712
bf0f6f24 2713 /*
a2a2d680 2714 * Update run-time statistics of the 'current'.
bf0f6f24 2715 */
b7cc0896 2716 update_curr(cfs_rq);
f269ae04 2717 enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
17bc14b7
LT
2718 account_entity_enqueue(cfs_rq, se);
2719 update_cfs_shares(cfs_rq);
bf0f6f24 2720
88ec22d3 2721 if (flags & ENQUEUE_WAKEUP) {
aeb73b04 2722 place_entity(cfs_rq, se, 0);
2396af69 2723 enqueue_sleeper(cfs_rq, se);
e9acbff6 2724 }
bf0f6f24 2725
d2417e5a 2726 update_stats_enqueue(cfs_rq, se);
ddc97297 2727 check_spread(cfs_rq, se);
83b699ed
SV
2728 if (se != cfs_rq->curr)
2729 __enqueue_entity(cfs_rq, se);
2069dd75 2730 se->on_rq = 1;
3d4b47b4 2731
d3d9dc33 2732 if (cfs_rq->nr_running == 1) {
3d4b47b4 2733 list_add_leaf_cfs_rq(cfs_rq);
d3d9dc33
PT
2734 check_enqueue_throttle(cfs_rq);
2735 }
bf0f6f24
IM
2736}
2737
2c13c919 2738static void __clear_buddies_last(struct sched_entity *se)
2002c695 2739{
2c13c919
RR
2740 for_each_sched_entity(se) {
2741 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 2742 if (cfs_rq->last != se)
2c13c919 2743 break;
f1044799
PZ
2744
2745 cfs_rq->last = NULL;
2c13c919
RR
2746 }
2747}
2002c695 2748
2c13c919
RR
2749static void __clear_buddies_next(struct sched_entity *se)
2750{
2751 for_each_sched_entity(se) {
2752 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 2753 if (cfs_rq->next != se)
2c13c919 2754 break;
f1044799
PZ
2755
2756 cfs_rq->next = NULL;
2c13c919 2757 }
2002c695
PZ
2758}
2759
ac53db59
RR
2760static void __clear_buddies_skip(struct sched_entity *se)
2761{
2762 for_each_sched_entity(se) {
2763 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 2764 if (cfs_rq->skip != se)
ac53db59 2765 break;
f1044799
PZ
2766
2767 cfs_rq->skip = NULL;
ac53db59
RR
2768 }
2769}
2770
a571bbea
PZ
2771static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
2772{
2c13c919
RR
2773 if (cfs_rq->last == se)
2774 __clear_buddies_last(se);
2775
2776 if (cfs_rq->next == se)
2777 __clear_buddies_next(se);
ac53db59
RR
2778
2779 if (cfs_rq->skip == se)
2780 __clear_buddies_skip(se);
a571bbea
PZ
2781}
2782
6c16a6dc 2783static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d8b4986d 2784
bf0f6f24 2785static void
371fd7e7 2786dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 2787{
a2a2d680
DA
2788 /*
2789 * Update run-time statistics of the 'current'.
2790 */
2791 update_curr(cfs_rq);
17bc14b7 2792 dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
a2a2d680 2793
19b6a2e3 2794 update_stats_dequeue(cfs_rq, se);
371fd7e7 2795 if (flags & DEQUEUE_SLEEP) {
67e9fb2a 2796#ifdef CONFIG_SCHEDSTATS
bf0f6f24
IM
2797 if (entity_is_task(se)) {
2798 struct task_struct *tsk = task_of(se);
2799
2800 if (tsk->state & TASK_INTERRUPTIBLE)
78becc27 2801 se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
bf0f6f24 2802 if (tsk->state & TASK_UNINTERRUPTIBLE)
78becc27 2803 se->statistics.block_start = rq_clock(rq_of(cfs_rq));
bf0f6f24 2804 }
db36cc7d 2805#endif
67e9fb2a
PZ
2806 }
2807
2002c695 2808 clear_buddies(cfs_rq, se);
4793241b 2809
83b699ed 2810 if (se != cfs_rq->curr)
30cfdcfc 2811 __dequeue_entity(cfs_rq, se);
17bc14b7 2812 se->on_rq = 0;
30cfdcfc 2813 account_entity_dequeue(cfs_rq, se);
88ec22d3
PZ
2814
2815 /*
2816 * Normalize the entity after updating the min_vruntime because the
2817 * update can refer to the ->curr item and we need to reflect this
2818 * movement in our normalized position.
2819 */
371fd7e7 2820 if (!(flags & DEQUEUE_SLEEP))
88ec22d3 2821 se->vruntime -= cfs_rq->min_vruntime;
1e876231 2822
d8b4986d
PT
2823 /* return excess runtime on last dequeue */
2824 return_cfs_rq_runtime(cfs_rq);
2825
1e876231 2826 update_min_vruntime(cfs_rq);
17bc14b7 2827 update_cfs_shares(cfs_rq);
bf0f6f24
IM
2828}
2829
2830/*
2831 * Preempt the current task with a newly woken task if needed:
2832 */
7c92e54f 2833static void
2e09bf55 2834check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
bf0f6f24 2835{
11697830 2836 unsigned long ideal_runtime, delta_exec;
f4cfb33e
WX
2837 struct sched_entity *se;
2838 s64 delta;
11697830 2839
6d0f0ebd 2840 ideal_runtime = sched_slice(cfs_rq, curr);
11697830 2841 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
a9f3e2b5 2842 if (delta_exec > ideal_runtime) {
bf0f6f24 2843 resched_task(rq_of(cfs_rq)->curr);
a9f3e2b5
MG
2844 /*
2845 * The current task ran long enough, ensure it doesn't get
2846 * re-elected due to buddy favours.
2847 */
2848 clear_buddies(cfs_rq, curr);
f685ceac
MG
2849 return;
2850 }
2851
2852 /*
2853 * Ensure that a task that missed wakeup preemption by a
2854 * narrow margin doesn't have to wait for a full slice.
2855 * This also mitigates buddy induced latencies under load.
2856 */
f685ceac
MG
2857 if (delta_exec < sysctl_sched_min_granularity)
2858 return;
2859
f4cfb33e
WX
2860 se = __pick_first_entity(cfs_rq);
2861 delta = curr->vruntime - se->vruntime;
f685ceac 2862
f4cfb33e
WX
2863 if (delta < 0)
2864 return;
d7d82944 2865
f4cfb33e
WX
2866 if (delta > ideal_runtime)
2867 resched_task(rq_of(cfs_rq)->curr);
bf0f6f24
IM
2868}
2869
83b699ed 2870static void
8494f412 2871set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 2872{
83b699ed
SV
2873 /* 'current' is not kept within the tree. */
2874 if (se->on_rq) {
2875 /*
2876 * Any task has to be enqueued before it get to execute on
2877 * a CPU. So account for the time it spent waiting on the
2878 * runqueue.
2879 */
2880 update_stats_wait_end(cfs_rq, se);
2881 __dequeue_entity(cfs_rq, se);
2882 }
2883
79303e9e 2884 update_stats_curr_start(cfs_rq, se);
429d43bc 2885 cfs_rq->curr = se;
eba1ed4b
IM
2886#ifdef CONFIG_SCHEDSTATS
2887 /*
2888 * Track our maximum slice length, if the CPU's load is at
2889 * least twice that of our own weight (i.e. dont track it
2890 * when there are only lesser-weight tasks around):
2891 */
495eca49 2892 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
41acab88 2893 se->statistics.slice_max = max(se->statistics.slice_max,
eba1ed4b
IM
2894 se->sum_exec_runtime - se->prev_sum_exec_runtime);
2895 }
2896#endif
4a55b450 2897 se->prev_sum_exec_runtime = se->sum_exec_runtime;
bf0f6f24
IM
2898}
2899
3f3a4904
PZ
2900static int
2901wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
2902
ac53db59
RR
2903/*
2904 * Pick the next process, keeping these things in mind, in this order:
2905 * 1) keep things fair between processes/task groups
2906 * 2) pick the "next" process, since someone really wants that to run
2907 * 3) pick the "last" process, for cache locality
2908 * 4) do not run the "skip" process, if something else is available
2909 */
678d5718
PZ
2910static struct sched_entity *
2911pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
aa2ac252 2912{
678d5718
PZ
2913 struct sched_entity *left = __pick_first_entity(cfs_rq);
2914 struct sched_entity *se;
2915
2916 /*
2917 * If curr is set we have to see if its left of the leftmost entity
2918 * still in the tree, provided there was anything in the tree at all.
2919 */
2920 if (!left || (curr && entity_before(curr, left)))
2921 left = curr;
2922
2923 se = left; /* ideally we run the leftmost entity */
f4b6755f 2924
ac53db59
RR
2925 /*
2926 * Avoid running the skip buddy, if running something else can
2927 * be done without getting too unfair.
2928 */
2929 if (cfs_rq->skip == se) {
678d5718
PZ
2930 struct sched_entity *second;
2931
2932 if (se == curr) {
2933 second = __pick_first_entity(cfs_rq);
2934 } else {
2935 second = __pick_next_entity(se);
2936 if (!second || (curr && entity_before(curr, second)))
2937 second = curr;
2938 }
2939
ac53db59
RR
2940 if (second && wakeup_preempt_entity(second, left) < 1)
2941 se = second;
2942 }
aa2ac252 2943
f685ceac
MG
2944 /*
2945 * Prefer last buddy, try to return the CPU to a preempted task.
2946 */
2947 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
2948 se = cfs_rq->last;
2949
ac53db59
RR
2950 /*
2951 * Someone really wants this to run. If it's not unfair, run it.
2952 */
2953 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
2954 se = cfs_rq->next;
2955
f685ceac 2956 clear_buddies(cfs_rq, se);
4793241b
PZ
2957
2958 return se;
aa2ac252
PZ
2959}
2960
678d5718 2961static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d3d9dc33 2962
ab6cde26 2963static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
bf0f6f24
IM
2964{
2965 /*
2966 * If still on the runqueue then deactivate_task()
2967 * was not called and update_curr() has to be done:
2968 */
2969 if (prev->on_rq)
b7cc0896 2970 update_curr(cfs_rq);
bf0f6f24 2971
d3d9dc33
PT
2972 /* throttle cfs_rqs exceeding runtime */
2973 check_cfs_rq_runtime(cfs_rq);
2974
ddc97297 2975 check_spread(cfs_rq, prev);
30cfdcfc 2976 if (prev->on_rq) {
5870db5b 2977 update_stats_wait_start(cfs_rq, prev);
30cfdcfc
DA
2978 /* Put 'current' back into the tree. */
2979 __enqueue_entity(cfs_rq, prev);
9d85f21c 2980 /* in !on_rq case, update occurred at dequeue */
9ee474f5 2981 update_entity_load_avg(prev, 1);
30cfdcfc 2982 }
429d43bc 2983 cfs_rq->curr = NULL;
bf0f6f24
IM
2984}
2985
8f4d37ec
PZ
2986static void
2987entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
bf0f6f24 2988{
bf0f6f24 2989 /*
30cfdcfc 2990 * Update run-time statistics of the 'current'.
bf0f6f24 2991 */
30cfdcfc 2992 update_curr(cfs_rq);
bf0f6f24 2993
9d85f21c
PT
2994 /*
2995 * Ensure that runnable average is periodically updated.
2996 */
9ee474f5 2997 update_entity_load_avg(curr, 1);
aff3e498 2998 update_cfs_rq_blocked_load(cfs_rq, 1);
bf0bd948 2999 update_cfs_shares(cfs_rq);
9d85f21c 3000
8f4d37ec
PZ
3001#ifdef CONFIG_SCHED_HRTICK
3002 /*
3003 * queued ticks are scheduled to match the slice, so don't bother
3004 * validating it and just reschedule.
3005 */
983ed7a6
HH
3006 if (queued) {
3007 resched_task(rq_of(cfs_rq)->curr);
3008 return;
3009 }
8f4d37ec
PZ
3010 /*
3011 * don't let the period tick interfere with the hrtick preemption
3012 */
3013 if (!sched_feat(DOUBLE_TICK) &&
3014 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3015 return;
3016#endif
3017
2c2efaed 3018 if (cfs_rq->nr_running > 1)
2e09bf55 3019 check_preempt_tick(cfs_rq, curr);
bf0f6f24
IM
3020}
3021
ab84d31e
PT
3022
3023/**************************************************
3024 * CFS bandwidth control machinery
3025 */
3026
3027#ifdef CONFIG_CFS_BANDWIDTH
029632fb
PZ
3028
3029#ifdef HAVE_JUMP_LABEL
c5905afb 3030static struct static_key __cfs_bandwidth_used;
029632fb
PZ
3031
3032static inline bool cfs_bandwidth_used(void)
3033{
c5905afb 3034 return static_key_false(&__cfs_bandwidth_used);
029632fb
PZ
3035}
3036
1ee14e6c 3037void cfs_bandwidth_usage_inc(void)
029632fb 3038{
1ee14e6c
BS
3039 static_key_slow_inc(&__cfs_bandwidth_used);
3040}
3041
3042void cfs_bandwidth_usage_dec(void)
3043{
3044 static_key_slow_dec(&__cfs_bandwidth_used);
029632fb
PZ
3045}
3046#else /* HAVE_JUMP_LABEL */
3047static bool cfs_bandwidth_used(void)
3048{
3049 return true;
3050}
3051
1ee14e6c
BS
3052void cfs_bandwidth_usage_inc(void) {}
3053void cfs_bandwidth_usage_dec(void) {}
029632fb
PZ
3054#endif /* HAVE_JUMP_LABEL */
3055
ab84d31e
PT
3056/*
3057 * default period for cfs group bandwidth.
3058 * default: 0.1s, units: nanoseconds
3059 */
3060static inline u64 default_cfs_period(void)
3061{
3062 return 100000000ULL;
3063}
ec12cb7f
PT
3064
3065static inline u64 sched_cfs_bandwidth_slice(void)
3066{
3067 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3068}
3069
a9cf55b2
PT
3070/*
3071 * Replenish runtime according to assigned quota and update expiration time.
3072 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3073 * additional synchronization around rq->lock.
3074 *
3075 * requires cfs_b->lock
3076 */
029632fb 3077void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
a9cf55b2
PT
3078{
3079 u64 now;
3080
3081 if (cfs_b->quota == RUNTIME_INF)
3082 return;
3083
3084 now = sched_clock_cpu(smp_processor_id());
3085 cfs_b->runtime = cfs_b->quota;
3086 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3087}
3088
029632fb
PZ
3089static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3090{
3091 return &tg->cfs_bandwidth;
3092}
3093
f1b17280
PT
3094/* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3095static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3096{
3097 if (unlikely(cfs_rq->throttle_count))
3098 return cfs_rq->throttled_clock_task;
3099
78becc27 3100 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
f1b17280
PT
3101}
3102
85dac906
PT
3103/* returns 0 on failure to allocate runtime */
3104static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f
PT
3105{
3106 struct task_group *tg = cfs_rq->tg;
3107 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
a9cf55b2 3108 u64 amount = 0, min_amount, expires;
ec12cb7f
PT
3109
3110 /* note: this is a positive sum as runtime_remaining <= 0 */
3111 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3112
3113 raw_spin_lock(&cfs_b->lock);
3114 if (cfs_b->quota == RUNTIME_INF)
3115 amount = min_amount;
58088ad0 3116 else {
a9cf55b2
PT
3117 /*
3118 * If the bandwidth pool has become inactive, then at least one
3119 * period must have elapsed since the last consumption.
3120 * Refresh the global state and ensure bandwidth timer becomes
3121 * active.
3122 */
3123 if (!cfs_b->timer_active) {
3124 __refill_cfs_bandwidth_runtime(cfs_b);
58088ad0 3125 __start_cfs_bandwidth(cfs_b);
a9cf55b2 3126 }
58088ad0
PT
3127
3128 if (cfs_b->runtime > 0) {
3129 amount = min(cfs_b->runtime, min_amount);
3130 cfs_b->runtime -= amount;
3131 cfs_b->idle = 0;
3132 }
ec12cb7f 3133 }
a9cf55b2 3134 expires = cfs_b->runtime_expires;
ec12cb7f
PT
3135 raw_spin_unlock(&cfs_b->lock);
3136
3137 cfs_rq->runtime_remaining += amount;
a9cf55b2
PT
3138 /*
3139 * we may have advanced our local expiration to account for allowed
3140 * spread between our sched_clock and the one on which runtime was
3141 * issued.
3142 */
3143 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3144 cfs_rq->runtime_expires = expires;
85dac906
PT
3145
3146 return cfs_rq->runtime_remaining > 0;
ec12cb7f
PT
3147}
3148
a9cf55b2
PT
3149/*
3150 * Note: This depends on the synchronization provided by sched_clock and the
3151 * fact that rq->clock snapshots this value.
3152 */
3153static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f 3154{
a9cf55b2 3155 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
a9cf55b2
PT
3156
3157 /* if the deadline is ahead of our clock, nothing to do */
78becc27 3158 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
ec12cb7f
PT
3159 return;
3160
a9cf55b2
PT
3161 if (cfs_rq->runtime_remaining < 0)
3162 return;
3163
3164 /*
3165 * If the local deadline has passed we have to consider the
3166 * possibility that our sched_clock is 'fast' and the global deadline
3167 * has not truly expired.
3168 *
3169 * Fortunately we can check determine whether this the case by checking
3170 * whether the global deadline has advanced.
3171 */
3172
3173 if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
3174 /* extend local deadline, drift is bounded above by 2 ticks */
3175 cfs_rq->runtime_expires += TICK_NSEC;
3176 } else {
3177 /* global deadline is ahead, expiration has passed */
3178 cfs_rq->runtime_remaining = 0;
3179 }
3180}
3181
9dbdb155 3182static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
a9cf55b2
PT
3183{
3184 /* dock delta_exec before expiring quota (as it could span periods) */
ec12cb7f 3185 cfs_rq->runtime_remaining -= delta_exec;
a9cf55b2
PT
3186 expire_cfs_rq_runtime(cfs_rq);
3187
3188 if (likely(cfs_rq->runtime_remaining > 0))
ec12cb7f
PT
3189 return;
3190
85dac906
PT
3191 /*
3192 * if we're unable to extend our runtime we resched so that the active
3193 * hierarchy can be throttled
3194 */
3195 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
3196 resched_task(rq_of(cfs_rq)->curr);
ec12cb7f
PT
3197}
3198
6c16a6dc 3199static __always_inline
9dbdb155 3200void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
ec12cb7f 3201{
56f570e5 3202 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
ec12cb7f
PT
3203 return;
3204
3205 __account_cfs_rq_runtime(cfs_rq, delta_exec);
3206}
3207
85dac906
PT
3208static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
3209{
56f570e5 3210 return cfs_bandwidth_used() && cfs_rq->throttled;
85dac906
PT
3211}
3212
64660c86
PT
3213/* check whether cfs_rq, or any parent, is throttled */
3214static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
3215{
56f570e5 3216 return cfs_bandwidth_used() && cfs_rq->throttle_count;
64660c86
PT
3217}
3218
3219/*
3220 * Ensure that neither of the group entities corresponding to src_cpu or
3221 * dest_cpu are members of a throttled hierarchy when performing group
3222 * load-balance operations.
3223 */
3224static inline int throttled_lb_pair(struct task_group *tg,
3225 int src_cpu, int dest_cpu)
3226{
3227 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
3228
3229 src_cfs_rq = tg->cfs_rq[src_cpu];
3230 dest_cfs_rq = tg->cfs_rq[dest_cpu];
3231
3232 return throttled_hierarchy(src_cfs_rq) ||
3233 throttled_hierarchy(dest_cfs_rq);
3234}
3235
3236/* updated child weight may affect parent so we have to do this bottom up */
3237static int tg_unthrottle_up(struct task_group *tg, void *data)
3238{
3239 struct rq *rq = data;
3240 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3241
3242 cfs_rq->throttle_count--;
3243#ifdef CONFIG_SMP
3244 if (!cfs_rq->throttle_count) {
f1b17280 3245 /* adjust cfs_rq_clock_task() */
78becc27 3246 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
f1b17280 3247 cfs_rq->throttled_clock_task;
64660c86
PT
3248 }
3249#endif
3250
3251 return 0;
3252}
3253
3254static int tg_throttle_down(struct task_group *tg, void *data)
3255{
3256 struct rq *rq = data;
3257 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3258
82958366
PT
3259 /* group is entering throttled state, stop time */
3260 if (!cfs_rq->throttle_count)
78becc27 3261 cfs_rq->throttled_clock_task = rq_clock_task(rq);
64660c86
PT
3262 cfs_rq->throttle_count++;
3263
3264 return 0;
3265}
3266
d3d9dc33 3267static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
85dac906
PT
3268{
3269 struct rq *rq = rq_of(cfs_rq);
3270 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3271 struct sched_entity *se;
3272 long task_delta, dequeue = 1;
3273
3274 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
3275
f1b17280 3276 /* freeze hierarchy runnable averages while throttled */
64660c86
PT
3277 rcu_read_lock();
3278 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
3279 rcu_read_unlock();
85dac906
PT
3280
3281 task_delta = cfs_rq->h_nr_running;
3282 for_each_sched_entity(se) {
3283 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
3284 /* throttled entity or throttle-on-deactivate */
3285 if (!se->on_rq)
3286 break;
3287
3288 if (dequeue)
3289 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
3290 qcfs_rq->h_nr_running -= task_delta;
3291
3292 if (qcfs_rq->load.weight)
3293 dequeue = 0;
3294 }
3295
3296 if (!se)
3297 rq->nr_running -= task_delta;
3298
3299 cfs_rq->throttled = 1;
78becc27 3300 cfs_rq->throttled_clock = rq_clock(rq);
85dac906
PT
3301 raw_spin_lock(&cfs_b->lock);
3302 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
f9f9ffc2
BS
3303 if (!cfs_b->timer_active)
3304 __start_cfs_bandwidth(cfs_b);
85dac906
PT
3305 raw_spin_unlock(&cfs_b->lock);
3306}
3307
029632fb 3308void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
671fd9da
PT
3309{
3310 struct rq *rq = rq_of(cfs_rq);
3311 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3312 struct sched_entity *se;
3313 int enqueue = 1;
3314 long task_delta;
3315
22b958d8 3316 se = cfs_rq->tg->se[cpu_of(rq)];
671fd9da
PT
3317
3318 cfs_rq->throttled = 0;
1a55af2e
FW
3319
3320 update_rq_clock(rq);
3321
671fd9da 3322 raw_spin_lock(&cfs_b->lock);
78becc27 3323 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
671fd9da
PT
3324 list_del_rcu(&cfs_rq->throttled_list);
3325 raw_spin_unlock(&cfs_b->lock);
3326
64660c86
PT
3327 /* update hierarchical throttle state */
3328 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
3329
671fd9da
PT
3330 if (!cfs_rq->load.weight)
3331 return;
3332
3333 task_delta = cfs_rq->h_nr_running;
3334 for_each_sched_entity(se) {
3335 if (se->on_rq)
3336 enqueue = 0;
3337
3338 cfs_rq = cfs_rq_of(se);
3339 if (enqueue)
3340 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
3341 cfs_rq->h_nr_running += task_delta;
3342
3343 if (cfs_rq_throttled(cfs_rq))
3344 break;
3345 }
3346
3347 if (!se)
3348 rq->nr_running += task_delta;
3349
3350 /* determine whether we need to wake up potentially idle cpu */
3351 if (rq->curr == rq->idle && rq->cfs.nr_running)
3352 resched_task(rq->curr);
3353}
3354
3355static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
3356 u64 remaining, u64 expires)
3357{
3358 struct cfs_rq *cfs_rq;
3359 u64 runtime = remaining;
3360
3361 rcu_read_lock();
3362 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
3363 throttled_list) {
3364 struct rq *rq = rq_of(cfs_rq);
3365
3366 raw_spin_lock(&rq->lock);
3367 if (!cfs_rq_throttled(cfs_rq))
3368 goto next;
3369
3370 runtime = -cfs_rq->runtime_remaining + 1;
3371 if (runtime > remaining)
3372 runtime = remaining;
3373 remaining -= runtime;
3374
3375 cfs_rq->runtime_remaining += runtime;
3376 cfs_rq->runtime_expires = expires;
3377
3378 /* we check whether we're throttled above */
3379 if (cfs_rq->runtime_remaining > 0)
3380 unthrottle_cfs_rq(cfs_rq);
3381
3382next:
3383 raw_spin_unlock(&rq->lock);
3384
3385 if (!remaining)
3386 break;
3387 }
3388 rcu_read_unlock();
3389
3390 return remaining;
3391}
3392
58088ad0
PT
3393/*
3394 * Responsible for refilling a task_group's bandwidth and unthrottling its
3395 * cfs_rqs as appropriate. If there has been no activity within the last
3396 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
3397 * used to track this state.
3398 */
3399static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
3400{
671fd9da
PT
3401 u64 runtime, runtime_expires;
3402 int idle = 1, throttled;
58088ad0
PT
3403
3404 raw_spin_lock(&cfs_b->lock);
3405 /* no need to continue the timer with no bandwidth constraint */
3406 if (cfs_b->quota == RUNTIME_INF)
3407 goto out_unlock;
3408
671fd9da
PT
3409 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
3410 /* idle depends on !throttled (for the case of a large deficit) */
3411 idle = cfs_b->idle && !throttled;
e8da1b18 3412 cfs_b->nr_periods += overrun;
671fd9da 3413
a9cf55b2
PT
3414 /* if we're going inactive then everything else can be deferred */
3415 if (idle)
3416 goto out_unlock;
3417
927b54fc
BS
3418 /*
3419 * if we have relooped after returning idle once, we need to update our
3420 * status as actually running, so that other cpus doing
3421 * __start_cfs_bandwidth will stop trying to cancel us.
3422 */
3423 cfs_b->timer_active = 1;
3424
a9cf55b2
PT
3425 __refill_cfs_bandwidth_runtime(cfs_b);
3426
671fd9da
PT
3427 if (!throttled) {
3428 /* mark as potentially idle for the upcoming period */
3429 cfs_b->idle = 1;
3430 goto out_unlock;
3431 }
3432
e8da1b18
NR
3433 /* account preceding periods in which throttling occurred */
3434 cfs_b->nr_throttled += overrun;
3435
671fd9da
PT
3436 /*
3437 * There are throttled entities so we must first use the new bandwidth
3438 * to unthrottle them before making it generally available. This
3439 * ensures that all existing debts will be paid before a new cfs_rq is
3440 * allowed to run.
3441 */
3442 runtime = cfs_b->runtime;
3443 runtime_expires = cfs_b->runtime_expires;
3444 cfs_b->runtime = 0;
3445
3446 /*
3447 * This check is repeated as we are holding onto the new bandwidth
3448 * while we unthrottle. This can potentially race with an unthrottled
3449 * group trying to acquire new bandwidth from the global pool.
3450 */
3451 while (throttled && runtime > 0) {
3452 raw_spin_unlock(&cfs_b->lock);
3453 /* we can't nest cfs_b->lock while distributing bandwidth */
3454 runtime = distribute_cfs_runtime(cfs_b, runtime,
3455 runtime_expires);
3456 raw_spin_lock(&cfs_b->lock);
3457
3458 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
3459 }
58088ad0 3460
671fd9da
PT
3461 /* return (any) remaining runtime */
3462 cfs_b->runtime = runtime;
3463 /*
3464 * While we are ensured activity in the period following an
3465 * unthrottle, this also covers the case in which the new bandwidth is
3466 * insufficient to cover the existing bandwidth deficit. (Forcing the
3467 * timer to remain active while there are any throttled entities.)
3468 */
3469 cfs_b->idle = 0;
58088ad0
PT
3470out_unlock:
3471 if (idle)
3472 cfs_b->timer_active = 0;
3473 raw_spin_unlock(&cfs_b->lock);
3474
3475 return idle;
3476}
d3d9dc33 3477
d8b4986d
PT
3478/* a cfs_rq won't donate quota below this amount */
3479static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
3480/* minimum remaining period time to redistribute slack quota */
3481static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
3482/* how long we wait to gather additional slack before distributing */
3483static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
3484
db06e78c
BS
3485/*
3486 * Are we near the end of the current quota period?
3487 *
3488 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
3489 * hrtimer base being cleared by __hrtimer_start_range_ns. In the case of
3490 * migrate_hrtimers, base is never cleared, so we are fine.
3491 */
d8b4986d
PT
3492static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
3493{
3494 struct hrtimer *refresh_timer = &cfs_b->period_timer;
3495 u64 remaining;
3496
3497 /* if the call-back is running a quota refresh is already occurring */
3498 if (hrtimer_callback_running(refresh_timer))
3499 return 1;
3500
3501 /* is a quota refresh about to occur? */
3502 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
3503 if (remaining < min_expire)
3504 return 1;
3505
3506 return 0;
3507}
3508
3509static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
3510{
3511 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
3512
3513 /* if there's a quota refresh soon don't bother with slack */
3514 if (runtime_refresh_within(cfs_b, min_left))
3515 return;
3516
3517 start_bandwidth_timer(&cfs_b->slack_timer,
3518 ns_to_ktime(cfs_bandwidth_slack_period));
3519}
3520
3521/* we know any runtime found here is valid as update_curr() precedes return */
3522static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3523{
3524 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3525 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
3526
3527 if (slack_runtime <= 0)
3528 return;
3529
3530 raw_spin_lock(&cfs_b->lock);
3531 if (cfs_b->quota != RUNTIME_INF &&
3532 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
3533 cfs_b->runtime += slack_runtime;
3534
3535 /* we are under rq->lock, defer unthrottling using a timer */
3536 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
3537 !list_empty(&cfs_b->throttled_cfs_rq))
3538 start_cfs_slack_bandwidth(cfs_b);
3539 }
3540 raw_spin_unlock(&cfs_b->lock);
3541
3542 /* even if it's not valid for return we don't want to try again */
3543 cfs_rq->runtime_remaining -= slack_runtime;
3544}
3545
3546static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3547{
56f570e5
PT
3548 if (!cfs_bandwidth_used())
3549 return;
3550
fccfdc6f 3551 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
d8b4986d
PT
3552 return;
3553
3554 __return_cfs_rq_runtime(cfs_rq);
3555}
3556
3557/*
3558 * This is done with a timer (instead of inline with bandwidth return) since
3559 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
3560 */
3561static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
3562{
3563 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
3564 u64 expires;
3565
3566 /* confirm we're still not at a refresh boundary */
db06e78c
BS
3567 raw_spin_lock(&cfs_b->lock);
3568 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
3569 raw_spin_unlock(&cfs_b->lock);
d8b4986d 3570 return;
db06e78c 3571 }
d8b4986d 3572
d8b4986d
PT
3573 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
3574 runtime = cfs_b->runtime;
3575 cfs_b->runtime = 0;
3576 }
3577 expires = cfs_b->runtime_expires;
3578 raw_spin_unlock(&cfs_b->lock);
3579
3580 if (!runtime)
3581 return;
3582
3583 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
3584
3585 raw_spin_lock(&cfs_b->lock);
3586 if (expires == cfs_b->runtime_expires)
3587 cfs_b->runtime = runtime;
3588 raw_spin_unlock(&cfs_b->lock);
3589}
3590
d3d9dc33
PT
3591/*
3592 * When a group wakes up we want to make sure that its quota is not already
3593 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
3594 * runtime as update_curr() throttling can not not trigger until it's on-rq.
3595 */
3596static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
3597{
56f570e5
PT
3598 if (!cfs_bandwidth_used())
3599 return;
3600
d3d9dc33
PT
3601 /* an active group must be handled by the update_curr()->put() path */
3602 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
3603 return;
3604
3605 /* ensure the group is not already throttled */
3606 if (cfs_rq_throttled(cfs_rq))
3607 return;
3608
3609 /* update runtime allocation */
3610 account_cfs_rq_runtime(cfs_rq, 0);
3611 if (cfs_rq->runtime_remaining <= 0)
3612 throttle_cfs_rq(cfs_rq);
3613}
3614
3615/* conditionally throttle active cfs_rq's from put_prev_entity() */
678d5718 3616static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
d3d9dc33 3617{
56f570e5 3618 if (!cfs_bandwidth_used())
678d5718 3619 return false;
56f570e5 3620
d3d9dc33 3621 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
678d5718 3622 return false;
d3d9dc33
PT
3623
3624 /*
3625 * it's possible for a throttled entity to be forced into a running
3626 * state (e.g. set_curr_task), in this case we're finished.
3627 */
3628 if (cfs_rq_throttled(cfs_rq))
678d5718 3629 return true;
d3d9dc33
PT
3630
3631 throttle_cfs_rq(cfs_rq);
678d5718 3632 return true;
d3d9dc33 3633}
029632fb 3634
029632fb
PZ
3635static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
3636{
3637 struct cfs_bandwidth *cfs_b =
3638 container_of(timer, struct cfs_bandwidth, slack_timer);
3639 do_sched_cfs_slack_timer(cfs_b);
3640
3641 return HRTIMER_NORESTART;
3642}
3643
3644static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
3645{
3646 struct cfs_bandwidth *cfs_b =
3647 container_of(timer, struct cfs_bandwidth, period_timer);
3648 ktime_t now;
3649 int overrun;
3650 int idle = 0;
3651
3652 for (;;) {
3653 now = hrtimer_cb_get_time(timer);
3654 overrun = hrtimer_forward(timer, now, cfs_b->period);
3655
3656 if (!overrun)
3657 break;
3658
3659 idle = do_sched_cfs_period_timer(cfs_b, overrun);
3660 }
3661
3662 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
3663}
3664
3665void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
3666{
3667 raw_spin_lock_init(&cfs_b->lock);
3668 cfs_b->runtime = 0;
3669 cfs_b->quota = RUNTIME_INF;
3670 cfs_b->period = ns_to_ktime(default_cfs_period());
3671
3672 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
3673 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3674 cfs_b->period_timer.function = sched_cfs_period_timer;
3675 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3676 cfs_b->slack_timer.function = sched_cfs_slack_timer;
3677}
3678
3679static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3680{
3681 cfs_rq->runtime_enabled = 0;
3682 INIT_LIST_HEAD(&cfs_rq->throttled_list);
3683}
3684
3685/* requires cfs_b->lock, may release to reprogram timer */
3686void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
3687{
3688 /*
3689 * The timer may be active because we're trying to set a new bandwidth
3690 * period or because we're racing with the tear-down path
3691 * (timer_active==0 becomes visible before the hrtimer call-back
3692 * terminates). In either case we ensure that it's re-programmed
3693 */
927b54fc
BS
3694 while (unlikely(hrtimer_active(&cfs_b->period_timer)) &&
3695 hrtimer_try_to_cancel(&cfs_b->period_timer) < 0) {
3696 /* bounce the lock to allow do_sched_cfs_period_timer to run */
029632fb 3697 raw_spin_unlock(&cfs_b->lock);
927b54fc 3698 cpu_relax();
029632fb
PZ
3699 raw_spin_lock(&cfs_b->lock);
3700 /* if someone else restarted the timer then we're done */
3701 if (cfs_b->timer_active)
3702 return;
3703 }
3704
3705 cfs_b->timer_active = 1;
3706 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
3707}
3708
3709static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
3710{
3711 hrtimer_cancel(&cfs_b->period_timer);
3712 hrtimer_cancel(&cfs_b->slack_timer);
3713}
3714
38dc3348 3715static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
029632fb
PZ
3716{
3717 struct cfs_rq *cfs_rq;
3718
3719 for_each_leaf_cfs_rq(rq, cfs_rq) {
3720 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3721
3722 if (!cfs_rq->runtime_enabled)
3723 continue;
3724
3725 /*
3726 * clock_task is not advancing so we just need to make sure
3727 * there's some valid quota amount
3728 */
3729 cfs_rq->runtime_remaining = cfs_b->quota;
3730 if (cfs_rq_throttled(cfs_rq))
3731 unthrottle_cfs_rq(cfs_rq);
3732 }
3733}
3734
3735#else /* CONFIG_CFS_BANDWIDTH */
f1b17280
PT
3736static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3737{
78becc27 3738 return rq_clock_task(rq_of(cfs_rq));
f1b17280
PT
3739}
3740
9dbdb155 3741static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
678d5718 3742static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
d3d9dc33 3743static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6c16a6dc 3744static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
85dac906
PT
3745
3746static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
3747{
3748 return 0;
3749}
64660c86
PT
3750
3751static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
3752{
3753 return 0;
3754}
3755
3756static inline int throttled_lb_pair(struct task_group *tg,
3757 int src_cpu, int dest_cpu)
3758{
3759 return 0;
3760}
029632fb
PZ
3761
3762void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
3763
3764#ifdef CONFIG_FAIR_GROUP_SCHED
3765static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
ab84d31e
PT
3766#endif
3767
029632fb
PZ
3768static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3769{
3770 return NULL;
3771}
3772static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
a4c96ae3 3773static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
029632fb
PZ
3774
3775#endif /* CONFIG_CFS_BANDWIDTH */
3776
bf0f6f24
IM
3777/**************************************************
3778 * CFS operations on tasks:
3779 */
3780
8f4d37ec
PZ
3781#ifdef CONFIG_SCHED_HRTICK
3782static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
3783{
8f4d37ec
PZ
3784 struct sched_entity *se = &p->se;
3785 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3786
3787 WARN_ON(task_rq(p) != rq);
3788
b39e66ea 3789 if (cfs_rq->nr_running > 1) {
8f4d37ec
PZ
3790 u64 slice = sched_slice(cfs_rq, se);
3791 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
3792 s64 delta = slice - ran;
3793
3794 if (delta < 0) {
3795 if (rq->curr == p)
3796 resched_task(p);
3797 return;
3798 }
3799
3800 /*
3801 * Don't schedule slices shorter than 10000ns, that just
3802 * doesn't make sense. Rely on vruntime for fairness.
3803 */
31656519 3804 if (rq->curr != p)
157124c1 3805 delta = max_t(s64, 10000LL, delta);
8f4d37ec 3806
31656519 3807 hrtick_start(rq, delta);
8f4d37ec
PZ
3808 }
3809}
a4c2f00f
PZ
3810
3811/*
3812 * called from enqueue/dequeue and updates the hrtick when the
3813 * current task is from our class and nr_running is low enough
3814 * to matter.
3815 */
3816static void hrtick_update(struct rq *rq)
3817{
3818 struct task_struct *curr = rq->curr;
3819
b39e66ea 3820 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
a4c2f00f
PZ
3821 return;
3822
3823 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
3824 hrtick_start_fair(rq, curr);
3825}
55e12e5e 3826#else /* !CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
3827static inline void
3828hrtick_start_fair(struct rq *rq, struct task_struct *p)
3829{
3830}
a4c2f00f
PZ
3831
3832static inline void hrtick_update(struct rq *rq)
3833{
3834}
8f4d37ec
PZ
3835#endif
3836
bf0f6f24
IM
3837/*
3838 * The enqueue_task method is called before nr_running is
3839 * increased. Here we update the fair scheduling stats and
3840 * then put the task into the rbtree:
3841 */
ea87bb78 3842static void
371fd7e7 3843enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
3844{
3845 struct cfs_rq *cfs_rq;
62fb1851 3846 struct sched_entity *se = &p->se;
bf0f6f24
IM
3847
3848 for_each_sched_entity(se) {
62fb1851 3849 if (se->on_rq)
bf0f6f24
IM
3850 break;
3851 cfs_rq = cfs_rq_of(se);
88ec22d3 3852 enqueue_entity(cfs_rq, se, flags);
85dac906
PT
3853
3854 /*
3855 * end evaluation on encountering a throttled cfs_rq
3856 *
3857 * note: in the case of encountering a throttled cfs_rq we will
3858 * post the final h_nr_running increment below.
3859 */
3860 if (cfs_rq_throttled(cfs_rq))
3861 break;
953bfcd1 3862 cfs_rq->h_nr_running++;
85dac906 3863
88ec22d3 3864 flags = ENQUEUE_WAKEUP;
bf0f6f24 3865 }
8f4d37ec 3866
2069dd75 3867 for_each_sched_entity(se) {
0f317143 3868 cfs_rq = cfs_rq_of(se);
953bfcd1 3869 cfs_rq->h_nr_running++;
2069dd75 3870
85dac906
PT
3871 if (cfs_rq_throttled(cfs_rq))
3872 break;
3873
17bc14b7 3874 update_cfs_shares(cfs_rq);
9ee474f5 3875 update_entity_load_avg(se, 1);
2069dd75
PZ
3876 }
3877
18bf2805
BS
3878 if (!se) {
3879 update_rq_runnable_avg(rq, rq->nr_running);
85dac906 3880 inc_nr_running(rq);
18bf2805 3881 }
a4c2f00f 3882 hrtick_update(rq);
bf0f6f24
IM
3883}
3884
2f36825b
VP
3885static void set_next_buddy(struct sched_entity *se);
3886
bf0f6f24
IM
3887/*
3888 * The dequeue_task method is called before nr_running is
3889 * decreased. We remove the task from the rbtree and
3890 * update the fair scheduling stats:
3891 */
371fd7e7 3892static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
3893{
3894 struct cfs_rq *cfs_rq;
62fb1851 3895 struct sched_entity *se = &p->se;
2f36825b 3896 int task_sleep = flags & DEQUEUE_SLEEP;
bf0f6f24
IM
3897
3898 for_each_sched_entity(se) {
3899 cfs_rq = cfs_rq_of(se);
371fd7e7 3900 dequeue_entity(cfs_rq, se, flags);
85dac906
PT
3901
3902 /*
3903 * end evaluation on encountering a throttled cfs_rq
3904 *
3905 * note: in the case of encountering a throttled cfs_rq we will
3906 * post the final h_nr_running decrement below.
3907 */
3908 if (cfs_rq_throttled(cfs_rq))
3909 break;
953bfcd1 3910 cfs_rq->h_nr_running--;
2069dd75 3911
bf0f6f24 3912 /* Don't dequeue parent if it has other entities besides us */
2f36825b
VP
3913 if (cfs_rq->load.weight) {
3914 /*
3915 * Bias pick_next to pick a task from this cfs_rq, as
3916 * p is sleeping when it is within its sched_slice.
3917 */
3918 if (task_sleep && parent_entity(se))
3919 set_next_buddy(parent_entity(se));
9598c82d
PT
3920
3921 /* avoid re-evaluating load for this entity */
3922 se = parent_entity(se);
bf0f6f24 3923 break;
2f36825b 3924 }
371fd7e7 3925 flags |= DEQUEUE_SLEEP;
bf0f6f24 3926 }
8f4d37ec 3927
2069dd75 3928 for_each_sched_entity(se) {
0f317143 3929 cfs_rq = cfs_rq_of(se);
953bfcd1 3930 cfs_rq->h_nr_running--;
2069dd75 3931
85dac906
PT
3932 if (cfs_rq_throttled(cfs_rq))
3933 break;
3934
17bc14b7 3935 update_cfs_shares(cfs_rq);
9ee474f5 3936 update_entity_load_avg(se, 1);
2069dd75
PZ
3937 }
3938
18bf2805 3939 if (!se) {
85dac906 3940 dec_nr_running(rq);
18bf2805
BS
3941 update_rq_runnable_avg(rq, 1);
3942 }
a4c2f00f 3943 hrtick_update(rq);
bf0f6f24
IM
3944}
3945
e7693a36 3946#ifdef CONFIG_SMP
029632fb
PZ
3947/* Used instead of source_load when we know the type == 0 */
3948static unsigned long weighted_cpuload(const int cpu)
3949{
b92486cb 3950 return cpu_rq(cpu)->cfs.runnable_load_avg;
029632fb
PZ
3951}
3952
3953/*
3954 * Return a low guess at the load of a migration-source cpu weighted
3955 * according to the scheduling class and "nice" value.
3956 *
3957 * We want to under-estimate the load of migration sources, to
3958 * balance conservatively.
3959 */
3960static unsigned long source_load(int cpu, int type)
3961{
3962 struct rq *rq = cpu_rq(cpu);
3963 unsigned long total = weighted_cpuload(cpu);
3964
3965 if (type == 0 || !sched_feat(LB_BIAS))
3966 return total;
3967
3968 return min(rq->cpu_load[type-1], total);
3969}
3970
3971/*
3972 * Return a high guess at the load of a migration-target cpu weighted
3973 * according to the scheduling class and "nice" value.
3974 */
3975static unsigned long target_load(int cpu, int type)
3976{
3977 struct rq *rq = cpu_rq(cpu);
3978 unsigned long total = weighted_cpuload(cpu);
3979
3980 if (type == 0 || !sched_feat(LB_BIAS))
3981 return total;
3982
3983 return max(rq->cpu_load[type-1], total);
3984}
3985
3986static unsigned long power_of(int cpu)
3987{
3988 return cpu_rq(cpu)->cpu_power;
3989}
3990
3991static unsigned long cpu_avg_load_per_task(int cpu)
3992{
3993 struct rq *rq = cpu_rq(cpu);
3994 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
b92486cb 3995 unsigned long load_avg = rq->cfs.runnable_load_avg;
029632fb
PZ
3996
3997 if (nr_running)
b92486cb 3998 return load_avg / nr_running;
029632fb
PZ
3999
4000 return 0;
4001}
4002
62470419
MW
4003static void record_wakee(struct task_struct *p)
4004{
4005 /*
4006 * Rough decay (wiping) for cost saving, don't worry
4007 * about the boundary, really active task won't care
4008 * about the loss.
4009 */
4010 if (jiffies > current->wakee_flip_decay_ts + HZ) {
4011 current->wakee_flips = 0;
4012 current->wakee_flip_decay_ts = jiffies;
4013 }
4014
4015 if (current->last_wakee != p) {
4016 current->last_wakee = p;
4017 current->wakee_flips++;
4018 }
4019}
098fb9db 4020
74f8e4b2 4021static void task_waking_fair(struct task_struct *p)
88ec22d3
PZ
4022{
4023 struct sched_entity *se = &p->se;
4024 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3fe1698b
PZ
4025 u64 min_vruntime;
4026
4027#ifndef CONFIG_64BIT
4028 u64 min_vruntime_copy;
88ec22d3 4029
3fe1698b
PZ
4030 do {
4031 min_vruntime_copy = cfs_rq->min_vruntime_copy;
4032 smp_rmb();
4033 min_vruntime = cfs_rq->min_vruntime;
4034 } while (min_vruntime != min_vruntime_copy);
4035#else
4036 min_vruntime = cfs_rq->min_vruntime;
4037#endif
88ec22d3 4038
3fe1698b 4039 se->vruntime -= min_vruntime;
62470419 4040 record_wakee(p);
88ec22d3
PZ
4041}
4042
bb3469ac 4043#ifdef CONFIG_FAIR_GROUP_SCHED
f5bfb7d9
PZ
4044/*
4045 * effective_load() calculates the load change as seen from the root_task_group
4046 *
4047 * Adding load to a group doesn't make a group heavier, but can cause movement
4048 * of group shares between cpus. Assuming the shares were perfectly aligned one
4049 * can calculate the shift in shares.
cf5f0acf
PZ
4050 *
4051 * Calculate the effective load difference if @wl is added (subtracted) to @tg
4052 * on this @cpu and results in a total addition (subtraction) of @wg to the
4053 * total group weight.
4054 *
4055 * Given a runqueue weight distribution (rw_i) we can compute a shares
4056 * distribution (s_i) using:
4057 *
4058 * s_i = rw_i / \Sum rw_j (1)
4059 *
4060 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
4061 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
4062 * shares distribution (s_i):
4063 *
4064 * rw_i = { 2, 4, 1, 0 }
4065 * s_i = { 2/7, 4/7, 1/7, 0 }
4066 *
4067 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
4068 * task used to run on and the CPU the waker is running on), we need to
4069 * compute the effect of waking a task on either CPU and, in case of a sync
4070 * wakeup, compute the effect of the current task going to sleep.
4071 *
4072 * So for a change of @wl to the local @cpu with an overall group weight change
4073 * of @wl we can compute the new shares distribution (s'_i) using:
4074 *
4075 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
4076 *
4077 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
4078 * differences in waking a task to CPU 0. The additional task changes the
4079 * weight and shares distributions like:
4080 *
4081 * rw'_i = { 3, 4, 1, 0 }
4082 * s'_i = { 3/8, 4/8, 1/8, 0 }
4083 *
4084 * We can then compute the difference in effective weight by using:
4085 *
4086 * dw_i = S * (s'_i - s_i) (3)
4087 *
4088 * Where 'S' is the group weight as seen by its parent.
4089 *
4090 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
4091 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
4092 * 4/7) times the weight of the group.
f5bfb7d9 4093 */
2069dd75 4094static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
bb3469ac 4095{
4be9daaa 4096 struct sched_entity *se = tg->se[cpu];
f1d239f7 4097
9722c2da 4098 if (!tg->parent) /* the trivial, non-cgroup case */
f1d239f7
PZ
4099 return wl;
4100
4be9daaa 4101 for_each_sched_entity(se) {
cf5f0acf 4102 long w, W;
4be9daaa 4103
977dda7c 4104 tg = se->my_q->tg;
bb3469ac 4105
cf5f0acf
PZ
4106 /*
4107 * W = @wg + \Sum rw_j
4108 */
4109 W = wg + calc_tg_weight(tg, se->my_q);
4be9daaa 4110
cf5f0acf
PZ
4111 /*
4112 * w = rw_i + @wl
4113 */
4114 w = se->my_q->load.weight + wl;
940959e9 4115
cf5f0acf
PZ
4116 /*
4117 * wl = S * s'_i; see (2)
4118 */
4119 if (W > 0 && w < W)
4120 wl = (w * tg->shares) / W;
977dda7c
PT
4121 else
4122 wl = tg->shares;
940959e9 4123
cf5f0acf
PZ
4124 /*
4125 * Per the above, wl is the new se->load.weight value; since
4126 * those are clipped to [MIN_SHARES, ...) do so now. See
4127 * calc_cfs_shares().
4128 */
977dda7c
PT
4129 if (wl < MIN_SHARES)
4130 wl = MIN_SHARES;
cf5f0acf
PZ
4131
4132 /*
4133 * wl = dw_i = S * (s'_i - s_i); see (3)
4134 */
977dda7c 4135 wl -= se->load.weight;
cf5f0acf
PZ
4136
4137 /*
4138 * Recursively apply this logic to all parent groups to compute
4139 * the final effective load change on the root group. Since
4140 * only the @tg group gets extra weight, all parent groups can
4141 * only redistribute existing shares. @wl is the shift in shares
4142 * resulting from this level per the above.
4143 */
4be9daaa 4144 wg = 0;
4be9daaa 4145 }
bb3469ac 4146
4be9daaa 4147 return wl;
bb3469ac
PZ
4148}
4149#else
4be9daaa 4150
58d081b5 4151static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
4be9daaa 4152{
83378269 4153 return wl;
bb3469ac 4154}
4be9daaa 4155
bb3469ac
PZ
4156#endif
4157
62470419
MW
4158static int wake_wide(struct task_struct *p)
4159{
7d9ffa89 4160 int factor = this_cpu_read(sd_llc_size);
62470419
MW
4161
4162 /*
4163 * Yeah, it's the switching-frequency, could means many wakee or
4164 * rapidly switch, use factor here will just help to automatically
4165 * adjust the loose-degree, so bigger node will lead to more pull.
4166 */
4167 if (p->wakee_flips > factor) {
4168 /*
4169 * wakee is somewhat hot, it needs certain amount of cpu
4170 * resource, so if waker is far more hot, prefer to leave
4171 * it alone.
4172 */
4173 if (current->wakee_flips > (factor * p->wakee_flips))
4174 return 1;
4175 }
4176
4177 return 0;
4178}
4179
c88d5910 4180static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
098fb9db 4181{
e37b6a7b 4182 s64 this_load, load;
c88d5910 4183 int idx, this_cpu, prev_cpu;
098fb9db 4184 unsigned long tl_per_task;
c88d5910 4185 struct task_group *tg;
83378269 4186 unsigned long weight;
b3137bc8 4187 int balanced;
098fb9db 4188
62470419
MW
4189 /*
4190 * If we wake multiple tasks be careful to not bounce
4191 * ourselves around too much.
4192 */
4193 if (wake_wide(p))
4194 return 0;
4195
c88d5910
PZ
4196 idx = sd->wake_idx;
4197 this_cpu = smp_processor_id();
4198 prev_cpu = task_cpu(p);
4199 load = source_load(prev_cpu, idx);
4200 this_load = target_load(this_cpu, idx);
098fb9db 4201
b3137bc8
MG
4202 /*
4203 * If sync wakeup then subtract the (maximum possible)
4204 * effect of the currently running task from the load
4205 * of the current CPU:
4206 */
83378269
PZ
4207 if (sync) {
4208 tg = task_group(current);
4209 weight = current->se.load.weight;
4210
c88d5910 4211 this_load += effective_load(tg, this_cpu, -weight, -weight);
83378269
PZ
4212 load += effective_load(tg, prev_cpu, 0, -weight);
4213 }
b3137bc8 4214
83378269
PZ
4215 tg = task_group(p);
4216 weight = p->se.load.weight;
b3137bc8 4217
71a29aa7
PZ
4218 /*
4219 * In low-load situations, where prev_cpu is idle and this_cpu is idle
c88d5910
PZ
4220 * due to the sync cause above having dropped this_load to 0, we'll
4221 * always have an imbalance, but there's really nothing you can do
4222 * about that, so that's good too.
71a29aa7
PZ
4223 *
4224 * Otherwise check if either cpus are near enough in load to allow this
4225 * task to be woken on this_cpu.
4226 */
e37b6a7b
PT
4227 if (this_load > 0) {
4228 s64 this_eff_load, prev_eff_load;
e51fd5e2
PZ
4229
4230 this_eff_load = 100;
4231 this_eff_load *= power_of(prev_cpu);
4232 this_eff_load *= this_load +
4233 effective_load(tg, this_cpu, weight, weight);
4234
4235 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
4236 prev_eff_load *= power_of(this_cpu);
4237 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
4238
4239 balanced = this_eff_load <= prev_eff_load;
4240 } else
4241 balanced = true;
b3137bc8 4242
098fb9db 4243 /*
4ae7d5ce
IM
4244 * If the currently running task will sleep within
4245 * a reasonable amount of time then attract this newly
4246 * woken task:
098fb9db 4247 */
2fb7635c
PZ
4248 if (sync && balanced)
4249 return 1;
098fb9db 4250
41acab88 4251 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
098fb9db
IM
4252 tl_per_task = cpu_avg_load_per_task(this_cpu);
4253
c88d5910
PZ
4254 if (balanced ||
4255 (this_load <= load &&
4256 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
098fb9db
IM
4257 /*
4258 * This domain has SD_WAKE_AFFINE and
4259 * p is cache cold in this domain, and
4260 * there is no bad imbalance.
4261 */
c88d5910 4262 schedstat_inc(sd, ttwu_move_affine);
41acab88 4263 schedstat_inc(p, se.statistics.nr_wakeups_affine);
098fb9db
IM
4264
4265 return 1;
4266 }
4267 return 0;
4268}
4269
aaee1203
PZ
4270/*
4271 * find_idlest_group finds and returns the least busy CPU group within the
4272 * domain.
4273 */
4274static struct sched_group *
78e7ed53 4275find_idlest_group(struct sched_domain *sd, struct task_struct *p,
c44f2a02 4276 int this_cpu, int sd_flag)
e7693a36 4277{
b3bd3de6 4278 struct sched_group *idlest = NULL, *group = sd->groups;
aaee1203 4279 unsigned long min_load = ULONG_MAX, this_load = 0;
c44f2a02 4280 int load_idx = sd->forkexec_idx;
aaee1203 4281 int imbalance = 100 + (sd->imbalance_pct-100)/2;
e7693a36 4282
c44f2a02
VG
4283 if (sd_flag & SD_BALANCE_WAKE)
4284 load_idx = sd->wake_idx;
4285
aaee1203
PZ
4286 do {
4287 unsigned long load, avg_load;
4288 int local_group;
4289 int i;
e7693a36 4290
aaee1203
PZ
4291 /* Skip over this group if it has no CPUs allowed */
4292 if (!cpumask_intersects(sched_group_cpus(group),
fa17b507 4293 tsk_cpus_allowed(p)))
aaee1203
PZ
4294 continue;
4295
4296 local_group = cpumask_test_cpu(this_cpu,
4297 sched_group_cpus(group));
4298
4299 /* Tally up the load of all CPUs in the group */
4300 avg_load = 0;
4301
4302 for_each_cpu(i, sched_group_cpus(group)) {
4303 /* Bias balancing toward cpus of our domain */
4304 if (local_group)
4305 load = source_load(i, load_idx);
4306 else
4307 load = target_load(i, load_idx);
4308
4309 avg_load += load;
4310 }
4311
4312 /* Adjust by relative CPU power of the group */
9c3f75cb 4313 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
aaee1203
PZ
4314
4315 if (local_group) {
4316 this_load = avg_load;
aaee1203
PZ
4317 } else if (avg_load < min_load) {
4318 min_load = avg_load;
4319 idlest = group;
4320 }
4321 } while (group = group->next, group != sd->groups);
4322
4323 if (!idlest || 100*this_load < imbalance*min_load)
4324 return NULL;
4325 return idlest;
4326}
4327
4328/*
4329 * find_idlest_cpu - find the idlest cpu among the cpus in group.
4330 */
4331static int
4332find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
4333{
4334 unsigned long load, min_load = ULONG_MAX;
4335 int idlest = -1;
4336 int i;
4337
4338 /* Traverse only the allowed CPUs */
fa17b507 4339 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
aaee1203
PZ
4340 load = weighted_cpuload(i);
4341
4342 if (load < min_load || (load == min_load && i == this_cpu)) {
4343 min_load = load;
4344 idlest = i;
e7693a36
GH
4345 }
4346 }
4347
aaee1203
PZ
4348 return idlest;
4349}
e7693a36 4350
a50bde51
PZ
4351/*
4352 * Try and locate an idle CPU in the sched_domain.
4353 */
99bd5e2f 4354static int select_idle_sibling(struct task_struct *p, int target)
a50bde51 4355{
99bd5e2f 4356 struct sched_domain *sd;
37407ea7 4357 struct sched_group *sg;
e0a79f52 4358 int i = task_cpu(p);
a50bde51 4359
e0a79f52
MG
4360 if (idle_cpu(target))
4361 return target;
99bd5e2f
SS
4362
4363 /*
e0a79f52 4364 * If the prevous cpu is cache affine and idle, don't be stupid.
99bd5e2f 4365 */
e0a79f52
MG
4366 if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
4367 return i;
a50bde51
PZ
4368
4369 /*
37407ea7 4370 * Otherwise, iterate the domains and find an elegible idle cpu.
a50bde51 4371 */
518cd623 4372 sd = rcu_dereference(per_cpu(sd_llc, target));
970e1789 4373 for_each_lower_domain(sd) {
37407ea7
LT
4374 sg = sd->groups;
4375 do {
4376 if (!cpumask_intersects(sched_group_cpus(sg),
4377 tsk_cpus_allowed(p)))
4378 goto next;
4379
4380 for_each_cpu(i, sched_group_cpus(sg)) {
e0a79f52 4381 if (i == target || !idle_cpu(i))
37407ea7
LT
4382 goto next;
4383 }
970e1789 4384
37407ea7
LT
4385 target = cpumask_first_and(sched_group_cpus(sg),
4386 tsk_cpus_allowed(p));
4387 goto done;
4388next:
4389 sg = sg->next;
4390 } while (sg != sd->groups);
4391 }
4392done:
a50bde51
PZ
4393 return target;
4394}
4395
aaee1203
PZ
4396/*
4397 * sched_balance_self: balance the current task (running on cpu) in domains
4398 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
4399 * SD_BALANCE_EXEC.
4400 *
4401 * Balance, ie. select the least loaded group.
4402 *
4403 * Returns the target CPU number, or the same CPU if no balancing is needed.
4404 *
4405 * preempt must be disabled.
4406 */
0017d735 4407static int
ac66f547 4408select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
aaee1203 4409{
29cd8bae 4410 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
c88d5910 4411 int cpu = smp_processor_id();
c88d5910 4412 int new_cpu = cpu;
99bd5e2f 4413 int want_affine = 0;
5158f4e4 4414 int sync = wake_flags & WF_SYNC;
c88d5910 4415
29baa747 4416 if (p->nr_cpus_allowed == 1)
76854c7e
MG
4417 return prev_cpu;
4418
0763a660 4419 if (sd_flag & SD_BALANCE_WAKE) {
fa17b507 4420 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
c88d5910
PZ
4421 want_affine = 1;
4422 new_cpu = prev_cpu;
4423 }
aaee1203 4424
dce840a0 4425 rcu_read_lock();
aaee1203 4426 for_each_domain(cpu, tmp) {
e4f42888
PZ
4427 if (!(tmp->flags & SD_LOAD_BALANCE))
4428 continue;
4429
fe3bcfe1 4430 /*
99bd5e2f
SS
4431 * If both cpu and prev_cpu are part of this domain,
4432 * cpu is a valid SD_WAKE_AFFINE target.
fe3bcfe1 4433 */
99bd5e2f
SS
4434 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
4435 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
4436 affine_sd = tmp;
29cd8bae 4437 break;
f03542a7 4438 }
29cd8bae 4439
f03542a7 4440 if (tmp->flags & sd_flag)
29cd8bae
PZ
4441 sd = tmp;
4442 }
4443
8b911acd 4444 if (affine_sd) {
f03542a7 4445 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
dce840a0
PZ
4446 prev_cpu = cpu;
4447
4448 new_cpu = select_idle_sibling(p, prev_cpu);
4449 goto unlock;
8b911acd 4450 }
e7693a36 4451
aaee1203
PZ
4452 while (sd) {
4453 struct sched_group *group;
c88d5910 4454 int weight;
098fb9db 4455
0763a660 4456 if (!(sd->flags & sd_flag)) {
aaee1203
PZ
4457 sd = sd->child;
4458 continue;
4459 }
098fb9db 4460
c44f2a02 4461 group = find_idlest_group(sd, p, cpu, sd_flag);
aaee1203
PZ
4462 if (!group) {
4463 sd = sd->child;
4464 continue;
4465 }
4ae7d5ce 4466
d7c33c49 4467 new_cpu = find_idlest_cpu(group, p, cpu);
aaee1203
PZ
4468 if (new_cpu == -1 || new_cpu == cpu) {
4469 /* Now try balancing at a lower domain level of cpu */
4470 sd = sd->child;
4471 continue;
e7693a36 4472 }
aaee1203
PZ
4473
4474 /* Now try balancing at a lower domain level of new_cpu */
4475 cpu = new_cpu;
669c55e9 4476 weight = sd->span_weight;
aaee1203
PZ
4477 sd = NULL;
4478 for_each_domain(cpu, tmp) {
669c55e9 4479 if (weight <= tmp->span_weight)
aaee1203 4480 break;
0763a660 4481 if (tmp->flags & sd_flag)
aaee1203
PZ
4482 sd = tmp;
4483 }
4484 /* while loop will break here if sd == NULL */
e7693a36 4485 }
dce840a0
PZ
4486unlock:
4487 rcu_read_unlock();
e7693a36 4488
c88d5910 4489 return new_cpu;
e7693a36 4490}
0a74bef8
PT
4491
4492/*
4493 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
4494 * cfs_rq_of(p) references at time of call are still valid and identify the
4495 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
4496 * other assumptions, including the state of rq->lock, should be made.
4497 */
4498static void
4499migrate_task_rq_fair(struct task_struct *p, int next_cpu)
4500{
aff3e498
PT
4501 struct sched_entity *se = &p->se;
4502 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4503
4504 /*
4505 * Load tracking: accumulate removed load so that it can be processed
4506 * when we next update owning cfs_rq under rq->lock. Tasks contribute
4507 * to blocked load iff they have a positive decay-count. It can never
4508 * be negative here since on-rq tasks have decay-count == 0.
4509 */
4510 if (se->avg.decay_count) {
4511 se->avg.decay_count = -__synchronize_entity_decay(se);
2509940f
AS
4512 atomic_long_add(se->avg.load_avg_contrib,
4513 &cfs_rq->removed_load);
aff3e498 4514 }
0a74bef8 4515}
e7693a36
GH
4516#endif /* CONFIG_SMP */
4517
e52fb7c0
PZ
4518static unsigned long
4519wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
0bbd3336
PZ
4520{
4521 unsigned long gran = sysctl_sched_wakeup_granularity;
4522
4523 /*
e52fb7c0
PZ
4524 * Since its curr running now, convert the gran from real-time
4525 * to virtual-time in his units.
13814d42
MG
4526 *
4527 * By using 'se' instead of 'curr' we penalize light tasks, so
4528 * they get preempted easier. That is, if 'se' < 'curr' then
4529 * the resulting gran will be larger, therefore penalizing the
4530 * lighter, if otoh 'se' > 'curr' then the resulting gran will
4531 * be smaller, again penalizing the lighter task.
4532 *
4533 * This is especially important for buddies when the leftmost
4534 * task is higher priority than the buddy.
0bbd3336 4535 */
f4ad9bd2 4536 return calc_delta_fair(gran, se);
0bbd3336
PZ
4537}
4538
464b7527
PZ
4539/*
4540 * Should 'se' preempt 'curr'.
4541 *
4542 * |s1
4543 * |s2
4544 * |s3
4545 * g
4546 * |<--->|c
4547 *
4548 * w(c, s1) = -1
4549 * w(c, s2) = 0
4550 * w(c, s3) = 1
4551 *
4552 */
4553static int
4554wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
4555{
4556 s64 gran, vdiff = curr->vruntime - se->vruntime;
4557
4558 if (vdiff <= 0)
4559 return -1;
4560
e52fb7c0 4561 gran = wakeup_gran(curr, se);
464b7527
PZ
4562 if (vdiff > gran)
4563 return 1;
4564
4565 return 0;
4566}
4567
02479099
PZ
4568static void set_last_buddy(struct sched_entity *se)
4569{
69c80f3e
VP
4570 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4571 return;
4572
4573 for_each_sched_entity(se)
4574 cfs_rq_of(se)->last = se;
02479099
PZ
4575}
4576
4577static void set_next_buddy(struct sched_entity *se)
4578{
69c80f3e
VP
4579 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4580 return;
4581
4582 for_each_sched_entity(se)
4583 cfs_rq_of(se)->next = se;
02479099
PZ
4584}
4585
ac53db59
RR
4586static void set_skip_buddy(struct sched_entity *se)
4587{
69c80f3e
VP
4588 for_each_sched_entity(se)
4589 cfs_rq_of(se)->skip = se;
ac53db59
RR
4590}
4591
bf0f6f24
IM
4592/*
4593 * Preempt the current task with a newly woken task if needed:
4594 */
5a9b86f6 4595static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
bf0f6f24
IM
4596{
4597 struct task_struct *curr = rq->curr;
8651a86c 4598 struct sched_entity *se = &curr->se, *pse = &p->se;
03e89e45 4599 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
f685ceac 4600 int scale = cfs_rq->nr_running >= sched_nr_latency;
2f36825b 4601 int next_buddy_marked = 0;
bf0f6f24 4602
4ae7d5ce
IM
4603 if (unlikely(se == pse))
4604 return;
4605
5238cdd3 4606 /*
ddcdf6e7 4607 * This is possible from callers such as move_task(), in which we
5238cdd3
PT
4608 * unconditionally check_prempt_curr() after an enqueue (which may have
4609 * lead to a throttle). This both saves work and prevents false
4610 * next-buddy nomination below.
4611 */
4612 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
4613 return;
4614
2f36825b 4615 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3cb63d52 4616 set_next_buddy(pse);
2f36825b
VP
4617 next_buddy_marked = 1;
4618 }
57fdc26d 4619
aec0a514
BR
4620 /*
4621 * We can come here with TIF_NEED_RESCHED already set from new task
4622 * wake up path.
5238cdd3
PT
4623 *
4624 * Note: this also catches the edge-case of curr being in a throttled
4625 * group (e.g. via set_curr_task), since update_curr() (in the
4626 * enqueue of curr) will have resulted in resched being set. This
4627 * prevents us from potentially nominating it as a false LAST_BUDDY
4628 * below.
aec0a514
BR
4629 */
4630 if (test_tsk_need_resched(curr))
4631 return;
4632
a2f5c9ab
DH
4633 /* Idle tasks are by definition preempted by non-idle tasks. */
4634 if (unlikely(curr->policy == SCHED_IDLE) &&
4635 likely(p->policy != SCHED_IDLE))
4636 goto preempt;
4637
91c234b4 4638 /*
a2f5c9ab
DH
4639 * Batch and idle tasks do not preempt non-idle tasks (their preemption
4640 * is driven by the tick):
91c234b4 4641 */
8ed92e51 4642 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
91c234b4 4643 return;
bf0f6f24 4644
464b7527 4645 find_matching_se(&se, &pse);
9bbd7374 4646 update_curr(cfs_rq_of(se));
002f128b 4647 BUG_ON(!pse);
2f36825b
VP
4648 if (wakeup_preempt_entity(se, pse) == 1) {
4649 /*
4650 * Bias pick_next to pick the sched entity that is
4651 * triggering this preemption.
4652 */
4653 if (!next_buddy_marked)
4654 set_next_buddy(pse);
3a7e73a2 4655 goto preempt;
2f36825b 4656 }
464b7527 4657
3a7e73a2 4658 return;
a65ac745 4659
3a7e73a2
PZ
4660preempt:
4661 resched_task(curr);
4662 /*
4663 * Only set the backward buddy when the current task is still
4664 * on the rq. This can happen when a wakeup gets interleaved
4665 * with schedule on the ->pre_schedule() or idle_balance()
4666 * point, either of which can * drop the rq lock.
4667 *
4668 * Also, during early boot the idle thread is in the fair class,
4669 * for obvious reasons its a bad idea to schedule back to it.
4670 */
4671 if (unlikely(!se->on_rq || curr == rq->idle))
4672 return;
4673
4674 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
4675 set_last_buddy(se);
bf0f6f24
IM
4676}
4677
606dba2e
PZ
4678static struct task_struct *
4679pick_next_task_fair(struct rq *rq, struct task_struct *prev)
bf0f6f24
IM
4680{
4681 struct cfs_rq *cfs_rq = &rq->cfs;
4682 struct sched_entity *se;
678d5718
PZ
4683 struct task_struct *p;
4684
4685#ifdef CONFIG_FAIR_GROUP_SCHED
4686 if (!cfs_rq->nr_running)
4687 return NULL;
4688
4689 if (!prev || prev->sched_class != &fair_sched_class)
4690 goto simple;
4691
4692 /*
4693 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
4694 * likely that a next task is from the same cgroup as the current.
4695 *
4696 * Therefore attempt to avoid putting and setting the entire cgroup
4697 * hierarchy, only change the part that actually changes.
4698 */
4699
4700 do {
4701 struct sched_entity *curr = cfs_rq->curr;
4702
4703 /*
4704 * Since we got here without doing put_prev_entity() we also
4705 * have to consider cfs_rq->curr. If it is still a runnable
4706 * entity, update_curr() will update its vruntime, otherwise
4707 * forget we've ever seen it.
4708 */
4709 if (curr && curr->on_rq)
4710 update_curr(cfs_rq);
4711 else
4712 curr = NULL;
4713
4714 /*
4715 * This call to check_cfs_rq_runtime() will do the throttle and
4716 * dequeue its entity in the parent(s). Therefore the 'simple'
4717 * nr_running test will indeed be correct.
4718 */
4719 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
4720 goto simple;
4721
4722 se = pick_next_entity(cfs_rq, curr);
4723 cfs_rq = group_cfs_rq(se);
4724 } while (cfs_rq);
4725
4726 p = task_of(se);
4727
4728 /*
4729 * Since we haven't yet done put_prev_entity and if the selected task
4730 * is a different task than we started out with, try and touch the
4731 * least amount of cfs_rqs.
4732 */
4733 if (prev != p) {
4734 struct sched_entity *pse = &prev->se;
4735
4736 while (!(cfs_rq = is_same_group(se, pse))) {
4737 int se_depth = se->depth;
4738 int pse_depth = pse->depth;
4739
4740 if (se_depth <= pse_depth) {
4741 put_prev_entity(cfs_rq_of(pse), pse);
4742 pse = parent_entity(pse);
4743 }
4744 if (se_depth >= pse_depth) {
4745 set_next_entity(cfs_rq_of(se), se);
4746 se = parent_entity(se);
4747 }
4748 }
4749
4750 put_prev_entity(cfs_rq, pse);
4751 set_next_entity(cfs_rq, se);
4752 }
4753
4754 if (hrtick_enabled(rq))
4755 hrtick_start_fair(rq, p);
4756
4757 return p;
4758simple:
4759 cfs_rq = &rq->cfs;
4760#endif
bf0f6f24 4761
36ace27e 4762 if (!cfs_rq->nr_running)
bf0f6f24
IM
4763 return NULL;
4764
606dba2e
PZ
4765 if (prev)
4766 prev->sched_class->put_prev_task(rq, prev);
4767
bf0f6f24 4768 do {
678d5718 4769 se = pick_next_entity(cfs_rq, NULL);
f4b6755f 4770 set_next_entity(cfs_rq, se);
bf0f6f24
IM
4771 cfs_rq = group_cfs_rq(se);
4772 } while (cfs_rq);
4773
8f4d37ec 4774 p = task_of(se);
678d5718 4775
b39e66ea
MG
4776 if (hrtick_enabled(rq))
4777 hrtick_start_fair(rq, p);
8f4d37ec
PZ
4778
4779 return p;
bf0f6f24
IM
4780}
4781
4782/*
4783 * Account for a descheduled task:
4784 */
31ee529c 4785static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
bf0f6f24
IM
4786{
4787 struct sched_entity *se = &prev->se;
4788 struct cfs_rq *cfs_rq;
4789
4790 for_each_sched_entity(se) {
4791 cfs_rq = cfs_rq_of(se);
ab6cde26 4792 put_prev_entity(cfs_rq, se);
bf0f6f24
IM
4793 }
4794}
4795
ac53db59
RR
4796/*
4797 * sched_yield() is very simple
4798 *
4799 * The magic of dealing with the ->skip buddy is in pick_next_entity.
4800 */
4801static void yield_task_fair(struct rq *rq)
4802{
4803 struct task_struct *curr = rq->curr;
4804 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4805 struct sched_entity *se = &curr->se;
4806
4807 /*
4808 * Are we the only task in the tree?
4809 */
4810 if (unlikely(rq->nr_running == 1))
4811 return;
4812
4813 clear_buddies(cfs_rq, se);
4814
4815 if (curr->policy != SCHED_BATCH) {
4816 update_rq_clock(rq);
4817 /*
4818 * Update run-time statistics of the 'current'.
4819 */
4820 update_curr(cfs_rq);
916671c0
MG
4821 /*
4822 * Tell update_rq_clock() that we've just updated,
4823 * so we don't do microscopic update in schedule()
4824 * and double the fastpath cost.
4825 */
4826 rq->skip_clock_update = 1;
ac53db59
RR
4827 }
4828
4829 set_skip_buddy(se);
4830}
4831
d95f4122
MG
4832static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
4833{
4834 struct sched_entity *se = &p->se;
4835
5238cdd3
PT
4836 /* throttled hierarchies are not runnable */
4837 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
d95f4122
MG
4838 return false;
4839
4840 /* Tell the scheduler that we'd really like pse to run next. */
4841 set_next_buddy(se);
4842
d95f4122
MG
4843 yield_task_fair(rq);
4844
4845 return true;
4846}
4847
681f3e68 4848#ifdef CONFIG_SMP
bf0f6f24 4849/**************************************************
e9c84cb8
PZ
4850 * Fair scheduling class load-balancing methods.
4851 *
4852 * BASICS
4853 *
4854 * The purpose of load-balancing is to achieve the same basic fairness the
4855 * per-cpu scheduler provides, namely provide a proportional amount of compute
4856 * time to each task. This is expressed in the following equation:
4857 *
4858 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
4859 *
4860 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
4861 * W_i,0 is defined as:
4862 *
4863 * W_i,0 = \Sum_j w_i,j (2)
4864 *
4865 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
4866 * is derived from the nice value as per prio_to_weight[].
4867 *
4868 * The weight average is an exponential decay average of the instantaneous
4869 * weight:
4870 *
4871 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
4872 *
4873 * P_i is the cpu power (or compute capacity) of cpu i, typically it is the
4874 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
4875 * can also include other factors [XXX].
4876 *
4877 * To achieve this balance we define a measure of imbalance which follows
4878 * directly from (1):
4879 *
4880 * imb_i,j = max{ avg(W/P), W_i/P_i } - min{ avg(W/P), W_j/P_j } (4)
4881 *
4882 * We them move tasks around to minimize the imbalance. In the continuous
4883 * function space it is obvious this converges, in the discrete case we get
4884 * a few fun cases generally called infeasible weight scenarios.
4885 *
4886 * [XXX expand on:
4887 * - infeasible weights;
4888 * - local vs global optima in the discrete case. ]
4889 *
4890 *
4891 * SCHED DOMAINS
4892 *
4893 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
4894 * for all i,j solution, we create a tree of cpus that follows the hardware
4895 * topology where each level pairs two lower groups (or better). This results
4896 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
4897 * tree to only the first of the previous level and we decrease the frequency
4898 * of load-balance at each level inv. proportional to the number of cpus in
4899 * the groups.
4900 *
4901 * This yields:
4902 *
4903 * log_2 n 1 n
4904 * \Sum { --- * --- * 2^i } = O(n) (5)
4905 * i = 0 2^i 2^i
4906 * `- size of each group
4907 * | | `- number of cpus doing load-balance
4908 * | `- freq
4909 * `- sum over all levels
4910 *
4911 * Coupled with a limit on how many tasks we can migrate every balance pass,
4912 * this makes (5) the runtime complexity of the balancer.
4913 *
4914 * An important property here is that each CPU is still (indirectly) connected
4915 * to every other cpu in at most O(log n) steps:
4916 *
4917 * The adjacency matrix of the resulting graph is given by:
4918 *
4919 * log_2 n
4920 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
4921 * k = 0
4922 *
4923 * And you'll find that:
4924 *
4925 * A^(log_2 n)_i,j != 0 for all i,j (7)
4926 *
4927 * Showing there's indeed a path between every cpu in at most O(log n) steps.
4928 * The task movement gives a factor of O(m), giving a convergence complexity
4929 * of:
4930 *
4931 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
4932 *
4933 *
4934 * WORK CONSERVING
4935 *
4936 * In order to avoid CPUs going idle while there's still work to do, new idle
4937 * balancing is more aggressive and has the newly idle cpu iterate up the domain
4938 * tree itself instead of relying on other CPUs to bring it work.
4939 *
4940 * This adds some complexity to both (5) and (8) but it reduces the total idle
4941 * time.
4942 *
4943 * [XXX more?]
4944 *
4945 *
4946 * CGROUPS
4947 *
4948 * Cgroups make a horror show out of (2), instead of a simple sum we get:
4949 *
4950 * s_k,i
4951 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
4952 * S_k
4953 *
4954 * Where
4955 *
4956 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
4957 *
4958 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
4959 *
4960 * The big problem is S_k, its a global sum needed to compute a local (W_i)
4961 * property.
4962 *
4963 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
4964 * rewrite all of this once again.]
4965 */
bf0f6f24 4966
ed387b78
HS
4967static unsigned long __read_mostly max_load_balance_interval = HZ/10;
4968
0ec8aa00
PZ
4969enum fbq_type { regular, remote, all };
4970
ddcdf6e7 4971#define LBF_ALL_PINNED 0x01
367456c7 4972#define LBF_NEED_BREAK 0x02
6263322c
PZ
4973#define LBF_DST_PINNED 0x04
4974#define LBF_SOME_PINNED 0x08
ddcdf6e7
PZ
4975
4976struct lb_env {
4977 struct sched_domain *sd;
4978
ddcdf6e7 4979 struct rq *src_rq;
85c1e7da 4980 int src_cpu;
ddcdf6e7
PZ
4981
4982 int dst_cpu;
4983 struct rq *dst_rq;
4984
88b8dac0
SV
4985 struct cpumask *dst_grpmask;
4986 int new_dst_cpu;
ddcdf6e7 4987 enum cpu_idle_type idle;
bd939f45 4988 long imbalance;
b9403130
MW
4989 /* The set of CPUs under consideration for load-balancing */
4990 struct cpumask *cpus;
4991
ddcdf6e7 4992 unsigned int flags;
367456c7
PZ
4993
4994 unsigned int loop;
4995 unsigned int loop_break;
4996 unsigned int loop_max;
0ec8aa00
PZ
4997
4998 enum fbq_type fbq_type;
ddcdf6e7
PZ
4999};
5000
1e3c88bd 5001/*
ddcdf6e7 5002 * move_task - move a task from one runqueue to another runqueue.
1e3c88bd
PZ
5003 * Both runqueues must be locked.
5004 */
ddcdf6e7 5005static void move_task(struct task_struct *p, struct lb_env *env)
1e3c88bd 5006{
ddcdf6e7
PZ
5007 deactivate_task(env->src_rq, p, 0);
5008 set_task_cpu(p, env->dst_cpu);
5009 activate_task(env->dst_rq, p, 0);
5010 check_preempt_curr(env->dst_rq, p, 0);
1e3c88bd
PZ
5011}
5012
029632fb
PZ
5013/*
5014 * Is this task likely cache-hot:
5015 */
5016static int
5017task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
5018{
5019 s64 delta;
5020
5021 if (p->sched_class != &fair_sched_class)
5022 return 0;
5023
5024 if (unlikely(p->policy == SCHED_IDLE))
5025 return 0;
5026
5027 /*
5028 * Buddy candidates are cache hot:
5029 */
5030 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
5031 (&p->se == cfs_rq_of(&p->se)->next ||
5032 &p->se == cfs_rq_of(&p->se)->last))
5033 return 1;
5034
5035 if (sysctl_sched_migration_cost == -1)
5036 return 1;
5037 if (sysctl_sched_migration_cost == 0)
5038 return 0;
5039
5040 delta = now - p->se.exec_start;
5041
5042 return delta < (s64)sysctl_sched_migration_cost;
5043}
5044
3a7053b3
MG
5045#ifdef CONFIG_NUMA_BALANCING
5046/* Returns true if the destination node has incurred more faults */
5047static bool migrate_improves_locality(struct task_struct *p, struct lb_env *env)
5048{
5049 int src_nid, dst_nid;
5050
ff1df896 5051 if (!sched_feat(NUMA_FAVOUR_HIGHER) || !p->numa_faults_memory ||
3a7053b3
MG
5052 !(env->sd->flags & SD_NUMA)) {
5053 return false;
5054 }
5055
5056 src_nid = cpu_to_node(env->src_cpu);
5057 dst_nid = cpu_to_node(env->dst_cpu);
5058
83e1d2cd 5059 if (src_nid == dst_nid)
3a7053b3
MG
5060 return false;
5061
83e1d2cd
MG
5062 /* Always encourage migration to the preferred node. */
5063 if (dst_nid == p->numa_preferred_nid)
5064 return true;
5065
887c290e
RR
5066 /* If both task and group weight improve, this move is a winner. */
5067 if (task_weight(p, dst_nid) > task_weight(p, src_nid) &&
5068 group_weight(p, dst_nid) > group_weight(p, src_nid))
3a7053b3
MG
5069 return true;
5070
5071 return false;
5072}
7a0f3083
MG
5073
5074
5075static bool migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
5076{
5077 int src_nid, dst_nid;
5078
5079 if (!sched_feat(NUMA) || !sched_feat(NUMA_RESIST_LOWER))
5080 return false;
5081
ff1df896 5082 if (!p->numa_faults_memory || !(env->sd->flags & SD_NUMA))
7a0f3083
MG
5083 return false;
5084
5085 src_nid = cpu_to_node(env->src_cpu);
5086 dst_nid = cpu_to_node(env->dst_cpu);
5087
83e1d2cd 5088 if (src_nid == dst_nid)
7a0f3083
MG
5089 return false;
5090
83e1d2cd
MG
5091 /* Migrating away from the preferred node is always bad. */
5092 if (src_nid == p->numa_preferred_nid)
5093 return true;
5094
887c290e
RR
5095 /* If either task or group weight get worse, don't do it. */
5096 if (task_weight(p, dst_nid) < task_weight(p, src_nid) ||
5097 group_weight(p, dst_nid) < group_weight(p, src_nid))
7a0f3083
MG
5098 return true;
5099
5100 return false;
5101}
5102
3a7053b3
MG
5103#else
5104static inline bool migrate_improves_locality(struct task_struct *p,
5105 struct lb_env *env)
5106{
5107 return false;
5108}
7a0f3083
MG
5109
5110static inline bool migrate_degrades_locality(struct task_struct *p,
5111 struct lb_env *env)
5112{
5113 return false;
5114}
3a7053b3
MG
5115#endif
5116
1e3c88bd
PZ
5117/*
5118 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
5119 */
5120static
8e45cb54 5121int can_migrate_task(struct task_struct *p, struct lb_env *env)
1e3c88bd
PZ
5122{
5123 int tsk_cache_hot = 0;
5124 /*
5125 * We do not migrate tasks that are:
d3198084 5126 * 1) throttled_lb_pair, or
1e3c88bd 5127 * 2) cannot be migrated to this CPU due to cpus_allowed, or
d3198084
JK
5128 * 3) running (obviously), or
5129 * 4) are cache-hot on their current CPU.
1e3c88bd 5130 */
d3198084
JK
5131 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
5132 return 0;
5133
ddcdf6e7 5134 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
e02e60c1 5135 int cpu;
88b8dac0 5136
41acab88 5137 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
88b8dac0 5138
6263322c
PZ
5139 env->flags |= LBF_SOME_PINNED;
5140
88b8dac0
SV
5141 /*
5142 * Remember if this task can be migrated to any other cpu in
5143 * our sched_group. We may want to revisit it if we couldn't
5144 * meet load balance goals by pulling other tasks on src_cpu.
5145 *
5146 * Also avoid computing new_dst_cpu if we have already computed
5147 * one in current iteration.
5148 */
6263322c 5149 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
88b8dac0
SV
5150 return 0;
5151
e02e60c1
JK
5152 /* Prevent to re-select dst_cpu via env's cpus */
5153 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
5154 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
6263322c 5155 env->flags |= LBF_DST_PINNED;
e02e60c1
JK
5156 env->new_dst_cpu = cpu;
5157 break;
5158 }
88b8dac0 5159 }
e02e60c1 5160
1e3c88bd
PZ
5161 return 0;
5162 }
88b8dac0
SV
5163
5164 /* Record that we found atleast one task that could run on dst_cpu */
8e45cb54 5165 env->flags &= ~LBF_ALL_PINNED;
1e3c88bd 5166
ddcdf6e7 5167 if (task_running(env->src_rq, p)) {
41acab88 5168 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
1e3c88bd
PZ
5169 return 0;
5170 }
5171
5172 /*
5173 * Aggressive migration if:
3a7053b3
MG
5174 * 1) destination numa is preferred
5175 * 2) task is cache cold, or
5176 * 3) too many balance attempts have failed.
1e3c88bd 5177 */
78becc27 5178 tsk_cache_hot = task_hot(p, rq_clock_task(env->src_rq), env->sd);
7a0f3083
MG
5179 if (!tsk_cache_hot)
5180 tsk_cache_hot = migrate_degrades_locality(p, env);
3a7053b3
MG
5181
5182 if (migrate_improves_locality(p, env)) {
5183#ifdef CONFIG_SCHEDSTATS
5184 if (tsk_cache_hot) {
5185 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
5186 schedstat_inc(p, se.statistics.nr_forced_migrations);
5187 }
5188#endif
5189 return 1;
5190 }
5191
1e3c88bd 5192 if (!tsk_cache_hot ||
8e45cb54 5193 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
4e2dcb73 5194
1e3c88bd 5195 if (tsk_cache_hot) {
8e45cb54 5196 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
41acab88 5197 schedstat_inc(p, se.statistics.nr_forced_migrations);
1e3c88bd 5198 }
4e2dcb73 5199
1e3c88bd
PZ
5200 return 1;
5201 }
5202
4e2dcb73
ZH
5203 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
5204 return 0;
1e3c88bd
PZ
5205}
5206
897c395f
PZ
5207/*
5208 * move_one_task tries to move exactly one task from busiest to this_rq, as
5209 * part of active balancing operations within "domain".
5210 * Returns 1 if successful and 0 otherwise.
5211 *
5212 * Called with both runqueues locked.
5213 */
8e45cb54 5214static int move_one_task(struct lb_env *env)
897c395f
PZ
5215{
5216 struct task_struct *p, *n;
897c395f 5217
367456c7 5218 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
367456c7
PZ
5219 if (!can_migrate_task(p, env))
5220 continue;
897c395f 5221
367456c7
PZ
5222 move_task(p, env);
5223 /*
5224 * Right now, this is only the second place move_task()
5225 * is called, so we can safely collect move_task()
5226 * stats here rather than inside move_task().
5227 */
5228 schedstat_inc(env->sd, lb_gained[env->idle]);
5229 return 1;
897c395f 5230 }
897c395f
PZ
5231 return 0;
5232}
5233
eb95308e
PZ
5234static const unsigned int sched_nr_migrate_break = 32;
5235
5d6523eb 5236/*
bd939f45 5237 * move_tasks tries to move up to imbalance weighted load from busiest to
5d6523eb
PZ
5238 * this_rq, as part of a balancing operation within domain "sd".
5239 * Returns 1 if successful and 0 otherwise.
5240 *
5241 * Called with both runqueues locked.
5242 */
5243static int move_tasks(struct lb_env *env)
1e3c88bd 5244{
5d6523eb
PZ
5245 struct list_head *tasks = &env->src_rq->cfs_tasks;
5246 struct task_struct *p;
367456c7
PZ
5247 unsigned long load;
5248 int pulled = 0;
1e3c88bd 5249
bd939f45 5250 if (env->imbalance <= 0)
5d6523eb 5251 return 0;
1e3c88bd 5252
5d6523eb
PZ
5253 while (!list_empty(tasks)) {
5254 p = list_first_entry(tasks, struct task_struct, se.group_node);
1e3c88bd 5255
367456c7
PZ
5256 env->loop++;
5257 /* We've more or less seen every task there is, call it quits */
5d6523eb 5258 if (env->loop > env->loop_max)
367456c7 5259 break;
5d6523eb
PZ
5260
5261 /* take a breather every nr_migrate tasks */
367456c7 5262 if (env->loop > env->loop_break) {
eb95308e 5263 env->loop_break += sched_nr_migrate_break;
8e45cb54 5264 env->flags |= LBF_NEED_BREAK;
ee00e66f 5265 break;
a195f004 5266 }
1e3c88bd 5267
d3198084 5268 if (!can_migrate_task(p, env))
367456c7
PZ
5269 goto next;
5270
5271 load = task_h_load(p);
5d6523eb 5272
eb95308e 5273 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
367456c7
PZ
5274 goto next;
5275
bd939f45 5276 if ((load / 2) > env->imbalance)
367456c7 5277 goto next;
1e3c88bd 5278
ddcdf6e7 5279 move_task(p, env);
ee00e66f 5280 pulled++;
bd939f45 5281 env->imbalance -= load;
1e3c88bd
PZ
5282
5283#ifdef CONFIG_PREEMPT
ee00e66f
PZ
5284 /*
5285 * NEWIDLE balancing is a source of latency, so preemptible
5286 * kernels will stop after the first task is pulled to minimize
5287 * the critical section.
5288 */
5d6523eb 5289 if (env->idle == CPU_NEWLY_IDLE)
ee00e66f 5290 break;
1e3c88bd
PZ
5291#endif
5292
ee00e66f
PZ
5293 /*
5294 * We only want to steal up to the prescribed amount of
5295 * weighted load.
5296 */
bd939f45 5297 if (env->imbalance <= 0)
ee00e66f 5298 break;
367456c7
PZ
5299
5300 continue;
5301next:
5d6523eb 5302 list_move_tail(&p->se.group_node, tasks);
1e3c88bd 5303 }
5d6523eb 5304
1e3c88bd 5305 /*
ddcdf6e7
PZ
5306 * Right now, this is one of only two places move_task() is called,
5307 * so we can safely collect move_task() stats here rather than
5308 * inside move_task().
1e3c88bd 5309 */
8e45cb54 5310 schedstat_add(env->sd, lb_gained[env->idle], pulled);
1e3c88bd 5311
5d6523eb 5312 return pulled;
1e3c88bd
PZ
5313}
5314
230059de 5315#ifdef CONFIG_FAIR_GROUP_SCHED
9e3081ca
PZ
5316/*
5317 * update tg->load_weight by folding this cpu's load_avg
5318 */
48a16753 5319static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
9e3081ca 5320{
48a16753
PT
5321 struct sched_entity *se = tg->se[cpu];
5322 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
9e3081ca 5323
48a16753
PT
5324 /* throttled entities do not contribute to load */
5325 if (throttled_hierarchy(cfs_rq))
5326 return;
9e3081ca 5327
aff3e498 5328 update_cfs_rq_blocked_load(cfs_rq, 1);
9e3081ca 5329
82958366
PT
5330 if (se) {
5331 update_entity_load_avg(se, 1);
5332 /*
5333 * We pivot on our runnable average having decayed to zero for
5334 * list removal. This generally implies that all our children
5335 * have also been removed (modulo rounding error or bandwidth
5336 * control); however, such cases are rare and we can fix these
5337 * at enqueue.
5338 *
5339 * TODO: fix up out-of-order children on enqueue.
5340 */
5341 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
5342 list_del_leaf_cfs_rq(cfs_rq);
5343 } else {
48a16753 5344 struct rq *rq = rq_of(cfs_rq);
82958366
PT
5345 update_rq_runnable_avg(rq, rq->nr_running);
5346 }
9e3081ca
PZ
5347}
5348
48a16753 5349static void update_blocked_averages(int cpu)
9e3081ca 5350{
9e3081ca 5351 struct rq *rq = cpu_rq(cpu);
48a16753
PT
5352 struct cfs_rq *cfs_rq;
5353 unsigned long flags;
9e3081ca 5354
48a16753
PT
5355 raw_spin_lock_irqsave(&rq->lock, flags);
5356 update_rq_clock(rq);
9763b67f
PZ
5357 /*
5358 * Iterates the task_group tree in a bottom up fashion, see
5359 * list_add_leaf_cfs_rq() for details.
5360 */
64660c86 5361 for_each_leaf_cfs_rq(rq, cfs_rq) {
48a16753
PT
5362 /*
5363 * Note: We may want to consider periodically releasing
5364 * rq->lock about these updates so that creating many task
5365 * groups does not result in continually extending hold time.
5366 */
5367 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
64660c86 5368 }
48a16753
PT
5369
5370 raw_spin_unlock_irqrestore(&rq->lock, flags);
9e3081ca
PZ
5371}
5372
9763b67f 5373/*
68520796 5374 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9763b67f
PZ
5375 * This needs to be done in a top-down fashion because the load of a child
5376 * group is a fraction of its parents load.
5377 */
68520796 5378static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9763b67f 5379{
68520796
VD
5380 struct rq *rq = rq_of(cfs_rq);
5381 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
a35b6466 5382 unsigned long now = jiffies;
68520796 5383 unsigned long load;
a35b6466 5384
68520796 5385 if (cfs_rq->last_h_load_update == now)
a35b6466
PZ
5386 return;
5387
68520796
VD
5388 cfs_rq->h_load_next = NULL;
5389 for_each_sched_entity(se) {
5390 cfs_rq = cfs_rq_of(se);
5391 cfs_rq->h_load_next = se;
5392 if (cfs_rq->last_h_load_update == now)
5393 break;
5394 }
a35b6466 5395
68520796 5396 if (!se) {
7e3115ef 5397 cfs_rq->h_load = cfs_rq->runnable_load_avg;
68520796
VD
5398 cfs_rq->last_h_load_update = now;
5399 }
5400
5401 while ((se = cfs_rq->h_load_next) != NULL) {
5402 load = cfs_rq->h_load;
5403 load = div64_ul(load * se->avg.load_avg_contrib,
5404 cfs_rq->runnable_load_avg + 1);
5405 cfs_rq = group_cfs_rq(se);
5406 cfs_rq->h_load = load;
5407 cfs_rq->last_h_load_update = now;
5408 }
9763b67f
PZ
5409}
5410
367456c7 5411static unsigned long task_h_load(struct task_struct *p)
230059de 5412{
367456c7 5413 struct cfs_rq *cfs_rq = task_cfs_rq(p);
230059de 5414
68520796 5415 update_cfs_rq_h_load(cfs_rq);
a003a25b
AS
5416 return div64_ul(p->se.avg.load_avg_contrib * cfs_rq->h_load,
5417 cfs_rq->runnable_load_avg + 1);
230059de
PZ
5418}
5419#else
48a16753 5420static inline void update_blocked_averages(int cpu)
9e3081ca
PZ
5421{
5422}
5423
367456c7 5424static unsigned long task_h_load(struct task_struct *p)
1e3c88bd 5425{
a003a25b 5426 return p->se.avg.load_avg_contrib;
1e3c88bd 5427}
230059de 5428#endif
1e3c88bd 5429
1e3c88bd 5430/********** Helpers for find_busiest_group ************************/
1e3c88bd
PZ
5431/*
5432 * sg_lb_stats - stats of a sched_group required for load_balancing
5433 */
5434struct sg_lb_stats {
5435 unsigned long avg_load; /*Avg load across the CPUs of the group */
5436 unsigned long group_load; /* Total load over the CPUs of the group */
1e3c88bd 5437 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
56cf515b 5438 unsigned long load_per_task;
3ae11c90 5439 unsigned long group_power;
147c5fc2
PZ
5440 unsigned int sum_nr_running; /* Nr tasks running in the group */
5441 unsigned int group_capacity;
5442 unsigned int idle_cpus;
5443 unsigned int group_weight;
1e3c88bd 5444 int group_imb; /* Is there an imbalance in the group ? */
fab47622 5445 int group_has_capacity; /* Is there extra capacity in the group? */
0ec8aa00
PZ
5446#ifdef CONFIG_NUMA_BALANCING
5447 unsigned int nr_numa_running;
5448 unsigned int nr_preferred_running;
5449#endif
1e3c88bd
PZ
5450};
5451
56cf515b
JK
5452/*
5453 * sd_lb_stats - Structure to store the statistics of a sched_domain
5454 * during load balancing.
5455 */
5456struct sd_lb_stats {
5457 struct sched_group *busiest; /* Busiest group in this sd */
5458 struct sched_group *local; /* Local group in this sd */
5459 unsigned long total_load; /* Total load of all groups in sd */
5460 unsigned long total_pwr; /* Total power of all groups in sd */
5461 unsigned long avg_load; /* Average load across all groups in sd */
5462
56cf515b 5463 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
147c5fc2 5464 struct sg_lb_stats local_stat; /* Statistics of the local group */
56cf515b
JK
5465};
5466
147c5fc2
PZ
5467static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
5468{
5469 /*
5470 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
5471 * local_stat because update_sg_lb_stats() does a full clear/assignment.
5472 * We must however clear busiest_stat::avg_load because
5473 * update_sd_pick_busiest() reads this before assignment.
5474 */
5475 *sds = (struct sd_lb_stats){
5476 .busiest = NULL,
5477 .local = NULL,
5478 .total_load = 0UL,
5479 .total_pwr = 0UL,
5480 .busiest_stat = {
5481 .avg_load = 0UL,
5482 },
5483 };
5484}
5485
1e3c88bd
PZ
5486/**
5487 * get_sd_load_idx - Obtain the load index for a given sched domain.
5488 * @sd: The sched_domain whose load_idx is to be obtained.
ed1b7732 5489 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
e69f6186
YB
5490 *
5491 * Return: The load index.
1e3c88bd
PZ
5492 */
5493static inline int get_sd_load_idx(struct sched_domain *sd,
5494 enum cpu_idle_type idle)
5495{
5496 int load_idx;
5497
5498 switch (idle) {
5499 case CPU_NOT_IDLE:
5500 load_idx = sd->busy_idx;
5501 break;
5502
5503 case CPU_NEWLY_IDLE:
5504 load_idx = sd->newidle_idx;
5505 break;
5506 default:
5507 load_idx = sd->idle_idx;
5508 break;
5509 }
5510
5511 return load_idx;
5512}
5513
15f803c9 5514static unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
1e3c88bd 5515{
1399fa78 5516 return SCHED_POWER_SCALE;
1e3c88bd
PZ
5517}
5518
5519unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
5520{
5521 return default_scale_freq_power(sd, cpu);
5522}
5523
15f803c9 5524static unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
1e3c88bd 5525{
669c55e9 5526 unsigned long weight = sd->span_weight;
1e3c88bd
PZ
5527 unsigned long smt_gain = sd->smt_gain;
5528
5529 smt_gain /= weight;
5530
5531 return smt_gain;
5532}
5533
5534unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
5535{
5536 return default_scale_smt_power(sd, cpu);
5537}
5538
15f803c9 5539static unsigned long scale_rt_power(int cpu)
1e3c88bd
PZ
5540{
5541 struct rq *rq = cpu_rq(cpu);
b654f7de 5542 u64 total, available, age_stamp, avg;
1e3c88bd 5543
b654f7de
PZ
5544 /*
5545 * Since we're reading these variables without serialization make sure
5546 * we read them once before doing sanity checks on them.
5547 */
5548 age_stamp = ACCESS_ONCE(rq->age_stamp);
5549 avg = ACCESS_ONCE(rq->rt_avg);
5550
78becc27 5551 total = sched_avg_period() + (rq_clock(rq) - age_stamp);
aa483808 5552
b654f7de 5553 if (unlikely(total < avg)) {
aa483808
VP
5554 /* Ensures that power won't end up being negative */
5555 available = 0;
5556 } else {
b654f7de 5557 available = total - avg;
aa483808 5558 }
1e3c88bd 5559
1399fa78
NR
5560 if (unlikely((s64)total < SCHED_POWER_SCALE))
5561 total = SCHED_POWER_SCALE;
1e3c88bd 5562
1399fa78 5563 total >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
5564
5565 return div_u64(available, total);
5566}
5567
5568static void update_cpu_power(struct sched_domain *sd, int cpu)
5569{
669c55e9 5570 unsigned long weight = sd->span_weight;
1399fa78 5571 unsigned long power = SCHED_POWER_SCALE;
1e3c88bd
PZ
5572 struct sched_group *sdg = sd->groups;
5573
1e3c88bd
PZ
5574 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
5575 if (sched_feat(ARCH_POWER))
5576 power *= arch_scale_smt_power(sd, cpu);
5577 else
5578 power *= default_scale_smt_power(sd, cpu);
5579
1399fa78 5580 power >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
5581 }
5582
9c3f75cb 5583 sdg->sgp->power_orig = power;
9d5efe05
SV
5584
5585 if (sched_feat(ARCH_POWER))
5586 power *= arch_scale_freq_power(sd, cpu);
5587 else
5588 power *= default_scale_freq_power(sd, cpu);
5589
1399fa78 5590 power >>= SCHED_POWER_SHIFT;
9d5efe05 5591
1e3c88bd 5592 power *= scale_rt_power(cpu);
1399fa78 5593 power >>= SCHED_POWER_SHIFT;
1e3c88bd
PZ
5594
5595 if (!power)
5596 power = 1;
5597
e51fd5e2 5598 cpu_rq(cpu)->cpu_power = power;
9c3f75cb 5599 sdg->sgp->power = power;
1e3c88bd
PZ
5600}
5601
029632fb 5602void update_group_power(struct sched_domain *sd, int cpu)
1e3c88bd
PZ
5603{
5604 struct sched_domain *child = sd->child;
5605 struct sched_group *group, *sdg = sd->groups;
863bffc8 5606 unsigned long power, power_orig;
4ec4412e
VG
5607 unsigned long interval;
5608
5609 interval = msecs_to_jiffies(sd->balance_interval);
5610 interval = clamp(interval, 1UL, max_load_balance_interval);
5611 sdg->sgp->next_update = jiffies + interval;
1e3c88bd
PZ
5612
5613 if (!child) {
5614 update_cpu_power(sd, cpu);
5615 return;
5616 }
5617
863bffc8 5618 power_orig = power = 0;
1e3c88bd 5619
74a5ce20
PZ
5620 if (child->flags & SD_OVERLAP) {
5621 /*
5622 * SD_OVERLAP domains cannot assume that child groups
5623 * span the current group.
5624 */
5625
863bffc8 5626 for_each_cpu(cpu, sched_group_cpus(sdg)) {
9abf24d4
SD
5627 struct sched_group_power *sgp;
5628 struct rq *rq = cpu_rq(cpu);
863bffc8 5629
9abf24d4
SD
5630 /*
5631 * build_sched_domains() -> init_sched_groups_power()
5632 * gets here before we've attached the domains to the
5633 * runqueues.
5634 *
5635 * Use power_of(), which is set irrespective of domains
5636 * in update_cpu_power().
5637 *
5638 * This avoids power/power_orig from being 0 and
5639 * causing divide-by-zero issues on boot.
5640 *
5641 * Runtime updates will correct power_orig.
5642 */
5643 if (unlikely(!rq->sd)) {
5644 power_orig += power_of(cpu);
5645 power += power_of(cpu);
5646 continue;
5647 }
863bffc8 5648
9abf24d4
SD
5649 sgp = rq->sd->groups->sgp;
5650 power_orig += sgp->power_orig;
5651 power += sgp->power;
863bffc8 5652 }
74a5ce20
PZ
5653 } else {
5654 /*
5655 * !SD_OVERLAP domains can assume that child groups
5656 * span the current group.
5657 */
5658
5659 group = child->groups;
5660 do {
863bffc8 5661 power_orig += group->sgp->power_orig;
74a5ce20
PZ
5662 power += group->sgp->power;
5663 group = group->next;
5664 } while (group != child->groups);
5665 }
1e3c88bd 5666
863bffc8
PZ
5667 sdg->sgp->power_orig = power_orig;
5668 sdg->sgp->power = power;
1e3c88bd
PZ
5669}
5670
9d5efe05
SV
5671/*
5672 * Try and fix up capacity for tiny siblings, this is needed when
5673 * things like SD_ASYM_PACKING need f_b_g to select another sibling
5674 * which on its own isn't powerful enough.
5675 *
5676 * See update_sd_pick_busiest() and check_asym_packing().
5677 */
5678static inline int
5679fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
5680{
5681 /*
1399fa78 5682 * Only siblings can have significantly less than SCHED_POWER_SCALE
9d5efe05 5683 */
a6c75f2f 5684 if (!(sd->flags & SD_SHARE_CPUPOWER))
9d5efe05
SV
5685 return 0;
5686
5687 /*
5688 * If ~90% of the cpu_power is still there, we're good.
5689 */
9c3f75cb 5690 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
9d5efe05
SV
5691 return 1;
5692
5693 return 0;
5694}
5695
30ce5dab
PZ
5696/*
5697 * Group imbalance indicates (and tries to solve) the problem where balancing
5698 * groups is inadequate due to tsk_cpus_allowed() constraints.
5699 *
5700 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
5701 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
5702 * Something like:
5703 *
5704 * { 0 1 2 3 } { 4 5 6 7 }
5705 * * * * *
5706 *
5707 * If we were to balance group-wise we'd place two tasks in the first group and
5708 * two tasks in the second group. Clearly this is undesired as it will overload
5709 * cpu 3 and leave one of the cpus in the second group unused.
5710 *
5711 * The current solution to this issue is detecting the skew in the first group
6263322c
PZ
5712 * by noticing the lower domain failed to reach balance and had difficulty
5713 * moving tasks due to affinity constraints.
30ce5dab
PZ
5714 *
5715 * When this is so detected; this group becomes a candidate for busiest; see
ed1b7732 5716 * update_sd_pick_busiest(). And calculate_imbalance() and
6263322c 5717 * find_busiest_group() avoid some of the usual balance conditions to allow it
30ce5dab
PZ
5718 * to create an effective group imbalance.
5719 *
5720 * This is a somewhat tricky proposition since the next run might not find the
5721 * group imbalance and decide the groups need to be balanced again. A most
5722 * subtle and fragile situation.
5723 */
5724
6263322c 5725static inline int sg_imbalanced(struct sched_group *group)
30ce5dab 5726{
6263322c 5727 return group->sgp->imbalance;
30ce5dab
PZ
5728}
5729
b37d9316
PZ
5730/*
5731 * Compute the group capacity.
5732 *
c61037e9
PZ
5733 * Avoid the issue where N*frac(smt_power) >= 1 creates 'phantom' cores by
5734 * first dividing out the smt factor and computing the actual number of cores
5735 * and limit power unit capacity with that.
b37d9316
PZ
5736 */
5737static inline int sg_capacity(struct lb_env *env, struct sched_group *group)
5738{
c61037e9
PZ
5739 unsigned int capacity, smt, cpus;
5740 unsigned int power, power_orig;
5741
5742 power = group->sgp->power;
5743 power_orig = group->sgp->power_orig;
5744 cpus = group->group_weight;
b37d9316 5745
c61037e9
PZ
5746 /* smt := ceil(cpus / power), assumes: 1 < smt_power < 2 */
5747 smt = DIV_ROUND_UP(SCHED_POWER_SCALE * cpus, power_orig);
5748 capacity = cpus / smt; /* cores */
b37d9316 5749
c61037e9 5750 capacity = min_t(unsigned, capacity, DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE));
b37d9316
PZ
5751 if (!capacity)
5752 capacity = fix_small_capacity(env->sd, group);
5753
5754 return capacity;
5755}
5756
1e3c88bd
PZ
5757/**
5758 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
cd96891d 5759 * @env: The load balancing environment.
1e3c88bd 5760 * @group: sched_group whose statistics are to be updated.
1e3c88bd 5761 * @load_idx: Load index of sched_domain of this_cpu for load calc.
1e3c88bd 5762 * @local_group: Does group contain this_cpu.
1e3c88bd
PZ
5763 * @sgs: variable to hold the statistics for this group.
5764 */
bd939f45
PZ
5765static inline void update_sg_lb_stats(struct lb_env *env,
5766 struct sched_group *group, int load_idx,
23f0d209 5767 int local_group, struct sg_lb_stats *sgs)
1e3c88bd 5768{
30ce5dab 5769 unsigned long load;
bd939f45 5770 int i;
1e3c88bd 5771
b72ff13c
PZ
5772 memset(sgs, 0, sizeof(*sgs));
5773
b9403130 5774 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
1e3c88bd
PZ
5775 struct rq *rq = cpu_rq(i);
5776
1e3c88bd 5777 /* Bias balancing toward cpus of our domain */
6263322c 5778 if (local_group)
04f733b4 5779 load = target_load(i, load_idx);
6263322c 5780 else
1e3c88bd 5781 load = source_load(i, load_idx);
1e3c88bd
PZ
5782
5783 sgs->group_load += load;
380c9077 5784 sgs->sum_nr_running += rq->nr_running;
0ec8aa00
PZ
5785#ifdef CONFIG_NUMA_BALANCING
5786 sgs->nr_numa_running += rq->nr_numa_running;
5787 sgs->nr_preferred_running += rq->nr_preferred_running;
5788#endif
1e3c88bd 5789 sgs->sum_weighted_load += weighted_cpuload(i);
aae6d3dd
SS
5790 if (idle_cpu(i))
5791 sgs->idle_cpus++;
1e3c88bd
PZ
5792 }
5793
1e3c88bd 5794 /* Adjust by relative CPU power of the group */
3ae11c90
PZ
5795 sgs->group_power = group->sgp->power;
5796 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / sgs->group_power;
1e3c88bd 5797
dd5feea1 5798 if (sgs->sum_nr_running)
38d0f770 5799 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
1e3c88bd 5800
aae6d3dd 5801 sgs->group_weight = group->group_weight;
fab47622 5802
b37d9316
PZ
5803 sgs->group_imb = sg_imbalanced(group);
5804 sgs->group_capacity = sg_capacity(env, group);
5805
fab47622
NR
5806 if (sgs->group_capacity > sgs->sum_nr_running)
5807 sgs->group_has_capacity = 1;
1e3c88bd
PZ
5808}
5809
532cb4c4
MN
5810/**
5811 * update_sd_pick_busiest - return 1 on busiest group
cd96891d 5812 * @env: The load balancing environment.
532cb4c4
MN
5813 * @sds: sched_domain statistics
5814 * @sg: sched_group candidate to be checked for being the busiest
b6b12294 5815 * @sgs: sched_group statistics
532cb4c4
MN
5816 *
5817 * Determine if @sg is a busier group than the previously selected
5818 * busiest group.
e69f6186
YB
5819 *
5820 * Return: %true if @sg is a busier group than the previously selected
5821 * busiest group. %false otherwise.
532cb4c4 5822 */
bd939f45 5823static bool update_sd_pick_busiest(struct lb_env *env,
532cb4c4
MN
5824 struct sd_lb_stats *sds,
5825 struct sched_group *sg,
bd939f45 5826 struct sg_lb_stats *sgs)
532cb4c4 5827{
56cf515b 5828 if (sgs->avg_load <= sds->busiest_stat.avg_load)
532cb4c4
MN
5829 return false;
5830
5831 if (sgs->sum_nr_running > sgs->group_capacity)
5832 return true;
5833
5834 if (sgs->group_imb)
5835 return true;
5836
5837 /*
5838 * ASYM_PACKING needs to move all the work to the lowest
5839 * numbered CPUs in the group, therefore mark all groups
5840 * higher than ourself as busy.
5841 */
bd939f45
PZ
5842 if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
5843 env->dst_cpu < group_first_cpu(sg)) {
532cb4c4
MN
5844 if (!sds->busiest)
5845 return true;
5846
5847 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
5848 return true;
5849 }
5850
5851 return false;
5852}
5853
0ec8aa00
PZ
5854#ifdef CONFIG_NUMA_BALANCING
5855static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
5856{
5857 if (sgs->sum_nr_running > sgs->nr_numa_running)
5858 return regular;
5859 if (sgs->sum_nr_running > sgs->nr_preferred_running)
5860 return remote;
5861 return all;
5862}
5863
5864static inline enum fbq_type fbq_classify_rq(struct rq *rq)
5865{
5866 if (rq->nr_running > rq->nr_numa_running)
5867 return regular;
5868 if (rq->nr_running > rq->nr_preferred_running)
5869 return remote;
5870 return all;
5871}
5872#else
5873static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
5874{
5875 return all;
5876}
5877
5878static inline enum fbq_type fbq_classify_rq(struct rq *rq)
5879{
5880 return regular;
5881}
5882#endif /* CONFIG_NUMA_BALANCING */
5883
1e3c88bd 5884/**
461819ac 5885 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
cd96891d 5886 * @env: The load balancing environment.
1e3c88bd
PZ
5887 * @sds: variable to hold the statistics for this sched_domain.
5888 */
0ec8aa00 5889static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 5890{
bd939f45
PZ
5891 struct sched_domain *child = env->sd->child;
5892 struct sched_group *sg = env->sd->groups;
56cf515b 5893 struct sg_lb_stats tmp_sgs;
1e3c88bd
PZ
5894 int load_idx, prefer_sibling = 0;
5895
5896 if (child && child->flags & SD_PREFER_SIBLING)
5897 prefer_sibling = 1;
5898
bd939f45 5899 load_idx = get_sd_load_idx(env->sd, env->idle);
1e3c88bd
PZ
5900
5901 do {
56cf515b 5902 struct sg_lb_stats *sgs = &tmp_sgs;
1e3c88bd
PZ
5903 int local_group;
5904
bd939f45 5905 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
56cf515b
JK
5906 if (local_group) {
5907 sds->local = sg;
5908 sgs = &sds->local_stat;
b72ff13c
PZ
5909
5910 if (env->idle != CPU_NEWLY_IDLE ||
5911 time_after_eq(jiffies, sg->sgp->next_update))
5912 update_group_power(env->sd, env->dst_cpu);
56cf515b 5913 }
1e3c88bd 5914
56cf515b 5915 update_sg_lb_stats(env, sg, load_idx, local_group, sgs);
1e3c88bd 5916
b72ff13c
PZ
5917 if (local_group)
5918 goto next_group;
5919
1e3c88bd
PZ
5920 /*
5921 * In case the child domain prefers tasks go to siblings
532cb4c4 5922 * first, lower the sg capacity to one so that we'll try
75dd321d
NR
5923 * and move all the excess tasks away. We lower the capacity
5924 * of a group only if the local group has the capacity to fit
5925 * these excess tasks, i.e. nr_running < group_capacity. The
5926 * extra check prevents the case where you always pull from the
5927 * heaviest group when it is already under-utilized (possible
5928 * with a large weight task outweighs the tasks on the system).
1e3c88bd 5929 */
b72ff13c
PZ
5930 if (prefer_sibling && sds->local &&
5931 sds->local_stat.group_has_capacity)
147c5fc2 5932 sgs->group_capacity = min(sgs->group_capacity, 1U);
1e3c88bd 5933
b72ff13c 5934 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
532cb4c4 5935 sds->busiest = sg;
56cf515b 5936 sds->busiest_stat = *sgs;
1e3c88bd
PZ
5937 }
5938
b72ff13c
PZ
5939next_group:
5940 /* Now, start updating sd_lb_stats */
5941 sds->total_load += sgs->group_load;
5942 sds->total_pwr += sgs->group_power;
5943
532cb4c4 5944 sg = sg->next;
bd939f45 5945 } while (sg != env->sd->groups);
0ec8aa00
PZ
5946
5947 if (env->sd->flags & SD_NUMA)
5948 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
532cb4c4
MN
5949}
5950
532cb4c4
MN
5951/**
5952 * check_asym_packing - Check to see if the group is packed into the
5953 * sched doman.
5954 *
5955 * This is primarily intended to used at the sibling level. Some
5956 * cores like POWER7 prefer to use lower numbered SMT threads. In the
5957 * case of POWER7, it can move to lower SMT modes only when higher
5958 * threads are idle. When in lower SMT modes, the threads will
5959 * perform better since they share less core resources. Hence when we
5960 * have idle threads, we want them to be the higher ones.
5961 *
5962 * This packing function is run on idle threads. It checks to see if
5963 * the busiest CPU in this domain (core in the P7 case) has a higher
5964 * CPU number than the packing function is being run on. Here we are
5965 * assuming lower CPU number will be equivalent to lower a SMT thread
5966 * number.
5967 *
e69f6186 5968 * Return: 1 when packing is required and a task should be moved to
b6b12294
MN
5969 * this CPU. The amount of the imbalance is returned in *imbalance.
5970 *
cd96891d 5971 * @env: The load balancing environment.
532cb4c4 5972 * @sds: Statistics of the sched_domain which is to be packed
532cb4c4 5973 */
bd939f45 5974static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
532cb4c4
MN
5975{
5976 int busiest_cpu;
5977
bd939f45 5978 if (!(env->sd->flags & SD_ASYM_PACKING))
532cb4c4
MN
5979 return 0;
5980
5981 if (!sds->busiest)
5982 return 0;
5983
5984 busiest_cpu = group_first_cpu(sds->busiest);
bd939f45 5985 if (env->dst_cpu > busiest_cpu)
532cb4c4
MN
5986 return 0;
5987
bd939f45 5988 env->imbalance = DIV_ROUND_CLOSEST(
3ae11c90
PZ
5989 sds->busiest_stat.avg_load * sds->busiest_stat.group_power,
5990 SCHED_POWER_SCALE);
bd939f45 5991
532cb4c4 5992 return 1;
1e3c88bd
PZ
5993}
5994
5995/**
5996 * fix_small_imbalance - Calculate the minor imbalance that exists
5997 * amongst the groups of a sched_domain, during
5998 * load balancing.
cd96891d 5999 * @env: The load balancing environment.
1e3c88bd 6000 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 6001 */
bd939f45
PZ
6002static inline
6003void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd
PZ
6004{
6005 unsigned long tmp, pwr_now = 0, pwr_move = 0;
6006 unsigned int imbn = 2;
dd5feea1 6007 unsigned long scaled_busy_load_per_task;
56cf515b 6008 struct sg_lb_stats *local, *busiest;
1e3c88bd 6009
56cf515b
JK
6010 local = &sds->local_stat;
6011 busiest = &sds->busiest_stat;
1e3c88bd 6012
56cf515b
JK
6013 if (!local->sum_nr_running)
6014 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
6015 else if (busiest->load_per_task > local->load_per_task)
6016 imbn = 1;
dd5feea1 6017
56cf515b
JK
6018 scaled_busy_load_per_task =
6019 (busiest->load_per_task * SCHED_POWER_SCALE) /
3ae11c90 6020 busiest->group_power;
56cf515b 6021
3029ede3
VD
6022 if (busiest->avg_load + scaled_busy_load_per_task >=
6023 local->avg_load + (scaled_busy_load_per_task * imbn)) {
56cf515b 6024 env->imbalance = busiest->load_per_task;
1e3c88bd
PZ
6025 return;
6026 }
6027
6028 /*
6029 * OK, we don't have enough imbalance to justify moving tasks,
6030 * however we may be able to increase total CPU power used by
6031 * moving them.
6032 */
6033
3ae11c90 6034 pwr_now += busiest->group_power *
56cf515b 6035 min(busiest->load_per_task, busiest->avg_load);
3ae11c90 6036 pwr_now += local->group_power *
56cf515b 6037 min(local->load_per_task, local->avg_load);
1399fa78 6038 pwr_now /= SCHED_POWER_SCALE;
1e3c88bd
PZ
6039
6040 /* Amount of load we'd subtract */
56cf515b 6041 tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
3ae11c90 6042 busiest->group_power;
56cf515b 6043 if (busiest->avg_load > tmp) {
3ae11c90 6044 pwr_move += busiest->group_power *
56cf515b
JK
6045 min(busiest->load_per_task,
6046 busiest->avg_load - tmp);
6047 }
1e3c88bd
PZ
6048
6049 /* Amount of load we'd add */
3ae11c90 6050 if (busiest->avg_load * busiest->group_power <
56cf515b 6051 busiest->load_per_task * SCHED_POWER_SCALE) {
3ae11c90
PZ
6052 tmp = (busiest->avg_load * busiest->group_power) /
6053 local->group_power;
56cf515b
JK
6054 } else {
6055 tmp = (busiest->load_per_task * SCHED_POWER_SCALE) /
3ae11c90 6056 local->group_power;
56cf515b 6057 }
3ae11c90
PZ
6058 pwr_move += local->group_power *
6059 min(local->load_per_task, local->avg_load + tmp);
1399fa78 6060 pwr_move /= SCHED_POWER_SCALE;
1e3c88bd
PZ
6061
6062 /* Move if we gain throughput */
6063 if (pwr_move > pwr_now)
56cf515b 6064 env->imbalance = busiest->load_per_task;
1e3c88bd
PZ
6065}
6066
6067/**
6068 * calculate_imbalance - Calculate the amount of imbalance present within the
6069 * groups of a given sched_domain during load balance.
bd939f45 6070 * @env: load balance environment
1e3c88bd 6071 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 6072 */
bd939f45 6073static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 6074{
dd5feea1 6075 unsigned long max_pull, load_above_capacity = ~0UL;
56cf515b
JK
6076 struct sg_lb_stats *local, *busiest;
6077
6078 local = &sds->local_stat;
56cf515b 6079 busiest = &sds->busiest_stat;
dd5feea1 6080
56cf515b 6081 if (busiest->group_imb) {
30ce5dab
PZ
6082 /*
6083 * In the group_imb case we cannot rely on group-wide averages
6084 * to ensure cpu-load equilibrium, look at wider averages. XXX
6085 */
56cf515b
JK
6086 busiest->load_per_task =
6087 min(busiest->load_per_task, sds->avg_load);
dd5feea1
SS
6088 }
6089
1e3c88bd
PZ
6090 /*
6091 * In the presence of smp nice balancing, certain scenarios can have
6092 * max load less than avg load(as we skip the groups at or below
6093 * its cpu_power, while calculating max_load..)
6094 */
b1885550
VD
6095 if (busiest->avg_load <= sds->avg_load ||
6096 local->avg_load >= sds->avg_load) {
bd939f45
PZ
6097 env->imbalance = 0;
6098 return fix_small_imbalance(env, sds);
1e3c88bd
PZ
6099 }
6100
56cf515b 6101 if (!busiest->group_imb) {
dd5feea1
SS
6102 /*
6103 * Don't want to pull so many tasks that a group would go idle.
30ce5dab
PZ
6104 * Except of course for the group_imb case, since then we might
6105 * have to drop below capacity to reach cpu-load equilibrium.
dd5feea1 6106 */
56cf515b
JK
6107 load_above_capacity =
6108 (busiest->sum_nr_running - busiest->group_capacity);
dd5feea1 6109
1399fa78 6110 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
3ae11c90 6111 load_above_capacity /= busiest->group_power;
dd5feea1
SS
6112 }
6113
6114 /*
6115 * We're trying to get all the cpus to the average_load, so we don't
6116 * want to push ourselves above the average load, nor do we wish to
6117 * reduce the max loaded cpu below the average load. At the same time,
6118 * we also don't want to reduce the group load below the group capacity
6119 * (so that we can implement power-savings policies etc). Thus we look
6120 * for the minimum possible imbalance.
dd5feea1 6121 */
30ce5dab 6122 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
1e3c88bd
PZ
6123
6124 /* How much load to actually move to equalise the imbalance */
56cf515b 6125 env->imbalance = min(
3ae11c90
PZ
6126 max_pull * busiest->group_power,
6127 (sds->avg_load - local->avg_load) * local->group_power
56cf515b 6128 ) / SCHED_POWER_SCALE;
1e3c88bd
PZ
6129
6130 /*
6131 * if *imbalance is less than the average load per runnable task
25985edc 6132 * there is no guarantee that any tasks will be moved so we'll have
1e3c88bd
PZ
6133 * a think about bumping its value to force at least one task to be
6134 * moved
6135 */
56cf515b 6136 if (env->imbalance < busiest->load_per_task)
bd939f45 6137 return fix_small_imbalance(env, sds);
1e3c88bd 6138}
fab47622 6139
1e3c88bd
PZ
6140/******* find_busiest_group() helpers end here *********************/
6141
6142/**
6143 * find_busiest_group - Returns the busiest group within the sched_domain
6144 * if there is an imbalance. If there isn't an imbalance, and
6145 * the user has opted for power-savings, it returns a group whose
6146 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
6147 * such a group exists.
6148 *
6149 * Also calculates the amount of weighted load which should be moved
6150 * to restore balance.
6151 *
cd96891d 6152 * @env: The load balancing environment.
1e3c88bd 6153 *
e69f6186 6154 * Return: - The busiest group if imbalance exists.
1e3c88bd
PZ
6155 * - If no imbalance and user has opted for power-savings balance,
6156 * return the least loaded group whose CPUs can be
6157 * put to idle by rebalancing its tasks onto our group.
6158 */
56cf515b 6159static struct sched_group *find_busiest_group(struct lb_env *env)
1e3c88bd 6160{
56cf515b 6161 struct sg_lb_stats *local, *busiest;
1e3c88bd
PZ
6162 struct sd_lb_stats sds;
6163
147c5fc2 6164 init_sd_lb_stats(&sds);
1e3c88bd
PZ
6165
6166 /*
6167 * Compute the various statistics relavent for load balancing at
6168 * this level.
6169 */
23f0d209 6170 update_sd_lb_stats(env, &sds);
56cf515b
JK
6171 local = &sds.local_stat;
6172 busiest = &sds.busiest_stat;
1e3c88bd 6173
bd939f45
PZ
6174 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
6175 check_asym_packing(env, &sds))
532cb4c4
MN
6176 return sds.busiest;
6177
cc57aa8f 6178 /* There is no busy sibling group to pull tasks from */
56cf515b 6179 if (!sds.busiest || busiest->sum_nr_running == 0)
1e3c88bd
PZ
6180 goto out_balanced;
6181
1399fa78 6182 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
b0432d8f 6183
866ab43e
PZ
6184 /*
6185 * If the busiest group is imbalanced the below checks don't
30ce5dab 6186 * work because they assume all things are equal, which typically
866ab43e
PZ
6187 * isn't true due to cpus_allowed constraints and the like.
6188 */
56cf515b 6189 if (busiest->group_imb)
866ab43e
PZ
6190 goto force_balance;
6191
cc57aa8f 6192 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
56cf515b
JK
6193 if (env->idle == CPU_NEWLY_IDLE && local->group_has_capacity &&
6194 !busiest->group_has_capacity)
fab47622
NR
6195 goto force_balance;
6196
cc57aa8f
PZ
6197 /*
6198 * If the local group is more busy than the selected busiest group
6199 * don't try and pull any tasks.
6200 */
56cf515b 6201 if (local->avg_load >= busiest->avg_load)
1e3c88bd
PZ
6202 goto out_balanced;
6203
cc57aa8f
PZ
6204 /*
6205 * Don't pull any tasks if this group is already above the domain
6206 * average load.
6207 */
56cf515b 6208 if (local->avg_load >= sds.avg_load)
1e3c88bd
PZ
6209 goto out_balanced;
6210
bd939f45 6211 if (env->idle == CPU_IDLE) {
aae6d3dd
SS
6212 /*
6213 * This cpu is idle. If the busiest group load doesn't
6214 * have more tasks than the number of available cpu's and
6215 * there is no imbalance between this and busiest group
6216 * wrt to idle cpu's, it is balanced.
6217 */
56cf515b
JK
6218 if ((local->idle_cpus < busiest->idle_cpus) &&
6219 busiest->sum_nr_running <= busiest->group_weight)
aae6d3dd 6220 goto out_balanced;
c186fafe
PZ
6221 } else {
6222 /*
6223 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
6224 * imbalance_pct to be conservative.
6225 */
56cf515b
JK
6226 if (100 * busiest->avg_load <=
6227 env->sd->imbalance_pct * local->avg_load)
c186fafe 6228 goto out_balanced;
aae6d3dd 6229 }
1e3c88bd 6230
fab47622 6231force_balance:
1e3c88bd 6232 /* Looks like there is an imbalance. Compute it */
bd939f45 6233 calculate_imbalance(env, &sds);
1e3c88bd
PZ
6234 return sds.busiest;
6235
6236out_balanced:
bd939f45 6237 env->imbalance = 0;
1e3c88bd
PZ
6238 return NULL;
6239}
6240
6241/*
6242 * find_busiest_queue - find the busiest runqueue among the cpus in group.
6243 */
bd939f45 6244static struct rq *find_busiest_queue(struct lb_env *env,
b9403130 6245 struct sched_group *group)
1e3c88bd
PZ
6246{
6247 struct rq *busiest = NULL, *rq;
95a79b80 6248 unsigned long busiest_load = 0, busiest_power = 1;
1e3c88bd
PZ
6249 int i;
6250
6906a408 6251 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
0ec8aa00
PZ
6252 unsigned long power, capacity, wl;
6253 enum fbq_type rt;
6254
6255 rq = cpu_rq(i);
6256 rt = fbq_classify_rq(rq);
1e3c88bd 6257
0ec8aa00
PZ
6258 /*
6259 * We classify groups/runqueues into three groups:
6260 * - regular: there are !numa tasks
6261 * - remote: there are numa tasks that run on the 'wrong' node
6262 * - all: there is no distinction
6263 *
6264 * In order to avoid migrating ideally placed numa tasks,
6265 * ignore those when there's better options.
6266 *
6267 * If we ignore the actual busiest queue to migrate another
6268 * task, the next balance pass can still reduce the busiest
6269 * queue by moving tasks around inside the node.
6270 *
6271 * If we cannot move enough load due to this classification
6272 * the next pass will adjust the group classification and
6273 * allow migration of more tasks.
6274 *
6275 * Both cases only affect the total convergence complexity.
6276 */
6277 if (rt > env->fbq_type)
6278 continue;
6279
6280 power = power_of(i);
6281 capacity = DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE);
9d5efe05 6282 if (!capacity)
bd939f45 6283 capacity = fix_small_capacity(env->sd, group);
9d5efe05 6284
6e40f5bb 6285 wl = weighted_cpuload(i);
1e3c88bd 6286
6e40f5bb
TG
6287 /*
6288 * When comparing with imbalance, use weighted_cpuload()
6289 * which is not scaled with the cpu power.
6290 */
bd939f45 6291 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
1e3c88bd
PZ
6292 continue;
6293
6e40f5bb
TG
6294 /*
6295 * For the load comparisons with the other cpu's, consider
6296 * the weighted_cpuload() scaled with the cpu power, so that
6297 * the load can be moved away from the cpu that is potentially
6298 * running at a lower capacity.
95a79b80
JK
6299 *
6300 * Thus we're looking for max(wl_i / power_i), crosswise
6301 * multiplication to rid ourselves of the division works out
6302 * to: wl_i * power_j > wl_j * power_i; where j is our
6303 * previous maximum.
6e40f5bb 6304 */
95a79b80
JK
6305 if (wl * busiest_power > busiest_load * power) {
6306 busiest_load = wl;
6307 busiest_power = power;
1e3c88bd
PZ
6308 busiest = rq;
6309 }
6310 }
6311
6312 return busiest;
6313}
6314
6315/*
6316 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
6317 * so long as it is large enough.
6318 */
6319#define MAX_PINNED_INTERVAL 512
6320
6321/* Working cpumask for load_balance and load_balance_newidle. */
e6252c3e 6322DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
1e3c88bd 6323
bd939f45 6324static int need_active_balance(struct lb_env *env)
1af3ed3d 6325{
bd939f45
PZ
6326 struct sched_domain *sd = env->sd;
6327
6328 if (env->idle == CPU_NEWLY_IDLE) {
532cb4c4
MN
6329
6330 /*
6331 * ASYM_PACKING needs to force migrate tasks from busy but
6332 * higher numbered CPUs in order to pack all tasks in the
6333 * lowest numbered CPUs.
6334 */
bd939f45 6335 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
532cb4c4 6336 return 1;
1af3ed3d
PZ
6337 }
6338
6339 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
6340}
6341
969c7921
TH
6342static int active_load_balance_cpu_stop(void *data);
6343
23f0d209
JK
6344static int should_we_balance(struct lb_env *env)
6345{
6346 struct sched_group *sg = env->sd->groups;
6347 struct cpumask *sg_cpus, *sg_mask;
6348 int cpu, balance_cpu = -1;
6349
6350 /*
6351 * In the newly idle case, we will allow all the cpu's
6352 * to do the newly idle load balance.
6353 */
6354 if (env->idle == CPU_NEWLY_IDLE)
6355 return 1;
6356
6357 sg_cpus = sched_group_cpus(sg);
6358 sg_mask = sched_group_mask(sg);
6359 /* Try to find first idle cpu */
6360 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
6361 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
6362 continue;
6363
6364 balance_cpu = cpu;
6365 break;
6366 }
6367
6368 if (balance_cpu == -1)
6369 balance_cpu = group_balance_cpu(sg);
6370
6371 /*
6372 * First idle cpu or the first cpu(busiest) in this sched group
6373 * is eligible for doing load balancing at this and above domains.
6374 */
b0cff9d8 6375 return balance_cpu == env->dst_cpu;
23f0d209
JK
6376}
6377
1e3c88bd
PZ
6378/*
6379 * Check this_cpu to ensure it is balanced within domain. Attempt to move
6380 * tasks if there is an imbalance.
6381 */
6382static int load_balance(int this_cpu, struct rq *this_rq,
6383 struct sched_domain *sd, enum cpu_idle_type idle,
23f0d209 6384 int *continue_balancing)
1e3c88bd 6385{
88b8dac0 6386 int ld_moved, cur_ld_moved, active_balance = 0;
6263322c 6387 struct sched_domain *sd_parent = sd->parent;
1e3c88bd 6388 struct sched_group *group;
1e3c88bd
PZ
6389 struct rq *busiest;
6390 unsigned long flags;
e6252c3e 6391 struct cpumask *cpus = __get_cpu_var(load_balance_mask);
1e3c88bd 6392
8e45cb54
PZ
6393 struct lb_env env = {
6394 .sd = sd,
ddcdf6e7
PZ
6395 .dst_cpu = this_cpu,
6396 .dst_rq = this_rq,
88b8dac0 6397 .dst_grpmask = sched_group_cpus(sd->groups),
8e45cb54 6398 .idle = idle,
eb95308e 6399 .loop_break = sched_nr_migrate_break,
b9403130 6400 .cpus = cpus,
0ec8aa00 6401 .fbq_type = all,
8e45cb54
PZ
6402 };
6403
cfc03118
JK
6404 /*
6405 * For NEWLY_IDLE load_balancing, we don't need to consider
6406 * other cpus in our group
6407 */
e02e60c1 6408 if (idle == CPU_NEWLY_IDLE)
cfc03118 6409 env.dst_grpmask = NULL;
cfc03118 6410
1e3c88bd
PZ
6411 cpumask_copy(cpus, cpu_active_mask);
6412
1e3c88bd
PZ
6413 schedstat_inc(sd, lb_count[idle]);
6414
6415redo:
23f0d209
JK
6416 if (!should_we_balance(&env)) {
6417 *continue_balancing = 0;
1e3c88bd 6418 goto out_balanced;
23f0d209 6419 }
1e3c88bd 6420
23f0d209 6421 group = find_busiest_group(&env);
1e3c88bd
PZ
6422 if (!group) {
6423 schedstat_inc(sd, lb_nobusyg[idle]);
6424 goto out_balanced;
6425 }
6426
b9403130 6427 busiest = find_busiest_queue(&env, group);
1e3c88bd
PZ
6428 if (!busiest) {
6429 schedstat_inc(sd, lb_nobusyq[idle]);
6430 goto out_balanced;
6431 }
6432
78feefc5 6433 BUG_ON(busiest == env.dst_rq);
1e3c88bd 6434
bd939f45 6435 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
1e3c88bd
PZ
6436
6437 ld_moved = 0;
6438 if (busiest->nr_running > 1) {
6439 /*
6440 * Attempt to move tasks. If find_busiest_group has found
6441 * an imbalance but busiest->nr_running <= 1, the group is
6442 * still unbalanced. ld_moved simply stays zero, so it is
6443 * correctly treated as an imbalance.
6444 */
8e45cb54 6445 env.flags |= LBF_ALL_PINNED;
c82513e5
PZ
6446 env.src_cpu = busiest->cpu;
6447 env.src_rq = busiest;
6448 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
8e45cb54 6449
5d6523eb 6450more_balance:
1e3c88bd 6451 local_irq_save(flags);
78feefc5 6452 double_rq_lock(env.dst_rq, busiest);
88b8dac0
SV
6453
6454 /*
6455 * cur_ld_moved - load moved in current iteration
6456 * ld_moved - cumulative load moved across iterations
6457 */
6458 cur_ld_moved = move_tasks(&env);
6459 ld_moved += cur_ld_moved;
78feefc5 6460 double_rq_unlock(env.dst_rq, busiest);
1e3c88bd
PZ
6461 local_irq_restore(flags);
6462
6463 /*
6464 * some other cpu did the load balance for us.
6465 */
88b8dac0
SV
6466 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
6467 resched_cpu(env.dst_cpu);
6468
f1cd0858
JK
6469 if (env.flags & LBF_NEED_BREAK) {
6470 env.flags &= ~LBF_NEED_BREAK;
6471 goto more_balance;
6472 }
6473
88b8dac0
SV
6474 /*
6475 * Revisit (affine) tasks on src_cpu that couldn't be moved to
6476 * us and move them to an alternate dst_cpu in our sched_group
6477 * where they can run. The upper limit on how many times we
6478 * iterate on same src_cpu is dependent on number of cpus in our
6479 * sched_group.
6480 *
6481 * This changes load balance semantics a bit on who can move
6482 * load to a given_cpu. In addition to the given_cpu itself
6483 * (or a ilb_cpu acting on its behalf where given_cpu is
6484 * nohz-idle), we now have balance_cpu in a position to move
6485 * load to given_cpu. In rare situations, this may cause
6486 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
6487 * _independently_ and at _same_ time to move some load to
6488 * given_cpu) causing exceess load to be moved to given_cpu.
6489 * This however should not happen so much in practice and
6490 * moreover subsequent load balance cycles should correct the
6491 * excess load moved.
6492 */
6263322c 6493 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
88b8dac0 6494
7aff2e3a
VD
6495 /* Prevent to re-select dst_cpu via env's cpus */
6496 cpumask_clear_cpu(env.dst_cpu, env.cpus);
6497
78feefc5 6498 env.dst_rq = cpu_rq(env.new_dst_cpu);
88b8dac0 6499 env.dst_cpu = env.new_dst_cpu;
6263322c 6500 env.flags &= ~LBF_DST_PINNED;
88b8dac0
SV
6501 env.loop = 0;
6502 env.loop_break = sched_nr_migrate_break;
e02e60c1 6503
88b8dac0
SV
6504 /*
6505 * Go back to "more_balance" rather than "redo" since we
6506 * need to continue with same src_cpu.
6507 */
6508 goto more_balance;
6509 }
1e3c88bd 6510
6263322c
PZ
6511 /*
6512 * We failed to reach balance because of affinity.
6513 */
6514 if (sd_parent) {
6515 int *group_imbalance = &sd_parent->groups->sgp->imbalance;
6516
6517 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) {
6518 *group_imbalance = 1;
6519 } else if (*group_imbalance)
6520 *group_imbalance = 0;
6521 }
6522
1e3c88bd 6523 /* All tasks on this runqueue were pinned by CPU affinity */
8e45cb54 6524 if (unlikely(env.flags & LBF_ALL_PINNED)) {
1e3c88bd 6525 cpumask_clear_cpu(cpu_of(busiest), cpus);
bbf18b19
PN
6526 if (!cpumask_empty(cpus)) {
6527 env.loop = 0;
6528 env.loop_break = sched_nr_migrate_break;
1e3c88bd 6529 goto redo;
bbf18b19 6530 }
1e3c88bd
PZ
6531 goto out_balanced;
6532 }
6533 }
6534
6535 if (!ld_moved) {
6536 schedstat_inc(sd, lb_failed[idle]);
58b26c4c
VP
6537 /*
6538 * Increment the failure counter only on periodic balance.
6539 * We do not want newidle balance, which can be very
6540 * frequent, pollute the failure counter causing
6541 * excessive cache_hot migrations and active balances.
6542 */
6543 if (idle != CPU_NEWLY_IDLE)
6544 sd->nr_balance_failed++;
1e3c88bd 6545
bd939f45 6546 if (need_active_balance(&env)) {
1e3c88bd
PZ
6547 raw_spin_lock_irqsave(&busiest->lock, flags);
6548
969c7921
TH
6549 /* don't kick the active_load_balance_cpu_stop,
6550 * if the curr task on busiest cpu can't be
6551 * moved to this_cpu
1e3c88bd
PZ
6552 */
6553 if (!cpumask_test_cpu(this_cpu,
fa17b507 6554 tsk_cpus_allowed(busiest->curr))) {
1e3c88bd
PZ
6555 raw_spin_unlock_irqrestore(&busiest->lock,
6556 flags);
8e45cb54 6557 env.flags |= LBF_ALL_PINNED;
1e3c88bd
PZ
6558 goto out_one_pinned;
6559 }
6560
969c7921
TH
6561 /*
6562 * ->active_balance synchronizes accesses to
6563 * ->active_balance_work. Once set, it's cleared
6564 * only after active load balance is finished.
6565 */
1e3c88bd
PZ
6566 if (!busiest->active_balance) {
6567 busiest->active_balance = 1;
6568 busiest->push_cpu = this_cpu;
6569 active_balance = 1;
6570 }
6571 raw_spin_unlock_irqrestore(&busiest->lock, flags);
969c7921 6572
bd939f45 6573 if (active_balance) {
969c7921
TH
6574 stop_one_cpu_nowait(cpu_of(busiest),
6575 active_load_balance_cpu_stop, busiest,
6576 &busiest->active_balance_work);
bd939f45 6577 }
1e3c88bd
PZ
6578
6579 /*
6580 * We've kicked active balancing, reset the failure
6581 * counter.
6582 */
6583 sd->nr_balance_failed = sd->cache_nice_tries+1;
6584 }
6585 } else
6586 sd->nr_balance_failed = 0;
6587
6588 if (likely(!active_balance)) {
6589 /* We were unbalanced, so reset the balancing interval */
6590 sd->balance_interval = sd->min_interval;
6591 } else {
6592 /*
6593 * If we've begun active balancing, start to back off. This
6594 * case may not be covered by the all_pinned logic if there
6595 * is only 1 task on the busy runqueue (because we don't call
6596 * move_tasks).
6597 */
6598 if (sd->balance_interval < sd->max_interval)
6599 sd->balance_interval *= 2;
6600 }
6601
1e3c88bd
PZ
6602 goto out;
6603
6604out_balanced:
6605 schedstat_inc(sd, lb_balanced[idle]);
6606
6607 sd->nr_balance_failed = 0;
6608
6609out_one_pinned:
6610 /* tune up the balancing interval */
8e45cb54 6611 if (((env.flags & LBF_ALL_PINNED) &&
5b54b56b 6612 sd->balance_interval < MAX_PINNED_INTERVAL) ||
1e3c88bd
PZ
6613 (sd->balance_interval < sd->max_interval))
6614 sd->balance_interval *= 2;
6615
46e49b38 6616 ld_moved = 0;
1e3c88bd 6617out:
1e3c88bd
PZ
6618 return ld_moved;
6619}
6620
1e3c88bd
PZ
6621/*
6622 * idle_balance is called by schedule() if this_cpu is about to become
6623 * idle. Attempts to pull tasks from other CPUs.
6624 */
3c4017c1 6625int idle_balance(struct rq *this_rq)
1e3c88bd
PZ
6626{
6627 struct sched_domain *sd;
6628 int pulled_task = 0;
6629 unsigned long next_balance = jiffies + HZ;
9bd721c5 6630 u64 curr_cost = 0;
b4f2ab43 6631 int this_cpu = this_rq->cpu;
1e3c88bd 6632
1e3c88bd 6633 if (this_rq->avg_idle < sysctl_sched_migration_cost)
3c4017c1 6634 return 0;
1e3c88bd 6635
f492e12e
PZ
6636 /*
6637 * Drop the rq->lock, but keep IRQ/preempt disabled.
6638 */
6639 raw_spin_unlock(&this_rq->lock);
6640
48a16753 6641 update_blocked_averages(this_cpu);
dce840a0 6642 rcu_read_lock();
1e3c88bd
PZ
6643 for_each_domain(this_cpu, sd) {
6644 unsigned long interval;
23f0d209 6645 int continue_balancing = 1;
9bd721c5 6646 u64 t0, domain_cost;
1e3c88bd
PZ
6647
6648 if (!(sd->flags & SD_LOAD_BALANCE))
6649 continue;
6650
9bd721c5
JL
6651 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
6652 break;
6653
f492e12e 6654 if (sd->flags & SD_BALANCE_NEWIDLE) {
9bd721c5
JL
6655 t0 = sched_clock_cpu(this_cpu);
6656
1e3c88bd 6657 /* If we've pulled tasks over stop searching: */
f492e12e 6658 pulled_task = load_balance(this_cpu, this_rq,
23f0d209
JK
6659 sd, CPU_NEWLY_IDLE,
6660 &continue_balancing);
9bd721c5
JL
6661
6662 domain_cost = sched_clock_cpu(this_cpu) - t0;
6663 if (domain_cost > sd->max_newidle_lb_cost)
6664 sd->max_newidle_lb_cost = domain_cost;
6665
6666 curr_cost += domain_cost;
f492e12e 6667 }
1e3c88bd
PZ
6668
6669 interval = msecs_to_jiffies(sd->balance_interval);
6670 if (time_after(next_balance, sd->last_balance + interval))
6671 next_balance = sd->last_balance + interval;
3c4017c1 6672 if (pulled_task)
1e3c88bd 6673 break;
1e3c88bd 6674 }
dce840a0 6675 rcu_read_unlock();
f492e12e
PZ
6676
6677 raw_spin_lock(&this_rq->lock);
6678
e5fc6611
DL
6679 /*
6680 * While browsing the domains, we released the rq lock.
6681 * A task could have be enqueued in the meantime
6682 */
6683 if (this_rq->nr_running && !pulled_task)
3c4017c1 6684 return 1;
e5fc6611 6685
1e3c88bd
PZ
6686 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
6687 /*
6688 * We are going idle. next_balance may be set based on
6689 * a busy processor. So reset next_balance.
6690 */
6691 this_rq->next_balance = next_balance;
6692 }
9bd721c5
JL
6693
6694 if (curr_cost > this_rq->max_idle_balance_cost)
6695 this_rq->max_idle_balance_cost = curr_cost;
3c4017c1
DL
6696
6697 return pulled_task;
1e3c88bd
PZ
6698}
6699
6700/*
969c7921
TH
6701 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
6702 * running tasks off the busiest CPU onto idle CPUs. It requires at
6703 * least 1 task to be running on each physical CPU where possible, and
6704 * avoids physical / logical imbalances.
1e3c88bd 6705 */
969c7921 6706static int active_load_balance_cpu_stop(void *data)
1e3c88bd 6707{
969c7921
TH
6708 struct rq *busiest_rq = data;
6709 int busiest_cpu = cpu_of(busiest_rq);
1e3c88bd 6710 int target_cpu = busiest_rq->push_cpu;
969c7921 6711 struct rq *target_rq = cpu_rq(target_cpu);
1e3c88bd 6712 struct sched_domain *sd;
969c7921
TH
6713
6714 raw_spin_lock_irq(&busiest_rq->lock);
6715
6716 /* make sure the requested cpu hasn't gone down in the meantime */
6717 if (unlikely(busiest_cpu != smp_processor_id() ||
6718 !busiest_rq->active_balance))
6719 goto out_unlock;
1e3c88bd
PZ
6720
6721 /* Is there any task to move? */
6722 if (busiest_rq->nr_running <= 1)
969c7921 6723 goto out_unlock;
1e3c88bd
PZ
6724
6725 /*
6726 * This condition is "impossible", if it occurs
6727 * we need to fix it. Originally reported by
6728 * Bjorn Helgaas on a 128-cpu setup.
6729 */
6730 BUG_ON(busiest_rq == target_rq);
6731
6732 /* move a task from busiest_rq to target_rq */
6733 double_lock_balance(busiest_rq, target_rq);
1e3c88bd
PZ
6734
6735 /* Search for an sd spanning us and the target CPU. */
dce840a0 6736 rcu_read_lock();
1e3c88bd
PZ
6737 for_each_domain(target_cpu, sd) {
6738 if ((sd->flags & SD_LOAD_BALANCE) &&
6739 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6740 break;
6741 }
6742
6743 if (likely(sd)) {
8e45cb54
PZ
6744 struct lb_env env = {
6745 .sd = sd,
ddcdf6e7
PZ
6746 .dst_cpu = target_cpu,
6747 .dst_rq = target_rq,
6748 .src_cpu = busiest_rq->cpu,
6749 .src_rq = busiest_rq,
8e45cb54
PZ
6750 .idle = CPU_IDLE,
6751 };
6752
1e3c88bd
PZ
6753 schedstat_inc(sd, alb_count);
6754
8e45cb54 6755 if (move_one_task(&env))
1e3c88bd
PZ
6756 schedstat_inc(sd, alb_pushed);
6757 else
6758 schedstat_inc(sd, alb_failed);
6759 }
dce840a0 6760 rcu_read_unlock();
1e3c88bd 6761 double_unlock_balance(busiest_rq, target_rq);
969c7921
TH
6762out_unlock:
6763 busiest_rq->active_balance = 0;
6764 raw_spin_unlock_irq(&busiest_rq->lock);
6765 return 0;
1e3c88bd
PZ
6766}
6767
3451d024 6768#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2
VP
6769/*
6770 * idle load balancing details
83cd4fe2
VP
6771 * - When one of the busy CPUs notice that there may be an idle rebalancing
6772 * needed, they will kick the idle load balancer, which then does idle
6773 * load balancing for all the idle CPUs.
6774 */
1e3c88bd 6775static struct {
83cd4fe2 6776 cpumask_var_t idle_cpus_mask;
0b005cf5 6777 atomic_t nr_cpus;
83cd4fe2
VP
6778 unsigned long next_balance; /* in jiffy units */
6779} nohz ____cacheline_aligned;
1e3c88bd 6780
3dd0337d 6781static inline int find_new_ilb(void)
1e3c88bd 6782{
0b005cf5 6783 int ilb = cpumask_first(nohz.idle_cpus_mask);
1e3c88bd 6784
786d6dc7
SS
6785 if (ilb < nr_cpu_ids && idle_cpu(ilb))
6786 return ilb;
6787
6788 return nr_cpu_ids;
1e3c88bd 6789}
1e3c88bd 6790
83cd4fe2
VP
6791/*
6792 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
6793 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
6794 * CPU (if there is one).
6795 */
0aeeeeba 6796static void nohz_balancer_kick(void)
83cd4fe2
VP
6797{
6798 int ilb_cpu;
6799
6800 nohz.next_balance++;
6801
3dd0337d 6802 ilb_cpu = find_new_ilb();
83cd4fe2 6803
0b005cf5
SS
6804 if (ilb_cpu >= nr_cpu_ids)
6805 return;
83cd4fe2 6806
cd490c5b 6807 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
1c792db7
SS
6808 return;
6809 /*
6810 * Use smp_send_reschedule() instead of resched_cpu().
6811 * This way we generate a sched IPI on the target cpu which
6812 * is idle. And the softirq performing nohz idle load balance
6813 * will be run before returning from the IPI.
6814 */
6815 smp_send_reschedule(ilb_cpu);
83cd4fe2
VP
6816 return;
6817}
6818
c1cc017c 6819static inline void nohz_balance_exit_idle(int cpu)
71325960
SS
6820{
6821 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
6822 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
6823 atomic_dec(&nohz.nr_cpus);
6824 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
6825 }
6826}
6827
69e1e811
SS
6828static inline void set_cpu_sd_state_busy(void)
6829{
6830 struct sched_domain *sd;
37dc6b50 6831 int cpu = smp_processor_id();
69e1e811 6832
69e1e811 6833 rcu_read_lock();
37dc6b50 6834 sd = rcu_dereference(per_cpu(sd_busy, cpu));
25f55d9d
VG
6835
6836 if (!sd || !sd->nohz_idle)
6837 goto unlock;
6838 sd->nohz_idle = 0;
6839
37dc6b50 6840 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
25f55d9d 6841unlock:
69e1e811
SS
6842 rcu_read_unlock();
6843}
6844
6845void set_cpu_sd_state_idle(void)
6846{
6847 struct sched_domain *sd;
37dc6b50 6848 int cpu = smp_processor_id();
69e1e811 6849
69e1e811 6850 rcu_read_lock();
37dc6b50 6851 sd = rcu_dereference(per_cpu(sd_busy, cpu));
25f55d9d
VG
6852
6853 if (!sd || sd->nohz_idle)
6854 goto unlock;
6855 sd->nohz_idle = 1;
6856
37dc6b50 6857 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
25f55d9d 6858unlock:
69e1e811
SS
6859 rcu_read_unlock();
6860}
6861
1e3c88bd 6862/*
c1cc017c 6863 * This routine will record that the cpu is going idle with tick stopped.
0b005cf5 6864 * This info will be used in performing idle load balancing in the future.
1e3c88bd 6865 */
c1cc017c 6866void nohz_balance_enter_idle(int cpu)
1e3c88bd 6867{
71325960
SS
6868 /*
6869 * If this cpu is going down, then nothing needs to be done.
6870 */
6871 if (!cpu_active(cpu))
6872 return;
6873
c1cc017c
AS
6874 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
6875 return;
1e3c88bd 6876
c1cc017c
AS
6877 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
6878 atomic_inc(&nohz.nr_cpus);
6879 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
1e3c88bd 6880}
71325960 6881
0db0628d 6882static int sched_ilb_notifier(struct notifier_block *nfb,
71325960
SS
6883 unsigned long action, void *hcpu)
6884{
6885 switch (action & ~CPU_TASKS_FROZEN) {
6886 case CPU_DYING:
c1cc017c 6887 nohz_balance_exit_idle(smp_processor_id());
71325960
SS
6888 return NOTIFY_OK;
6889 default:
6890 return NOTIFY_DONE;
6891 }
6892}
1e3c88bd
PZ
6893#endif
6894
6895static DEFINE_SPINLOCK(balancing);
6896
49c022e6
PZ
6897/*
6898 * Scale the max load_balance interval with the number of CPUs in the system.
6899 * This trades load-balance latency on larger machines for less cross talk.
6900 */
029632fb 6901void update_max_interval(void)
49c022e6
PZ
6902{
6903 max_load_balance_interval = HZ*num_online_cpus()/10;
6904}
6905
1e3c88bd
PZ
6906/*
6907 * It checks each scheduling domain to see if it is due to be balanced,
6908 * and initiates a balancing operation if so.
6909 *
b9b0853a 6910 * Balancing parameters are set up in init_sched_domains.
1e3c88bd 6911 */
f7ed0a89 6912static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
1e3c88bd 6913{
23f0d209 6914 int continue_balancing = 1;
f7ed0a89 6915 int cpu = rq->cpu;
1e3c88bd 6916 unsigned long interval;
04f733b4 6917 struct sched_domain *sd;
1e3c88bd
PZ
6918 /* Earliest time when we have to do rebalance again */
6919 unsigned long next_balance = jiffies + 60*HZ;
6920 int update_next_balance = 0;
f48627e6
JL
6921 int need_serialize, need_decay = 0;
6922 u64 max_cost = 0;
1e3c88bd 6923
48a16753 6924 update_blocked_averages(cpu);
2069dd75 6925
dce840a0 6926 rcu_read_lock();
1e3c88bd 6927 for_each_domain(cpu, sd) {
f48627e6
JL
6928 /*
6929 * Decay the newidle max times here because this is a regular
6930 * visit to all the domains. Decay ~1% per second.
6931 */
6932 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
6933 sd->max_newidle_lb_cost =
6934 (sd->max_newidle_lb_cost * 253) / 256;
6935 sd->next_decay_max_lb_cost = jiffies + HZ;
6936 need_decay = 1;
6937 }
6938 max_cost += sd->max_newidle_lb_cost;
6939
1e3c88bd
PZ
6940 if (!(sd->flags & SD_LOAD_BALANCE))
6941 continue;
6942
f48627e6
JL
6943 /*
6944 * Stop the load balance at this level. There is another
6945 * CPU in our sched group which is doing load balancing more
6946 * actively.
6947 */
6948 if (!continue_balancing) {
6949 if (need_decay)
6950 continue;
6951 break;
6952 }
6953
1e3c88bd
PZ
6954 interval = sd->balance_interval;
6955 if (idle != CPU_IDLE)
6956 interval *= sd->busy_factor;
6957
6958 /* scale ms to jiffies */
6959 interval = msecs_to_jiffies(interval);
49c022e6 6960 interval = clamp(interval, 1UL, max_load_balance_interval);
1e3c88bd
PZ
6961
6962 need_serialize = sd->flags & SD_SERIALIZE;
6963
6964 if (need_serialize) {
6965 if (!spin_trylock(&balancing))
6966 goto out;
6967 }
6968
6969 if (time_after_eq(jiffies, sd->last_balance + interval)) {
23f0d209 6970 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
1e3c88bd 6971 /*
6263322c 6972 * The LBF_DST_PINNED logic could have changed
de5eb2dd
JK
6973 * env->dst_cpu, so we can't know our idle
6974 * state even if we migrated tasks. Update it.
1e3c88bd 6975 */
de5eb2dd 6976 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
1e3c88bd
PZ
6977 }
6978 sd->last_balance = jiffies;
6979 }
6980 if (need_serialize)
6981 spin_unlock(&balancing);
6982out:
6983 if (time_after(next_balance, sd->last_balance + interval)) {
6984 next_balance = sd->last_balance + interval;
6985 update_next_balance = 1;
6986 }
f48627e6
JL
6987 }
6988 if (need_decay) {
1e3c88bd 6989 /*
f48627e6
JL
6990 * Ensure the rq-wide value also decays but keep it at a
6991 * reasonable floor to avoid funnies with rq->avg_idle.
1e3c88bd 6992 */
f48627e6
JL
6993 rq->max_idle_balance_cost =
6994 max((u64)sysctl_sched_migration_cost, max_cost);
1e3c88bd 6995 }
dce840a0 6996 rcu_read_unlock();
1e3c88bd
PZ
6997
6998 /*
6999 * next_balance will be updated only when there is a need.
7000 * When the cpu is attached to null domain for ex, it will not be
7001 * updated.
7002 */
7003 if (likely(update_next_balance))
7004 rq->next_balance = next_balance;
7005}
7006
3451d024 7007#ifdef CONFIG_NO_HZ_COMMON
1e3c88bd 7008/*
3451d024 7009 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
1e3c88bd
PZ
7010 * rebalancing for all the cpus for whom scheduler ticks are stopped.
7011 */
208cb16b 7012static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
83cd4fe2 7013{
208cb16b 7014 int this_cpu = this_rq->cpu;
83cd4fe2
VP
7015 struct rq *rq;
7016 int balance_cpu;
7017
1c792db7
SS
7018 if (idle != CPU_IDLE ||
7019 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
7020 goto end;
83cd4fe2
VP
7021
7022 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
8a6d42d1 7023 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
83cd4fe2
VP
7024 continue;
7025
7026 /*
7027 * If this cpu gets work to do, stop the load balancing
7028 * work being done for other cpus. Next load
7029 * balancing owner will pick it up.
7030 */
1c792db7 7031 if (need_resched())
83cd4fe2 7032 break;
83cd4fe2 7033
5ed4f1d9
VG
7034 rq = cpu_rq(balance_cpu);
7035
7036 raw_spin_lock_irq(&rq->lock);
7037 update_rq_clock(rq);
7038 update_idle_cpu_load(rq);
7039 raw_spin_unlock_irq(&rq->lock);
83cd4fe2 7040
f7ed0a89 7041 rebalance_domains(rq, CPU_IDLE);
83cd4fe2 7042
83cd4fe2
VP
7043 if (time_after(this_rq->next_balance, rq->next_balance))
7044 this_rq->next_balance = rq->next_balance;
7045 }
7046 nohz.next_balance = this_rq->next_balance;
1c792db7
SS
7047end:
7048 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
83cd4fe2
VP
7049}
7050
7051/*
0b005cf5
SS
7052 * Current heuristic for kicking the idle load balancer in the presence
7053 * of an idle cpu is the system.
7054 * - This rq has more than one task.
7055 * - At any scheduler domain level, this cpu's scheduler group has multiple
7056 * busy cpu's exceeding the group's power.
7057 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
7058 * domain span are idle.
83cd4fe2 7059 */
4a725627 7060static inline int nohz_kick_needed(struct rq *rq)
83cd4fe2
VP
7061{
7062 unsigned long now = jiffies;
0b005cf5 7063 struct sched_domain *sd;
37dc6b50 7064 struct sched_group_power *sgp;
4a725627 7065 int nr_busy, cpu = rq->cpu;
83cd4fe2 7066
4a725627 7067 if (unlikely(rq->idle_balance))
83cd4fe2
VP
7068 return 0;
7069
1c792db7
SS
7070 /*
7071 * We may be recently in ticked or tickless idle mode. At the first
7072 * busy tick after returning from idle, we will update the busy stats.
7073 */
69e1e811 7074 set_cpu_sd_state_busy();
c1cc017c 7075 nohz_balance_exit_idle(cpu);
0b005cf5
SS
7076
7077 /*
7078 * None are in tickless mode and hence no need for NOHZ idle load
7079 * balancing.
7080 */
7081 if (likely(!atomic_read(&nohz.nr_cpus)))
7082 return 0;
1c792db7
SS
7083
7084 if (time_before(now, nohz.next_balance))
83cd4fe2
VP
7085 return 0;
7086
0b005cf5
SS
7087 if (rq->nr_running >= 2)
7088 goto need_kick;
83cd4fe2 7089
067491b7 7090 rcu_read_lock();
37dc6b50 7091 sd = rcu_dereference(per_cpu(sd_busy, cpu));
83cd4fe2 7092
37dc6b50
PM
7093 if (sd) {
7094 sgp = sd->groups->sgp;
7095 nr_busy = atomic_read(&sgp->nr_busy_cpus);
0b005cf5 7096
37dc6b50 7097 if (nr_busy > 1)
067491b7 7098 goto need_kick_unlock;
83cd4fe2 7099 }
37dc6b50
PM
7100
7101 sd = rcu_dereference(per_cpu(sd_asym, cpu));
7102
7103 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
7104 sched_domain_span(sd)) < cpu))
7105 goto need_kick_unlock;
7106
067491b7 7107 rcu_read_unlock();
83cd4fe2 7108 return 0;
067491b7
PZ
7109
7110need_kick_unlock:
7111 rcu_read_unlock();
0b005cf5
SS
7112need_kick:
7113 return 1;
83cd4fe2
VP
7114}
7115#else
208cb16b 7116static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
83cd4fe2
VP
7117#endif
7118
7119/*
7120 * run_rebalance_domains is triggered when needed from the scheduler tick.
7121 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
7122 */
1e3c88bd
PZ
7123static void run_rebalance_domains(struct softirq_action *h)
7124{
208cb16b 7125 struct rq *this_rq = this_rq();
6eb57e0d 7126 enum cpu_idle_type idle = this_rq->idle_balance ?
1e3c88bd
PZ
7127 CPU_IDLE : CPU_NOT_IDLE;
7128
f7ed0a89 7129 rebalance_domains(this_rq, idle);
1e3c88bd 7130
1e3c88bd 7131 /*
83cd4fe2 7132 * If this cpu has a pending nohz_balance_kick, then do the
1e3c88bd
PZ
7133 * balancing on behalf of the other idle cpus whose ticks are
7134 * stopped.
7135 */
208cb16b 7136 nohz_idle_balance(this_rq, idle);
1e3c88bd
PZ
7137}
7138
63f609b1 7139static inline int on_null_domain(struct rq *rq)
1e3c88bd 7140{
63f609b1 7141 return !rcu_dereference_sched(rq->sd);
1e3c88bd
PZ
7142}
7143
7144/*
7145 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
1e3c88bd 7146 */
7caff66f 7147void trigger_load_balance(struct rq *rq)
1e3c88bd 7148{
1e3c88bd 7149 /* Don't need to rebalance while attached to NULL domain */
c726099e
DL
7150 if (unlikely(on_null_domain(rq)))
7151 return;
7152
7153 if (time_after_eq(jiffies, rq->next_balance))
1e3c88bd 7154 raise_softirq(SCHED_SOFTIRQ);
3451d024 7155#ifdef CONFIG_NO_HZ_COMMON
c726099e 7156 if (nohz_kick_needed(rq))
0aeeeeba 7157 nohz_balancer_kick();
83cd4fe2 7158#endif
1e3c88bd
PZ
7159}
7160
0bcdcf28
CE
7161static void rq_online_fair(struct rq *rq)
7162{
7163 update_sysctl();
7164}
7165
7166static void rq_offline_fair(struct rq *rq)
7167{
7168 update_sysctl();
a4c96ae3
PB
7169
7170 /* Ensure any throttled groups are reachable by pick_next_task */
7171 unthrottle_offline_cfs_rqs(rq);
0bcdcf28
CE
7172}
7173
55e12e5e 7174#endif /* CONFIG_SMP */
e1d1484f 7175
bf0f6f24
IM
7176/*
7177 * scheduler tick hitting a task of our scheduling class:
7178 */
8f4d37ec 7179static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
bf0f6f24
IM
7180{
7181 struct cfs_rq *cfs_rq;
7182 struct sched_entity *se = &curr->se;
7183
7184 for_each_sched_entity(se) {
7185 cfs_rq = cfs_rq_of(se);
8f4d37ec 7186 entity_tick(cfs_rq, se, queued);
bf0f6f24 7187 }
18bf2805 7188
10e84b97 7189 if (numabalancing_enabled)
cbee9f88 7190 task_tick_numa(rq, curr);
3d59eebc 7191
18bf2805 7192 update_rq_runnable_avg(rq, 1);
bf0f6f24
IM
7193}
7194
7195/*
cd29fe6f
PZ
7196 * called on fork with the child task as argument from the parent's context
7197 * - child not yet on the tasklist
7198 * - preemption disabled
bf0f6f24 7199 */
cd29fe6f 7200static void task_fork_fair(struct task_struct *p)
bf0f6f24 7201{
4fc420c9
DN
7202 struct cfs_rq *cfs_rq;
7203 struct sched_entity *se = &p->se, *curr;
00bf7bfc 7204 int this_cpu = smp_processor_id();
cd29fe6f
PZ
7205 struct rq *rq = this_rq();
7206 unsigned long flags;
7207
05fa785c 7208 raw_spin_lock_irqsave(&rq->lock, flags);
bf0f6f24 7209
861d034e
PZ
7210 update_rq_clock(rq);
7211
4fc420c9
DN
7212 cfs_rq = task_cfs_rq(current);
7213 curr = cfs_rq->curr;
7214
6c9a27f5
DN
7215 /*
7216 * Not only the cpu but also the task_group of the parent might have
7217 * been changed after parent->se.parent,cfs_rq were copied to
7218 * child->se.parent,cfs_rq. So call __set_task_cpu() to make those
7219 * of child point to valid ones.
7220 */
7221 rcu_read_lock();
7222 __set_task_cpu(p, this_cpu);
7223 rcu_read_unlock();
bf0f6f24 7224
7109c442 7225 update_curr(cfs_rq);
cd29fe6f 7226
b5d9d734
MG
7227 if (curr)
7228 se->vruntime = curr->vruntime;
aeb73b04 7229 place_entity(cfs_rq, se, 1);
4d78e7b6 7230
cd29fe6f 7231 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
87fefa38 7232 /*
edcb60a3
IM
7233 * Upon rescheduling, sched_class::put_prev_task() will place
7234 * 'current' within the tree based on its new key value.
7235 */
4d78e7b6 7236 swap(curr->vruntime, se->vruntime);
aec0a514 7237 resched_task(rq->curr);
4d78e7b6 7238 }
bf0f6f24 7239
88ec22d3
PZ
7240 se->vruntime -= cfs_rq->min_vruntime;
7241
05fa785c 7242 raw_spin_unlock_irqrestore(&rq->lock, flags);
bf0f6f24
IM
7243}
7244
cb469845
SR
7245/*
7246 * Priority of the task has changed. Check to see if we preempt
7247 * the current task.
7248 */
da7a735e
PZ
7249static void
7250prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
cb469845 7251{
da7a735e
PZ
7252 if (!p->se.on_rq)
7253 return;
7254
cb469845
SR
7255 /*
7256 * Reschedule if we are currently running on this runqueue and
7257 * our priority decreased, or if we are not currently running on
7258 * this runqueue and our priority is higher than the current's
7259 */
da7a735e 7260 if (rq->curr == p) {
cb469845
SR
7261 if (p->prio > oldprio)
7262 resched_task(rq->curr);
7263 } else
15afe09b 7264 check_preempt_curr(rq, p, 0);
cb469845
SR
7265}
7266
da7a735e
PZ
7267static void switched_from_fair(struct rq *rq, struct task_struct *p)
7268{
7269 struct sched_entity *se = &p->se;
7270 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7271
7272 /*
7273 * Ensure the task's vruntime is normalized, so that when its
7274 * switched back to the fair class the enqueue_entity(.flags=0) will
7275 * do the right thing.
7276 *
7277 * If it was on_rq, then the dequeue_entity(.flags=0) will already
7278 * have normalized the vruntime, if it was !on_rq, then only when
7279 * the task is sleeping will it still have non-normalized vruntime.
7280 */
7281 if (!se->on_rq && p->state != TASK_RUNNING) {
7282 /*
7283 * Fix up our vruntime so that the current sleep doesn't
7284 * cause 'unlimited' sleep bonus.
7285 */
7286 place_entity(cfs_rq, se, 0);
7287 se->vruntime -= cfs_rq->min_vruntime;
7288 }
9ee474f5 7289
141965c7 7290#ifdef CONFIG_SMP
9ee474f5
PT
7291 /*
7292 * Remove our load from contribution when we leave sched_fair
7293 * and ensure we don't carry in an old decay_count if we
7294 * switch back.
7295 */
87e3c8ae
KT
7296 if (se->avg.decay_count) {
7297 __synchronize_entity_decay(se);
7298 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
9ee474f5
PT
7299 }
7300#endif
da7a735e
PZ
7301}
7302
cb469845
SR
7303/*
7304 * We switched to the sched_fair class.
7305 */
da7a735e 7306static void switched_to_fair(struct rq *rq, struct task_struct *p)
cb469845 7307{
da7a735e
PZ
7308 if (!p->se.on_rq)
7309 return;
7310
cb469845
SR
7311 /*
7312 * We were most likely switched from sched_rt, so
7313 * kick off the schedule if running, otherwise just see
7314 * if we can still preempt the current task.
7315 */
da7a735e 7316 if (rq->curr == p)
cb469845
SR
7317 resched_task(rq->curr);
7318 else
15afe09b 7319 check_preempt_curr(rq, p, 0);
cb469845
SR
7320}
7321
83b699ed
SV
7322/* Account for a task changing its policy or group.
7323 *
7324 * This routine is mostly called to set cfs_rq->curr field when a task
7325 * migrates between groups/classes.
7326 */
7327static void set_curr_task_fair(struct rq *rq)
7328{
7329 struct sched_entity *se = &rq->curr->se;
7330
ec12cb7f
PT
7331 for_each_sched_entity(se) {
7332 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7333
7334 set_next_entity(cfs_rq, se);
7335 /* ensure bandwidth has been allocated on our new cfs_rq */
7336 account_cfs_rq_runtime(cfs_rq, 0);
7337 }
83b699ed
SV
7338}
7339
029632fb
PZ
7340void init_cfs_rq(struct cfs_rq *cfs_rq)
7341{
7342 cfs_rq->tasks_timeline = RB_ROOT;
029632fb
PZ
7343 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7344#ifndef CONFIG_64BIT
7345 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7346#endif
141965c7 7347#ifdef CONFIG_SMP
9ee474f5 7348 atomic64_set(&cfs_rq->decay_counter, 1);
2509940f 7349 atomic_long_set(&cfs_rq->removed_load, 0);
9ee474f5 7350#endif
029632fb
PZ
7351}
7352
810b3817 7353#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02 7354static void task_move_group_fair(struct task_struct *p, int on_rq)
810b3817 7355{
fed14d45 7356 struct sched_entity *se = &p->se;
aff3e498 7357 struct cfs_rq *cfs_rq;
fed14d45 7358
b2b5ce02
PZ
7359 /*
7360 * If the task was not on the rq at the time of this cgroup movement
7361 * it must have been asleep, sleeping tasks keep their ->vruntime
7362 * absolute on their old rq until wakeup (needed for the fair sleeper
7363 * bonus in place_entity()).
7364 *
7365 * If it was on the rq, we've just 'preempted' it, which does convert
7366 * ->vruntime to a relative base.
7367 *
7368 * Make sure both cases convert their relative position when migrating
7369 * to another cgroup's rq. This does somewhat interfere with the
7370 * fair sleeper stuff for the first placement, but who cares.
7371 */
7ceff013
DN
7372 /*
7373 * When !on_rq, vruntime of the task has usually NOT been normalized.
7374 * But there are some cases where it has already been normalized:
7375 *
7376 * - Moving a forked child which is waiting for being woken up by
7377 * wake_up_new_task().
62af3783
DN
7378 * - Moving a task which has been woken up by try_to_wake_up() and
7379 * waiting for actually being woken up by sched_ttwu_pending().
7ceff013
DN
7380 *
7381 * To prevent boost or penalty in the new cfs_rq caused by delta
7382 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
7383 */
fed14d45 7384 if (!on_rq && (!se->sum_exec_runtime || p->state == TASK_WAKING))
7ceff013
DN
7385 on_rq = 1;
7386
b2b5ce02 7387 if (!on_rq)
fed14d45 7388 se->vruntime -= cfs_rq_of(se)->min_vruntime;
b2b5ce02 7389 set_task_rq(p, task_cpu(p));
fed14d45 7390 se->depth = se->parent ? se->parent->depth + 1 : 0;
aff3e498 7391 if (!on_rq) {
fed14d45
PZ
7392 cfs_rq = cfs_rq_of(se);
7393 se->vruntime += cfs_rq->min_vruntime;
aff3e498
PT
7394#ifdef CONFIG_SMP
7395 /*
7396 * migrate_task_rq_fair() will have removed our previous
7397 * contribution, but we must synchronize for ongoing future
7398 * decay.
7399 */
fed14d45
PZ
7400 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
7401 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
aff3e498
PT
7402#endif
7403 }
810b3817 7404}
029632fb
PZ
7405
7406void free_fair_sched_group(struct task_group *tg)
7407{
7408 int i;
7409
7410 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
7411
7412 for_each_possible_cpu(i) {
7413 if (tg->cfs_rq)
7414 kfree(tg->cfs_rq[i]);
7415 if (tg->se)
7416 kfree(tg->se[i]);
7417 }
7418
7419 kfree(tg->cfs_rq);
7420 kfree(tg->se);
7421}
7422
7423int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7424{
7425 struct cfs_rq *cfs_rq;
7426 struct sched_entity *se;
7427 int i;
7428
7429 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7430 if (!tg->cfs_rq)
7431 goto err;
7432 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7433 if (!tg->se)
7434 goto err;
7435
7436 tg->shares = NICE_0_LOAD;
7437
7438 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
7439
7440 for_each_possible_cpu(i) {
7441 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
7442 GFP_KERNEL, cpu_to_node(i));
7443 if (!cfs_rq)
7444 goto err;
7445
7446 se = kzalloc_node(sizeof(struct sched_entity),
7447 GFP_KERNEL, cpu_to_node(i));
7448 if (!se)
7449 goto err_free_rq;
7450
7451 init_cfs_rq(cfs_rq);
7452 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
7453 }
7454
7455 return 1;
7456
7457err_free_rq:
7458 kfree(cfs_rq);
7459err:
7460 return 0;
7461}
7462
7463void unregister_fair_sched_group(struct task_group *tg, int cpu)
7464{
7465 struct rq *rq = cpu_rq(cpu);
7466 unsigned long flags;
7467
7468 /*
7469 * Only empty task groups can be destroyed; so we can speculatively
7470 * check on_list without danger of it being re-added.
7471 */
7472 if (!tg->cfs_rq[cpu]->on_list)
7473 return;
7474
7475 raw_spin_lock_irqsave(&rq->lock, flags);
7476 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
7477 raw_spin_unlock_irqrestore(&rq->lock, flags);
7478}
7479
7480void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7481 struct sched_entity *se, int cpu,
7482 struct sched_entity *parent)
7483{
7484 struct rq *rq = cpu_rq(cpu);
7485
7486 cfs_rq->tg = tg;
7487 cfs_rq->rq = rq;
029632fb
PZ
7488 init_cfs_rq_runtime(cfs_rq);
7489
7490 tg->cfs_rq[cpu] = cfs_rq;
7491 tg->se[cpu] = se;
7492
7493 /* se could be NULL for root_task_group */
7494 if (!se)
7495 return;
7496
fed14d45 7497 if (!parent) {
029632fb 7498 se->cfs_rq = &rq->cfs;
fed14d45
PZ
7499 se->depth = 0;
7500 } else {
029632fb 7501 se->cfs_rq = parent->my_q;
fed14d45
PZ
7502 se->depth = parent->depth + 1;
7503 }
029632fb
PZ
7504
7505 se->my_q = cfs_rq;
0ac9b1c2
PT
7506 /* guarantee group entities always have weight */
7507 update_load_set(&se->load, NICE_0_LOAD);
029632fb
PZ
7508 se->parent = parent;
7509}
7510
7511static DEFINE_MUTEX(shares_mutex);
7512
7513int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7514{
7515 int i;
7516 unsigned long flags;
7517
7518 /*
7519 * We can't change the weight of the root cgroup.
7520 */
7521 if (!tg->se[0])
7522 return -EINVAL;
7523
7524 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
7525
7526 mutex_lock(&shares_mutex);
7527 if (tg->shares == shares)
7528 goto done;
7529
7530 tg->shares = shares;
7531 for_each_possible_cpu(i) {
7532 struct rq *rq = cpu_rq(i);
7533 struct sched_entity *se;
7534
7535 se = tg->se[i];
7536 /* Propagate contribution to hierarchy */
7537 raw_spin_lock_irqsave(&rq->lock, flags);
71b1da46
FW
7538
7539 /* Possible calls to update_curr() need rq clock */
7540 update_rq_clock(rq);
17bc14b7 7541 for_each_sched_entity(se)
029632fb
PZ
7542 update_cfs_shares(group_cfs_rq(se));
7543 raw_spin_unlock_irqrestore(&rq->lock, flags);
7544 }
7545
7546done:
7547 mutex_unlock(&shares_mutex);
7548 return 0;
7549}
7550#else /* CONFIG_FAIR_GROUP_SCHED */
7551
7552void free_fair_sched_group(struct task_group *tg) { }
7553
7554int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7555{
7556 return 1;
7557}
7558
7559void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
7560
7561#endif /* CONFIG_FAIR_GROUP_SCHED */
7562
810b3817 7563
6d686f45 7564static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
0d721cea
PW
7565{
7566 struct sched_entity *se = &task->se;
0d721cea
PW
7567 unsigned int rr_interval = 0;
7568
7569 /*
7570 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
7571 * idle runqueue:
7572 */
0d721cea 7573 if (rq->cfs.load.weight)
a59f4e07 7574 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
0d721cea
PW
7575
7576 return rr_interval;
7577}
7578
bf0f6f24
IM
7579/*
7580 * All the scheduling class methods:
7581 */
029632fb 7582const struct sched_class fair_sched_class = {
5522d5d5 7583 .next = &idle_sched_class,
bf0f6f24
IM
7584 .enqueue_task = enqueue_task_fair,
7585 .dequeue_task = dequeue_task_fair,
7586 .yield_task = yield_task_fair,
d95f4122 7587 .yield_to_task = yield_to_task_fair,
bf0f6f24 7588
2e09bf55 7589 .check_preempt_curr = check_preempt_wakeup,
bf0f6f24
IM
7590
7591 .pick_next_task = pick_next_task_fair,
7592 .put_prev_task = put_prev_task_fair,
7593
681f3e68 7594#ifdef CONFIG_SMP
4ce72a2c 7595 .select_task_rq = select_task_rq_fair,
0a74bef8 7596 .migrate_task_rq = migrate_task_rq_fair,
141965c7 7597
0bcdcf28
CE
7598 .rq_online = rq_online_fair,
7599 .rq_offline = rq_offline_fair,
88ec22d3
PZ
7600
7601 .task_waking = task_waking_fair,
681f3e68 7602#endif
bf0f6f24 7603
83b699ed 7604 .set_curr_task = set_curr_task_fair,
bf0f6f24 7605 .task_tick = task_tick_fair,
cd29fe6f 7606 .task_fork = task_fork_fair,
cb469845
SR
7607
7608 .prio_changed = prio_changed_fair,
da7a735e 7609 .switched_from = switched_from_fair,
cb469845 7610 .switched_to = switched_to_fair,
810b3817 7611
0d721cea
PW
7612 .get_rr_interval = get_rr_interval_fair,
7613
810b3817 7614#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02 7615 .task_move_group = task_move_group_fair,
810b3817 7616#endif
bf0f6f24
IM
7617};
7618
7619#ifdef CONFIG_SCHED_DEBUG
029632fb 7620void print_cfs_stats(struct seq_file *m, int cpu)
bf0f6f24 7621{
bf0f6f24
IM
7622 struct cfs_rq *cfs_rq;
7623
5973e5b9 7624 rcu_read_lock();
c3b64f1e 7625 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5cef9eca 7626 print_cfs_rq(m, cpu, cfs_rq);
5973e5b9 7627 rcu_read_unlock();
bf0f6f24
IM
7628}
7629#endif
029632fb
PZ
7630
7631__init void init_sched_fair_class(void)
7632{
7633#ifdef CONFIG_SMP
7634 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7635
3451d024 7636#ifdef CONFIG_NO_HZ_COMMON
554cecaf 7637 nohz.next_balance = jiffies;
029632fb 7638 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
71325960 7639 cpu_notifier(sched_ilb_notifier, 0);
029632fb
PZ
7640#endif
7641#endif /* SMP */
7642
7643}