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