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