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