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