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