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