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