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