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