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