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