]> git.proxmox.com Git - mirror_ubuntu-kernels.git/blame - kernel/sched/fair.c
sched/fair: Take thermal pressure into account while estimating energy
[mirror_ubuntu-kernels.git] / kernel / sched / fair.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
bf0f6f24
IM
2/*
3 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4 *
5 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6 *
7 * Interactivity improvements by Mike Galbraith
8 * (C) 2007 Mike Galbraith <efault@gmx.de>
9 *
10 * Various enhancements by Dmitry Adamushko.
11 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12 *
13 * Group scheduling enhancements by Srivatsa Vaddagiri
14 * Copyright IBM Corporation, 2007
15 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16 *
17 * Scaled math optimizations by Thomas Gleixner
18 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
21805085
PZ
19 *
20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
90eec103 21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
bf0f6f24 22 */
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)
08f7c2f4 3096 * \Sum grq->load.weight
cef27403
PZ
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)
08f7c2f4 3110 * tg->load_avg
cef27403
PZ
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)
08f7c2f4 3126 * grp->load.weight
cef27403
PZ
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)
08f7c2f4 3145 * tg_load_avg'
17de4ee0
PZ
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{
7c7ad626 3456 long delta, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
0dacee1b
VG
3457 unsigned long load_avg;
3458 u64 load_sum = 0;
95d68593 3459 u32 divider;
09a43ace 3460
0e2d2aaa
PZ
3461 if (!runnable_sum)
3462 return;
09a43ace 3463
0e2d2aaa 3464 gcfs_rq->prop_runnable_sum = 0;
09a43ace 3465
95d68593
VG
3466 /*
3467 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3468 * See ___update_load_avg() for details.
3469 */
87e867b4 3470 divider = get_pelt_divider(&cfs_rq->avg);
95d68593 3471
a4c3c049
VG
3472 if (runnable_sum >= 0) {
3473 /*
3474 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
3475 * the CPU is saturated running == runnable.
3476 */
3477 runnable_sum += se->avg.load_sum;
95d68593 3478 runnable_sum = min_t(long, runnable_sum, divider);
a4c3c049
VG
3479 } else {
3480 /*
3481 * Estimate the new unweighted runnable_sum of the gcfs_rq by
3482 * assuming all tasks are equally runnable.
3483 */
3484 if (scale_load_down(gcfs_rq->load.weight)) {
3485 load_sum = div_s64(gcfs_rq->avg.load_sum,
3486 scale_load_down(gcfs_rq->load.weight));
3487 }
3488
3489 /* But make sure to not inflate se's runnable */
3490 runnable_sum = min(se->avg.load_sum, load_sum);
3491 }
3492
3493 /*
3494 * runnable_sum can't be lower than running_sum
23127296
VG
3495 * Rescale running sum to be in the same range as runnable sum
3496 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
3497 * runnable_sum is in [0 : LOAD_AVG_MAX]
a4c3c049 3498 */
23127296 3499 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
a4c3c049
VG
3500 runnable_sum = max(runnable_sum, running_sum);
3501
0e2d2aaa 3502 load_sum = (s64)se_weight(se) * runnable_sum;
95d68593 3503 load_avg = div_s64(load_sum, divider);
09a43ace 3504
83c5e9d5
DE
3505 se->avg.load_sum = runnable_sum;
3506
7c7ad626 3507 delta = load_avg - se->avg.load_avg;
83c5e9d5
DE
3508 if (!delta)
3509 return;
09a43ace 3510
a4c3c049 3511 se->avg.load_avg = load_avg;
7c7ad626
VG
3512
3513 add_positive(&cfs_rq->avg.load_avg, delta);
3514 cfs_rq->avg.load_sum = cfs_rq->avg.load_avg * divider;
09a43ace
VG
3515}
3516
0e2d2aaa 3517static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
09a43ace 3518{
0e2d2aaa
PZ
3519 cfs_rq->propagate = 1;
3520 cfs_rq->prop_runnable_sum += runnable_sum;
09a43ace
VG
3521}
3522
3523/* Update task and its cfs_rq load average */
3524static inline int propagate_entity_load_avg(struct sched_entity *se)
3525{
0e2d2aaa 3526 struct cfs_rq *cfs_rq, *gcfs_rq;
09a43ace
VG
3527
3528 if (entity_is_task(se))
3529 return 0;
3530
0e2d2aaa
PZ
3531 gcfs_rq = group_cfs_rq(se);
3532 if (!gcfs_rq->propagate)
09a43ace
VG
3533 return 0;
3534
0e2d2aaa
PZ
3535 gcfs_rq->propagate = 0;
3536
09a43ace
VG
3537 cfs_rq = cfs_rq_of(se);
3538
0e2d2aaa 3539 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
09a43ace 3540
0e2d2aaa 3541 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
9f683953 3542 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
0dacee1b 3543 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
09a43ace 3544
ba19f51f 3545 trace_pelt_cfs_tp(cfs_rq);
8de6242c 3546 trace_pelt_se_tp(se);
ba19f51f 3547
09a43ace
VG
3548 return 1;
3549}
3550
bc427898
VG
3551/*
3552 * Check if we need to update the load and the utilization of a blocked
3553 * group_entity:
3554 */
3555static inline bool skip_blocked_update(struct sched_entity *se)
3556{
3557 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3558
3559 /*
3560 * If sched_entity still have not zero load or utilization, we have to
3561 * decay it:
3562 */
3563 if (se->avg.load_avg || se->avg.util_avg)
3564 return false;
3565
3566 /*
3567 * If there is a pending propagation, we have to update the load and
3568 * the utilization of the sched_entity:
3569 */
0e2d2aaa 3570 if (gcfs_rq->propagate)
bc427898
VG
3571 return false;
3572
3573 /*
3574 * Otherwise, the load and the utilization of the sched_entity is
3575 * already zero and there is no pending propagation, so it will be a
3576 * waste of time to try to decay it:
3577 */
3578 return true;
3579}
3580
6e83125c 3581#else /* CONFIG_FAIR_GROUP_SCHED */
09a43ace 3582
fe749158 3583static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
09a43ace
VG
3584
3585static inline int propagate_entity_load_avg(struct sched_entity *se)
3586{
3587 return 0;
3588}
3589
0e2d2aaa 3590static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
09a43ace 3591
6e83125c 3592#endif /* CONFIG_FAIR_GROUP_SCHED */
c566e8e9 3593
3d30544f
PZ
3594/**
3595 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
23127296 3596 * @now: current time, as per cfs_rq_clock_pelt()
3d30544f 3597 * @cfs_rq: cfs_rq to update
3d30544f
PZ
3598 *
3599 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3600 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3601 * post_init_entity_util_avg().
3602 *
3603 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3604 *
7c3edd2c
PZ
3605 * Returns true if the load decayed or we removed load.
3606 *
3607 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3608 * call update_tg_load_avg() when this function returns true.
3d30544f 3609 */
a2c6c91f 3610static inline int
3a123bbb 3611update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
2dac754e 3612{
9f683953 3613 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
9d89c257 3614 struct sched_avg *sa = &cfs_rq->avg;
2a2f5d4e 3615 int decayed = 0;
2dac754e 3616
2a2f5d4e
PZ
3617 if (cfs_rq->removed.nr) {
3618 unsigned long r;
87e867b4 3619 u32 divider = get_pelt_divider(&cfs_rq->avg);
2a2f5d4e
PZ
3620
3621 raw_spin_lock(&cfs_rq->removed.lock);
3622 swap(cfs_rq->removed.util_avg, removed_util);
3623 swap(cfs_rq->removed.load_avg, removed_load);
9f683953 3624 swap(cfs_rq->removed.runnable_avg, removed_runnable);
2a2f5d4e
PZ
3625 cfs_rq->removed.nr = 0;
3626 raw_spin_unlock(&cfs_rq->removed.lock);
3627
2a2f5d4e 3628 r = removed_load;
89741892 3629 sub_positive(&sa->load_avg, r);
9a2dd585 3630 sub_positive(&sa->load_sum, r * divider);
2dac754e 3631
2a2f5d4e 3632 r = removed_util;
89741892 3633 sub_positive(&sa->util_avg, r);
9a2dd585 3634 sub_positive(&sa->util_sum, r * divider);
2a2f5d4e 3635
9f683953
VG
3636 r = removed_runnable;
3637 sub_positive(&sa->runnable_avg, r);
3638 sub_positive(&sa->runnable_sum, r * divider);
3639
3640 /*
3641 * removed_runnable is the unweighted version of removed_load so we
3642 * can use it to estimate removed_load_sum.
3643 */
3644 add_tg_cfs_propagate(cfs_rq,
3645 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
2a2f5d4e
PZ
3646
3647 decayed = 1;
9d89c257 3648 }
36ee28e4 3649
23127296 3650 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
36ee28e4 3651
9d89c257
YD
3652#ifndef CONFIG_64BIT
3653 smp_wmb();
3654 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3655#endif
36ee28e4 3656
2a2f5d4e 3657 return decayed;
21e96f88
SM
3658}
3659
3d30544f
PZ
3660/**
3661 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3662 * @cfs_rq: cfs_rq to attach to
3663 * @se: sched_entity to attach
3664 *
3665 * Must call update_cfs_rq_load_avg() before this, since we rely on
3666 * cfs_rq->avg.last_update_time being current.
3667 */
a4f9a0e5 3668static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
a05e8c51 3669{
95d68593
VG
3670 /*
3671 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3672 * See ___update_load_avg() for details.
3673 */
87e867b4 3674 u32 divider = get_pelt_divider(&cfs_rq->avg);
f207934f
PZ
3675
3676 /*
3677 * When we attach the @se to the @cfs_rq, we must align the decay
3678 * window because without that, really weird and wonderful things can
3679 * happen.
3680 *
3681 * XXX illustrate
3682 */
a05e8c51 3683 se->avg.last_update_time = cfs_rq->avg.last_update_time;
f207934f
PZ
3684 se->avg.period_contrib = cfs_rq->avg.period_contrib;
3685
3686 /*
3687 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
3688 * period_contrib. This isn't strictly correct, but since we're
3689 * entirely outside of the PELT hierarchy, nobody cares if we truncate
3690 * _sum a little.
3691 */
3692 se->avg.util_sum = se->avg.util_avg * divider;
3693
9f683953
VG
3694 se->avg.runnable_sum = se->avg.runnable_avg * divider;
3695
f207934f
PZ
3696 se->avg.load_sum = divider;
3697 if (se_weight(se)) {
3698 se->avg.load_sum =
3699 div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
3700 }
3701
8d5b9025 3702 enqueue_load_avg(cfs_rq, se);
a05e8c51
BP
3703 cfs_rq->avg.util_avg += se->avg.util_avg;
3704 cfs_rq->avg.util_sum += se->avg.util_sum;
9f683953
VG
3705 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
3706 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
0e2d2aaa
PZ
3707
3708 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
a2c6c91f 3709
a4f9a0e5 3710 cfs_rq_util_change(cfs_rq, 0);
ba19f51f
QY
3711
3712 trace_pelt_cfs_tp(cfs_rq);
a05e8c51
BP
3713}
3714
3d30544f
PZ
3715/**
3716 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3717 * @cfs_rq: cfs_rq to detach from
3718 * @se: sched_entity to detach
3719 *
3720 * Must call update_cfs_rq_load_avg() before this, since we rely on
3721 * cfs_rq->avg.last_update_time being current.
3722 */
a05e8c51
BP
3723static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3724{
fcf6631f
VG
3725 /*
3726 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3727 * See ___update_load_avg() for details.
3728 */
3729 u32 divider = get_pelt_divider(&cfs_rq->avg);
3730
8d5b9025 3731 dequeue_load_avg(cfs_rq, se);
89741892 3732 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
fcf6631f 3733 cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * divider;
9f683953 3734 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
fcf6631f 3735 cfs_rq->avg.runnable_sum = cfs_rq->avg.runnable_avg * divider;
0e2d2aaa
PZ
3736
3737 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
a2c6c91f 3738
ea14b57e 3739 cfs_rq_util_change(cfs_rq, 0);
ba19f51f
QY
3740
3741 trace_pelt_cfs_tp(cfs_rq);
a05e8c51
BP
3742}
3743
b382a531
PZ
3744/*
3745 * Optional action to be done while updating the load average
3746 */
3747#define UPDATE_TG 0x1
3748#define SKIP_AGE_LOAD 0x2
3749#define DO_ATTACH 0x4
3750
3751/* Update task and its cfs_rq load average */
3752static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3753{
23127296 3754 u64 now = cfs_rq_clock_pelt(cfs_rq);
b382a531
PZ
3755 int decayed;
3756
3757 /*
3758 * Track task load average for carrying it to new CPU after migrated, and
3759 * track group sched_entity load average for task_h_load calc in migration
3760 */
3761 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
23127296 3762 __update_load_avg_se(now, cfs_rq, se);
b382a531
PZ
3763
3764 decayed = update_cfs_rq_load_avg(now, cfs_rq);
3765 decayed |= propagate_entity_load_avg(se);
3766
3767 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
3768
ea14b57e
PZ
3769 /*
3770 * DO_ATTACH means we're here from enqueue_entity().
3771 * !last_update_time means we've passed through
3772 * migrate_task_rq_fair() indicating we migrated.
3773 *
3774 * IOW we're enqueueing a task on a new CPU.
3775 */
a4f9a0e5 3776 attach_entity_load_avg(cfs_rq, se);
fe749158 3777 update_tg_load_avg(cfs_rq);
b382a531 3778
bef69dd8
VG
3779 } else if (decayed) {
3780 cfs_rq_util_change(cfs_rq, 0);
3781
3782 if (flags & UPDATE_TG)
fe749158 3783 update_tg_load_avg(cfs_rq);
bef69dd8 3784 }
b382a531
PZ
3785}
3786
9d89c257 3787#ifndef CONFIG_64BIT
0905f04e
YD
3788static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3789{
9d89c257 3790 u64 last_update_time_copy;
0905f04e 3791 u64 last_update_time;
9ee474f5 3792
9d89c257
YD
3793 do {
3794 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3795 smp_rmb();
3796 last_update_time = cfs_rq->avg.last_update_time;
3797 } while (last_update_time != last_update_time_copy);
0905f04e
YD
3798
3799 return last_update_time;
3800}
9d89c257 3801#else
0905f04e
YD
3802static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3803{
3804 return cfs_rq->avg.last_update_time;
3805}
9d89c257
YD
3806#endif
3807
104cb16d
MR
3808/*
3809 * Synchronize entity load avg of dequeued entity without locking
3810 * the previous rq.
3811 */
71b47eaf 3812static void sync_entity_load_avg(struct sched_entity *se)
104cb16d
MR
3813{
3814 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3815 u64 last_update_time;
3816
3817 last_update_time = cfs_rq_last_update_time(cfs_rq);
23127296 3818 __update_load_avg_blocked_se(last_update_time, se);
104cb16d
MR
3819}
3820
0905f04e
YD
3821/*
3822 * Task first catches up with cfs_rq, and then subtract
3823 * itself from the cfs_rq (task must be off the queue now).
3824 */
71b47eaf 3825static void remove_entity_load_avg(struct sched_entity *se)
0905f04e
YD
3826{
3827 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2a2f5d4e 3828 unsigned long flags;
0905f04e
YD
3829
3830 /*
7dc603c9
PZ
3831 * tasks cannot exit without having gone through wake_up_new_task() ->
3832 * post_init_entity_util_avg() which will have added things to the
3833 * cfs_rq, so we can remove unconditionally.
0905f04e 3834 */
0905f04e 3835
104cb16d 3836 sync_entity_load_avg(se);
2a2f5d4e
PZ
3837
3838 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
3839 ++cfs_rq->removed.nr;
3840 cfs_rq->removed.util_avg += se->avg.util_avg;
3841 cfs_rq->removed.load_avg += se->avg.load_avg;
9f683953 3842 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
2a2f5d4e 3843 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
2dac754e 3844}
642dbc39 3845
9f683953
VG
3846static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
3847{
3848 return cfs_rq->avg.runnable_avg;
3849}
3850
7ea241af
YD
3851static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3852{
3853 return cfs_rq->avg.load_avg;
3854}
3855
d91cecc1
CY
3856static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
3857
7f65ea42
PB
3858static inline unsigned long task_util(struct task_struct *p)
3859{
3860 return READ_ONCE(p->se.avg.util_avg);
3861}
3862
3863static inline unsigned long _task_util_est(struct task_struct *p)
3864{
3865 struct util_est ue = READ_ONCE(p->se.avg.util_est);
3866
92a801e5 3867 return (max(ue.ewma, ue.enqueued) | UTIL_AVG_UNCHANGED);
7f65ea42
PB
3868}
3869
3870static inline unsigned long task_util_est(struct task_struct *p)
3871{
3872 return max(task_util(p), _task_util_est(p));
3873}
3874
a7008c07
VS
3875#ifdef CONFIG_UCLAMP_TASK
3876static inline unsigned long uclamp_task_util(struct task_struct *p)
3877{
3878 return clamp(task_util_est(p),
3879 uclamp_eff_value(p, UCLAMP_MIN),
3880 uclamp_eff_value(p, UCLAMP_MAX));
3881}
3882#else
3883static inline unsigned long uclamp_task_util(struct task_struct *p)
3884{
3885 return task_util_est(p);
3886}
3887#endif
3888
7f65ea42
PB
3889static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
3890 struct task_struct *p)
3891{
3892 unsigned int enqueued;
3893
3894 if (!sched_feat(UTIL_EST))
3895 return;
3896
3897 /* Update root cfs_rq's estimated utilization */
3898 enqueued = cfs_rq->avg.util_est.enqueued;
92a801e5 3899 enqueued += _task_util_est(p);
7f65ea42 3900 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4581bea8
VD
3901
3902 trace_sched_util_est_cfs_tp(cfs_rq);
7f65ea42
PB
3903}
3904
8c1f560c
XY
3905static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
3906 struct task_struct *p)
3907{
3908 unsigned int enqueued;
3909
3910 if (!sched_feat(UTIL_EST))
3911 return;
3912
3913 /* Update root cfs_rq's estimated utilization */
3914 enqueued = cfs_rq->avg.util_est.enqueued;
3915 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
3916 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3917
3918 trace_sched_util_est_cfs_tp(cfs_rq);
3919}
3920
b89997aa
VD
3921#define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
3922
7f65ea42
PB
3923/*
3924 * Check if a (signed) value is within a specified (unsigned) margin,
3925 * based on the observation that:
3926 *
3927 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
3928 *
3b03706f 3929 * NOTE: this only works when value + margin < INT_MAX.
7f65ea42
PB
3930 */
3931static inline bool within_margin(int value, int margin)
3932{
3933 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
3934}
3935
8c1f560c
XY
3936static inline void util_est_update(struct cfs_rq *cfs_rq,
3937 struct task_struct *p,
3938 bool task_sleep)
7f65ea42 3939{
b89997aa 3940 long last_ewma_diff, last_enqueued_diff;
7f65ea42
PB
3941 struct util_est ue;
3942
3943 if (!sched_feat(UTIL_EST))
3944 return;
3945
7f65ea42
PB
3946 /*
3947 * Skip update of task's estimated utilization when the task has not
3948 * yet completed an activation, e.g. being migrated.
3949 */
3950 if (!task_sleep)
3951 return;
3952
d519329f
PB
3953 /*
3954 * If the PELT values haven't changed since enqueue time,
3955 * skip the util_est update.
3956 */
3957 ue = p->se.avg.util_est;
3958 if (ue.enqueued & UTIL_AVG_UNCHANGED)
3959 return;
3960
b89997aa
VD
3961 last_enqueued_diff = ue.enqueued;
3962
b8c96361
PB
3963 /*
3964 * Reset EWMA on utilization increases, the moving average is used only
3965 * to smooth utilization decreases.
3966 */
3967 ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
3968 if (sched_feat(UTIL_EST_FASTUP)) {
3969 if (ue.ewma < ue.enqueued) {
3970 ue.ewma = ue.enqueued;
3971 goto done;
3972 }
3973 }
3974
7f65ea42 3975 /*
b89997aa 3976 * Skip update of task's estimated utilization when its members are
7f65ea42
PB
3977 * already ~1% close to its last activation value.
3978 */
7f65ea42 3979 last_ewma_diff = ue.enqueued - ue.ewma;
b89997aa
VD
3980 last_enqueued_diff -= ue.enqueued;
3981 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
3982 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
3983 goto done;
3984
7f65ea42 3985 return;
b89997aa 3986 }
7f65ea42 3987
10a35e68
VG
3988 /*
3989 * To avoid overestimation of actual task utilization, skip updates if
3990 * we cannot grant there is idle time in this CPU.
3991 */
8c1f560c 3992 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
10a35e68
VG
3993 return;
3994
7f65ea42
PB
3995 /*
3996 * Update Task's estimated utilization
3997 *
3998 * When *p completes an activation we can consolidate another sample
3999 * of the task size. This is done by storing the current PELT value
4000 * as ue.enqueued and by using this value to update the Exponential
4001 * Weighted Moving Average (EWMA):
4002 *
4003 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4004 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4005 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4006 * = w * ( last_ewma_diff ) + ewma(t-1)
4007 * = w * (last_ewma_diff + ewma(t-1) / w)
4008 *
4009 * Where 'w' is the weight of new samples, which is configured to be
4010 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4011 */
4012 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4013 ue.ewma += last_ewma_diff;
4014 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
b8c96361 4015done:
7f65ea42 4016 WRITE_ONCE(p->se.avg.util_est, ue);
4581bea8
VD
4017
4018 trace_sched_util_est_se_tp(&p->se);
7f65ea42
PB
4019}
4020
3b1baa64
MR
4021static inline int task_fits_capacity(struct task_struct *p, long capacity)
4022{
a7008c07 4023 return fits_capacity(uclamp_task_util(p), capacity);
3b1baa64
MR
4024}
4025
4026static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4027{
4028 if (!static_branch_unlikely(&sched_asym_cpucapacity))
4029 return;
4030
0ae78eec 4031 if (!p || p->nr_cpus_allowed == 1) {
3b1baa64
MR
4032 rq->misfit_task_load = 0;
4033 return;
4034 }
4035
4036 if (task_fits_capacity(p, capacity_of(cpu_of(rq)))) {
4037 rq->misfit_task_load = 0;
4038 return;
4039 }
4040
01cfcde9
VG
4041 /*
4042 * Make sure that misfit_task_load will not be null even if
4043 * task_h_load() returns 0.
4044 */
4045 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
3b1baa64
MR
4046}
4047
38033c37
PZ
4048#else /* CONFIG_SMP */
4049
d31b1a66
VG
4050#define UPDATE_TG 0x0
4051#define SKIP_AGE_LOAD 0x0
b382a531 4052#define DO_ATTACH 0x0
d31b1a66 4053
88c0616e 4054static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
536bd00c 4055{
ea14b57e 4056 cfs_rq_util_change(cfs_rq, 0);
536bd00c
RW
4057}
4058
9d89c257 4059static inline void remove_entity_load_avg(struct sched_entity *se) {}
6e83125c 4060
a05e8c51 4061static inline void
a4f9a0e5 4062attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
a05e8c51
BP
4063static inline void
4064detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4065
d91cecc1 4066static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
6e83125c
PZ
4067{
4068 return 0;
4069}
4070
7f65ea42
PB
4071static inline void
4072util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4073
4074static inline void
8c1f560c
XY
4075util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4076
4077static inline void
4078util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4079 bool task_sleep) {}
3b1baa64 4080static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
7f65ea42 4081
38033c37 4082#endif /* CONFIG_SMP */
9d85f21c 4083
ddc97297
PZ
4084static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
4085{
4086#ifdef CONFIG_SCHED_DEBUG
4087 s64 d = se->vruntime - cfs_rq->min_vruntime;
4088
4089 if (d < 0)
4090 d = -d;
4091
4092 if (d > 3*sysctl_sched_latency)
ae92882e 4093 schedstat_inc(cfs_rq->nr_spread_over);
ddc97297
PZ
4094#endif
4095}
4096
aeb73b04
PZ
4097static void
4098place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
4099{
1af5f730 4100 u64 vruntime = cfs_rq->min_vruntime;
94dfb5e7 4101
2cb8600e
PZ
4102 /*
4103 * The 'current' period is already promised to the current tasks,
4104 * however the extra weight of the new task will slow them down a
4105 * little, place the new task so that it fits in the slot that
4106 * stays open at the end.
4107 */
94dfb5e7 4108 if (initial && sched_feat(START_DEBIT))
f9c0b095 4109 vruntime += sched_vslice(cfs_rq, se);
aeb73b04 4110
a2e7a7eb 4111 /* sleeps up to a single latency don't count. */
5ca9880c 4112 if (!initial) {
a2e7a7eb 4113 unsigned long thresh = sysctl_sched_latency;
a7be37ac 4114
a2e7a7eb
MG
4115 /*
4116 * Halve their sleep time's effect, to allow
4117 * for a gentler effect of sleepers:
4118 */
4119 if (sched_feat(GENTLE_FAIR_SLEEPERS))
4120 thresh >>= 1;
51e0304c 4121
a2e7a7eb 4122 vruntime -= thresh;
aeb73b04
PZ
4123 }
4124
b5d9d734 4125 /* ensure we never gain time by being placed backwards. */
16c8f1c7 4126 se->vruntime = max_vruntime(se->vruntime, vruntime);
aeb73b04
PZ
4127}
4128
d3d9dc33
PT
4129static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
4130
cb251765
MG
4131static inline void check_schedstat_required(void)
4132{
4133#ifdef CONFIG_SCHEDSTATS
4134 if (schedstat_enabled())
4135 return;
4136
4137 /* Force schedstat enabled if a dependent tracepoint is active */
4138 if (trace_sched_stat_wait_enabled() ||
4139 trace_sched_stat_sleep_enabled() ||
4140 trace_sched_stat_iowait_enabled() ||
4141 trace_sched_stat_blocked_enabled() ||
4142 trace_sched_stat_runtime_enabled()) {
eda8dca5 4143 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
cb251765 4144 "stat_blocked and stat_runtime require the "
f67abed5 4145 "kernel parameter schedstats=enable or "
cb251765
MG
4146 "kernel.sched_schedstats=1\n");
4147 }
4148#endif
4149}
4150
fe61468b 4151static inline bool cfs_bandwidth_used(void);
b5179ac7
PZ
4152
4153/*
4154 * MIGRATION
4155 *
4156 * dequeue
4157 * update_curr()
4158 * update_min_vruntime()
4159 * vruntime -= min_vruntime
4160 *
4161 * enqueue
4162 * update_curr()
4163 * update_min_vruntime()
4164 * vruntime += min_vruntime
4165 *
4166 * this way the vruntime transition between RQs is done when both
4167 * min_vruntime are up-to-date.
4168 *
4169 * WAKEUP (remote)
4170 *
59efa0ba 4171 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
b5179ac7
PZ
4172 * vruntime -= min_vruntime
4173 *
4174 * enqueue
4175 * update_curr()
4176 * update_min_vruntime()
4177 * vruntime += min_vruntime
4178 *
4179 * this way we don't have the most up-to-date min_vruntime on the originating
4180 * CPU and an up-to-date min_vruntime on the destination CPU.
4181 */
4182
bf0f6f24 4183static void
88ec22d3 4184enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 4185{
2f950354
PZ
4186 bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
4187 bool curr = cfs_rq->curr == se;
4188
88ec22d3 4189 /*
2f950354
PZ
4190 * If we're the current task, we must renormalise before calling
4191 * update_curr().
88ec22d3 4192 */
2f950354 4193 if (renorm && curr)
88ec22d3
PZ
4194 se->vruntime += cfs_rq->min_vruntime;
4195
2f950354
PZ
4196 update_curr(cfs_rq);
4197
bf0f6f24 4198 /*
2f950354
PZ
4199 * Otherwise, renormalise after, such that we're placed at the current
4200 * moment in time, instead of some random moment in the past. Being
4201 * placed in the past could significantly boost this task to the
4202 * fairness detriment of existing tasks.
bf0f6f24 4203 */
2f950354
PZ
4204 if (renorm && !curr)
4205 se->vruntime += cfs_rq->min_vruntime;
4206
89ee048f
VG
4207 /*
4208 * When enqueuing a sched_entity, we must:
4209 * - Update loads to have both entity and cfs_rq synced with now.
9f683953 4210 * - Add its load to cfs_rq->runnable_avg
89ee048f
VG
4211 * - For group_entity, update its weight to reflect the new share of
4212 * its group cfs_rq
4213 * - Add its new weight to cfs_rq->load.weight
4214 */
b382a531 4215 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
9f683953 4216 se_update_runnable(se);
1ea6c46a 4217 update_cfs_group(se);
17bc14b7 4218 account_entity_enqueue(cfs_rq, se);
bf0f6f24 4219
1a3d027c 4220 if (flags & ENQUEUE_WAKEUP)
aeb73b04 4221 place_entity(cfs_rq, se, 0);
bf0f6f24 4222
cb251765 4223 check_schedstat_required();
4fa8d299
JP
4224 update_stats_enqueue(cfs_rq, se, flags);
4225 check_spread(cfs_rq, se);
2f950354 4226 if (!curr)
83b699ed 4227 __enqueue_entity(cfs_rq, se);
2069dd75 4228 se->on_rq = 1;
3d4b47b4 4229
fe61468b
VG
4230 /*
4231 * When bandwidth control is enabled, cfs might have been removed
4232 * because of a parent been throttled but cfs->nr_running > 1. Try to
3b03706f 4233 * add it unconditionally.
fe61468b
VG
4234 */
4235 if (cfs_rq->nr_running == 1 || cfs_bandwidth_used())
3d4b47b4 4236 list_add_leaf_cfs_rq(cfs_rq);
fe61468b
VG
4237
4238 if (cfs_rq->nr_running == 1)
d3d9dc33 4239 check_enqueue_throttle(cfs_rq);
bf0f6f24
IM
4240}
4241
2c13c919 4242static void __clear_buddies_last(struct sched_entity *se)
2002c695 4243{
2c13c919
RR
4244 for_each_sched_entity(se) {
4245 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 4246 if (cfs_rq->last != se)
2c13c919 4247 break;
f1044799
PZ
4248
4249 cfs_rq->last = NULL;
2c13c919
RR
4250 }
4251}
2002c695 4252
2c13c919
RR
4253static void __clear_buddies_next(struct sched_entity *se)
4254{
4255 for_each_sched_entity(se) {
4256 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 4257 if (cfs_rq->next != se)
2c13c919 4258 break;
f1044799
PZ
4259
4260 cfs_rq->next = NULL;
2c13c919 4261 }
2002c695
PZ
4262}
4263
ac53db59
RR
4264static void __clear_buddies_skip(struct sched_entity *se)
4265{
4266 for_each_sched_entity(se) {
4267 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 4268 if (cfs_rq->skip != se)
ac53db59 4269 break;
f1044799
PZ
4270
4271 cfs_rq->skip = NULL;
ac53db59
RR
4272 }
4273}
4274
a571bbea
PZ
4275static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
4276{
2c13c919
RR
4277 if (cfs_rq->last == se)
4278 __clear_buddies_last(se);
4279
4280 if (cfs_rq->next == se)
4281 __clear_buddies_next(se);
ac53db59
RR
4282
4283 if (cfs_rq->skip == se)
4284 __clear_buddies_skip(se);
a571bbea
PZ
4285}
4286
6c16a6dc 4287static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d8b4986d 4288
bf0f6f24 4289static void
371fd7e7 4290dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 4291{
a2a2d680
DA
4292 /*
4293 * Update run-time statistics of the 'current'.
4294 */
4295 update_curr(cfs_rq);
89ee048f
VG
4296
4297 /*
4298 * When dequeuing a sched_entity, we must:
4299 * - Update loads to have both entity and cfs_rq synced with now.
9f683953 4300 * - Subtract its load from the cfs_rq->runnable_avg.
dfcb245e 4301 * - Subtract its previous weight from cfs_rq->load.weight.
89ee048f
VG
4302 * - For group entity, update its weight to reflect the new share
4303 * of its group cfs_rq.
4304 */
88c0616e 4305 update_load_avg(cfs_rq, se, UPDATE_TG);
9f683953 4306 se_update_runnable(se);
a2a2d680 4307
4fa8d299 4308 update_stats_dequeue(cfs_rq, se, flags);
67e9fb2a 4309
2002c695 4310 clear_buddies(cfs_rq, se);
4793241b 4311
83b699ed 4312 if (se != cfs_rq->curr)
30cfdcfc 4313 __dequeue_entity(cfs_rq, se);
17bc14b7 4314 se->on_rq = 0;
30cfdcfc 4315 account_entity_dequeue(cfs_rq, se);
88ec22d3
PZ
4316
4317 /*
b60205c7
PZ
4318 * Normalize after update_curr(); which will also have moved
4319 * min_vruntime if @se is the one holding it back. But before doing
4320 * update_min_vruntime() again, which will discount @se's position and
4321 * can move min_vruntime forward still more.
88ec22d3 4322 */
371fd7e7 4323 if (!(flags & DEQUEUE_SLEEP))
88ec22d3 4324 se->vruntime -= cfs_rq->min_vruntime;
1e876231 4325
d8b4986d
PT
4326 /* return excess runtime on last dequeue */
4327 return_cfs_rq_runtime(cfs_rq);
4328
1ea6c46a 4329 update_cfs_group(se);
b60205c7
PZ
4330
4331 /*
4332 * Now advance min_vruntime if @se was the entity holding it back,
4333 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4334 * put back on, and if we advance min_vruntime, we'll be placed back
4335 * further than we started -- ie. we'll be penalized.
4336 */
9845c49c 4337 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
b60205c7 4338 update_min_vruntime(cfs_rq);
bf0f6f24
IM
4339}
4340
4341/*
4342 * Preempt the current task with a newly woken task if needed:
4343 */
7c92e54f 4344static void
2e09bf55 4345check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
bf0f6f24 4346{
11697830 4347 unsigned long ideal_runtime, delta_exec;
f4cfb33e
WX
4348 struct sched_entity *se;
4349 s64 delta;
11697830 4350
6d0f0ebd 4351 ideal_runtime = sched_slice(cfs_rq, curr);
11697830 4352 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
a9f3e2b5 4353 if (delta_exec > ideal_runtime) {
8875125e 4354 resched_curr(rq_of(cfs_rq));
a9f3e2b5
MG
4355 /*
4356 * The current task ran long enough, ensure it doesn't get
4357 * re-elected due to buddy favours.
4358 */
4359 clear_buddies(cfs_rq, curr);
f685ceac
MG
4360 return;
4361 }
4362
4363 /*
4364 * Ensure that a task that missed wakeup preemption by a
4365 * narrow margin doesn't have to wait for a full slice.
4366 * This also mitigates buddy induced latencies under load.
4367 */
f685ceac
MG
4368 if (delta_exec < sysctl_sched_min_granularity)
4369 return;
4370
f4cfb33e
WX
4371 se = __pick_first_entity(cfs_rq);
4372 delta = curr->vruntime - se->vruntime;
f685ceac 4373
f4cfb33e
WX
4374 if (delta < 0)
4375 return;
d7d82944 4376
f4cfb33e 4377 if (delta > ideal_runtime)
8875125e 4378 resched_curr(rq_of(cfs_rq));
bf0f6f24
IM
4379}
4380
83b699ed 4381static void
8494f412 4382set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 4383{
21f56ffe
PZ
4384 clear_buddies(cfs_rq, se);
4385
83b699ed
SV
4386 /* 'current' is not kept within the tree. */
4387 if (se->on_rq) {
4388 /*
4389 * Any task has to be enqueued before it get to execute on
4390 * a CPU. So account for the time it spent waiting on the
4391 * runqueue.
4392 */
4fa8d299 4393 update_stats_wait_end(cfs_rq, se);
83b699ed 4394 __dequeue_entity(cfs_rq, se);
88c0616e 4395 update_load_avg(cfs_rq, se, UPDATE_TG);
83b699ed
SV
4396 }
4397
79303e9e 4398 update_stats_curr_start(cfs_rq, se);
429d43bc 4399 cfs_rq->curr = se;
4fa8d299 4400
eba1ed4b
IM
4401 /*
4402 * Track our maximum slice length, if the CPU's load is at
4403 * least twice that of our own weight (i.e. dont track it
4404 * when there are only lesser-weight tasks around):
4405 */
f2bedc47
DE
4406 if (schedstat_enabled() &&
4407 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
4fa8d299
JP
4408 schedstat_set(se->statistics.slice_max,
4409 max((u64)schedstat_val(se->statistics.slice_max),
4410 se->sum_exec_runtime - se->prev_sum_exec_runtime));
eba1ed4b 4411 }
4fa8d299 4412
4a55b450 4413 se->prev_sum_exec_runtime = se->sum_exec_runtime;
bf0f6f24
IM
4414}
4415
3f3a4904
PZ
4416static int
4417wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
4418
ac53db59
RR
4419/*
4420 * Pick the next process, keeping these things in mind, in this order:
4421 * 1) keep things fair between processes/task groups
4422 * 2) pick the "next" process, since someone really wants that to run
4423 * 3) pick the "last" process, for cache locality
4424 * 4) do not run the "skip" process, if something else is available
4425 */
678d5718
PZ
4426static struct sched_entity *
4427pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
aa2ac252 4428{
678d5718
PZ
4429 struct sched_entity *left = __pick_first_entity(cfs_rq);
4430 struct sched_entity *se;
4431
4432 /*
4433 * If curr is set we have to see if its left of the leftmost entity
4434 * still in the tree, provided there was anything in the tree at all.
4435 */
4436 if (!left || (curr && entity_before(curr, left)))
4437 left = curr;
4438
4439 se = left; /* ideally we run the leftmost entity */
f4b6755f 4440
ac53db59
RR
4441 /*
4442 * Avoid running the skip buddy, if running something else can
4443 * be done without getting too unfair.
4444 */
21f56ffe 4445 if (cfs_rq->skip && cfs_rq->skip == se) {
678d5718
PZ
4446 struct sched_entity *second;
4447
4448 if (se == curr) {
4449 second = __pick_first_entity(cfs_rq);
4450 } else {
4451 second = __pick_next_entity(se);
4452 if (!second || (curr && entity_before(curr, second)))
4453 second = curr;
4454 }
4455
ac53db59
RR
4456 if (second && wakeup_preempt_entity(second, left) < 1)
4457 se = second;
4458 }
aa2ac252 4459
9abb8973
PO
4460 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) {
4461 /*
4462 * Someone really wants this to run. If it's not unfair, run it.
4463 */
ac53db59 4464 se = cfs_rq->next;
9abb8973
PO
4465 } else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) {
4466 /*
4467 * Prefer last buddy, try to return the CPU to a preempted task.
4468 */
4469 se = cfs_rq->last;
4470 }
ac53db59 4471
4793241b 4472 return se;
aa2ac252
PZ
4473}
4474
678d5718 4475static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d3d9dc33 4476
ab6cde26 4477static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
bf0f6f24
IM
4478{
4479 /*
4480 * If still on the runqueue then deactivate_task()
4481 * was not called and update_curr() has to be done:
4482 */
4483 if (prev->on_rq)
b7cc0896 4484 update_curr(cfs_rq);
bf0f6f24 4485
d3d9dc33
PT
4486 /* throttle cfs_rqs exceeding runtime */
4487 check_cfs_rq_runtime(cfs_rq);
4488
4fa8d299 4489 check_spread(cfs_rq, prev);
cb251765 4490
30cfdcfc 4491 if (prev->on_rq) {
4fa8d299 4492 update_stats_wait_start(cfs_rq, prev);
30cfdcfc
DA
4493 /* Put 'current' back into the tree. */
4494 __enqueue_entity(cfs_rq, prev);
9d85f21c 4495 /* in !on_rq case, update occurred at dequeue */
88c0616e 4496 update_load_avg(cfs_rq, prev, 0);
30cfdcfc 4497 }
429d43bc 4498 cfs_rq->curr = NULL;
bf0f6f24
IM
4499}
4500
8f4d37ec
PZ
4501static void
4502entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
bf0f6f24 4503{
bf0f6f24 4504 /*
30cfdcfc 4505 * Update run-time statistics of the 'current'.
bf0f6f24 4506 */
30cfdcfc 4507 update_curr(cfs_rq);
bf0f6f24 4508
9d85f21c
PT
4509 /*
4510 * Ensure that runnable average is periodically updated.
4511 */
88c0616e 4512 update_load_avg(cfs_rq, curr, UPDATE_TG);
1ea6c46a 4513 update_cfs_group(curr);
9d85f21c 4514
8f4d37ec
PZ
4515#ifdef CONFIG_SCHED_HRTICK
4516 /*
4517 * queued ticks are scheduled to match the slice, so don't bother
4518 * validating it and just reschedule.
4519 */
983ed7a6 4520 if (queued) {
8875125e 4521 resched_curr(rq_of(cfs_rq));
983ed7a6
HH
4522 return;
4523 }
8f4d37ec
PZ
4524 /*
4525 * don't let the period tick interfere with the hrtick preemption
4526 */
4527 if (!sched_feat(DOUBLE_TICK) &&
4528 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
4529 return;
4530#endif
4531
2c2efaed 4532 if (cfs_rq->nr_running > 1)
2e09bf55 4533 check_preempt_tick(cfs_rq, curr);
bf0f6f24
IM
4534}
4535
ab84d31e
PT
4536
4537/**************************************************
4538 * CFS bandwidth control machinery
4539 */
4540
4541#ifdef CONFIG_CFS_BANDWIDTH
029632fb 4542
e9666d10 4543#ifdef CONFIG_JUMP_LABEL
c5905afb 4544static struct static_key __cfs_bandwidth_used;
029632fb
PZ
4545
4546static inline bool cfs_bandwidth_used(void)
4547{
c5905afb 4548 return static_key_false(&__cfs_bandwidth_used);
029632fb
PZ
4549}
4550
1ee14e6c 4551void cfs_bandwidth_usage_inc(void)
029632fb 4552{
ce48c146 4553 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
1ee14e6c
BS
4554}
4555
4556void cfs_bandwidth_usage_dec(void)
4557{
ce48c146 4558 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
029632fb 4559}
e9666d10 4560#else /* CONFIG_JUMP_LABEL */
029632fb
PZ
4561static bool cfs_bandwidth_used(void)
4562{
4563 return true;
4564}
4565
1ee14e6c
BS
4566void cfs_bandwidth_usage_inc(void) {}
4567void cfs_bandwidth_usage_dec(void) {}
e9666d10 4568#endif /* CONFIG_JUMP_LABEL */
029632fb 4569
ab84d31e
PT
4570/*
4571 * default period for cfs group bandwidth.
4572 * default: 0.1s, units: nanoseconds
4573 */
4574static inline u64 default_cfs_period(void)
4575{
4576 return 100000000ULL;
4577}
ec12cb7f
PT
4578
4579static inline u64 sched_cfs_bandwidth_slice(void)
4580{
4581 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
4582}
4583
a9cf55b2 4584/*
763a9ec0
QC
4585 * Replenish runtime according to assigned quota. We use sched_clock_cpu
4586 * directly instead of rq->clock to avoid adding additional synchronization
4587 * around rq->lock.
a9cf55b2
PT
4588 *
4589 * requires cfs_b->lock
4590 */
029632fb 4591void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
a9cf55b2 4592{
763a9ec0
QC
4593 if (cfs_b->quota != RUNTIME_INF)
4594 cfs_b->runtime = cfs_b->quota;
a9cf55b2
PT
4595}
4596
029632fb
PZ
4597static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4598{
4599 return &tg->cfs_bandwidth;
4600}
4601
85dac906 4602/* returns 0 on failure to allocate runtime */
e98fa02c
PT
4603static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
4604 struct cfs_rq *cfs_rq, u64 target_runtime)
ec12cb7f 4605{
e98fa02c
PT
4606 u64 min_amount, amount = 0;
4607
4608 lockdep_assert_held(&cfs_b->lock);
ec12cb7f
PT
4609
4610 /* note: this is a positive sum as runtime_remaining <= 0 */
e98fa02c 4611 min_amount = target_runtime - cfs_rq->runtime_remaining;
ec12cb7f 4612
ec12cb7f
PT
4613 if (cfs_b->quota == RUNTIME_INF)
4614 amount = min_amount;
58088ad0 4615 else {
77a4d1a1 4616 start_cfs_bandwidth(cfs_b);
58088ad0
PT
4617
4618 if (cfs_b->runtime > 0) {
4619 amount = min(cfs_b->runtime, min_amount);
4620 cfs_b->runtime -= amount;
4621 cfs_b->idle = 0;
4622 }
ec12cb7f 4623 }
ec12cb7f
PT
4624
4625 cfs_rq->runtime_remaining += amount;
85dac906
PT
4626
4627 return cfs_rq->runtime_remaining > 0;
ec12cb7f
PT
4628}
4629
e98fa02c
PT
4630/* returns 0 on failure to allocate runtime */
4631static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4632{
4633 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4634 int ret;
4635
4636 raw_spin_lock(&cfs_b->lock);
4637 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
4638 raw_spin_unlock(&cfs_b->lock);
4639
4640 return ret;
4641}
4642
9dbdb155 4643static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
a9cf55b2
PT
4644{
4645 /* dock delta_exec before expiring quota (as it could span periods) */
ec12cb7f 4646 cfs_rq->runtime_remaining -= delta_exec;
a9cf55b2
PT
4647
4648 if (likely(cfs_rq->runtime_remaining > 0))
ec12cb7f
PT
4649 return;
4650
5e2d2cc2
L
4651 if (cfs_rq->throttled)
4652 return;
85dac906
PT
4653 /*
4654 * if we're unable to extend our runtime we resched so that the active
4655 * hierarchy can be throttled
4656 */
4657 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
8875125e 4658 resched_curr(rq_of(cfs_rq));
ec12cb7f
PT
4659}
4660
6c16a6dc 4661static __always_inline
9dbdb155 4662void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
ec12cb7f 4663{
56f570e5 4664 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
ec12cb7f
PT
4665 return;
4666
4667 __account_cfs_rq_runtime(cfs_rq, delta_exec);
4668}
4669
85dac906
PT
4670static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4671{
56f570e5 4672 return cfs_bandwidth_used() && cfs_rq->throttled;
85dac906
PT
4673}
4674
64660c86
PT
4675/* check whether cfs_rq, or any parent, is throttled */
4676static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4677{
56f570e5 4678 return cfs_bandwidth_used() && cfs_rq->throttle_count;
64660c86
PT
4679}
4680
4681/*
4682 * Ensure that neither of the group entities corresponding to src_cpu or
4683 * dest_cpu are members of a throttled hierarchy when performing group
4684 * load-balance operations.
4685 */
4686static inline int throttled_lb_pair(struct task_group *tg,
4687 int src_cpu, int dest_cpu)
4688{
4689 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4690
4691 src_cfs_rq = tg->cfs_rq[src_cpu];
4692 dest_cfs_rq = tg->cfs_rq[dest_cpu];
4693
4694 return throttled_hierarchy(src_cfs_rq) ||
4695 throttled_hierarchy(dest_cfs_rq);
4696}
4697
64660c86
PT
4698static int tg_unthrottle_up(struct task_group *tg, void *data)
4699{
4700 struct rq *rq = data;
4701 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4702
4703 cfs_rq->throttle_count--;
64660c86 4704 if (!cfs_rq->throttle_count) {
78becc27 4705 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
f1b17280 4706 cfs_rq->throttled_clock_task;
31bc6aea
VG
4707
4708 /* Add cfs_rq with already running entity in the list */
4709 if (cfs_rq->nr_running >= 1)
4710 list_add_leaf_cfs_rq(cfs_rq);
64660c86 4711 }
64660c86
PT
4712
4713 return 0;
4714}
4715
4716static int tg_throttle_down(struct task_group *tg, void *data)
4717{
4718 struct rq *rq = data;
4719 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4720
82958366 4721 /* group is entering throttled state, stop time */
31bc6aea 4722 if (!cfs_rq->throttle_count) {
78becc27 4723 cfs_rq->throttled_clock_task = rq_clock_task(rq);
31bc6aea
VG
4724 list_del_leaf_cfs_rq(cfs_rq);
4725 }
64660c86
PT
4726 cfs_rq->throttle_count++;
4727
4728 return 0;
4729}
4730
e98fa02c 4731static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
85dac906
PT
4732{
4733 struct rq *rq = rq_of(cfs_rq);
4734 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4735 struct sched_entity *se;
43e9f7f2 4736 long task_delta, idle_task_delta, dequeue = 1;
e98fa02c
PT
4737
4738 raw_spin_lock(&cfs_b->lock);
4739 /* This will start the period timer if necessary */
4740 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
4741 /*
4742 * We have raced with bandwidth becoming available, and if we
4743 * actually throttled the timer might not unthrottle us for an
4744 * entire period. We additionally needed to make sure that any
4745 * subsequent check_cfs_rq_runtime calls agree not to throttle
4746 * us, as we may commit to do cfs put_prev+pick_next, so we ask
4747 * for 1ns of runtime rather than just check cfs_b.
4748 */
4749 dequeue = 0;
4750 } else {
4751 list_add_tail_rcu(&cfs_rq->throttled_list,
4752 &cfs_b->throttled_cfs_rq);
4753 }
4754 raw_spin_unlock(&cfs_b->lock);
4755
4756 if (!dequeue)
4757 return false; /* Throttle no longer required. */
85dac906
PT
4758
4759 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4760
f1b17280 4761 /* freeze hierarchy runnable averages while throttled */
64660c86
PT
4762 rcu_read_lock();
4763 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4764 rcu_read_unlock();
85dac906
PT
4765
4766 task_delta = cfs_rq->h_nr_running;
43e9f7f2 4767 idle_task_delta = cfs_rq->idle_h_nr_running;
85dac906
PT
4768 for_each_sched_entity(se) {
4769 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4770 /* throttled entity or throttle-on-deactivate */
4771 if (!se->on_rq)
b6d37a76 4772 goto done;
85dac906 4773
b6d37a76 4774 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
6212437f 4775
85dac906 4776 qcfs_rq->h_nr_running -= task_delta;
43e9f7f2 4777 qcfs_rq->idle_h_nr_running -= idle_task_delta;
85dac906 4778
b6d37a76
PW
4779 if (qcfs_rq->load.weight) {
4780 /* Avoid re-evaluating load for this entity: */
4781 se = parent_entity(se);
4782 break;
4783 }
4784 }
4785
4786 for_each_sched_entity(se) {
4787 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4788 /* throttled entity or throttle-on-deactivate */
4789 if (!se->on_rq)
4790 goto done;
4791
4792 update_load_avg(qcfs_rq, se, 0);
4793 se_update_runnable(se);
4794
4795 qcfs_rq->h_nr_running -= task_delta;
4796 qcfs_rq->idle_h_nr_running -= idle_task_delta;
85dac906
PT
4797 }
4798
b6d37a76
PW
4799 /* At this point se is NULL and we are at root level*/
4800 sub_nr_running(rq, task_delta);
85dac906 4801
b6d37a76 4802done:
c06f04c7 4803 /*
e98fa02c
PT
4804 * Note: distribution will already see us throttled via the
4805 * throttled-list. rq->lock protects completion.
c06f04c7 4806 */
e98fa02c
PT
4807 cfs_rq->throttled = 1;
4808 cfs_rq->throttled_clock = rq_clock(rq);
4809 return true;
85dac906
PT
4810}
4811
029632fb 4812void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
671fd9da
PT
4813{
4814 struct rq *rq = rq_of(cfs_rq);
4815 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4816 struct sched_entity *se;
43e9f7f2 4817 long task_delta, idle_task_delta;
671fd9da 4818
22b958d8 4819 se = cfs_rq->tg->se[cpu_of(rq)];
671fd9da
PT
4820
4821 cfs_rq->throttled = 0;
1a55af2e
FW
4822
4823 update_rq_clock(rq);
4824
671fd9da 4825 raw_spin_lock(&cfs_b->lock);
78becc27 4826 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
671fd9da
PT
4827 list_del_rcu(&cfs_rq->throttled_list);
4828 raw_spin_unlock(&cfs_b->lock);
4829
64660c86
PT
4830 /* update hierarchical throttle state */
4831 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4832
671fd9da
PT
4833 if (!cfs_rq->load.weight)
4834 return;
4835
4836 task_delta = cfs_rq->h_nr_running;
43e9f7f2 4837 idle_task_delta = cfs_rq->idle_h_nr_running;
671fd9da
PT
4838 for_each_sched_entity(se) {
4839 if (se->on_rq)
39f23ce0
VG
4840 break;
4841 cfs_rq = cfs_rq_of(se);
4842 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4843
4844 cfs_rq->h_nr_running += task_delta;
4845 cfs_rq->idle_h_nr_running += idle_task_delta;
4846
4847 /* end evaluation on encountering a throttled cfs_rq */
4848 if (cfs_rq_throttled(cfs_rq))
4849 goto unthrottle_throttle;
4850 }
671fd9da 4851
39f23ce0 4852 for_each_sched_entity(se) {
671fd9da 4853 cfs_rq = cfs_rq_of(se);
39f23ce0
VG
4854
4855 update_load_avg(cfs_rq, se, UPDATE_TG);
4856 se_update_runnable(se);
6212437f 4857
671fd9da 4858 cfs_rq->h_nr_running += task_delta;
43e9f7f2 4859 cfs_rq->idle_h_nr_running += idle_task_delta;
671fd9da 4860
39f23ce0
VG
4861
4862 /* end evaluation on encountering a throttled cfs_rq */
671fd9da 4863 if (cfs_rq_throttled(cfs_rq))
39f23ce0
VG
4864 goto unthrottle_throttle;
4865
4866 /*
4867 * One parent has been throttled and cfs_rq removed from the
4868 * list. Add it back to not break the leaf list.
4869 */
4870 if (throttled_hierarchy(cfs_rq))
4871 list_add_leaf_cfs_rq(cfs_rq);
671fd9da
PT
4872 }
4873
39f23ce0
VG
4874 /* At this point se is NULL and we are at root level*/
4875 add_nr_running(rq, task_delta);
671fd9da 4876
39f23ce0 4877unthrottle_throttle:
fe61468b
VG
4878 /*
4879 * The cfs_rq_throttled() breaks in the above iteration can result in
4880 * incomplete leaf list maintenance, resulting in triggering the
4881 * assertion below.
4882 */
4883 for_each_sched_entity(se) {
4884 cfs_rq = cfs_rq_of(se);
4885
39f23ce0
VG
4886 if (list_add_leaf_cfs_rq(cfs_rq))
4887 break;
fe61468b
VG
4888 }
4889
4890 assert_list_leaf_cfs_rq(rq);
4891
97fb7a0a 4892 /* Determine whether we need to wake up potentially idle CPU: */
671fd9da 4893 if (rq->curr == rq->idle && rq->cfs.nr_running)
8875125e 4894 resched_curr(rq);
671fd9da
PT
4895}
4896
26a8b127 4897static void distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
671fd9da
PT
4898{
4899 struct cfs_rq *cfs_rq;
26a8b127 4900 u64 runtime, remaining = 1;
671fd9da
PT
4901
4902 rcu_read_lock();
4903 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4904 throttled_list) {
4905 struct rq *rq = rq_of(cfs_rq);
8a8c69c3 4906 struct rq_flags rf;
671fd9da 4907
c0ad4aa4 4908 rq_lock_irqsave(rq, &rf);
671fd9da
PT
4909 if (!cfs_rq_throttled(cfs_rq))
4910 goto next;
4911
5e2d2cc2
L
4912 /* By the above check, this should never be true */
4913 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
4914
26a8b127 4915 raw_spin_lock(&cfs_b->lock);
671fd9da 4916 runtime = -cfs_rq->runtime_remaining + 1;
26a8b127
HC
4917 if (runtime > cfs_b->runtime)
4918 runtime = cfs_b->runtime;
4919 cfs_b->runtime -= runtime;
4920 remaining = cfs_b->runtime;
4921 raw_spin_unlock(&cfs_b->lock);
671fd9da
PT
4922
4923 cfs_rq->runtime_remaining += runtime;
671fd9da
PT
4924
4925 /* we check whether we're throttled above */
4926 if (cfs_rq->runtime_remaining > 0)
4927 unthrottle_cfs_rq(cfs_rq);
4928
4929next:
c0ad4aa4 4930 rq_unlock_irqrestore(rq, &rf);
671fd9da
PT
4931
4932 if (!remaining)
4933 break;
4934 }
4935 rcu_read_unlock();
671fd9da
PT
4936}
4937
58088ad0
PT
4938/*
4939 * Responsible for refilling a task_group's bandwidth and unthrottling its
4940 * cfs_rqs as appropriate. If there has been no activity within the last
4941 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4942 * used to track this state.
4943 */
c0ad4aa4 4944static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
58088ad0 4945{
51f2176d 4946 int throttled;
58088ad0 4947
58088ad0
PT
4948 /* no need to continue the timer with no bandwidth constraint */
4949 if (cfs_b->quota == RUNTIME_INF)
51f2176d 4950 goto out_deactivate;
58088ad0 4951
671fd9da 4952 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
e8da1b18 4953 cfs_b->nr_periods += overrun;
671fd9da 4954
51f2176d
BS
4955 /*
4956 * idle depends on !throttled (for the case of a large deficit), and if
4957 * we're going inactive then everything else can be deferred
4958 */
4959 if (cfs_b->idle && !throttled)
4960 goto out_deactivate;
a9cf55b2
PT
4961
4962 __refill_cfs_bandwidth_runtime(cfs_b);
4963
671fd9da
PT
4964 if (!throttled) {
4965 /* mark as potentially idle for the upcoming period */
4966 cfs_b->idle = 1;
51f2176d 4967 return 0;
671fd9da
PT
4968 }
4969
e8da1b18
NR
4970 /* account preceding periods in which throttling occurred */
4971 cfs_b->nr_throttled += overrun;
4972
671fd9da 4973 /*
26a8b127 4974 * This check is repeated as we release cfs_b->lock while we unthrottle.
671fd9da 4975 */
ab93a4bc 4976 while (throttled && cfs_b->runtime > 0) {
c0ad4aa4 4977 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
671fd9da 4978 /* we can't nest cfs_b->lock while distributing bandwidth */
26a8b127 4979 distribute_cfs_runtime(cfs_b);
c0ad4aa4 4980 raw_spin_lock_irqsave(&cfs_b->lock, flags);
671fd9da
PT
4981
4982 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4983 }
58088ad0 4984
671fd9da
PT
4985 /*
4986 * While we are ensured activity in the period following an
4987 * unthrottle, this also covers the case in which the new bandwidth is
4988 * insufficient to cover the existing bandwidth deficit. (Forcing the
4989 * timer to remain active while there are any throttled entities.)
4990 */
4991 cfs_b->idle = 0;
58088ad0 4992
51f2176d
BS
4993 return 0;
4994
4995out_deactivate:
51f2176d 4996 return 1;
58088ad0 4997}
d3d9dc33 4998
d8b4986d
PT
4999/* a cfs_rq won't donate quota below this amount */
5000static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5001/* minimum remaining period time to redistribute slack quota */
5002static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5003/* how long we wait to gather additional slack before distributing */
5004static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5005
db06e78c
BS
5006/*
5007 * Are we near the end of the current quota period?
5008 *
5009 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4961b6e1 5010 * hrtimer base being cleared by hrtimer_start. In the case of
db06e78c
BS
5011 * migrate_hrtimers, base is never cleared, so we are fine.
5012 */
d8b4986d
PT
5013static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5014{
5015 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5016 u64 remaining;
5017
5018 /* if the call-back is running a quota refresh is already occurring */
5019 if (hrtimer_callback_running(refresh_timer))
5020 return 1;
5021
5022 /* is a quota refresh about to occur? */
5023 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5024 if (remaining < min_expire)
5025 return 1;
5026
5027 return 0;
5028}
5029
5030static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5031{
5032 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5033
5034 /* if there's a quota refresh soon don't bother with slack */
5035 if (runtime_refresh_within(cfs_b, min_left))
5036 return;
5037
66567fcb 5038 /* don't push forwards an existing deferred unthrottle */
5039 if (cfs_b->slack_started)
5040 return;
5041 cfs_b->slack_started = true;
5042
4cfafd30
PZ
5043 hrtimer_start(&cfs_b->slack_timer,
5044 ns_to_ktime(cfs_bandwidth_slack_period),
5045 HRTIMER_MODE_REL);
d8b4986d
PT
5046}
5047
5048/* we know any runtime found here is valid as update_curr() precedes return */
5049static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5050{
5051 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5052 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5053
5054 if (slack_runtime <= 0)
5055 return;
5056
5057 raw_spin_lock(&cfs_b->lock);
de53fd7a 5058 if (cfs_b->quota != RUNTIME_INF) {
d8b4986d
PT
5059 cfs_b->runtime += slack_runtime;
5060
5061 /* we are under rq->lock, defer unthrottling using a timer */
5062 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5063 !list_empty(&cfs_b->throttled_cfs_rq))
5064 start_cfs_slack_bandwidth(cfs_b);
5065 }
5066 raw_spin_unlock(&cfs_b->lock);
5067
5068 /* even if it's not valid for return we don't want to try again */
5069 cfs_rq->runtime_remaining -= slack_runtime;
5070}
5071
5072static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5073{
56f570e5
PT
5074 if (!cfs_bandwidth_used())
5075 return;
5076
fccfdc6f 5077 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
d8b4986d
PT
5078 return;
5079
5080 __return_cfs_rq_runtime(cfs_rq);
5081}
5082
5083/*
5084 * This is done with a timer (instead of inline with bandwidth return) since
5085 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5086 */
5087static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5088{
5089 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
c0ad4aa4 5090 unsigned long flags;
d8b4986d
PT
5091
5092 /* confirm we're still not at a refresh boundary */
c0ad4aa4 5093 raw_spin_lock_irqsave(&cfs_b->lock, flags);
66567fcb 5094 cfs_b->slack_started = false;
baa9be4f 5095
db06e78c 5096 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
c0ad4aa4 5097 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
d8b4986d 5098 return;
db06e78c 5099 }
d8b4986d 5100
c06f04c7 5101 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
d8b4986d 5102 runtime = cfs_b->runtime;
c06f04c7 5103
c0ad4aa4 5104 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
d8b4986d
PT
5105
5106 if (!runtime)
5107 return;
5108
26a8b127 5109 distribute_cfs_runtime(cfs_b);
d8b4986d
PT
5110}
5111
d3d9dc33
PT
5112/*
5113 * When a group wakes up we want to make sure that its quota is not already
5114 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
c034f48e 5115 * runtime as update_curr() throttling can not trigger until it's on-rq.
d3d9dc33
PT
5116 */
5117static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
5118{
56f570e5
PT
5119 if (!cfs_bandwidth_used())
5120 return;
5121
d3d9dc33
PT
5122 /* an active group must be handled by the update_curr()->put() path */
5123 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
5124 return;
5125
5126 /* ensure the group is not already throttled */
5127 if (cfs_rq_throttled(cfs_rq))
5128 return;
5129
5130 /* update runtime allocation */
5131 account_cfs_rq_runtime(cfs_rq, 0);
5132 if (cfs_rq->runtime_remaining <= 0)
5133 throttle_cfs_rq(cfs_rq);
5134}
5135
55e16d30
PZ
5136static void sync_throttle(struct task_group *tg, int cpu)
5137{
5138 struct cfs_rq *pcfs_rq, *cfs_rq;
5139
5140 if (!cfs_bandwidth_used())
5141 return;
5142
5143 if (!tg->parent)
5144 return;
5145
5146 cfs_rq = tg->cfs_rq[cpu];
5147 pcfs_rq = tg->parent->cfs_rq[cpu];
5148
5149 cfs_rq->throttle_count = pcfs_rq->throttle_count;
b8922125 5150 cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
55e16d30
PZ
5151}
5152
d3d9dc33 5153/* conditionally throttle active cfs_rq's from put_prev_entity() */
678d5718 5154static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
d3d9dc33 5155{
56f570e5 5156 if (!cfs_bandwidth_used())
678d5718 5157 return false;
56f570e5 5158
d3d9dc33 5159 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
678d5718 5160 return false;
d3d9dc33
PT
5161
5162 /*
5163 * it's possible for a throttled entity to be forced into a running
5164 * state (e.g. set_curr_task), in this case we're finished.
5165 */
5166 if (cfs_rq_throttled(cfs_rq))
678d5718 5167 return true;
d3d9dc33 5168
e98fa02c 5169 return throttle_cfs_rq(cfs_rq);
d3d9dc33 5170}
029632fb 5171
029632fb
PZ
5172static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
5173{
5174 struct cfs_bandwidth *cfs_b =
5175 container_of(timer, struct cfs_bandwidth, slack_timer);
77a4d1a1 5176
029632fb
PZ
5177 do_sched_cfs_slack_timer(cfs_b);
5178
5179 return HRTIMER_NORESTART;
5180}
5181
2e8e1922
PA
5182extern const u64 max_cfs_quota_period;
5183
029632fb
PZ
5184static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
5185{
5186 struct cfs_bandwidth *cfs_b =
5187 container_of(timer, struct cfs_bandwidth, period_timer);
c0ad4aa4 5188 unsigned long flags;
029632fb
PZ
5189 int overrun;
5190 int idle = 0;
2e8e1922 5191 int count = 0;
029632fb 5192
c0ad4aa4 5193 raw_spin_lock_irqsave(&cfs_b->lock, flags);
029632fb 5194 for (;;) {
77a4d1a1 5195 overrun = hrtimer_forward_now(timer, cfs_b->period);
029632fb
PZ
5196 if (!overrun)
5197 break;
5198
5a6d6a6c
HC
5199 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
5200
2e8e1922
PA
5201 if (++count > 3) {
5202 u64 new, old = ktime_to_ns(cfs_b->period);
5203
4929a4e6
XZ
5204 /*
5205 * Grow period by a factor of 2 to avoid losing precision.
5206 * Precision loss in the quota/period ratio can cause __cfs_schedulable
5207 * to fail.
5208 */
5209 new = old * 2;
5210 if (new < max_cfs_quota_period) {
5211 cfs_b->period = ns_to_ktime(new);
5212 cfs_b->quota *= 2;
5213
5214 pr_warn_ratelimited(
5215 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5216 smp_processor_id(),
5217 div_u64(new, NSEC_PER_USEC),
5218 div_u64(cfs_b->quota, NSEC_PER_USEC));
5219 } else {
5220 pr_warn_ratelimited(
5221 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5222 smp_processor_id(),
5223 div_u64(old, NSEC_PER_USEC),
5224 div_u64(cfs_b->quota, NSEC_PER_USEC));
5225 }
2e8e1922
PA
5226
5227 /* reset count so we don't come right back in here */
5228 count = 0;
5229 }
029632fb 5230 }
4cfafd30
PZ
5231 if (idle)
5232 cfs_b->period_active = 0;
c0ad4aa4 5233 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
029632fb
PZ
5234
5235 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
5236}
5237
5238void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5239{
5240 raw_spin_lock_init(&cfs_b->lock);
5241 cfs_b->runtime = 0;
5242 cfs_b->quota = RUNTIME_INF;
5243 cfs_b->period = ns_to_ktime(default_cfs_period());
5244
5245 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4cfafd30 5246 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
029632fb
PZ
5247 cfs_b->period_timer.function = sched_cfs_period_timer;
5248 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5249 cfs_b->slack_timer.function = sched_cfs_slack_timer;
66567fcb 5250 cfs_b->slack_started = false;
029632fb
PZ
5251}
5252
5253static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5254{
5255 cfs_rq->runtime_enabled = 0;
5256 INIT_LIST_HEAD(&cfs_rq->throttled_list);
5257}
5258
77a4d1a1 5259void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
029632fb 5260{
4cfafd30 5261 lockdep_assert_held(&cfs_b->lock);
029632fb 5262
f1d1be8a
XP
5263 if (cfs_b->period_active)
5264 return;
5265
5266 cfs_b->period_active = 1;
763a9ec0 5267 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
f1d1be8a 5268 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
029632fb
PZ
5269}
5270
5271static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5272{
7f1a169b
TH
5273 /* init_cfs_bandwidth() was not called */
5274 if (!cfs_b->throttled_cfs_rq.next)
5275 return;
5276
029632fb
PZ
5277 hrtimer_cancel(&cfs_b->period_timer);
5278 hrtimer_cancel(&cfs_b->slack_timer);
5279}
5280
502ce005 5281/*
97fb7a0a 5282 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
502ce005
PZ
5283 *
5284 * The race is harmless, since modifying bandwidth settings of unhooked group
5285 * bits doesn't do much.
5286 */
5287
3b03706f 5288/* cpu online callback */
0e59bdae
KT
5289static void __maybe_unused update_runtime_enabled(struct rq *rq)
5290{
502ce005 5291 struct task_group *tg;
0e59bdae 5292
5cb9eaa3 5293 lockdep_assert_rq_held(rq);
502ce005
PZ
5294
5295 rcu_read_lock();
5296 list_for_each_entry_rcu(tg, &task_groups, list) {
5297 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
5298 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
0e59bdae
KT
5299
5300 raw_spin_lock(&cfs_b->lock);
5301 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
5302 raw_spin_unlock(&cfs_b->lock);
5303 }
502ce005 5304 rcu_read_unlock();
0e59bdae
KT
5305}
5306
502ce005 5307/* cpu offline callback */
38dc3348 5308static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
029632fb 5309{
502ce005
PZ
5310 struct task_group *tg;
5311
5cb9eaa3 5312 lockdep_assert_rq_held(rq);
502ce005
PZ
5313
5314 rcu_read_lock();
5315 list_for_each_entry_rcu(tg, &task_groups, list) {
5316 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
029632fb 5317
029632fb
PZ
5318 if (!cfs_rq->runtime_enabled)
5319 continue;
5320
5321 /*
5322 * clock_task is not advancing so we just need to make sure
5323 * there's some valid quota amount
5324 */
51f2176d 5325 cfs_rq->runtime_remaining = 1;
0e59bdae 5326 /*
97fb7a0a 5327 * Offline rq is schedulable till CPU is completely disabled
0e59bdae
KT
5328 * in take_cpu_down(), so we prevent new cfs throttling here.
5329 */
5330 cfs_rq->runtime_enabled = 0;
5331
029632fb
PZ
5332 if (cfs_rq_throttled(cfs_rq))
5333 unthrottle_cfs_rq(cfs_rq);
5334 }
502ce005 5335 rcu_read_unlock();
029632fb
PZ
5336}
5337
5338#else /* CONFIG_CFS_BANDWIDTH */
f6783319
VG
5339
5340static inline bool cfs_bandwidth_used(void)
5341{
5342 return false;
5343}
5344
9dbdb155 5345static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
678d5718 5346static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
d3d9dc33 5347static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
55e16d30 5348static inline void sync_throttle(struct task_group *tg, int cpu) {}
6c16a6dc 5349static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
85dac906
PT
5350
5351static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5352{
5353 return 0;
5354}
64660c86
PT
5355
5356static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5357{
5358 return 0;
5359}
5360
5361static inline int throttled_lb_pair(struct task_group *tg,
5362 int src_cpu, int dest_cpu)
5363{
5364 return 0;
5365}
029632fb
PZ
5366
5367void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5368
5369#ifdef CONFIG_FAIR_GROUP_SCHED
5370static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
ab84d31e
PT
5371#endif
5372
029632fb
PZ
5373static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5374{
5375 return NULL;
5376}
5377static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
0e59bdae 5378static inline void update_runtime_enabled(struct rq *rq) {}
a4c96ae3 5379static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
029632fb
PZ
5380
5381#endif /* CONFIG_CFS_BANDWIDTH */
5382
bf0f6f24
IM
5383/**************************************************
5384 * CFS operations on tasks:
5385 */
5386
8f4d37ec
PZ
5387#ifdef CONFIG_SCHED_HRTICK
5388static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
5389{
8f4d37ec
PZ
5390 struct sched_entity *se = &p->se;
5391 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5392
9148a3a1 5393 SCHED_WARN_ON(task_rq(p) != rq);
8f4d37ec 5394
8bf46a39 5395 if (rq->cfs.h_nr_running > 1) {
8f4d37ec
PZ
5396 u64 slice = sched_slice(cfs_rq, se);
5397 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
5398 s64 delta = slice - ran;
5399
5400 if (delta < 0) {
65bcf072 5401 if (task_current(rq, p))
8875125e 5402 resched_curr(rq);
8f4d37ec
PZ
5403 return;
5404 }
31656519 5405 hrtick_start(rq, delta);
8f4d37ec
PZ
5406 }
5407}
a4c2f00f
PZ
5408
5409/*
5410 * called from enqueue/dequeue and updates the hrtick when the
5411 * current task is from our class and nr_running is low enough
5412 * to matter.
5413 */
5414static void hrtick_update(struct rq *rq)
5415{
5416 struct task_struct *curr = rq->curr;
5417
e0ee463c 5418 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
a4c2f00f
PZ
5419 return;
5420
5421 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
5422 hrtick_start_fair(rq, curr);
5423}
55e12e5e 5424#else /* !CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
5425static inline void
5426hrtick_start_fair(struct rq *rq, struct task_struct *p)
5427{
5428}
a4c2f00f
PZ
5429
5430static inline void hrtick_update(struct rq *rq)
5431{
5432}
8f4d37ec
PZ
5433#endif
5434
2802bf3c
MR
5435#ifdef CONFIG_SMP
5436static inline unsigned long cpu_util(int cpu);
2802bf3c
MR
5437
5438static inline bool cpu_overutilized(int cpu)
5439{
60e17f5c 5440 return !fits_capacity(cpu_util(cpu), capacity_of(cpu));
2802bf3c
MR
5441}
5442
5443static inline void update_overutilized_status(struct rq *rq)
5444{
f9f240f9 5445 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
2802bf3c 5446 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
f9f240f9
QY
5447 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
5448 }
2802bf3c
MR
5449}
5450#else
5451static inline void update_overutilized_status(struct rq *rq) { }
5452#endif
5453
323af6de
VK
5454/* Runqueue only has SCHED_IDLE tasks enqueued */
5455static int sched_idle_rq(struct rq *rq)
5456{
5457 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
5458 rq->nr_running);
5459}
5460
afa70d94 5461#ifdef CONFIG_SMP
323af6de
VK
5462static int sched_idle_cpu(int cpu)
5463{
5464 return sched_idle_rq(cpu_rq(cpu));
5465}
afa70d94 5466#endif
323af6de 5467
bf0f6f24
IM
5468/*
5469 * The enqueue_task method is called before nr_running is
5470 * increased. Here we update the fair scheduling stats and
5471 * then put the task into the rbtree:
5472 */
ea87bb78 5473static void
371fd7e7 5474enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
5475{
5476 struct cfs_rq *cfs_rq;
62fb1851 5477 struct sched_entity *se = &p->se;
43e9f7f2 5478 int idle_h_nr_running = task_has_idle_policy(p);
8e1ac429 5479 int task_new = !(flags & ENQUEUE_WAKEUP);
bf0f6f24 5480
2539fc82
PB
5481 /*
5482 * The code below (indirectly) updates schedutil which looks at
5483 * the cfs_rq utilization to select a frequency.
5484 * Let's add the task's estimated utilization to the cfs_rq's
5485 * estimated utilization, before we update schedutil.
5486 */
5487 util_est_enqueue(&rq->cfs, p);
5488
8c34ab19
RW
5489 /*
5490 * If in_iowait is set, the code below may not trigger any cpufreq
5491 * utilization updates, so do it here explicitly with the IOWAIT flag
5492 * passed.
5493 */
5494 if (p->in_iowait)
674e7541 5495 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
8c34ab19 5496
bf0f6f24 5497 for_each_sched_entity(se) {
62fb1851 5498 if (se->on_rq)
bf0f6f24
IM
5499 break;
5500 cfs_rq = cfs_rq_of(se);
88ec22d3 5501 enqueue_entity(cfs_rq, se, flags);
85dac906 5502
953bfcd1 5503 cfs_rq->h_nr_running++;
43e9f7f2 5504 cfs_rq->idle_h_nr_running += idle_h_nr_running;
85dac906 5505
6d4d2246
VG
5506 /* end evaluation on encountering a throttled cfs_rq */
5507 if (cfs_rq_throttled(cfs_rq))
5508 goto enqueue_throttle;
5509
88ec22d3 5510 flags = ENQUEUE_WAKEUP;
bf0f6f24 5511 }
8f4d37ec 5512
2069dd75 5513 for_each_sched_entity(se) {
0f317143 5514 cfs_rq = cfs_rq_of(se);
2069dd75 5515
88c0616e 5516 update_load_avg(cfs_rq, se, UPDATE_TG);
9f683953 5517 se_update_runnable(se);
1ea6c46a 5518 update_cfs_group(se);
6d4d2246
VG
5519
5520 cfs_rq->h_nr_running++;
5521 cfs_rq->idle_h_nr_running += idle_h_nr_running;
5ab297ba
VG
5522
5523 /* end evaluation on encountering a throttled cfs_rq */
5524 if (cfs_rq_throttled(cfs_rq))
5525 goto enqueue_throttle;
b34cb07d
PA
5526
5527 /*
5528 * One parent has been throttled and cfs_rq removed from the
5529 * list. Add it back to not break the leaf list.
5530 */
5531 if (throttled_hierarchy(cfs_rq))
5532 list_add_leaf_cfs_rq(cfs_rq);
2069dd75
PZ
5533 }
5534
7d148be6
VG
5535 /* At this point se is NULL and we are at root level*/
5536 add_nr_running(rq, 1);
2802bf3c 5537
7d148be6
VG
5538 /*
5539 * Since new tasks are assigned an initial util_avg equal to
5540 * half of the spare capacity of their CPU, tiny tasks have the
5541 * ability to cross the overutilized threshold, which will
5542 * result in the load balancer ruining all the task placement
5543 * done by EAS. As a way to mitigate that effect, do not account
5544 * for the first enqueue operation of new tasks during the
5545 * overutilized flag detection.
5546 *
5547 * A better way of solving this problem would be to wait for
5548 * the PELT signals of tasks to converge before taking them
5549 * into account, but that is not straightforward to implement,
5550 * and the following generally works well enough in practice.
5551 */
8e1ac429 5552 if (!task_new)
7d148be6 5553 update_overutilized_status(rq);
cd126afe 5554
7d148be6 5555enqueue_throttle:
f6783319
VG
5556 if (cfs_bandwidth_used()) {
5557 /*
5558 * When bandwidth control is enabled; the cfs_rq_throttled()
5559 * breaks in the above iteration can result in incomplete
5560 * leaf list maintenance, resulting in triggering the assertion
5561 * below.
5562 */
5563 for_each_sched_entity(se) {
5564 cfs_rq = cfs_rq_of(se);
5565
5566 if (list_add_leaf_cfs_rq(cfs_rq))
5567 break;
5568 }
5569 }
5570
5d299eab
PZ
5571 assert_list_leaf_cfs_rq(rq);
5572
a4c2f00f 5573 hrtick_update(rq);
bf0f6f24
IM
5574}
5575
2f36825b
VP
5576static void set_next_buddy(struct sched_entity *se);
5577
bf0f6f24
IM
5578/*
5579 * The dequeue_task method is called before nr_running is
5580 * decreased. We remove the task from the rbtree and
5581 * update the fair scheduling stats:
5582 */
371fd7e7 5583static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
5584{
5585 struct cfs_rq *cfs_rq;
62fb1851 5586 struct sched_entity *se = &p->se;
2f36825b 5587 int task_sleep = flags & DEQUEUE_SLEEP;
43e9f7f2 5588 int idle_h_nr_running = task_has_idle_policy(p);
323af6de 5589 bool was_sched_idle = sched_idle_rq(rq);
bf0f6f24 5590
8c1f560c
XY
5591 util_est_dequeue(&rq->cfs, p);
5592
bf0f6f24
IM
5593 for_each_sched_entity(se) {
5594 cfs_rq = cfs_rq_of(se);
371fd7e7 5595 dequeue_entity(cfs_rq, se, flags);
85dac906 5596
953bfcd1 5597 cfs_rq->h_nr_running--;
43e9f7f2 5598 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
2069dd75 5599
6d4d2246
VG
5600 /* end evaluation on encountering a throttled cfs_rq */
5601 if (cfs_rq_throttled(cfs_rq))
5602 goto dequeue_throttle;
5603
bf0f6f24 5604 /* Don't dequeue parent if it has other entities besides us */
2f36825b 5605 if (cfs_rq->load.weight) {
754bd598
KK
5606 /* Avoid re-evaluating load for this entity: */
5607 se = parent_entity(se);
2f36825b
VP
5608 /*
5609 * Bias pick_next to pick a task from this cfs_rq, as
5610 * p is sleeping when it is within its sched_slice.
5611 */
754bd598
KK
5612 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
5613 set_next_buddy(se);
bf0f6f24 5614 break;
2f36825b 5615 }
371fd7e7 5616 flags |= DEQUEUE_SLEEP;
bf0f6f24 5617 }
8f4d37ec 5618
2069dd75 5619 for_each_sched_entity(se) {
0f317143 5620 cfs_rq = cfs_rq_of(se);
2069dd75 5621
88c0616e 5622 update_load_avg(cfs_rq, se, UPDATE_TG);
9f683953 5623 se_update_runnable(se);
1ea6c46a 5624 update_cfs_group(se);
6d4d2246
VG
5625
5626 cfs_rq->h_nr_running--;
5627 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5ab297ba
VG
5628
5629 /* end evaluation on encountering a throttled cfs_rq */
5630 if (cfs_rq_throttled(cfs_rq))
5631 goto dequeue_throttle;
5632
2069dd75
PZ
5633 }
5634
423d02e1
PW
5635 /* At this point se is NULL and we are at root level*/
5636 sub_nr_running(rq, 1);
cd126afe 5637
323af6de
VK
5638 /* balance early to pull high priority tasks */
5639 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
5640 rq->next_balance = jiffies;
5641
423d02e1 5642dequeue_throttle:
8c1f560c 5643 util_est_update(&rq->cfs, p, task_sleep);
a4c2f00f 5644 hrtick_update(rq);
bf0f6f24
IM
5645}
5646
e7693a36 5647#ifdef CONFIG_SMP
10e2f1ac
PZ
5648
5649/* Working cpumask for: load_balance, load_balance_newidle. */
5650DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5651DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
5652
9fd81dd5 5653#ifdef CONFIG_NO_HZ_COMMON
e022e0d3
PZ
5654
5655static struct {
5656 cpumask_var_t idle_cpus_mask;
5657 atomic_t nr_cpus;
f643ea22 5658 int has_blocked; /* Idle CPUS has blocked load */
e022e0d3 5659 unsigned long next_balance; /* in jiffy units */
f643ea22 5660 unsigned long next_blocked; /* Next update of blocked load in jiffies */
e022e0d3
PZ
5661} nohz ____cacheline_aligned;
5662
9fd81dd5 5663#endif /* CONFIG_NO_HZ_COMMON */
3289bdb4 5664
b0fb1eb4
VG
5665static unsigned long cpu_load(struct rq *rq)
5666{
5667 return cfs_rq_load_avg(&rq->cfs);
5668}
5669
3318544b
VG
5670/*
5671 * cpu_load_without - compute CPU load without any contributions from *p
5672 * @cpu: the CPU which load is requested
5673 * @p: the task which load should be discounted
5674 *
5675 * The load of a CPU is defined by the load of tasks currently enqueued on that
5676 * CPU as well as tasks which are currently sleeping after an execution on that
5677 * CPU.
5678 *
5679 * This method returns the load of the specified CPU by discounting the load of
5680 * the specified task, whenever the task is currently contributing to the CPU
5681 * load.
5682 */
5683static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
5684{
5685 struct cfs_rq *cfs_rq;
5686 unsigned int load;
5687
5688 /* Task has no contribution or is new */
5689 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5690 return cpu_load(rq);
5691
5692 cfs_rq = &rq->cfs;
5693 load = READ_ONCE(cfs_rq->avg.load_avg);
5694
5695 /* Discount task's util from CPU's util */
5696 lsub_positive(&load, task_h_load(p));
5697
5698 return load;
5699}
5700
9f683953
VG
5701static unsigned long cpu_runnable(struct rq *rq)
5702{
5703 return cfs_rq_runnable_avg(&rq->cfs);
5704}
5705
070f5e86
VG
5706static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
5707{
5708 struct cfs_rq *cfs_rq;
5709 unsigned int runnable;
5710
5711 /* Task has no contribution or is new */
5712 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5713 return cpu_runnable(rq);
5714
5715 cfs_rq = &rq->cfs;
5716 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
5717
5718 /* Discount task's runnable from CPU's runnable */
5719 lsub_positive(&runnable, p->se.avg.runnable_avg);
5720
5721 return runnable;
5722}
5723
ced549fa 5724static unsigned long capacity_of(int cpu)
029632fb 5725{
ced549fa 5726 return cpu_rq(cpu)->cpu_capacity;
029632fb
PZ
5727}
5728
c58d25f3
PZ
5729static void record_wakee(struct task_struct *p)
5730{
5731 /*
5732 * Only decay a single time; tasks that have less then 1 wakeup per
5733 * jiffy will not have built up many flips.
5734 */
5735 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5736 current->wakee_flips >>= 1;
5737 current->wakee_flip_decay_ts = jiffies;
5738 }
5739
5740 if (current->last_wakee != p) {
5741 current->last_wakee = p;
5742 current->wakee_flips++;
5743 }
5744}
5745
63b0e9ed
MG
5746/*
5747 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
c58d25f3 5748 *
63b0e9ed 5749 * A waker of many should wake a different task than the one last awakened
c58d25f3
PZ
5750 * at a frequency roughly N times higher than one of its wakees.
5751 *
5752 * In order to determine whether we should let the load spread vs consolidating
5753 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5754 * partner, and a factor of lls_size higher frequency in the other.
5755 *
5756 * With both conditions met, we can be relatively sure that the relationship is
5757 * non-monogamous, with partner count exceeding socket size.
5758 *
5759 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5760 * whatever is irrelevant, spread criteria is apparent partner count exceeds
5761 * socket size.
63b0e9ed 5762 */
62470419
MW
5763static int wake_wide(struct task_struct *p)
5764{
63b0e9ed
MG
5765 unsigned int master = current->wakee_flips;
5766 unsigned int slave = p->wakee_flips;
17c891ab 5767 int factor = __this_cpu_read(sd_llc_size);
62470419 5768
63b0e9ed
MG
5769 if (master < slave)
5770 swap(master, slave);
5771 if (slave < factor || master < slave * factor)
5772 return 0;
5773 return 1;
62470419
MW
5774}
5775
90001d67 5776/*
d153b153
PZ
5777 * The purpose of wake_affine() is to quickly determine on which CPU we can run
5778 * soonest. For the purpose of speed we only consider the waking and previous
5779 * CPU.
90001d67 5780 *
7332dec0
MG
5781 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
5782 * cache-affine and is (or will be) idle.
f2cdd9cc
PZ
5783 *
5784 * wake_affine_weight() - considers the weight to reflect the average
5785 * scheduling latency of the CPUs. This seems to work
5786 * for the overloaded case.
90001d67 5787 */
3b76c4a3 5788static int
89a55f56 5789wake_affine_idle(int this_cpu, int prev_cpu, int sync)
90001d67 5790{
7332dec0
MG
5791 /*
5792 * If this_cpu is idle, it implies the wakeup is from interrupt
5793 * context. Only allow the move if cache is shared. Otherwise an
5794 * interrupt intensive workload could force all tasks onto one
5795 * node depending on the IO topology or IRQ affinity settings.
806486c3
MG
5796 *
5797 * If the prev_cpu is idle and cache affine then avoid a migration.
5798 * There is no guarantee that the cache hot data from an interrupt
5799 * is more important than cache hot data on the prev_cpu and from
5800 * a cpufreq perspective, it's better to have higher utilisation
5801 * on one CPU.
7332dec0 5802 */
943d355d
RJ
5803 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
5804 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
90001d67 5805
d153b153 5806 if (sync && cpu_rq(this_cpu)->nr_running == 1)
3b76c4a3 5807 return this_cpu;
90001d67 5808
d8fcb81f
JL
5809 if (available_idle_cpu(prev_cpu))
5810 return prev_cpu;
5811
3b76c4a3 5812 return nr_cpumask_bits;
90001d67
PZ
5813}
5814
3b76c4a3 5815static int
f2cdd9cc
PZ
5816wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
5817 int this_cpu, int prev_cpu, int sync)
90001d67 5818{
90001d67
PZ
5819 s64 this_eff_load, prev_eff_load;
5820 unsigned long task_load;
5821
11f10e54 5822 this_eff_load = cpu_load(cpu_rq(this_cpu));
90001d67 5823
90001d67
PZ
5824 if (sync) {
5825 unsigned long current_load = task_h_load(current);
5826
f2cdd9cc 5827 if (current_load > this_eff_load)
3b76c4a3 5828 return this_cpu;
90001d67 5829
f2cdd9cc 5830 this_eff_load -= current_load;
90001d67
PZ
5831 }
5832
90001d67
PZ
5833 task_load = task_h_load(p);
5834
f2cdd9cc
PZ
5835 this_eff_load += task_load;
5836 if (sched_feat(WA_BIAS))
5837 this_eff_load *= 100;
5838 this_eff_load *= capacity_of(prev_cpu);
90001d67 5839
11f10e54 5840 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
f2cdd9cc
PZ
5841 prev_eff_load -= task_load;
5842 if (sched_feat(WA_BIAS))
5843 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
5844 prev_eff_load *= capacity_of(this_cpu);
90001d67 5845
082f764a
MG
5846 /*
5847 * If sync, adjust the weight of prev_eff_load such that if
5848 * prev_eff == this_eff that select_idle_sibling() will consider
5849 * stacking the wakee on top of the waker if no other CPU is
5850 * idle.
5851 */
5852 if (sync)
5853 prev_eff_load += 1;
5854
5855 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
90001d67
PZ
5856}
5857
772bd008 5858static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7ebb66a1 5859 int this_cpu, int prev_cpu, int sync)
098fb9db 5860{
3b76c4a3 5861 int target = nr_cpumask_bits;
098fb9db 5862
89a55f56 5863 if (sched_feat(WA_IDLE))
3b76c4a3 5864 target = wake_affine_idle(this_cpu, prev_cpu, sync);
90001d67 5865
3b76c4a3
MG
5866 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
5867 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
098fb9db 5868
ae92882e 5869 schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
3b76c4a3
MG
5870 if (target == nr_cpumask_bits)
5871 return prev_cpu;
098fb9db 5872
3b76c4a3
MG
5873 schedstat_inc(sd->ttwu_move_affine);
5874 schedstat_inc(p->se.statistics.nr_wakeups_affine);
5875 return target;
098fb9db
IM
5876}
5877
aaee1203 5878static struct sched_group *
45da2773 5879find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
aaee1203
PZ
5880
5881/*
97fb7a0a 5882 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
aaee1203
PZ
5883 */
5884static int
18bd1b4b 5885find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
aaee1203
PZ
5886{
5887 unsigned long load, min_load = ULONG_MAX;
83a0a96a
NP
5888 unsigned int min_exit_latency = UINT_MAX;
5889 u64 latest_idle_timestamp = 0;
5890 int least_loaded_cpu = this_cpu;
17346452 5891 int shallowest_idle_cpu = -1;
aaee1203
PZ
5892 int i;
5893
eaecf41f
MR
5894 /* Check if we have any choice: */
5895 if (group->group_weight == 1)
ae4df9d6 5896 return cpumask_first(sched_group_span(group));
eaecf41f 5897
aaee1203 5898 /* Traverse only the allowed CPUs */
3bd37062 5899 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
97886d9d
AL
5900 struct rq *rq = cpu_rq(i);
5901
5902 if (!sched_core_cookie_match(rq, p))
5903 continue;
5904
17346452
VK
5905 if (sched_idle_cpu(i))
5906 return i;
5907
943d355d 5908 if (available_idle_cpu(i)) {
83a0a96a
NP
5909 struct cpuidle_state *idle = idle_get_state(rq);
5910 if (idle && idle->exit_latency < min_exit_latency) {
5911 /*
5912 * We give priority to a CPU whose idle state
5913 * has the smallest exit latency irrespective
5914 * of any idle timestamp.
5915 */
5916 min_exit_latency = idle->exit_latency;
5917 latest_idle_timestamp = rq->idle_stamp;
5918 shallowest_idle_cpu = i;
5919 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
5920 rq->idle_stamp > latest_idle_timestamp) {
5921 /*
5922 * If equal or no active idle state, then
5923 * the most recently idled CPU might have
5924 * a warmer cache.
5925 */
5926 latest_idle_timestamp = rq->idle_stamp;
5927 shallowest_idle_cpu = i;
5928 }
17346452 5929 } else if (shallowest_idle_cpu == -1) {
11f10e54 5930 load = cpu_load(cpu_rq(i));
18cec7e0 5931 if (load < min_load) {
83a0a96a
NP
5932 min_load = load;
5933 least_loaded_cpu = i;
5934 }
e7693a36
GH
5935 }
5936 }
5937
17346452 5938 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
aaee1203 5939}
e7693a36 5940
18bd1b4b
BJ
5941static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
5942 int cpu, int prev_cpu, int sd_flag)
5943{
93f50f90 5944 int new_cpu = cpu;
18bd1b4b 5945
3bd37062 5946 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6fee85cc
BJ
5947 return prev_cpu;
5948
c976a862 5949 /*
57abff06 5950 * We need task's util for cpu_util_without, sync it up to
c469933e 5951 * prev_cpu's last_update_time.
c976a862
VK
5952 */
5953 if (!(sd_flag & SD_BALANCE_FORK))
5954 sync_entity_load_avg(&p->se);
5955
18bd1b4b
BJ
5956 while (sd) {
5957 struct sched_group *group;
5958 struct sched_domain *tmp;
5959 int weight;
5960
5961 if (!(sd->flags & sd_flag)) {
5962 sd = sd->child;
5963 continue;
5964 }
5965
45da2773 5966 group = find_idlest_group(sd, p, cpu);
18bd1b4b
BJ
5967 if (!group) {
5968 sd = sd->child;
5969 continue;
5970 }
5971
5972 new_cpu = find_idlest_group_cpu(group, p, cpu);
e90381ea 5973 if (new_cpu == cpu) {
97fb7a0a 5974 /* Now try balancing at a lower domain level of 'cpu': */
18bd1b4b
BJ
5975 sd = sd->child;
5976 continue;
5977 }
5978
97fb7a0a 5979 /* Now try balancing at a lower domain level of 'new_cpu': */
18bd1b4b
BJ
5980 cpu = new_cpu;
5981 weight = sd->span_weight;
5982 sd = NULL;
5983 for_each_domain(cpu, tmp) {
5984 if (weight <= tmp->span_weight)
5985 break;
5986 if (tmp->flags & sd_flag)
5987 sd = tmp;
5988 }
18bd1b4b
BJ
5989 }
5990
5991 return new_cpu;
5992}
5993
97886d9d 5994static inline int __select_idle_cpu(int cpu, struct task_struct *p)
9fe1f127 5995{
97886d9d
AL
5996 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
5997 sched_cpu_cookie_match(cpu_rq(cpu), p))
9fe1f127
MG
5998 return cpu;
5999
6000 return -1;
6001}
6002
10e2f1ac 6003#ifdef CONFIG_SCHED_SMT
ba2591a5 6004DEFINE_STATIC_KEY_FALSE(sched_smt_present);
b284909a 6005EXPORT_SYMBOL_GPL(sched_smt_present);
10e2f1ac
PZ
6006
6007static inline void set_idle_cores(int cpu, int val)
6008{
6009 struct sched_domain_shared *sds;
6010
6011 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6012 if (sds)
6013 WRITE_ONCE(sds->has_idle_cores, val);
6014}
6015
6016static inline bool test_idle_cores(int cpu, bool def)
6017{
6018 struct sched_domain_shared *sds;
6019
c722f35b
RR
6020 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6021 if (sds)
6022 return READ_ONCE(sds->has_idle_cores);
10e2f1ac
PZ
6023
6024 return def;
6025}
6026
6027/*
6028 * Scans the local SMT mask to see if the entire core is idle, and records this
6029 * information in sd_llc_shared->has_idle_cores.
6030 *
6031 * Since SMT siblings share all cache levels, inspecting this limited remote
6032 * state should be fairly cheap.
6033 */
1b568f0a 6034void __update_idle_core(struct rq *rq)
10e2f1ac
PZ
6035{
6036 int core = cpu_of(rq);
6037 int cpu;
6038
6039 rcu_read_lock();
6040 if (test_idle_cores(core, true))
6041 goto unlock;
6042
6043 for_each_cpu(cpu, cpu_smt_mask(core)) {
6044 if (cpu == core)
6045 continue;
6046
943d355d 6047 if (!available_idle_cpu(cpu))
10e2f1ac
PZ
6048 goto unlock;
6049 }
6050
6051 set_idle_cores(core, 1);
6052unlock:
6053 rcu_read_unlock();
6054}
6055
6056/*
6057 * Scan the entire LLC domain for idle cores; this dynamically switches off if
6058 * there are no idle cores left in the system; tracked through
6059 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6060 */
9fe1f127 6061static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
10e2f1ac 6062{
9fe1f127
MG
6063 bool idle = true;
6064 int cpu;
10e2f1ac 6065
1b568f0a 6066 if (!static_branch_likely(&sched_smt_present))
97886d9d 6067 return __select_idle_cpu(core, p);
10e2f1ac 6068
9fe1f127
MG
6069 for_each_cpu(cpu, cpu_smt_mask(core)) {
6070 if (!available_idle_cpu(cpu)) {
6071 idle = false;
6072 if (*idle_cpu == -1) {
6073 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
6074 *idle_cpu = cpu;
6075 break;
6076 }
6077 continue;
bec2860a 6078 }
9fe1f127 6079 break;
10e2f1ac 6080 }
9fe1f127
MG
6081 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
6082 *idle_cpu = cpu;
10e2f1ac
PZ
6083 }
6084
9fe1f127
MG
6085 if (idle)
6086 return core;
10e2f1ac 6087
9fe1f127 6088 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
10e2f1ac
PZ
6089 return -1;
6090}
6091
c722f35b
RR
6092/*
6093 * Scan the local SMT mask for idle CPUs.
6094 */
6095static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6096{
6097 int cpu;
6098
6099 for_each_cpu(cpu, cpu_smt_mask(target)) {
6100 if (!cpumask_test_cpu(cpu, p->cpus_ptr) ||
6101 !cpumask_test_cpu(cpu, sched_domain_span(sd)))
6102 continue;
6103 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6104 return cpu;
6105 }
6106
6107 return -1;
6108}
6109
10e2f1ac
PZ
6110#else /* CONFIG_SCHED_SMT */
6111
9fe1f127 6112static inline void set_idle_cores(int cpu, int val)
10e2f1ac 6113{
9fe1f127
MG
6114}
6115
6116static inline bool test_idle_cores(int cpu, bool def)
6117{
6118 return def;
6119}
6120
6121static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
6122{
97886d9d 6123 return __select_idle_cpu(core, p);
10e2f1ac
PZ
6124}
6125
c722f35b
RR
6126static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6127{
6128 return -1;
6129}
6130
10e2f1ac
PZ
6131#endif /* CONFIG_SCHED_SMT */
6132
6133/*
6134 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6135 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6136 * average idle time for this rq (as found in rq->avg_idle).
a50bde51 6137 */
c722f35b 6138static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
10e2f1ac 6139{
60588bfa 6140 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
9fe1f127 6141 int i, cpu, idle_cpu = -1, nr = INT_MAX;
9fe1f127 6142 int this = smp_processor_id();
9cfb38a7 6143 struct sched_domain *this_sd;
d76343c6 6144 u64 time;
10e2f1ac 6145
9cfb38a7
WL
6146 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
6147 if (!this_sd)
6148 return -1;
6149
bae4ec13
MG
6150 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6151
c722f35b 6152 if (sched_feat(SIS_PROP) && !has_idle_core) {
e6e0dc2d 6153 u64 avg_cost, avg_idle, span_avg;
1ad3aaf3 6154
e6e0dc2d
MG
6155 /*
6156 * Due to large variance we need a large fuzz factor;
6157 * hackbench in particularly is sensitive here.
6158 */
6159 avg_idle = this_rq()->avg_idle / 512;
6160 avg_cost = this_sd->avg_scan_cost + 1;
10e2f1ac 6161
e6e0dc2d 6162 span_avg = sd->span_weight * avg_idle;
1ad3aaf3
PZ
6163 if (span_avg > 4*avg_cost)
6164 nr = div_u64(span_avg, avg_cost);
6165 else
6166 nr = 4;
10e2f1ac 6167
bae4ec13
MG
6168 time = cpu_clock(this);
6169 }
60588bfa
CJ
6170
6171 for_each_cpu_wrap(cpu, cpus, target) {
c722f35b 6172 if (has_idle_core) {
9fe1f127
MG
6173 i = select_idle_core(p, cpu, cpus, &idle_cpu);
6174 if ((unsigned int)i < nr_cpumask_bits)
6175 return i;
6176
6177 } else {
6178 if (!--nr)
6179 return -1;
97886d9d 6180 idle_cpu = __select_idle_cpu(cpu, p);
9fe1f127
MG
6181 if ((unsigned int)idle_cpu < nr_cpumask_bits)
6182 break;
6183 }
10e2f1ac
PZ
6184 }
6185
c722f35b 6186 if (has_idle_core)
02dbb724 6187 set_idle_cores(target, false);
9fe1f127 6188
c722f35b 6189 if (sched_feat(SIS_PROP) && !has_idle_core) {
bae4ec13
MG
6190 time = cpu_clock(this) - time;
6191 update_avg(&this_sd->avg_scan_cost, time);
6192 }
10e2f1ac 6193
9fe1f127 6194 return idle_cpu;
10e2f1ac
PZ
6195}
6196
b7a33161
MR
6197/*
6198 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
6199 * the task fits. If no CPU is big enough, but there are idle ones, try to
6200 * maximize capacity.
6201 */
6202static int
6203select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
6204{
b4c9c9f1 6205 unsigned long task_util, best_cap = 0;
b7a33161
MR
6206 int cpu, best_cpu = -1;
6207 struct cpumask *cpus;
6208
b7a33161
MR
6209 cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6210 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6211
b4c9c9f1
VG
6212 task_util = uclamp_task_util(p);
6213
b7a33161
MR
6214 for_each_cpu_wrap(cpu, cpus, target) {
6215 unsigned long cpu_cap = capacity_of(cpu);
6216
6217 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
6218 continue;
b4c9c9f1 6219 if (fits_capacity(task_util, cpu_cap))
b7a33161
MR
6220 return cpu;
6221
6222 if (cpu_cap > best_cap) {
6223 best_cap = cpu_cap;
6224 best_cpu = cpu;
6225 }
6226 }
6227
6228 return best_cpu;
6229}
6230
b4c9c9f1
VG
6231static inline bool asym_fits_capacity(int task_util, int cpu)
6232{
6233 if (static_branch_unlikely(&sched_asym_cpucapacity))
6234 return fits_capacity(task_util, capacity_of(cpu));
6235
6236 return true;
6237}
6238
10e2f1ac
PZ
6239/*
6240 * Try and locate an idle core/thread in the LLC cache domain.
a50bde51 6241 */
772bd008 6242static int select_idle_sibling(struct task_struct *p, int prev, int target)
a50bde51 6243{
c722f35b 6244 bool has_idle_core = false;
99bd5e2f 6245 struct sched_domain *sd;
b4c9c9f1 6246 unsigned long task_util;
32e839dd 6247 int i, recent_used_cpu;
a50bde51 6248
b7a33161 6249 /*
b4c9c9f1
VG
6250 * On asymmetric system, update task utilization because we will check
6251 * that the task fits with cpu's capacity.
b7a33161
MR
6252 */
6253 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
b4c9c9f1
VG
6254 sync_entity_load_avg(&p->se);
6255 task_util = uclamp_task_util(p);
b7a33161
MR
6256 }
6257
9099a147
PZ
6258 /*
6259 * per-cpu select_idle_mask usage
6260 */
6261 lockdep_assert_irqs_disabled();
6262
b4c9c9f1
VG
6263 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
6264 asym_fits_capacity(task_util, target))
e0a79f52 6265 return target;
99bd5e2f
SS
6266
6267 /*
97fb7a0a 6268 * If the previous CPU is cache affine and idle, don't be stupid:
99bd5e2f 6269 */
3c29e651 6270 if (prev != target && cpus_share_cache(prev, target) &&
b4c9c9f1
VG
6271 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
6272 asym_fits_capacity(task_util, prev))
772bd008 6273 return prev;
a50bde51 6274
52262ee5
MG
6275 /*
6276 * Allow a per-cpu kthread to stack with the wakee if the
6277 * kworker thread and the tasks previous CPUs are the same.
6278 * The assumption is that the wakee queued work for the
6279 * per-cpu kthread that is now complete and the wakeup is
6280 * essentially a sync wakeup. An obvious example of this
6281 * pattern is IO completions.
6282 */
6283 if (is_per_cpu_kthread(current) &&
6284 prev == smp_processor_id() &&
6285 this_rq()->nr_running <= 1) {
6286 return prev;
6287 }
6288
97fb7a0a 6289 /* Check a recently used CPU as a potential idle candidate: */
32e839dd
MG
6290 recent_used_cpu = p->recent_used_cpu;
6291 if (recent_used_cpu != prev &&
6292 recent_used_cpu != target &&
6293 cpus_share_cache(recent_used_cpu, target) &&
3c29e651 6294 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
b4c9c9f1
VG
6295 cpumask_test_cpu(p->recent_used_cpu, p->cpus_ptr) &&
6296 asym_fits_capacity(task_util, recent_used_cpu)) {
32e839dd
MG
6297 /*
6298 * Replace recent_used_cpu with prev as it is a potential
97fb7a0a 6299 * candidate for the next wake:
32e839dd
MG
6300 */
6301 p->recent_used_cpu = prev;
6302 return recent_used_cpu;
6303 }
6304
b4c9c9f1
VG
6305 /*
6306 * For asymmetric CPU capacity systems, our domain of interest is
6307 * sd_asym_cpucapacity rather than sd_llc.
6308 */
6309 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6310 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
6311 /*
6312 * On an asymmetric CPU capacity system where an exclusive
6313 * cpuset defines a symmetric island (i.e. one unique
6314 * capacity_orig value through the cpuset), the key will be set
6315 * but the CPUs within that cpuset will not have a domain with
6316 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
6317 * capacity path.
6318 */
6319 if (sd) {
6320 i = select_idle_capacity(p, sd, target);
6321 return ((unsigned)i < nr_cpumask_bits) ? i : target;
6322 }
6323 }
6324
518cd623 6325 sd = rcu_dereference(per_cpu(sd_llc, target));
10e2f1ac
PZ
6326 if (!sd)
6327 return target;
772bd008 6328
c722f35b
RR
6329 if (sched_smt_active()) {
6330 has_idle_core = test_idle_cores(target, false);
6331
6332 if (!has_idle_core && cpus_share_cache(prev, target)) {
6333 i = select_idle_smt(p, sd, prev);
6334 if ((unsigned int)i < nr_cpumask_bits)
6335 return i;
6336 }
6337 }
6338
6339 i = select_idle_cpu(p, sd, has_idle_core, target);
10e2f1ac
PZ
6340 if ((unsigned)i < nr_cpumask_bits)
6341 return i;
6342
a50bde51
PZ
6343 return target;
6344}
231678b7 6345
f9be3e59 6346/**
59a74b15 6347 * cpu_util - Estimates the amount of capacity of a CPU used by CFS tasks.
f9be3e59
PB
6348 * @cpu: the CPU to get the utilization of
6349 *
6350 * The unit of the return value must be the one of capacity so we can compare
6351 * the utilization with the capacity of the CPU that is available for CFS task
6352 * (ie cpu_capacity).
231678b7
DE
6353 *
6354 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
6355 * recent utilization of currently non-runnable tasks on a CPU. It represents
6356 * the amount of utilization of a CPU in the range [0..capacity_orig] where
6357 * capacity_orig is the cpu_capacity available at the highest frequency
6358 * (arch_scale_freq_capacity()).
6359 * The utilization of a CPU converges towards a sum equal to or less than the
6360 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
6361 * the running time on this CPU scaled by capacity_curr.
6362 *
f9be3e59
PB
6363 * The estimated utilization of a CPU is defined to be the maximum between its
6364 * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
6365 * currently RUNNABLE on that CPU.
6366 * This allows to properly represent the expected utilization of a CPU which
6367 * has just got a big task running since a long sleep period. At the same time
6368 * however it preserves the benefits of the "blocked utilization" in
6369 * describing the potential for other tasks waking up on the same CPU.
6370 *
231678b7
DE
6371 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
6372 * higher than capacity_orig because of unfortunate rounding in
6373 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
6374 * the average stabilizes with the new running time. We need to check that the
6375 * utilization stays within the range of [0..capacity_orig] and cap it if
6376 * necessary. Without utilization capping, a group could be seen as overloaded
6377 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
6378 * available capacity. We allow utilization to overshoot capacity_curr (but not
6379 * capacity_orig) as it useful for predicting the capacity required after task
6380 * migrations (scheduler-driven DVFS).
f9be3e59
PB
6381 *
6382 * Return: the (estimated) utilization for the specified CPU
8bb5b00c 6383 */
f9be3e59 6384static inline unsigned long cpu_util(int cpu)
8bb5b00c 6385{
f9be3e59
PB
6386 struct cfs_rq *cfs_rq;
6387 unsigned int util;
6388
6389 cfs_rq = &cpu_rq(cpu)->cfs;
6390 util = READ_ONCE(cfs_rq->avg.util_avg);
6391
6392 if (sched_feat(UTIL_EST))
6393 util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
8bb5b00c 6394
f9be3e59 6395 return min_t(unsigned long, util, capacity_orig_of(cpu));
8bb5b00c 6396}
a50bde51 6397
104cb16d 6398/*
c469933e
PB
6399 * cpu_util_without: compute cpu utilization without any contributions from *p
6400 * @cpu: the CPU which utilization is requested
6401 * @p: the task which utilization should be discounted
6402 *
6403 * The utilization of a CPU is defined by the utilization of tasks currently
6404 * enqueued on that CPU as well as tasks which are currently sleeping after an
6405 * execution on that CPU.
6406 *
6407 * This method returns the utilization of the specified CPU by discounting the
6408 * utilization of the specified task, whenever the task is currently
6409 * contributing to the CPU utilization.
104cb16d 6410 */
c469933e 6411static unsigned long cpu_util_without(int cpu, struct task_struct *p)
104cb16d 6412{
f9be3e59
PB
6413 struct cfs_rq *cfs_rq;
6414 unsigned int util;
104cb16d
MR
6415
6416 /* Task has no contribution or is new */
f9be3e59 6417 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
104cb16d
MR
6418 return cpu_util(cpu);
6419
f9be3e59
PB
6420 cfs_rq = &cpu_rq(cpu)->cfs;
6421 util = READ_ONCE(cfs_rq->avg.util_avg);
6422
c469933e 6423 /* Discount task's util from CPU's util */
b5c0ce7b 6424 lsub_positive(&util, task_util(p));
104cb16d 6425
f9be3e59
PB
6426 /*
6427 * Covered cases:
6428 *
6429 * a) if *p is the only task sleeping on this CPU, then:
6430 * cpu_util (== task_util) > util_est (== 0)
6431 * and thus we return:
c469933e 6432 * cpu_util_without = (cpu_util - task_util) = 0
f9be3e59
PB
6433 *
6434 * b) if other tasks are SLEEPING on this CPU, which is now exiting
6435 * IDLE, then:
6436 * cpu_util >= task_util
6437 * cpu_util > util_est (== 0)
6438 * and thus we discount *p's blocked utilization to return:
c469933e 6439 * cpu_util_without = (cpu_util - task_util) >= 0
f9be3e59
PB
6440 *
6441 * c) if other tasks are RUNNABLE on that CPU and
6442 * util_est > cpu_util
6443 * then we use util_est since it returns a more restrictive
6444 * estimation of the spare capacity on that CPU, by just
6445 * considering the expected utilization of tasks already
6446 * runnable on that CPU.
6447 *
6448 * Cases a) and b) are covered by the above code, while case c) is
6449 * covered by the following code when estimated utilization is
6450 * enabled.
6451 */
c469933e
PB
6452 if (sched_feat(UTIL_EST)) {
6453 unsigned int estimated =
6454 READ_ONCE(cfs_rq->avg.util_est.enqueued);
6455
6456 /*
6457 * Despite the following checks we still have a small window
6458 * for a possible race, when an execl's select_task_rq_fair()
6459 * races with LB's detach_task():
6460 *
6461 * detach_task()
6462 * p->on_rq = TASK_ON_RQ_MIGRATING;
6463 * ---------------------------------- A
6464 * deactivate_task() \
6465 * dequeue_task() + RaceTime
6466 * util_est_dequeue() /
6467 * ---------------------------------- B
6468 *
6469 * The additional check on "current == p" it's required to
6470 * properly fix the execl regression and it helps in further
6471 * reducing the chances for the above race.
6472 */
b5c0ce7b
PB
6473 if (unlikely(task_on_rq_queued(p) || current == p))
6474 lsub_positive(&estimated, _task_util_est(p));
6475
c469933e
PB
6476 util = max(util, estimated);
6477 }
f9be3e59
PB
6478
6479 /*
6480 * Utilization (estimated) can exceed the CPU capacity, thus let's
6481 * clamp to the maximum CPU capacity to ensure consistency with
6482 * the cpu_util call.
6483 */
6484 return min_t(unsigned long, util, capacity_orig_of(cpu));
104cb16d
MR
6485}
6486
390031e4
QP
6487/*
6488 * Predicts what cpu_util(@cpu) would return if @p was migrated (and enqueued)
6489 * to @dst_cpu.
6490 */
6491static unsigned long cpu_util_next(int cpu, struct task_struct *p, int dst_cpu)
6492{
6493 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
6494 unsigned long util_est, util = READ_ONCE(cfs_rq->avg.util_avg);
6495
6496 /*
6497 * If @p migrates from @cpu to another, remove its contribution. Or,
6498 * if @p migrates from another CPU to @cpu, add its contribution. In
6499 * the other cases, @cpu is not impacted by the migration, so the
6500 * util_avg should already be correct.
6501 */
6502 if (task_cpu(p) == cpu && dst_cpu != cpu)
736cc6b3 6503 lsub_positive(&util, task_util(p));
390031e4
QP
6504 else if (task_cpu(p) != cpu && dst_cpu == cpu)
6505 util += task_util(p);
6506
6507 if (sched_feat(UTIL_EST)) {
6508 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
6509
6510 /*
6511 * During wake-up, the task isn't enqueued yet and doesn't
6512 * appear in the cfs_rq->avg.util_est.enqueued of any rq,
6513 * so just add it (if needed) to "simulate" what will be
6514 * cpu_util() after the task has been enqueued.
6515 */
6516 if (dst_cpu == cpu)
6517 util_est += _task_util_est(p);
6518
6519 util = max(util, util_est);
6520 }
6521
6522 return min(util, capacity_orig_of(cpu));
6523}
6524
6525/*
eb92692b 6526 * compute_energy(): Estimates the energy that @pd would consume if @p was
390031e4 6527 * migrated to @dst_cpu. compute_energy() predicts what will be the utilization
eb92692b 6528 * landscape of @pd's CPUs after the task migration, and uses the Energy Model
390031e4
QP
6529 * to compute what would be the energy if we decided to actually migrate that
6530 * task.
6531 */
6532static long
6533compute_energy(struct task_struct *p, int dst_cpu, struct perf_domain *pd)
6534{
eb92692b
QP
6535 struct cpumask *pd_mask = perf_domain_span(pd);
6536 unsigned long cpu_cap = arch_scale_cpu_capacity(cpumask_first(pd_mask));
6537 unsigned long max_util = 0, sum_util = 0;
489f1645 6538 unsigned long _cpu_cap = cpu_cap;
390031e4
QP
6539 int cpu;
6540
489f1645
LL
6541 _cpu_cap -= arch_scale_thermal_pressure(cpumask_first(pd_mask));
6542
eb92692b
QP
6543 /*
6544 * The capacity state of CPUs of the current rd can be driven by CPUs
6545 * of another rd if they belong to the same pd. So, account for the
6546 * utilization of these CPUs too by masking pd with cpu_online_mask
6547 * instead of the rd span.
6548 *
6549 * If an entire pd is outside of the current rd, it will not appear in
6550 * its pd list and will not be accounted by compute_energy().
6551 */
6552 for_each_cpu_and(cpu, pd_mask, cpu_online_mask) {
0372e1cf
VD
6553 unsigned long util_freq = cpu_util_next(cpu, p, dst_cpu);
6554 unsigned long cpu_util, util_running = util_freq;
6555 struct task_struct *tsk = NULL;
6556
6557 /*
6558 * When @p is placed on @cpu:
6559 *
6560 * util_running = max(cpu_util, cpu_util_est) +
6561 * max(task_util, _task_util_est)
6562 *
6563 * while cpu_util_next is: max(cpu_util + task_util,
6564 * cpu_util_est + _task_util_est)
6565 */
6566 if (cpu == dst_cpu) {
6567 tsk = p;
6568 util_running =
6569 cpu_util_next(cpu, p, -1) + task_util_est(p);
6570 }
af24bde8
PB
6571
6572 /*
eb92692b
QP
6573 * Busy time computation: utilization clamping is not
6574 * required since the ratio (sum_util / cpu_capacity)
6575 * is already enough to scale the EM reported power
6576 * consumption at the (eventually clamped) cpu_capacity.
af24bde8 6577 */
489f1645
LL
6578 cpu_util = effective_cpu_util(cpu, util_running, cpu_cap,
6579 ENERGY_UTIL, NULL);
6580
6581 sum_util += min(cpu_util, _cpu_cap);
af24bde8 6582
390031e4 6583 /*
eb92692b
QP
6584 * Performance domain frequency: utilization clamping
6585 * must be considered since it affects the selection
6586 * of the performance domain frequency.
6587 * NOTE: in case RT tasks are running, by default the
6588 * FREQUENCY_UTIL's utilization can be max OPP.
390031e4 6589 */
0372e1cf 6590 cpu_util = effective_cpu_util(cpu, util_freq, cpu_cap,
eb92692b 6591 FREQUENCY_UTIL, tsk);
489f1645 6592 max_util = max(max_util, min(cpu_util, _cpu_cap));
390031e4
QP
6593 }
6594
f0b56947 6595 return em_cpu_energy(pd->em_pd, max_util, sum_util);
390031e4
QP
6596}
6597
732cd75b
QP
6598/*
6599 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
6600 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
6601 * spare capacity in each performance domain and uses it as a potential
6602 * candidate to execute the task. Then, it uses the Energy Model to figure
6603 * out which of the CPU candidates is the most energy-efficient.
6604 *
6605 * The rationale for this heuristic is as follows. In a performance domain,
6606 * all the most energy efficient CPU candidates (according to the Energy
6607 * Model) are those for which we'll request a low frequency. When there are
6608 * several CPUs for which the frequency request will be the same, we don't
6609 * have enough data to break the tie between them, because the Energy Model
6610 * only includes active power costs. With this model, if we assume that
6611 * frequency requests follow utilization (e.g. using schedutil), the CPU with
6612 * the maximum spare capacity in a performance domain is guaranteed to be among
6613 * the best candidates of the performance domain.
6614 *
6615 * In practice, it could be preferable from an energy standpoint to pack
6616 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
6617 * but that could also hurt our chances to go cluster idle, and we have no
6618 * ways to tell with the current Energy Model if this is actually a good
6619 * idea or not. So, find_energy_efficient_cpu() basically favors
6620 * cluster-packing, and spreading inside a cluster. That should at least be
6621 * a good thing for latency, and this is consistent with the idea that most
6622 * of the energy savings of EAS come from the asymmetry of the system, and
6623 * not so much from breaking the tie between identical CPUs. That's also the
6624 * reason why EAS is enabled in the topology code only for systems where
6625 * SD_ASYM_CPUCAPACITY is set.
6626 *
6627 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
6628 * they don't have any useful utilization data yet and it's not possible to
6629 * forecast their impact on energy consumption. Consequently, they will be
6630 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
6631 * to be energy-inefficient in some use-cases. The alternative would be to
6632 * bias new tasks towards specific types of CPUs first, or to try to infer
6633 * their util_avg from the parent task, but those heuristics could hurt
6634 * other use-cases too. So, until someone finds a better way to solve this,
6635 * let's keep things simple by re-using the existing slow path.
6636 */
732cd75b
QP
6637static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
6638{
eb92692b 6639 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
732cd75b 6640 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
619e090c 6641 int cpu, best_energy_cpu = prev_cpu, target = -1;
eb92692b 6642 unsigned long cpu_cap, util, base_energy = 0;
732cd75b 6643 struct sched_domain *sd;
eb92692b 6644 struct perf_domain *pd;
732cd75b
QP
6645
6646 rcu_read_lock();
6647 pd = rcu_dereference(rd->pd);
6648 if (!pd || READ_ONCE(rd->overutilized))
619e090c 6649 goto unlock;
732cd75b
QP
6650
6651 /*
6652 * Energy-aware wake-up happens on the lowest sched_domain starting
6653 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
6654 */
6655 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
6656 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
6657 sd = sd->parent;
6658 if (!sd)
619e090c
PG
6659 goto unlock;
6660
6661 target = prev_cpu;
732cd75b
QP
6662
6663 sync_entity_load_avg(&p->se);
6664 if (!task_util_est(p))
6665 goto unlock;
6666
6667 for (; pd; pd = pd->next) {
eb92692b 6668 unsigned long cur_delta, spare_cap, max_spare_cap = 0;
8d4c97c1 6669 bool compute_prev_delta = false;
eb92692b 6670 unsigned long base_energy_pd;
732cd75b
QP
6671 int max_spare_cap_cpu = -1;
6672
6673 for_each_cpu_and(cpu, perf_domain_span(pd), sched_domain_span(sd)) {
3bd37062 6674 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
732cd75b
QP
6675 continue;
6676
732cd75b
QP
6677 util = cpu_util_next(cpu, p, cpu);
6678 cpu_cap = capacity_of(cpu);
da0777d3
LL
6679 spare_cap = cpu_cap;
6680 lsub_positive(&spare_cap, util);
1d42509e
VS
6681
6682 /*
6683 * Skip CPUs that cannot satisfy the capacity request.
6684 * IOW, placing the task there would make the CPU
6685 * overutilized. Take uclamp into account to see how
6686 * much capacity we can get out of the CPU; this is
a5418be9 6687 * aligned with sched_cpu_util().
1d42509e
VS
6688 */
6689 util = uclamp_rq_util_with(cpu_rq(cpu), util, p);
60e17f5c 6690 if (!fits_capacity(util, cpu_cap))
732cd75b
QP
6691 continue;
6692
732cd75b 6693 if (cpu == prev_cpu) {
8d4c97c1
PG
6694 /* Always use prev_cpu as a candidate. */
6695 compute_prev_delta = true;
6696 } else if (spare_cap > max_spare_cap) {
6697 /*
6698 * Find the CPU with the maximum spare capacity
6699 * in the performance domain.
6700 */
732cd75b
QP
6701 max_spare_cap = spare_cap;
6702 max_spare_cap_cpu = cpu;
6703 }
6704 }
6705
8d4c97c1
PG
6706 if (max_spare_cap_cpu < 0 && !compute_prev_delta)
6707 continue;
6708
6709 /* Compute the 'base' energy of the pd, without @p */
6710 base_energy_pd = compute_energy(p, -1, pd);
6711 base_energy += base_energy_pd;
6712
6713 /* Evaluate the energy impact of using prev_cpu. */
6714 if (compute_prev_delta) {
6715 prev_delta = compute_energy(p, prev_cpu, pd);
619e090c
PG
6716 if (prev_delta < base_energy_pd)
6717 goto unlock;
8d4c97c1
PG
6718 prev_delta -= base_energy_pd;
6719 best_delta = min(best_delta, prev_delta);
6720 }
6721
6722 /* Evaluate the energy impact of using max_spare_cap_cpu. */
6723 if (max_spare_cap_cpu >= 0) {
eb92692b 6724 cur_delta = compute_energy(p, max_spare_cap_cpu, pd);
619e090c
PG
6725 if (cur_delta < base_energy_pd)
6726 goto unlock;
eb92692b
QP
6727 cur_delta -= base_energy_pd;
6728 if (cur_delta < best_delta) {
6729 best_delta = cur_delta;
732cd75b
QP
6730 best_energy_cpu = max_spare_cap_cpu;
6731 }
6732 }
6733 }
732cd75b
QP
6734 rcu_read_unlock();
6735
6736 /*
6737 * Pick the best CPU if prev_cpu cannot be used, or if it saves at
6738 * least 6% of the energy used by prev_cpu.
6739 */
619e090c
PG
6740 if ((prev_delta == ULONG_MAX) ||
6741 (prev_delta - best_delta) > ((prev_delta + base_energy) >> 4))
6742 target = best_energy_cpu;
732cd75b 6743
619e090c 6744 return target;
732cd75b 6745
619e090c 6746unlock:
732cd75b
QP
6747 rcu_read_unlock();
6748
619e090c 6749 return target;
732cd75b
QP
6750}
6751
aaee1203 6752/*
de91b9cb 6753 * select_task_rq_fair: Select target runqueue for the waking task in domains
3aef1551 6754 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
de91b9cb 6755 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
aaee1203 6756 *
97fb7a0a
IM
6757 * Balances load by selecting the idlest CPU in the idlest group, or under
6758 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
aaee1203 6759 *
97fb7a0a 6760 * Returns the target CPU number.
aaee1203 6761 */
0017d735 6762static int
3aef1551 6763select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
aaee1203 6764{
3aef1551 6765 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
f1d88b44 6766 struct sched_domain *tmp, *sd = NULL;
c88d5910 6767 int cpu = smp_processor_id();
63b0e9ed 6768 int new_cpu = prev_cpu;
99bd5e2f 6769 int want_affine = 0;
3aef1551
VS
6770 /* SD_flags and WF_flags share the first nibble */
6771 int sd_flag = wake_flags & 0xF;
c88d5910 6772
9099a147
PZ
6773 /*
6774 * required for stable ->cpus_allowed
6775 */
6776 lockdep_assert_held(&p->pi_lock);
dc824eb8 6777 if (wake_flags & WF_TTWU) {
c58d25f3 6778 record_wakee(p);
732cd75b 6779
f8a696f2 6780 if (sched_energy_enabled()) {
732cd75b
QP
6781 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
6782 if (new_cpu >= 0)
6783 return new_cpu;
6784 new_cpu = prev_cpu;
6785 }
6786
00061968 6787 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
c58d25f3 6788 }
aaee1203 6789
dce840a0 6790 rcu_read_lock();
aaee1203 6791 for_each_domain(cpu, tmp) {
fe3bcfe1 6792 /*
97fb7a0a 6793 * If both 'cpu' and 'prev_cpu' are part of this domain,
99bd5e2f 6794 * cpu is a valid SD_WAKE_AFFINE target.
fe3bcfe1 6795 */
99bd5e2f
SS
6796 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6797 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
f1d88b44
VK
6798 if (cpu != prev_cpu)
6799 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
6800
6801 sd = NULL; /* Prefer wake_affine over balance flags */
29cd8bae 6802 break;
f03542a7 6803 }
29cd8bae 6804
f03542a7 6805 if (tmp->flags & sd_flag)
29cd8bae 6806 sd = tmp;
63b0e9ed
MG
6807 else if (!want_affine)
6808 break;
29cd8bae
PZ
6809 }
6810
f1d88b44
VK
6811 if (unlikely(sd)) {
6812 /* Slow path */
18bd1b4b 6813 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
dc824eb8 6814 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
f1d88b44 6815 /* Fast path */
f1d88b44
VK
6816 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6817
6818 if (want_affine)
6819 current->recent_used_cpu = cpu;
e7693a36 6820 }
dce840a0 6821 rcu_read_unlock();
e7693a36 6822
c88d5910 6823 return new_cpu;
e7693a36 6824}
0a74bef8 6825
144d8487
PZ
6826static void detach_entity_cfs_rq(struct sched_entity *se);
6827
0a74bef8 6828/*
97fb7a0a 6829 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
0a74bef8 6830 * cfs_rq_of(p) references at time of call are still valid and identify the
97fb7a0a 6831 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
0a74bef8 6832 */
3f9672ba 6833static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
0a74bef8 6834{
59efa0ba
PZ
6835 /*
6836 * As blocked tasks retain absolute vruntime the migration needs to
6837 * deal with this by subtracting the old and adding the new
6838 * min_vruntime -- the latter is done by enqueue_entity() when placing
6839 * the task on the new runqueue.
6840 */
6841 if (p->state == TASK_WAKING) {
6842 struct sched_entity *se = &p->se;
6843 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6844 u64 min_vruntime;
6845
6846#ifndef CONFIG_64BIT
6847 u64 min_vruntime_copy;
6848
6849 do {
6850 min_vruntime_copy = cfs_rq->min_vruntime_copy;
6851 smp_rmb();
6852 min_vruntime = cfs_rq->min_vruntime;
6853 } while (min_vruntime != min_vruntime_copy);
6854#else
6855 min_vruntime = cfs_rq->min_vruntime;
6856#endif
6857
6858 se->vruntime -= min_vruntime;
6859 }
6860
144d8487
PZ
6861 if (p->on_rq == TASK_ON_RQ_MIGRATING) {
6862 /*
6863 * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
6864 * rq->lock and can modify state directly.
6865 */
5cb9eaa3 6866 lockdep_assert_rq_held(task_rq(p));
144d8487
PZ
6867 detach_entity_cfs_rq(&p->se);
6868
6869 } else {
6870 /*
6871 * We are supposed to update the task to "current" time, then
6872 * its up to date and ready to go to new CPU/cfs_rq. But we
6873 * have difficulty in getting what current time is, so simply
6874 * throw away the out-of-date time. This will result in the
6875 * wakee task is less decayed, but giving the wakee more load
6876 * sounds not bad.
6877 */
6878 remove_entity_load_avg(&p->se);
6879 }
9d89c257
YD
6880
6881 /* Tell new CPU we are migrated */
6882 p->se.avg.last_update_time = 0;
3944a927
BS
6883
6884 /* We have migrated, no longer consider this task hot */
9d89c257 6885 p->se.exec_start = 0;
3f9672ba
SD
6886
6887 update_scan_period(p, new_cpu);
0a74bef8 6888}
12695578
YD
6889
6890static void task_dead_fair(struct task_struct *p)
6891{
6892 remove_entity_load_avg(&p->se);
6893}
6e2df058
PZ
6894
6895static int
6896balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6897{
6898 if (rq->nr_running)
6899 return 1;
6900
6901 return newidle_balance(rq, rf) != 0;
6902}
e7693a36
GH
6903#endif /* CONFIG_SMP */
6904
a555e9d8 6905static unsigned long wakeup_gran(struct sched_entity *se)
0bbd3336
PZ
6906{
6907 unsigned long gran = sysctl_sched_wakeup_granularity;
6908
6909 /*
e52fb7c0
PZ
6910 * Since its curr running now, convert the gran from real-time
6911 * to virtual-time in his units.
13814d42
MG
6912 *
6913 * By using 'se' instead of 'curr' we penalize light tasks, so
6914 * they get preempted easier. That is, if 'se' < 'curr' then
6915 * the resulting gran will be larger, therefore penalizing the
6916 * lighter, if otoh 'se' > 'curr' then the resulting gran will
6917 * be smaller, again penalizing the lighter task.
6918 *
6919 * This is especially important for buddies when the leftmost
6920 * task is higher priority than the buddy.
0bbd3336 6921 */
f4ad9bd2 6922 return calc_delta_fair(gran, se);
0bbd3336
PZ
6923}
6924
464b7527
PZ
6925/*
6926 * Should 'se' preempt 'curr'.
6927 *
6928 * |s1
6929 * |s2
6930 * |s3
6931 * g
6932 * |<--->|c
6933 *
6934 * w(c, s1) = -1
6935 * w(c, s2) = 0
6936 * w(c, s3) = 1
6937 *
6938 */
6939static int
6940wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
6941{
6942 s64 gran, vdiff = curr->vruntime - se->vruntime;
6943
6944 if (vdiff <= 0)
6945 return -1;
6946
a555e9d8 6947 gran = wakeup_gran(se);
464b7527
PZ
6948 if (vdiff > gran)
6949 return 1;
6950
6951 return 0;
6952}
6953
02479099
PZ
6954static void set_last_buddy(struct sched_entity *se)
6955{
1da1843f 6956 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
69c80f3e
VP
6957 return;
6958
c5ae366e
DA
6959 for_each_sched_entity(se) {
6960 if (SCHED_WARN_ON(!se->on_rq))
6961 return;
69c80f3e 6962 cfs_rq_of(se)->last = se;
c5ae366e 6963 }
02479099
PZ
6964}
6965
6966static void set_next_buddy(struct sched_entity *se)
6967{
1da1843f 6968 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
69c80f3e
VP
6969 return;
6970
c5ae366e
DA
6971 for_each_sched_entity(se) {
6972 if (SCHED_WARN_ON(!se->on_rq))
6973 return;
69c80f3e 6974 cfs_rq_of(se)->next = se;
c5ae366e 6975 }
02479099
PZ
6976}
6977
ac53db59
RR
6978static void set_skip_buddy(struct sched_entity *se)
6979{
69c80f3e
VP
6980 for_each_sched_entity(se)
6981 cfs_rq_of(se)->skip = se;
ac53db59
RR
6982}
6983
bf0f6f24
IM
6984/*
6985 * Preempt the current task with a newly woken task if needed:
6986 */
5a9b86f6 6987static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
bf0f6f24
IM
6988{
6989 struct task_struct *curr = rq->curr;
8651a86c 6990 struct sched_entity *se = &curr->se, *pse = &p->se;
03e89e45 6991 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
f685ceac 6992 int scale = cfs_rq->nr_running >= sched_nr_latency;
2f36825b 6993 int next_buddy_marked = 0;
bf0f6f24 6994
4ae7d5ce
IM
6995 if (unlikely(se == pse))
6996 return;
6997
5238cdd3 6998 /*
163122b7 6999 * This is possible from callers such as attach_tasks(), in which we
3b03706f 7000 * unconditionally check_preempt_curr() after an enqueue (which may have
5238cdd3
PT
7001 * lead to a throttle). This both saves work and prevents false
7002 * next-buddy nomination below.
7003 */
7004 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
7005 return;
7006
2f36825b 7007 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3cb63d52 7008 set_next_buddy(pse);
2f36825b
VP
7009 next_buddy_marked = 1;
7010 }
57fdc26d 7011
aec0a514
BR
7012 /*
7013 * We can come here with TIF_NEED_RESCHED already set from new task
7014 * wake up path.
5238cdd3
PT
7015 *
7016 * Note: this also catches the edge-case of curr being in a throttled
7017 * group (e.g. via set_curr_task), since update_curr() (in the
7018 * enqueue of curr) will have resulted in resched being set. This
7019 * prevents us from potentially nominating it as a false LAST_BUDDY
7020 * below.
aec0a514
BR
7021 */
7022 if (test_tsk_need_resched(curr))
7023 return;
7024
a2f5c9ab 7025 /* Idle tasks are by definition preempted by non-idle tasks. */
1da1843f
VK
7026 if (unlikely(task_has_idle_policy(curr)) &&
7027 likely(!task_has_idle_policy(p)))
a2f5c9ab
DH
7028 goto preempt;
7029
91c234b4 7030 /*
a2f5c9ab
DH
7031 * Batch and idle tasks do not preempt non-idle tasks (their preemption
7032 * is driven by the tick):
91c234b4 7033 */
8ed92e51 7034 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
91c234b4 7035 return;
bf0f6f24 7036
464b7527 7037 find_matching_se(&se, &pse);
9bbd7374 7038 update_curr(cfs_rq_of(se));
002f128b 7039 BUG_ON(!pse);
2f36825b
VP
7040 if (wakeup_preempt_entity(se, pse) == 1) {
7041 /*
7042 * Bias pick_next to pick the sched entity that is
7043 * triggering this preemption.
7044 */
7045 if (!next_buddy_marked)
7046 set_next_buddy(pse);
3a7e73a2 7047 goto preempt;
2f36825b 7048 }
464b7527 7049
3a7e73a2 7050 return;
a65ac745 7051
3a7e73a2 7052preempt:
8875125e 7053 resched_curr(rq);
3a7e73a2
PZ
7054 /*
7055 * Only set the backward buddy when the current task is still
7056 * on the rq. This can happen when a wakeup gets interleaved
7057 * with schedule on the ->pre_schedule() or idle_balance()
7058 * point, either of which can * drop the rq lock.
7059 *
7060 * Also, during early boot the idle thread is in the fair class,
7061 * for obvious reasons its a bad idea to schedule back to it.
7062 */
7063 if (unlikely(!se->on_rq || curr == rq->idle))
7064 return;
7065
7066 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7067 set_last_buddy(se);
bf0f6f24
IM
7068}
7069
21f56ffe
PZ
7070#ifdef CONFIG_SMP
7071static struct task_struct *pick_task_fair(struct rq *rq)
7072{
7073 struct sched_entity *se;
7074 struct cfs_rq *cfs_rq;
7075
7076again:
7077 cfs_rq = &rq->cfs;
7078 if (!cfs_rq->nr_running)
7079 return NULL;
7080
7081 do {
7082 struct sched_entity *curr = cfs_rq->curr;
7083
7084 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
7085 if (curr) {
7086 if (curr->on_rq)
7087 update_curr(cfs_rq);
7088 else
7089 curr = NULL;
7090
7091 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
7092 goto again;
7093 }
7094
7095 se = pick_next_entity(cfs_rq, curr);
7096 cfs_rq = group_cfs_rq(se);
7097 } while (cfs_rq);
7098
7099 return task_of(se);
7100}
7101#endif
7102
5d7d6056 7103struct task_struct *
d8ac8971 7104pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
bf0f6f24
IM
7105{
7106 struct cfs_rq *cfs_rq = &rq->cfs;
7107 struct sched_entity *se;
678d5718 7108 struct task_struct *p;
37e117c0 7109 int new_tasks;
678d5718 7110
6e83125c 7111again:
6e2df058 7112 if (!sched_fair_runnable(rq))
38033c37 7113 goto idle;
678d5718 7114
9674f5ca 7115#ifdef CONFIG_FAIR_GROUP_SCHED
67692435 7116 if (!prev || prev->sched_class != &fair_sched_class)
678d5718
PZ
7117 goto simple;
7118
7119 /*
7120 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7121 * likely that a next task is from the same cgroup as the current.
7122 *
7123 * Therefore attempt to avoid putting and setting the entire cgroup
7124 * hierarchy, only change the part that actually changes.
7125 */
7126
7127 do {
7128 struct sched_entity *curr = cfs_rq->curr;
7129
7130 /*
7131 * Since we got here without doing put_prev_entity() we also
7132 * have to consider cfs_rq->curr. If it is still a runnable
7133 * entity, update_curr() will update its vruntime, otherwise
7134 * forget we've ever seen it.
7135 */
54d27365
BS
7136 if (curr) {
7137 if (curr->on_rq)
7138 update_curr(cfs_rq);
7139 else
7140 curr = NULL;
678d5718 7141
54d27365
BS
7142 /*
7143 * This call to check_cfs_rq_runtime() will do the
7144 * throttle and dequeue its entity in the parent(s).
9674f5ca 7145 * Therefore the nr_running test will indeed
54d27365
BS
7146 * be correct.
7147 */
9674f5ca
VK
7148 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
7149 cfs_rq = &rq->cfs;
7150
7151 if (!cfs_rq->nr_running)
7152 goto idle;
7153
54d27365 7154 goto simple;
9674f5ca 7155 }
54d27365 7156 }
678d5718
PZ
7157
7158 se = pick_next_entity(cfs_rq, curr);
7159 cfs_rq = group_cfs_rq(se);
7160 } while (cfs_rq);
7161
7162 p = task_of(se);
7163
7164 /*
7165 * Since we haven't yet done put_prev_entity and if the selected task
7166 * is a different task than we started out with, try and touch the
7167 * least amount of cfs_rqs.
7168 */
7169 if (prev != p) {
7170 struct sched_entity *pse = &prev->se;
7171
7172 while (!(cfs_rq = is_same_group(se, pse))) {
7173 int se_depth = se->depth;
7174 int pse_depth = pse->depth;
7175
7176 if (se_depth <= pse_depth) {
7177 put_prev_entity(cfs_rq_of(pse), pse);
7178 pse = parent_entity(pse);
7179 }
7180 if (se_depth >= pse_depth) {
7181 set_next_entity(cfs_rq_of(se), se);
7182 se = parent_entity(se);
7183 }
7184 }
7185
7186 put_prev_entity(cfs_rq, pse);
7187 set_next_entity(cfs_rq, se);
7188 }
7189
93824900 7190 goto done;
678d5718 7191simple:
678d5718 7192#endif
67692435
PZ
7193 if (prev)
7194 put_prev_task(rq, prev);
606dba2e 7195
bf0f6f24 7196 do {
678d5718 7197 se = pick_next_entity(cfs_rq, NULL);
f4b6755f 7198 set_next_entity(cfs_rq, se);
bf0f6f24
IM
7199 cfs_rq = group_cfs_rq(se);
7200 } while (cfs_rq);
7201
8f4d37ec 7202 p = task_of(se);
678d5718 7203
13a453c2 7204done: __maybe_unused;
93824900
UR
7205#ifdef CONFIG_SMP
7206 /*
7207 * Move the next running task to the front of
7208 * the list, so our cfs_tasks list becomes MRU
7209 * one.
7210 */
7211 list_move(&p->se.group_node, &rq->cfs_tasks);
7212#endif
7213
e0ee463c 7214 if (hrtick_enabled_fair(rq))
b39e66ea 7215 hrtick_start_fair(rq, p);
8f4d37ec 7216
3b1baa64
MR
7217 update_misfit_status(p, rq);
7218
8f4d37ec 7219 return p;
38033c37
PZ
7220
7221idle:
67692435
PZ
7222 if (!rf)
7223 return NULL;
7224
5ba553ef 7225 new_tasks = newidle_balance(rq, rf);
46f69fa3 7226
37e117c0 7227 /*
5ba553ef 7228 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
37e117c0
PZ
7229 * possible for any higher priority task to appear. In that case we
7230 * must re-start the pick_next_entity() loop.
7231 */
e4aa358b 7232 if (new_tasks < 0)
37e117c0
PZ
7233 return RETRY_TASK;
7234
e4aa358b 7235 if (new_tasks > 0)
38033c37 7236 goto again;
38033c37 7237
23127296
VG
7238 /*
7239 * rq is about to be idle, check if we need to update the
7240 * lost_idle_time of clock_pelt
7241 */
7242 update_idle_rq_clock_pelt(rq);
7243
38033c37 7244 return NULL;
bf0f6f24
IM
7245}
7246
98c2f700
PZ
7247static struct task_struct *__pick_next_task_fair(struct rq *rq)
7248{
7249 return pick_next_task_fair(rq, NULL, NULL);
7250}
7251
bf0f6f24
IM
7252/*
7253 * Account for a descheduled task:
7254 */
6e2df058 7255static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
bf0f6f24
IM
7256{
7257 struct sched_entity *se = &prev->se;
7258 struct cfs_rq *cfs_rq;
7259
7260 for_each_sched_entity(se) {
7261 cfs_rq = cfs_rq_of(se);
ab6cde26 7262 put_prev_entity(cfs_rq, se);
bf0f6f24
IM
7263 }
7264}
7265
ac53db59
RR
7266/*
7267 * sched_yield() is very simple
7268 *
7269 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7270 */
7271static void yield_task_fair(struct rq *rq)
7272{
7273 struct task_struct *curr = rq->curr;
7274 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7275 struct sched_entity *se = &curr->se;
7276
7277 /*
7278 * Are we the only task in the tree?
7279 */
7280 if (unlikely(rq->nr_running == 1))
7281 return;
7282
7283 clear_buddies(cfs_rq, se);
7284
7285 if (curr->policy != SCHED_BATCH) {
7286 update_rq_clock(rq);
7287 /*
7288 * Update run-time statistics of the 'current'.
7289 */
7290 update_curr(cfs_rq);
916671c0
MG
7291 /*
7292 * Tell update_rq_clock() that we've just updated,
7293 * so we don't do microscopic update in schedule()
7294 * and double the fastpath cost.
7295 */
adcc8da8 7296 rq_clock_skip_update(rq);
ac53db59
RR
7297 }
7298
7299 set_skip_buddy(se);
7300}
7301
0900acf2 7302static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
d95f4122
MG
7303{
7304 struct sched_entity *se = &p->se;
7305
5238cdd3
PT
7306 /* throttled hierarchies are not runnable */
7307 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
d95f4122
MG
7308 return false;
7309
7310 /* Tell the scheduler that we'd really like pse to run next. */
7311 set_next_buddy(se);
7312
d95f4122
MG
7313 yield_task_fair(rq);
7314
7315 return true;
7316}
7317
681f3e68 7318#ifdef CONFIG_SMP
bf0f6f24 7319/**************************************************
e9c84cb8
PZ
7320 * Fair scheduling class load-balancing methods.
7321 *
7322 * BASICS
7323 *
7324 * The purpose of load-balancing is to achieve the same basic fairness the
97fb7a0a 7325 * per-CPU scheduler provides, namely provide a proportional amount of compute
e9c84cb8
PZ
7326 * time to each task. This is expressed in the following equation:
7327 *
7328 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
7329 *
97fb7a0a 7330 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
e9c84cb8
PZ
7331 * W_i,0 is defined as:
7332 *
7333 * W_i,0 = \Sum_j w_i,j (2)
7334 *
97fb7a0a 7335 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
1c3de5e1 7336 * is derived from the nice value as per sched_prio_to_weight[].
e9c84cb8
PZ
7337 *
7338 * The weight average is an exponential decay average of the instantaneous
7339 * weight:
7340 *
7341 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
7342 *
97fb7a0a 7343 * C_i is the compute capacity of CPU i, typically it is the
e9c84cb8
PZ
7344 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7345 * can also include other factors [XXX].
7346 *
7347 * To achieve this balance we define a measure of imbalance which follows
7348 * directly from (1):
7349 *
ced549fa 7350 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
e9c84cb8
PZ
7351 *
7352 * We them move tasks around to minimize the imbalance. In the continuous
7353 * function space it is obvious this converges, in the discrete case we get
7354 * a few fun cases generally called infeasible weight scenarios.
7355 *
7356 * [XXX expand on:
7357 * - infeasible weights;
7358 * - local vs global optima in the discrete case. ]
7359 *
7360 *
7361 * SCHED DOMAINS
7362 *
7363 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
97fb7a0a 7364 * for all i,j solution, we create a tree of CPUs that follows the hardware
e9c84cb8 7365 * topology where each level pairs two lower groups (or better). This results
97fb7a0a 7366 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
e9c84cb8 7367 * tree to only the first of the previous level and we decrease the frequency
97fb7a0a 7368 * of load-balance at each level inv. proportional to the number of CPUs in
e9c84cb8
PZ
7369 * the groups.
7370 *
7371 * This yields:
7372 *
7373 * log_2 n 1 n
7374 * \Sum { --- * --- * 2^i } = O(n) (5)
7375 * i = 0 2^i 2^i
7376 * `- size of each group
97fb7a0a 7377 * | | `- number of CPUs doing load-balance
e9c84cb8
PZ
7378 * | `- freq
7379 * `- sum over all levels
7380 *
7381 * Coupled with a limit on how many tasks we can migrate every balance pass,
7382 * this makes (5) the runtime complexity of the balancer.
7383 *
7384 * An important property here is that each CPU is still (indirectly) connected
97fb7a0a 7385 * to every other CPU in at most O(log n) steps:
e9c84cb8
PZ
7386 *
7387 * The adjacency matrix of the resulting graph is given by:
7388 *
97a7142f 7389 * log_2 n
e9c84cb8
PZ
7390 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
7391 * k = 0
7392 *
7393 * And you'll find that:
7394 *
7395 * A^(log_2 n)_i,j != 0 for all i,j (7)
7396 *
97fb7a0a 7397 * Showing there's indeed a path between every CPU in at most O(log n) steps.
e9c84cb8
PZ
7398 * The task movement gives a factor of O(m), giving a convergence complexity
7399 * of:
7400 *
7401 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
7402 *
7403 *
7404 * WORK CONSERVING
7405 *
7406 * In order to avoid CPUs going idle while there's still work to do, new idle
97fb7a0a 7407 * balancing is more aggressive and has the newly idle CPU iterate up the domain
e9c84cb8
PZ
7408 * tree itself instead of relying on other CPUs to bring it work.
7409 *
7410 * This adds some complexity to both (5) and (8) but it reduces the total idle
7411 * time.
7412 *
7413 * [XXX more?]
7414 *
7415 *
7416 * CGROUPS
7417 *
7418 * Cgroups make a horror show out of (2), instead of a simple sum we get:
7419 *
7420 * s_k,i
7421 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
7422 * S_k
7423 *
7424 * Where
7425 *
7426 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
7427 *
97fb7a0a 7428 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
e9c84cb8
PZ
7429 *
7430 * The big problem is S_k, its a global sum needed to compute a local (W_i)
7431 * property.
7432 *
7433 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7434 * rewrite all of this once again.]
97a7142f 7435 */
bf0f6f24 7436
ed387b78
HS
7437static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7438
0ec8aa00
PZ
7439enum fbq_type { regular, remote, all };
7440
0b0695f2 7441/*
a9723389
VG
7442 * 'group_type' describes the group of CPUs at the moment of load balancing.
7443 *
0b0695f2 7444 * The enum is ordered by pulling priority, with the group with lowest priority
a9723389
VG
7445 * first so the group_type can simply be compared when selecting the busiest
7446 * group. See update_sd_pick_busiest().
0b0695f2 7447 */
3b1baa64 7448enum group_type {
a9723389 7449 /* The group has spare capacity that can be used to run more tasks. */
0b0695f2 7450 group_has_spare = 0,
a9723389
VG
7451 /*
7452 * The group is fully used and the tasks don't compete for more CPU
7453 * cycles. Nevertheless, some tasks might wait before running.
7454 */
0b0695f2 7455 group_fully_busy,
a9723389
VG
7456 /*
7457 * SD_ASYM_CPUCAPACITY only: One task doesn't fit with CPU's capacity
7458 * and must be migrated to a more powerful CPU.
7459 */
3b1baa64 7460 group_misfit_task,
a9723389
VG
7461 /*
7462 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
7463 * and the task should be migrated to it instead of running on the
7464 * current CPU.
7465 */
0b0695f2 7466 group_asym_packing,
a9723389
VG
7467 /*
7468 * The tasks' affinity constraints previously prevented the scheduler
7469 * from balancing the load across the system.
7470 */
3b1baa64 7471 group_imbalanced,
a9723389
VG
7472 /*
7473 * The CPU is overloaded and can't provide expected CPU cycles to all
7474 * tasks.
7475 */
0b0695f2
VG
7476 group_overloaded
7477};
7478
7479enum migration_type {
7480 migrate_load = 0,
7481 migrate_util,
7482 migrate_task,
7483 migrate_misfit
3b1baa64
MR
7484};
7485
ddcdf6e7 7486#define LBF_ALL_PINNED 0x01
367456c7 7487#define LBF_NEED_BREAK 0x02
6263322c
PZ
7488#define LBF_DST_PINNED 0x04
7489#define LBF_SOME_PINNED 0x08
23fb06d9 7490#define LBF_ACTIVE_LB 0x10
ddcdf6e7
PZ
7491
7492struct lb_env {
7493 struct sched_domain *sd;
7494
ddcdf6e7 7495 struct rq *src_rq;
85c1e7da 7496 int src_cpu;
ddcdf6e7
PZ
7497
7498 int dst_cpu;
7499 struct rq *dst_rq;
7500
88b8dac0
SV
7501 struct cpumask *dst_grpmask;
7502 int new_dst_cpu;
ddcdf6e7 7503 enum cpu_idle_type idle;
bd939f45 7504 long imbalance;
b9403130
MW
7505 /* The set of CPUs under consideration for load-balancing */
7506 struct cpumask *cpus;
7507
ddcdf6e7 7508 unsigned int flags;
367456c7
PZ
7509
7510 unsigned int loop;
7511 unsigned int loop_break;
7512 unsigned int loop_max;
0ec8aa00
PZ
7513
7514 enum fbq_type fbq_type;
0b0695f2 7515 enum migration_type migration_type;
163122b7 7516 struct list_head tasks;
ddcdf6e7
PZ
7517};
7518
029632fb
PZ
7519/*
7520 * Is this task likely cache-hot:
7521 */
5d5e2b1b 7522static int task_hot(struct task_struct *p, struct lb_env *env)
029632fb
PZ
7523{
7524 s64 delta;
7525
5cb9eaa3 7526 lockdep_assert_rq_held(env->src_rq);
e5673f28 7527
029632fb
PZ
7528 if (p->sched_class != &fair_sched_class)
7529 return 0;
7530
1da1843f 7531 if (unlikely(task_has_idle_policy(p)))
029632fb
PZ
7532 return 0;
7533
ec73240b
JD
7534 /* SMT siblings share cache */
7535 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
7536 return 0;
7537
029632fb
PZ
7538 /*
7539 * Buddy candidates are cache hot:
7540 */
5d5e2b1b 7541 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
029632fb
PZ
7542 (&p->se == cfs_rq_of(&p->se)->next ||
7543 &p->se == cfs_rq_of(&p->se)->last))
7544 return 1;
7545
7546 if (sysctl_sched_migration_cost == -1)
7547 return 1;
97886d9d
AL
7548
7549 /*
7550 * Don't migrate task if the task's cookie does not match
7551 * with the destination CPU's core cookie.
7552 */
7553 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
7554 return 1;
7555
029632fb
PZ
7556 if (sysctl_sched_migration_cost == 0)
7557 return 0;
7558
5d5e2b1b 7559 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
029632fb
PZ
7560
7561 return delta < (s64)sysctl_sched_migration_cost;
7562}
7563
3a7053b3 7564#ifdef CONFIG_NUMA_BALANCING
c1ceac62 7565/*
2a1ed24c
SD
7566 * Returns 1, if task migration degrades locality
7567 * Returns 0, if task migration improves locality i.e migration preferred.
7568 * Returns -1, if task migration is not affected by locality.
c1ceac62 7569 */
2a1ed24c 7570static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
3a7053b3 7571{
b1ad065e 7572 struct numa_group *numa_group = rcu_dereference(p->numa_group);
f35678b6
SD
7573 unsigned long src_weight, dst_weight;
7574 int src_nid, dst_nid, dist;
3a7053b3 7575
2a595721 7576 if (!static_branch_likely(&sched_numa_balancing))
2a1ed24c
SD
7577 return -1;
7578
c3b9bc5b 7579 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
2a1ed24c 7580 return -1;
7a0f3083
MG
7581
7582 src_nid = cpu_to_node(env->src_cpu);
7583 dst_nid = cpu_to_node(env->dst_cpu);
7584
83e1d2cd 7585 if (src_nid == dst_nid)
2a1ed24c 7586 return -1;
7a0f3083 7587
2a1ed24c
SD
7588 /* Migrating away from the preferred node is always bad. */
7589 if (src_nid == p->numa_preferred_nid) {
7590 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7591 return 1;
7592 else
7593 return -1;
7594 }
b1ad065e 7595
c1ceac62
RR
7596 /* Encourage migration to the preferred node. */
7597 if (dst_nid == p->numa_preferred_nid)
2a1ed24c 7598 return 0;
b1ad065e 7599
739294fb 7600 /* Leaving a core idle is often worse than degrading locality. */
f35678b6 7601 if (env->idle == CPU_IDLE)
739294fb
RR
7602 return -1;
7603
f35678b6 7604 dist = node_distance(src_nid, dst_nid);
c1ceac62 7605 if (numa_group) {
f35678b6
SD
7606 src_weight = group_weight(p, src_nid, dist);
7607 dst_weight = group_weight(p, dst_nid, dist);
c1ceac62 7608 } else {
f35678b6
SD
7609 src_weight = task_weight(p, src_nid, dist);
7610 dst_weight = task_weight(p, dst_nid, dist);
b1ad065e
RR
7611 }
7612
f35678b6 7613 return dst_weight < src_weight;
7a0f3083
MG
7614}
7615
3a7053b3 7616#else
2a1ed24c 7617static inline int migrate_degrades_locality(struct task_struct *p,
3a7053b3
MG
7618 struct lb_env *env)
7619{
2a1ed24c 7620 return -1;
7a0f3083 7621}
3a7053b3
MG
7622#endif
7623
1e3c88bd
PZ
7624/*
7625 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7626 */
7627static
8e45cb54 7628int can_migrate_task(struct task_struct *p, struct lb_env *env)
1e3c88bd 7629{
2a1ed24c 7630 int tsk_cache_hot;
e5673f28 7631
5cb9eaa3 7632 lockdep_assert_rq_held(env->src_rq);
e5673f28 7633
1e3c88bd
PZ
7634 /*
7635 * We do not migrate tasks that are:
d3198084 7636 * 1) throttled_lb_pair, or
3bd37062 7637 * 2) cannot be migrated to this CPU due to cpus_ptr, or
d3198084
JK
7638 * 3) running (obviously), or
7639 * 4) are cache-hot on their current CPU.
1e3c88bd 7640 */
d3198084
JK
7641 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7642 return 0;
7643
9bcb959d 7644 /* Disregard pcpu kthreads; they are where they need to be. */
3a7956e2 7645 if (kthread_is_per_cpu(p))
9bcb959d
LC
7646 return 0;
7647
3bd37062 7648 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
e02e60c1 7649 int cpu;
88b8dac0 7650
ae92882e 7651 schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
88b8dac0 7652
6263322c
PZ
7653 env->flags |= LBF_SOME_PINNED;
7654
88b8dac0 7655 /*
97fb7a0a 7656 * Remember if this task can be migrated to any other CPU in
88b8dac0
SV
7657 * our sched_group. We may want to revisit it if we couldn't
7658 * meet load balance goals by pulling other tasks on src_cpu.
7659 *
23fb06d9
VS
7660 * Avoid computing new_dst_cpu
7661 * - for NEWLY_IDLE
7662 * - if we have already computed one in current iteration
7663 * - if it's an active balance
88b8dac0 7664 */
23fb06d9
VS
7665 if (env->idle == CPU_NEWLY_IDLE ||
7666 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
88b8dac0
SV
7667 return 0;
7668
97fb7a0a 7669 /* Prevent to re-select dst_cpu via env's CPUs: */
e02e60c1 7670 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
3bd37062 7671 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
6263322c 7672 env->flags |= LBF_DST_PINNED;
e02e60c1
JK
7673 env->new_dst_cpu = cpu;
7674 break;
7675 }
88b8dac0 7676 }
e02e60c1 7677
1e3c88bd
PZ
7678 return 0;
7679 }
88b8dac0 7680
3b03706f 7681 /* Record that we found at least one task that could run on dst_cpu */
8e45cb54 7682 env->flags &= ~LBF_ALL_PINNED;
1e3c88bd 7683
ddcdf6e7 7684 if (task_running(env->src_rq, p)) {
ae92882e 7685 schedstat_inc(p->se.statistics.nr_failed_migrations_running);
1e3c88bd
PZ
7686 return 0;
7687 }
7688
7689 /*
7690 * Aggressive migration if:
23fb06d9
VS
7691 * 1) active balance
7692 * 2) destination numa is preferred
7693 * 3) task is cache cold, or
7694 * 4) too many balance attempts have failed.
1e3c88bd 7695 */
23fb06d9
VS
7696 if (env->flags & LBF_ACTIVE_LB)
7697 return 1;
7698
2a1ed24c
SD
7699 tsk_cache_hot = migrate_degrades_locality(p, env);
7700 if (tsk_cache_hot == -1)
7701 tsk_cache_hot = task_hot(p, env);
3a7053b3 7702
2a1ed24c 7703 if (tsk_cache_hot <= 0 ||
7a96c231 7704 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
2a1ed24c 7705 if (tsk_cache_hot == 1) {
ae92882e
JP
7706 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
7707 schedstat_inc(p->se.statistics.nr_forced_migrations);
3a7053b3 7708 }
1e3c88bd
PZ
7709 return 1;
7710 }
7711
ae92882e 7712 schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
4e2dcb73 7713 return 0;
1e3c88bd
PZ
7714}
7715
897c395f 7716/*
163122b7
KT
7717 * detach_task() -- detach the task for the migration specified in env
7718 */
7719static void detach_task(struct task_struct *p, struct lb_env *env)
7720{
5cb9eaa3 7721 lockdep_assert_rq_held(env->src_rq);
163122b7 7722
5704ac0a 7723 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
163122b7
KT
7724 set_task_cpu(p, env->dst_cpu);
7725}
7726
897c395f 7727/*
e5673f28 7728 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
897c395f 7729 * part of active balancing operations within "domain".
897c395f 7730 *
e5673f28 7731 * Returns a task if successful and NULL otherwise.
897c395f 7732 */
e5673f28 7733static struct task_struct *detach_one_task(struct lb_env *env)
897c395f 7734{
93824900 7735 struct task_struct *p;
897c395f 7736
5cb9eaa3 7737 lockdep_assert_rq_held(env->src_rq);
e5673f28 7738
93824900
UR
7739 list_for_each_entry_reverse(p,
7740 &env->src_rq->cfs_tasks, se.group_node) {
367456c7
PZ
7741 if (!can_migrate_task(p, env))
7742 continue;
897c395f 7743
163122b7 7744 detach_task(p, env);
e5673f28 7745
367456c7 7746 /*
e5673f28 7747 * Right now, this is only the second place where
163122b7 7748 * lb_gained[env->idle] is updated (other is detach_tasks)
e5673f28 7749 * so we can safely collect stats here rather than
163122b7 7750 * inside detach_tasks().
367456c7 7751 */
ae92882e 7752 schedstat_inc(env->sd->lb_gained[env->idle]);
e5673f28 7753 return p;
897c395f 7754 }
e5673f28 7755 return NULL;
897c395f
PZ
7756}
7757
eb95308e
PZ
7758static const unsigned int sched_nr_migrate_break = 32;
7759
5d6523eb 7760/*
0b0695f2 7761 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
163122b7 7762 * busiest_rq, as part of a balancing operation within domain "sd".
5d6523eb 7763 *
163122b7 7764 * Returns number of detached tasks if successful and 0 otherwise.
5d6523eb 7765 */
163122b7 7766static int detach_tasks(struct lb_env *env)
1e3c88bd 7767{
5d6523eb 7768 struct list_head *tasks = &env->src_rq->cfs_tasks;
0b0695f2 7769 unsigned long util, load;
5d6523eb 7770 struct task_struct *p;
163122b7
KT
7771 int detached = 0;
7772
5cb9eaa3 7773 lockdep_assert_rq_held(env->src_rq);
1e3c88bd 7774
acb4decc
AL
7775 /*
7776 * Source run queue has been emptied by another CPU, clear
7777 * LBF_ALL_PINNED flag as we will not test any task.
7778 */
7779 if (env->src_rq->nr_running <= 1) {
7780 env->flags &= ~LBF_ALL_PINNED;
7781 return 0;
7782 }
7783
bd939f45 7784 if (env->imbalance <= 0)
5d6523eb 7785 return 0;
1e3c88bd 7786
5d6523eb 7787 while (!list_empty(tasks)) {
985d3a4c
YD
7788 /*
7789 * We don't want to steal all, otherwise we may be treated likewise,
7790 * which could at worst lead to a livelock crash.
7791 */
7792 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
7793 break;
7794
93824900 7795 p = list_last_entry(tasks, struct task_struct, se.group_node);
1e3c88bd 7796
367456c7
PZ
7797 env->loop++;
7798 /* We've more or less seen every task there is, call it quits */
5d6523eb 7799 if (env->loop > env->loop_max)
367456c7 7800 break;
5d6523eb
PZ
7801
7802 /* take a breather every nr_migrate tasks */
367456c7 7803 if (env->loop > env->loop_break) {
eb95308e 7804 env->loop_break += sched_nr_migrate_break;
8e45cb54 7805 env->flags |= LBF_NEED_BREAK;
ee00e66f 7806 break;
a195f004 7807 }
1e3c88bd 7808
d3198084 7809 if (!can_migrate_task(p, env))
367456c7
PZ
7810 goto next;
7811
0b0695f2
VG
7812 switch (env->migration_type) {
7813 case migrate_load:
01cfcde9
VG
7814 /*
7815 * Depending of the number of CPUs and tasks and the
7816 * cgroup hierarchy, task_h_load() can return a null
7817 * value. Make sure that env->imbalance decreases
7818 * otherwise detach_tasks() will stop only after
7819 * detaching up to loop_max tasks.
7820 */
7821 load = max_t(unsigned long, task_h_load(p), 1);
5d6523eb 7822
0b0695f2
VG
7823 if (sched_feat(LB_MIN) &&
7824 load < 16 && !env->sd->nr_balance_failed)
7825 goto next;
367456c7 7826
6cf82d55
VG
7827 /*
7828 * Make sure that we don't migrate too much load.
7829 * Nevertheless, let relax the constraint if
7830 * scheduler fails to find a good waiting task to
7831 * migrate.
7832 */
39a2a6eb 7833 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
0b0695f2
VG
7834 goto next;
7835
7836 env->imbalance -= load;
7837 break;
7838
7839 case migrate_util:
7840 util = task_util_est(p);
7841
7842 if (util > env->imbalance)
7843 goto next;
7844
7845 env->imbalance -= util;
7846 break;
7847
7848 case migrate_task:
7849 env->imbalance--;
7850 break;
7851
7852 case migrate_misfit:
c63be7be
VG
7853 /* This is not a misfit task */
7854 if (task_fits_capacity(p, capacity_of(env->src_cpu)))
0b0695f2
VG
7855 goto next;
7856
7857 env->imbalance = 0;
7858 break;
7859 }
1e3c88bd 7860
163122b7
KT
7861 detach_task(p, env);
7862 list_add(&p->se.group_node, &env->tasks);
7863
7864 detached++;
1e3c88bd 7865
c1a280b6 7866#ifdef CONFIG_PREEMPTION
ee00e66f
PZ
7867 /*
7868 * NEWIDLE balancing is a source of latency, so preemptible
163122b7 7869 * kernels will stop after the first task is detached to minimize
ee00e66f
PZ
7870 * the critical section.
7871 */
5d6523eb 7872 if (env->idle == CPU_NEWLY_IDLE)
ee00e66f 7873 break;
1e3c88bd
PZ
7874#endif
7875
ee00e66f
PZ
7876 /*
7877 * We only want to steal up to the prescribed amount of
0b0695f2 7878 * load/util/tasks.
ee00e66f 7879 */
bd939f45 7880 if (env->imbalance <= 0)
ee00e66f 7881 break;
367456c7
PZ
7882
7883 continue;
7884next:
93824900 7885 list_move(&p->se.group_node, tasks);
1e3c88bd 7886 }
5d6523eb 7887
1e3c88bd 7888 /*
163122b7
KT
7889 * Right now, this is one of only two places we collect this stat
7890 * so we can safely collect detach_one_task() stats here rather
7891 * than inside detach_one_task().
1e3c88bd 7892 */
ae92882e 7893 schedstat_add(env->sd->lb_gained[env->idle], detached);
1e3c88bd 7894
163122b7
KT
7895 return detached;
7896}
7897
7898/*
7899 * attach_task() -- attach the task detached by detach_task() to its new rq.
7900 */
7901static void attach_task(struct rq *rq, struct task_struct *p)
7902{
5cb9eaa3 7903 lockdep_assert_rq_held(rq);
163122b7
KT
7904
7905 BUG_ON(task_rq(p) != rq);
5704ac0a 7906 activate_task(rq, p, ENQUEUE_NOCLOCK);
163122b7
KT
7907 check_preempt_curr(rq, p, 0);
7908}
7909
7910/*
7911 * attach_one_task() -- attaches the task returned from detach_one_task() to
7912 * its new rq.
7913 */
7914static void attach_one_task(struct rq *rq, struct task_struct *p)
7915{
8a8c69c3
PZ
7916 struct rq_flags rf;
7917
7918 rq_lock(rq, &rf);
5704ac0a 7919 update_rq_clock(rq);
163122b7 7920 attach_task(rq, p);
8a8c69c3 7921 rq_unlock(rq, &rf);
163122b7
KT
7922}
7923
7924/*
7925 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
7926 * new rq.
7927 */
7928static void attach_tasks(struct lb_env *env)
7929{
7930 struct list_head *tasks = &env->tasks;
7931 struct task_struct *p;
8a8c69c3 7932 struct rq_flags rf;
163122b7 7933
8a8c69c3 7934 rq_lock(env->dst_rq, &rf);
5704ac0a 7935 update_rq_clock(env->dst_rq);
163122b7
KT
7936
7937 while (!list_empty(tasks)) {
7938 p = list_first_entry(tasks, struct task_struct, se.group_node);
7939 list_del_init(&p->se.group_node);
1e3c88bd 7940
163122b7
KT
7941 attach_task(env->dst_rq, p);
7942 }
7943
8a8c69c3 7944 rq_unlock(env->dst_rq, &rf);
1e3c88bd
PZ
7945}
7946
b0c79224 7947#ifdef CONFIG_NO_HZ_COMMON
1936c53c
VG
7948static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
7949{
7950 if (cfs_rq->avg.load_avg)
7951 return true;
7952
7953 if (cfs_rq->avg.util_avg)
7954 return true;
7955
7956 return false;
7957}
7958
91c27493 7959static inline bool others_have_blocked(struct rq *rq)
371bf427
VG
7960{
7961 if (READ_ONCE(rq->avg_rt.util_avg))
7962 return true;
7963
3727e0e1
VG
7964 if (READ_ONCE(rq->avg_dl.util_avg))
7965 return true;
7966
b4eccf5f
TG
7967 if (thermal_load_avg(rq))
7968 return true;
7969
11d4afd4 7970#ifdef CONFIG_HAVE_SCHED_AVG_IRQ
91c27493
VG
7971 if (READ_ONCE(rq->avg_irq.util_avg))
7972 return true;
7973#endif
7974
371bf427
VG
7975 return false;
7976}
7977
39b6a429 7978static inline void update_blocked_load_tick(struct rq *rq)
b0c79224 7979{
39b6a429
VG
7980 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
7981}
b0c79224 7982
39b6a429
VG
7983static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
7984{
b0c79224
VS
7985 if (!has_blocked)
7986 rq->has_blocked_load = 0;
7987}
7988#else
7989static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
7990static inline bool others_have_blocked(struct rq *rq) { return false; }
39b6a429 7991static inline void update_blocked_load_tick(struct rq *rq) {}
b0c79224
VS
7992static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
7993#endif
7994
bef69dd8
VG
7995static bool __update_blocked_others(struct rq *rq, bool *done)
7996{
7997 const struct sched_class *curr_class;
7998 u64 now = rq_clock_pelt(rq);
b4eccf5f 7999 unsigned long thermal_pressure;
bef69dd8
VG
8000 bool decayed;
8001
8002 /*
8003 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
8004 * DL and IRQ signals have been updated before updating CFS.
8005 */
8006 curr_class = rq->curr->sched_class;
8007
b4eccf5f
TG
8008 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
8009
bef69dd8
VG
8010 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
8011 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
05289b90 8012 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
bef69dd8
VG
8013 update_irq_load_avg(rq, 0);
8014
8015 if (others_have_blocked(rq))
8016 *done = false;
8017
8018 return decayed;
8019}
8020
1936c53c
VG
8021#ifdef CONFIG_FAIR_GROUP_SCHED
8022
039ae8bc
VG
8023static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
8024{
8025 if (cfs_rq->load.weight)
8026 return false;
8027
8028 if (cfs_rq->avg.load_sum)
8029 return false;
8030
8031 if (cfs_rq->avg.util_sum)
8032 return false;
8033
9f683953
VG
8034 if (cfs_rq->avg.runnable_sum)
8035 return false;
8036
9e077b52
VG
8037 /*
8038 * _avg must be null when _sum are null because _avg = _sum / divider
8039 * Make sure that rounding and/or propagation of PELT values never
8040 * break this.
8041 */
8042 SCHED_WARN_ON(cfs_rq->avg.load_avg ||
8043 cfs_rq->avg.util_avg ||
8044 cfs_rq->avg.runnable_avg);
8045
039ae8bc
VG
8046 return true;
8047}
8048
bef69dd8 8049static bool __update_blocked_fair(struct rq *rq, bool *done)
9e3081ca 8050{
039ae8bc 8051 struct cfs_rq *cfs_rq, *pos;
bef69dd8
VG
8052 bool decayed = false;
8053 int cpu = cpu_of(rq);
b90f7c9d 8054
9763b67f
PZ
8055 /*
8056 * Iterates the task_group tree in a bottom up fashion, see
8057 * list_add_leaf_cfs_rq() for details.
8058 */
039ae8bc 8059 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
bc427898
VG
8060 struct sched_entity *se;
8061
bef69dd8 8062 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
fe749158 8063 update_tg_load_avg(cfs_rq);
4e516076 8064
bef69dd8
VG
8065 if (cfs_rq == &rq->cfs)
8066 decayed = true;
8067 }
8068
bc427898
VG
8069 /* Propagate pending load changes to the parent, if any: */
8070 se = cfs_rq->tg->se[cpu];
8071 if (se && !skip_blocked_update(se))
02da26ad 8072 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
a9e7f654 8073
039ae8bc
VG
8074 /*
8075 * There can be a lot of idle CPU cgroups. Don't let fully
8076 * decayed cfs_rqs linger on the list.
8077 */
8078 if (cfs_rq_is_decayed(cfs_rq))
8079 list_del_leaf_cfs_rq(cfs_rq);
8080
1936c53c
VG
8081 /* Don't need periodic decay once load/util_avg are null */
8082 if (cfs_rq_has_blocked(cfs_rq))
bef69dd8 8083 *done = false;
9d89c257 8084 }
12b04875 8085
bef69dd8 8086 return decayed;
9e3081ca
PZ
8087}
8088
9763b67f 8089/*
68520796 8090 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9763b67f
PZ
8091 * This needs to be done in a top-down fashion because the load of a child
8092 * group is a fraction of its parents load.
8093 */
68520796 8094static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9763b67f 8095{
68520796
VD
8096 struct rq *rq = rq_of(cfs_rq);
8097 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
a35b6466 8098 unsigned long now = jiffies;
68520796 8099 unsigned long load;
a35b6466 8100
68520796 8101 if (cfs_rq->last_h_load_update == now)
a35b6466
PZ
8102 return;
8103
0e9f0245 8104 WRITE_ONCE(cfs_rq->h_load_next, NULL);
68520796
VD
8105 for_each_sched_entity(se) {
8106 cfs_rq = cfs_rq_of(se);
0e9f0245 8107 WRITE_ONCE(cfs_rq->h_load_next, se);
68520796
VD
8108 if (cfs_rq->last_h_load_update == now)
8109 break;
8110 }
a35b6466 8111
68520796 8112 if (!se) {
7ea241af 8113 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
68520796
VD
8114 cfs_rq->last_h_load_update = now;
8115 }
8116
0e9f0245 8117 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
68520796 8118 load = cfs_rq->h_load;
7ea241af
YD
8119 load = div64_ul(load * se->avg.load_avg,
8120 cfs_rq_load_avg(cfs_rq) + 1);
68520796
VD
8121 cfs_rq = group_cfs_rq(se);
8122 cfs_rq->h_load = load;
8123 cfs_rq->last_h_load_update = now;
8124 }
9763b67f
PZ
8125}
8126
367456c7 8127static unsigned long task_h_load(struct task_struct *p)
230059de 8128{
367456c7 8129 struct cfs_rq *cfs_rq = task_cfs_rq(p);
230059de 8130
68520796 8131 update_cfs_rq_h_load(cfs_rq);
9d89c257 8132 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
7ea241af 8133 cfs_rq_load_avg(cfs_rq) + 1);
230059de
PZ
8134}
8135#else
bef69dd8 8136static bool __update_blocked_fair(struct rq *rq, bool *done)
9e3081ca 8137{
6c1d47c0 8138 struct cfs_rq *cfs_rq = &rq->cfs;
bef69dd8 8139 bool decayed;
b90f7c9d 8140
bef69dd8
VG
8141 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
8142 if (cfs_rq_has_blocked(cfs_rq))
8143 *done = false;
b90f7c9d 8144
bef69dd8 8145 return decayed;
9e3081ca
PZ
8146}
8147
367456c7 8148static unsigned long task_h_load(struct task_struct *p)
1e3c88bd 8149{
9d89c257 8150 return p->se.avg.load_avg;
1e3c88bd 8151}
230059de 8152#endif
1e3c88bd 8153
bef69dd8
VG
8154static void update_blocked_averages(int cpu)
8155{
8156 bool decayed = false, done = true;
8157 struct rq *rq = cpu_rq(cpu);
8158 struct rq_flags rf;
8159
8160 rq_lock_irqsave(rq, &rf);
39b6a429 8161 update_blocked_load_tick(rq);
bef69dd8
VG
8162 update_rq_clock(rq);
8163
8164 decayed |= __update_blocked_others(rq, &done);
8165 decayed |= __update_blocked_fair(rq, &done);
8166
8167 update_blocked_load_status(rq, !done);
8168 if (decayed)
8169 cpufreq_update_util(rq, 0);
8170 rq_unlock_irqrestore(rq, &rf);
8171}
8172
1e3c88bd 8173/********** Helpers for find_busiest_group ************************/
caeb178c 8174
1e3c88bd
PZ
8175/*
8176 * sg_lb_stats - stats of a sched_group required for load_balancing
8177 */
8178struct sg_lb_stats {
8179 unsigned long avg_load; /*Avg load across the CPUs of the group */
8180 unsigned long group_load; /* Total load over the CPUs of the group */
63b2ca30 8181 unsigned long group_capacity;
070f5e86
VG
8182 unsigned long group_util; /* Total utilization over the CPUs of the group */
8183 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
5e23e474 8184 unsigned int sum_nr_running; /* Nr of tasks running in the group */
a3498347 8185 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
147c5fc2
PZ
8186 unsigned int idle_cpus;
8187 unsigned int group_weight;
caeb178c 8188 enum group_type group_type;
490ba971 8189 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
3b1baa64 8190 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
0ec8aa00
PZ
8191#ifdef CONFIG_NUMA_BALANCING
8192 unsigned int nr_numa_running;
8193 unsigned int nr_preferred_running;
8194#endif
1e3c88bd
PZ
8195};
8196
56cf515b
JK
8197/*
8198 * sd_lb_stats - Structure to store the statistics of a sched_domain
8199 * during load balancing.
8200 */
8201struct sd_lb_stats {
8202 struct sched_group *busiest; /* Busiest group in this sd */
8203 struct sched_group *local; /* Local group in this sd */
8204 unsigned long total_load; /* Total load of all groups in sd */
63b2ca30 8205 unsigned long total_capacity; /* Total capacity of all groups in sd */
56cf515b 8206 unsigned long avg_load; /* Average load across all groups in sd */
0b0695f2 8207 unsigned int prefer_sibling; /* tasks should go to sibling first */
56cf515b 8208
56cf515b 8209 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
147c5fc2 8210 struct sg_lb_stats local_stat; /* Statistics of the local group */
56cf515b
JK
8211};
8212
147c5fc2
PZ
8213static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
8214{
8215 /*
8216 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
8217 * local_stat because update_sg_lb_stats() does a full clear/assignment.
0b0695f2
VG
8218 * We must however set busiest_stat::group_type and
8219 * busiest_stat::idle_cpus to the worst busiest group because
8220 * update_sd_pick_busiest() reads these before assignment.
147c5fc2
PZ
8221 */
8222 *sds = (struct sd_lb_stats){
8223 .busiest = NULL,
8224 .local = NULL,
8225 .total_load = 0UL,
63b2ca30 8226 .total_capacity = 0UL,
147c5fc2 8227 .busiest_stat = {
0b0695f2
VG
8228 .idle_cpus = UINT_MAX,
8229 .group_type = group_has_spare,
147c5fc2
PZ
8230 },
8231 };
8232}
8233
1ca2034e 8234static unsigned long scale_rt_capacity(int cpu)
1e3c88bd
PZ
8235{
8236 struct rq *rq = cpu_rq(cpu);
8ec59c0f 8237 unsigned long max = arch_scale_cpu_capacity(cpu);
523e979d 8238 unsigned long used, free;
523e979d 8239 unsigned long irq;
b654f7de 8240
2e62c474 8241 irq = cpu_util_irq(rq);
cadefd3d 8242
523e979d
VG
8243 if (unlikely(irq >= max))
8244 return 1;
aa483808 8245
467b7d01
TG
8246 /*
8247 * avg_rt.util_avg and avg_dl.util_avg track binary signals
8248 * (running and not running) with weights 0 and 1024 respectively.
8249 * avg_thermal.load_avg tracks thermal pressure and the weighted
8250 * average uses the actual delta max capacity(load).
8251 */
523e979d
VG
8252 used = READ_ONCE(rq->avg_rt.util_avg);
8253 used += READ_ONCE(rq->avg_dl.util_avg);
467b7d01 8254 used += thermal_load_avg(rq);
1e3c88bd 8255
523e979d
VG
8256 if (unlikely(used >= max))
8257 return 1;
1e3c88bd 8258
523e979d 8259 free = max - used;
2e62c474
VG
8260
8261 return scale_irq_capacity(free, irq, max);
1e3c88bd
PZ
8262}
8263
ced549fa 8264static void update_cpu_capacity(struct sched_domain *sd, int cpu)
1e3c88bd 8265{
1ca2034e 8266 unsigned long capacity = scale_rt_capacity(cpu);
1e3c88bd
PZ
8267 struct sched_group *sdg = sd->groups;
8268
8ec59c0f 8269 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
1e3c88bd 8270
ced549fa
NP
8271 if (!capacity)
8272 capacity = 1;
1e3c88bd 8273
ced549fa 8274 cpu_rq(cpu)->cpu_capacity = capacity;
51cf18c9
VD
8275 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
8276
ced549fa 8277 sdg->sgc->capacity = capacity;
bf475ce0 8278 sdg->sgc->min_capacity = capacity;
e3d6d0cb 8279 sdg->sgc->max_capacity = capacity;
1e3c88bd
PZ
8280}
8281
63b2ca30 8282void update_group_capacity(struct sched_domain *sd, int cpu)
1e3c88bd
PZ
8283{
8284 struct sched_domain *child = sd->child;
8285 struct sched_group *group, *sdg = sd->groups;
e3d6d0cb 8286 unsigned long capacity, min_capacity, max_capacity;
4ec4412e
VG
8287 unsigned long interval;
8288
8289 interval = msecs_to_jiffies(sd->balance_interval);
8290 interval = clamp(interval, 1UL, max_load_balance_interval);
63b2ca30 8291 sdg->sgc->next_update = jiffies + interval;
1e3c88bd
PZ
8292
8293 if (!child) {
ced549fa 8294 update_cpu_capacity(sd, cpu);
1e3c88bd
PZ
8295 return;
8296 }
8297
dc7ff76e 8298 capacity = 0;
bf475ce0 8299 min_capacity = ULONG_MAX;
e3d6d0cb 8300 max_capacity = 0;
1e3c88bd 8301
74a5ce20
PZ
8302 if (child->flags & SD_OVERLAP) {
8303 /*
8304 * SD_OVERLAP domains cannot assume that child groups
8305 * span the current group.
8306 */
8307
ae4df9d6 8308 for_each_cpu(cpu, sched_group_span(sdg)) {
4c58f57f 8309 unsigned long cpu_cap = capacity_of(cpu);
863bffc8 8310
4c58f57f
PL
8311 capacity += cpu_cap;
8312 min_capacity = min(cpu_cap, min_capacity);
8313 max_capacity = max(cpu_cap, max_capacity);
863bffc8 8314 }
74a5ce20
PZ
8315 } else {
8316 /*
8317 * !SD_OVERLAP domains can assume that child groups
8318 * span the current group.
97a7142f 8319 */
74a5ce20
PZ
8320
8321 group = child->groups;
8322 do {
bf475ce0
MR
8323 struct sched_group_capacity *sgc = group->sgc;
8324
8325 capacity += sgc->capacity;
8326 min_capacity = min(sgc->min_capacity, min_capacity);
e3d6d0cb 8327 max_capacity = max(sgc->max_capacity, max_capacity);
74a5ce20
PZ
8328 group = group->next;
8329 } while (group != child->groups);
8330 }
1e3c88bd 8331
63b2ca30 8332 sdg->sgc->capacity = capacity;
bf475ce0 8333 sdg->sgc->min_capacity = min_capacity;
e3d6d0cb 8334 sdg->sgc->max_capacity = max_capacity;
1e3c88bd
PZ
8335}
8336
9d5efe05 8337/*
ea67821b
VG
8338 * Check whether the capacity of the rq has been noticeably reduced by side
8339 * activity. The imbalance_pct is used for the threshold.
8340 * Return true is the capacity is reduced
9d5efe05
SV
8341 */
8342static inline int
ea67821b 8343check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9d5efe05 8344{
ea67821b
VG
8345 return ((rq->cpu_capacity * sd->imbalance_pct) <
8346 (rq->cpu_capacity_orig * 100));
9d5efe05
SV
8347}
8348
a0fe2cf0
VS
8349/*
8350 * Check whether a rq has a misfit task and if it looks like we can actually
8351 * help that task: we can migrate the task to a CPU of higher capacity, or
8352 * the task's current CPU is heavily pressured.
8353 */
8354static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
8355{
8356 return rq->misfit_task_load &&
8357 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
8358 check_cpu_capacity(rq, sd));
8359}
8360
30ce5dab
PZ
8361/*
8362 * Group imbalance indicates (and tries to solve) the problem where balancing
3bd37062 8363 * groups is inadequate due to ->cpus_ptr constraints.
30ce5dab 8364 *
97fb7a0a
IM
8365 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
8366 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
30ce5dab
PZ
8367 * Something like:
8368 *
2b4d5b25
IM
8369 * { 0 1 2 3 } { 4 5 6 7 }
8370 * * * * *
30ce5dab
PZ
8371 *
8372 * If we were to balance group-wise we'd place two tasks in the first group and
8373 * two tasks in the second group. Clearly this is undesired as it will overload
97fb7a0a 8374 * cpu 3 and leave one of the CPUs in the second group unused.
30ce5dab
PZ
8375 *
8376 * The current solution to this issue is detecting the skew in the first group
6263322c
PZ
8377 * by noticing the lower domain failed to reach balance and had difficulty
8378 * moving tasks due to affinity constraints.
30ce5dab
PZ
8379 *
8380 * When this is so detected; this group becomes a candidate for busiest; see
ed1b7732 8381 * update_sd_pick_busiest(). And calculate_imbalance() and
6263322c 8382 * find_busiest_group() avoid some of the usual balance conditions to allow it
30ce5dab
PZ
8383 * to create an effective group imbalance.
8384 *
8385 * This is a somewhat tricky proposition since the next run might not find the
8386 * group imbalance and decide the groups need to be balanced again. A most
8387 * subtle and fragile situation.
8388 */
8389
6263322c 8390static inline int sg_imbalanced(struct sched_group *group)
30ce5dab 8391{
63b2ca30 8392 return group->sgc->imbalance;
30ce5dab
PZ
8393}
8394
b37d9316 8395/*
ea67821b
VG
8396 * group_has_capacity returns true if the group has spare capacity that could
8397 * be used by some tasks.
8398 * We consider that a group has spare capacity if the * number of task is
9e91d61d
DE
8399 * smaller than the number of CPUs or if the utilization is lower than the
8400 * available capacity for CFS tasks.
ea67821b
VG
8401 * For the latter, we use a threshold to stabilize the state, to take into
8402 * account the variance of the tasks' load and to return true if the available
8403 * capacity in meaningful for the load balancer.
8404 * As an example, an available capacity of 1% can appear but it doesn't make
8405 * any benefit for the load balance.
b37d9316 8406 */
ea67821b 8407static inline bool
57abff06 8408group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
b37d9316 8409{
5e23e474 8410 if (sgs->sum_nr_running < sgs->group_weight)
ea67821b 8411 return true;
c61037e9 8412
070f5e86
VG
8413 if ((sgs->group_capacity * imbalance_pct) <
8414 (sgs->group_runnable * 100))
8415 return false;
8416
ea67821b 8417 if ((sgs->group_capacity * 100) >
57abff06 8418 (sgs->group_util * imbalance_pct))
ea67821b 8419 return true;
b37d9316 8420
ea67821b
VG
8421 return false;
8422}
8423
8424/*
8425 * group_is_overloaded returns true if the group has more tasks than it can
8426 * handle.
8427 * group_is_overloaded is not equals to !group_has_capacity because a group
8428 * with the exact right number of tasks, has no more spare capacity but is not
8429 * overloaded so both group_has_capacity and group_is_overloaded return
8430 * false.
8431 */
8432static inline bool
57abff06 8433group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
ea67821b 8434{
5e23e474 8435 if (sgs->sum_nr_running <= sgs->group_weight)
ea67821b 8436 return false;
b37d9316 8437
ea67821b 8438 if ((sgs->group_capacity * 100) <
57abff06 8439 (sgs->group_util * imbalance_pct))
ea67821b 8440 return true;
b37d9316 8441
070f5e86
VG
8442 if ((sgs->group_capacity * imbalance_pct) <
8443 (sgs->group_runnable * 100))
8444 return true;
8445
ea67821b 8446 return false;
b37d9316
PZ
8447}
8448
79a89f92 8449static inline enum
57abff06 8450group_type group_classify(unsigned int imbalance_pct,
0b0695f2 8451 struct sched_group *group,
79a89f92 8452 struct sg_lb_stats *sgs)
caeb178c 8453{
57abff06 8454 if (group_is_overloaded(imbalance_pct, sgs))
caeb178c
RR
8455 return group_overloaded;
8456
8457 if (sg_imbalanced(group))
8458 return group_imbalanced;
8459
0b0695f2
VG
8460 if (sgs->group_asym_packing)
8461 return group_asym_packing;
8462
3b1baa64
MR
8463 if (sgs->group_misfit_task_load)
8464 return group_misfit_task;
8465
57abff06 8466 if (!group_has_capacity(imbalance_pct, sgs))
0b0695f2
VG
8467 return group_fully_busy;
8468
8469 return group_has_spare;
caeb178c
RR
8470}
8471
1e3c88bd
PZ
8472/**
8473 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
cd96891d 8474 * @env: The load balancing environment.
1e3c88bd 8475 * @group: sched_group whose statistics are to be updated.
1e3c88bd 8476 * @sgs: variable to hold the statistics for this group.
630246a0 8477 * @sg_status: Holds flag indicating the status of the sched_group
1e3c88bd 8478 */
bd939f45 8479static inline void update_sg_lb_stats(struct lb_env *env,
630246a0
QP
8480 struct sched_group *group,
8481 struct sg_lb_stats *sgs,
8482 int *sg_status)
1e3c88bd 8483{
0b0695f2 8484 int i, nr_running, local_group;
1e3c88bd 8485
b72ff13c
PZ
8486 memset(sgs, 0, sizeof(*sgs));
8487
0b0695f2
VG
8488 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(group));
8489
ae4df9d6 8490 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
1e3c88bd
PZ
8491 struct rq *rq = cpu_rq(i);
8492
b0fb1eb4 8493 sgs->group_load += cpu_load(rq);
9e91d61d 8494 sgs->group_util += cpu_util(i);
070f5e86 8495 sgs->group_runnable += cpu_runnable(rq);
a3498347 8496 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
4486edd1 8497
a426f99c 8498 nr_running = rq->nr_running;
5e23e474
VG
8499 sgs->sum_nr_running += nr_running;
8500
a426f99c 8501 if (nr_running > 1)
630246a0 8502 *sg_status |= SG_OVERLOAD;
4486edd1 8503
2802bf3c
MR
8504 if (cpu_overutilized(i))
8505 *sg_status |= SG_OVERUTILIZED;
4486edd1 8506
0ec8aa00
PZ
8507#ifdef CONFIG_NUMA_BALANCING
8508 sgs->nr_numa_running += rq->nr_numa_running;
8509 sgs->nr_preferred_running += rq->nr_preferred_running;
8510#endif
a426f99c
WL
8511 /*
8512 * No need to call idle_cpu() if nr_running is not 0
8513 */
0b0695f2 8514 if (!nr_running && idle_cpu(i)) {
aae6d3dd 8515 sgs->idle_cpus++;
0b0695f2
VG
8516 /* Idle cpu can't have misfit task */
8517 continue;
8518 }
8519
8520 if (local_group)
8521 continue;
3b1baa64 8522
0b0695f2 8523 /* Check for a misfit task on the cpu */
3b1baa64 8524 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
757ffdd7 8525 sgs->group_misfit_task_load < rq->misfit_task_load) {
3b1baa64 8526 sgs->group_misfit_task_load = rq->misfit_task_load;
630246a0 8527 *sg_status |= SG_OVERLOAD;
757ffdd7 8528 }
1e3c88bd
PZ
8529 }
8530
0b0695f2
VG
8531 /* Check if dst CPU is idle and preferred to this group */
8532 if (env->sd->flags & SD_ASYM_PACKING &&
8533 env->idle != CPU_NOT_IDLE &&
8534 sgs->sum_h_nr_running &&
8535 sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu)) {
8536 sgs->group_asym_packing = 1;
8537 }
8538
63b2ca30 8539 sgs->group_capacity = group->sgc->capacity;
1e3c88bd 8540
aae6d3dd 8541 sgs->group_weight = group->group_weight;
b37d9316 8542
57abff06 8543 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
0b0695f2
VG
8544
8545 /* Computing avg_load makes sense only when group is overloaded */
8546 if (sgs->group_type == group_overloaded)
8547 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8548 sgs->group_capacity;
1e3c88bd
PZ
8549}
8550
532cb4c4
MN
8551/**
8552 * update_sd_pick_busiest - return 1 on busiest group
cd96891d 8553 * @env: The load balancing environment.
532cb4c4
MN
8554 * @sds: sched_domain statistics
8555 * @sg: sched_group candidate to be checked for being the busiest
b6b12294 8556 * @sgs: sched_group statistics
532cb4c4
MN
8557 *
8558 * Determine if @sg is a busier group than the previously selected
8559 * busiest group.
e69f6186
YB
8560 *
8561 * Return: %true if @sg is a busier group than the previously selected
8562 * busiest group. %false otherwise.
532cb4c4 8563 */
bd939f45 8564static bool update_sd_pick_busiest(struct lb_env *env,
532cb4c4
MN
8565 struct sd_lb_stats *sds,
8566 struct sched_group *sg,
bd939f45 8567 struct sg_lb_stats *sgs)
532cb4c4 8568{
caeb178c 8569 struct sg_lb_stats *busiest = &sds->busiest_stat;
532cb4c4 8570
0b0695f2
VG
8571 /* Make sure that there is at least one task to pull */
8572 if (!sgs->sum_h_nr_running)
8573 return false;
8574
cad68e55
MR
8575 /*
8576 * Don't try to pull misfit tasks we can't help.
8577 * We can use max_capacity here as reduction in capacity on some
8578 * CPUs in the group should either be possible to resolve
8579 * internally or be covered by avg_load imbalance (eventually).
8580 */
8581 if (sgs->group_type == group_misfit_task &&
4aed8aa4 8582 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
0b0695f2 8583 sds->local_stat.group_type != group_has_spare))
cad68e55
MR
8584 return false;
8585
caeb178c 8586 if (sgs->group_type > busiest->group_type)
532cb4c4
MN
8587 return true;
8588
caeb178c
RR
8589 if (sgs->group_type < busiest->group_type)
8590 return false;
8591
9e0994c0 8592 /*
0b0695f2
VG
8593 * The candidate and the current busiest group are the same type of
8594 * group. Let check which one is the busiest according to the type.
9e0994c0 8595 */
9e0994c0 8596
0b0695f2
VG
8597 switch (sgs->group_type) {
8598 case group_overloaded:
8599 /* Select the overloaded group with highest avg_load. */
8600 if (sgs->avg_load <= busiest->avg_load)
8601 return false;
8602 break;
8603
8604 case group_imbalanced:
8605 /*
8606 * Select the 1st imbalanced group as we don't have any way to
8607 * choose one more than another.
8608 */
9e0994c0
MR
8609 return false;
8610
0b0695f2
VG
8611 case group_asym_packing:
8612 /* Prefer to move from lowest priority CPU's work */
8613 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
8614 return false;
8615 break;
532cb4c4 8616
0b0695f2
VG
8617 case group_misfit_task:
8618 /*
8619 * If we have more than one misfit sg go with the biggest
8620 * misfit.
8621 */
8622 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
8623 return false;
8624 break;
532cb4c4 8625
0b0695f2
VG
8626 case group_fully_busy:
8627 /*
8628 * Select the fully busy group with highest avg_load. In
8629 * theory, there is no need to pull task from such kind of
8630 * group because tasks have all compute capacity that they need
8631 * but we can still improve the overall throughput by reducing
8632 * contention when accessing shared HW resources.
8633 *
8634 * XXX for now avg_load is not computed and always 0 so we
8635 * select the 1st one.
8636 */
8637 if (sgs->avg_load <= busiest->avg_load)
8638 return false;
8639 break;
8640
8641 case group_has_spare:
8642 /*
5f68eb19
VG
8643 * Select not overloaded group with lowest number of idle cpus
8644 * and highest number of running tasks. We could also compare
8645 * the spare capacity which is more stable but it can end up
8646 * that the group has less spare capacity but finally more idle
0b0695f2
VG
8647 * CPUs which means less opportunity to pull tasks.
8648 */
5f68eb19 8649 if (sgs->idle_cpus > busiest->idle_cpus)
0b0695f2 8650 return false;
5f68eb19
VG
8651 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
8652 (sgs->sum_nr_running <= busiest->sum_nr_running))
8653 return false;
8654
0b0695f2 8655 break;
532cb4c4
MN
8656 }
8657
0b0695f2
VG
8658 /*
8659 * Candidate sg has no more than one task per CPU and has higher
8660 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
8661 * throughput. Maximize throughput, power/energy consequences are not
8662 * considered.
8663 */
8664 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
8665 (sgs->group_type <= group_fully_busy) &&
4aed8aa4 8666 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
0b0695f2
VG
8667 return false;
8668
8669 return true;
532cb4c4
MN
8670}
8671
0ec8aa00
PZ
8672#ifdef CONFIG_NUMA_BALANCING
8673static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8674{
a3498347 8675 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
0ec8aa00 8676 return regular;
a3498347 8677 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
0ec8aa00
PZ
8678 return remote;
8679 return all;
8680}
8681
8682static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8683{
8684 if (rq->nr_running > rq->nr_numa_running)
8685 return regular;
8686 if (rq->nr_running > rq->nr_preferred_running)
8687 return remote;
8688 return all;
8689}
8690#else
8691static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8692{
8693 return all;
8694}
8695
8696static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8697{
8698 return regular;
8699}
8700#endif /* CONFIG_NUMA_BALANCING */
8701
57abff06
VG
8702
8703struct sg_lb_stats;
8704
3318544b
VG
8705/*
8706 * task_running_on_cpu - return 1 if @p is running on @cpu.
8707 */
8708
8709static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
8710{
8711 /* Task has no contribution or is new */
8712 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8713 return 0;
8714
8715 if (task_on_rq_queued(p))
8716 return 1;
8717
8718 return 0;
8719}
8720
8721/**
8722 * idle_cpu_without - would a given CPU be idle without p ?
8723 * @cpu: the processor on which idleness is tested.
8724 * @p: task which should be ignored.
8725 *
8726 * Return: 1 if the CPU would be idle. 0 otherwise.
8727 */
8728static int idle_cpu_without(int cpu, struct task_struct *p)
8729{
8730 struct rq *rq = cpu_rq(cpu);
8731
8732 if (rq->curr != rq->idle && rq->curr != p)
8733 return 0;
8734
8735 /*
8736 * rq->nr_running can't be used but an updated version without the
8737 * impact of p on cpu must be used instead. The updated nr_running
8738 * be computed and tested before calling idle_cpu_without().
8739 */
8740
8741#ifdef CONFIG_SMP
126c2092 8742 if (rq->ttwu_pending)
3318544b
VG
8743 return 0;
8744#endif
8745
8746 return 1;
8747}
8748
57abff06
VG
8749/*
8750 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
3318544b 8751 * @sd: The sched_domain level to look for idlest group.
57abff06
VG
8752 * @group: sched_group whose statistics are to be updated.
8753 * @sgs: variable to hold the statistics for this group.
3318544b 8754 * @p: The task for which we look for the idlest group/CPU.
57abff06
VG
8755 */
8756static inline void update_sg_wakeup_stats(struct sched_domain *sd,
8757 struct sched_group *group,
8758 struct sg_lb_stats *sgs,
8759 struct task_struct *p)
8760{
8761 int i, nr_running;
8762
8763 memset(sgs, 0, sizeof(*sgs));
8764
8765 for_each_cpu(i, sched_group_span(group)) {
8766 struct rq *rq = cpu_rq(i);
3318544b 8767 unsigned int local;
57abff06 8768
3318544b 8769 sgs->group_load += cpu_load_without(rq, p);
57abff06 8770 sgs->group_util += cpu_util_without(i, p);
070f5e86 8771 sgs->group_runnable += cpu_runnable_without(rq, p);
3318544b
VG
8772 local = task_running_on_cpu(i, p);
8773 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
57abff06 8774
3318544b 8775 nr_running = rq->nr_running - local;
57abff06
VG
8776 sgs->sum_nr_running += nr_running;
8777
8778 /*
3318544b 8779 * No need to call idle_cpu_without() if nr_running is not 0
57abff06 8780 */
3318544b 8781 if (!nr_running && idle_cpu_without(i, p))
57abff06
VG
8782 sgs->idle_cpus++;
8783
57abff06
VG
8784 }
8785
8786 /* Check if task fits in the group */
8787 if (sd->flags & SD_ASYM_CPUCAPACITY &&
8788 !task_fits_capacity(p, group->sgc->max_capacity)) {
8789 sgs->group_misfit_task_load = 1;
8790 }
8791
8792 sgs->group_capacity = group->sgc->capacity;
8793
289de359
VG
8794 sgs->group_weight = group->group_weight;
8795
57abff06
VG
8796 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
8797
8798 /*
8799 * Computing avg_load makes sense only when group is fully busy or
8800 * overloaded
8801 */
6c8116c9
TZ
8802 if (sgs->group_type == group_fully_busy ||
8803 sgs->group_type == group_overloaded)
57abff06
VG
8804 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8805 sgs->group_capacity;
8806}
8807
8808static bool update_pick_idlest(struct sched_group *idlest,
8809 struct sg_lb_stats *idlest_sgs,
8810 struct sched_group *group,
8811 struct sg_lb_stats *sgs)
8812{
8813 if (sgs->group_type < idlest_sgs->group_type)
8814 return true;
8815
8816 if (sgs->group_type > idlest_sgs->group_type)
8817 return false;
8818
8819 /*
8820 * The candidate and the current idlest group are the same type of
8821 * group. Let check which one is the idlest according to the type.
8822 */
8823
8824 switch (sgs->group_type) {
8825 case group_overloaded:
8826 case group_fully_busy:
8827 /* Select the group with lowest avg_load. */
8828 if (idlest_sgs->avg_load <= sgs->avg_load)
8829 return false;
8830 break;
8831
8832 case group_imbalanced:
8833 case group_asym_packing:
8834 /* Those types are not used in the slow wakeup path */
8835 return false;
8836
8837 case group_misfit_task:
8838 /* Select group with the highest max capacity */
8839 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
8840 return false;
8841 break;
8842
8843 case group_has_spare:
8844 /* Select group with most idle CPUs */
3edecfef 8845 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
57abff06 8846 return false;
3edecfef
PP
8847
8848 /* Select group with lowest group_util */
8849 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
8850 idlest_sgs->group_util <= sgs->group_util)
8851 return false;
8852
57abff06
VG
8853 break;
8854 }
8855
8856 return true;
8857}
8858
23e6082a
MG
8859/*
8860 * Allow a NUMA imbalance if busy CPUs is less than 25% of the domain.
8861 * This is an approximation as the number of running tasks may not be
8862 * related to the number of busy CPUs due to sched_setaffinity.
8863 */
8864static inline bool allow_numa_imbalance(int dst_running, int dst_weight)
8865{
8866 return (dst_running < (dst_weight >> 2));
8867}
8868
57abff06
VG
8869/*
8870 * find_idlest_group() finds and returns the least busy CPU group within the
8871 * domain.
8872 *
8873 * Assumes p is allowed on at least one CPU in sd.
8874 */
8875static struct sched_group *
45da2773 8876find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
57abff06
VG
8877{
8878 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
8879 struct sg_lb_stats local_sgs, tmp_sgs;
8880 struct sg_lb_stats *sgs;
8881 unsigned long imbalance;
8882 struct sg_lb_stats idlest_sgs = {
8883 .avg_load = UINT_MAX,
8884 .group_type = group_overloaded,
8885 };
8886
57abff06
VG
8887 do {
8888 int local_group;
8889
8890 /* Skip over this group if it has no CPUs allowed */
8891 if (!cpumask_intersects(sched_group_span(group),
8892 p->cpus_ptr))
8893 continue;
8894
97886d9d
AL
8895 /* Skip over this group if no cookie matched */
8896 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
8897 continue;
8898
57abff06
VG
8899 local_group = cpumask_test_cpu(this_cpu,
8900 sched_group_span(group));
8901
8902 if (local_group) {
8903 sgs = &local_sgs;
8904 local = group;
8905 } else {
8906 sgs = &tmp_sgs;
8907 }
8908
8909 update_sg_wakeup_stats(sd, group, sgs, p);
8910
8911 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
8912 idlest = group;
8913 idlest_sgs = *sgs;
8914 }
8915
8916 } while (group = group->next, group != sd->groups);
8917
8918
8919 /* There is no idlest group to push tasks to */
8920 if (!idlest)
8921 return NULL;
8922
7ed735c3
VG
8923 /* The local group has been skipped because of CPU affinity */
8924 if (!local)
8925 return idlest;
8926
57abff06
VG
8927 /*
8928 * If the local group is idler than the selected idlest group
8929 * don't try and push the task.
8930 */
8931 if (local_sgs.group_type < idlest_sgs.group_type)
8932 return NULL;
8933
8934 /*
8935 * If the local group is busier than the selected idlest group
8936 * try and push the task.
8937 */
8938 if (local_sgs.group_type > idlest_sgs.group_type)
8939 return idlest;
8940
8941 switch (local_sgs.group_type) {
8942 case group_overloaded:
8943 case group_fully_busy:
5c339005
MG
8944
8945 /* Calculate allowed imbalance based on load */
8946 imbalance = scale_load_down(NICE_0_LOAD) *
8947 (sd->imbalance_pct-100) / 100;
8948
57abff06
VG
8949 /*
8950 * When comparing groups across NUMA domains, it's possible for
8951 * the local domain to be very lightly loaded relative to the
8952 * remote domains but "imbalance" skews the comparison making
8953 * remote CPUs look much more favourable. When considering
8954 * cross-domain, add imbalance to the load on the remote node
8955 * and consider staying local.
8956 */
8957
8958 if ((sd->flags & SD_NUMA) &&
8959 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
8960 return NULL;
8961
8962 /*
8963 * If the local group is less loaded than the selected
8964 * idlest group don't try and push any tasks.
8965 */
8966 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
8967 return NULL;
8968
8969 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
8970 return NULL;
8971 break;
8972
8973 case group_imbalanced:
8974 case group_asym_packing:
8975 /* Those type are not used in the slow wakeup path */
8976 return NULL;
8977
8978 case group_misfit_task:
8979 /* Select group with the highest max capacity */
8980 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
8981 return NULL;
8982 break;
8983
8984 case group_has_spare:
8985 if (sd->flags & SD_NUMA) {
8986#ifdef CONFIG_NUMA_BALANCING
8987 int idlest_cpu;
8988 /*
8989 * If there is spare capacity at NUMA, try to select
8990 * the preferred node
8991 */
8992 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
8993 return NULL;
8994
8995 idlest_cpu = cpumask_first(sched_group_span(idlest));
8996 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
8997 return idlest;
8998#endif
8999 /*
9000 * Otherwise, keep the task on this node to stay close
9001 * its wakeup source and improve locality. If there is
9002 * a real need of migration, periodic load balance will
9003 * take care of it.
9004 */
23e6082a 9005 if (allow_numa_imbalance(local_sgs.sum_nr_running, sd->span_weight))
57abff06
VG
9006 return NULL;
9007 }
9008
9009 /*
9010 * Select group with highest number of idle CPUs. We could also
9011 * compare the utilization which is more stable but it can end
9012 * up that the group has less spare capacity but finally more
9013 * idle CPUs which means more opportunity to run task.
9014 */
9015 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
9016 return NULL;
9017 break;
9018 }
9019
9020 return idlest;
9021}
9022
1e3c88bd 9023/**
461819ac 9024 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
cd96891d 9025 * @env: The load balancing environment.
1e3c88bd
PZ
9026 * @sds: variable to hold the statistics for this sched_domain.
9027 */
0b0695f2 9028
0ec8aa00 9029static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 9030{
bd939f45
PZ
9031 struct sched_domain *child = env->sd->child;
9032 struct sched_group *sg = env->sd->groups;
05b40e05 9033 struct sg_lb_stats *local = &sds->local_stat;
56cf515b 9034 struct sg_lb_stats tmp_sgs;
630246a0 9035 int sg_status = 0;
1e3c88bd 9036
1e3c88bd 9037 do {
56cf515b 9038 struct sg_lb_stats *sgs = &tmp_sgs;
1e3c88bd
PZ
9039 int local_group;
9040
ae4df9d6 9041 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
56cf515b
JK
9042 if (local_group) {
9043 sds->local = sg;
05b40e05 9044 sgs = local;
b72ff13c
PZ
9045
9046 if (env->idle != CPU_NEWLY_IDLE ||
63b2ca30
NP
9047 time_after_eq(jiffies, sg->sgc->next_update))
9048 update_group_capacity(env->sd, env->dst_cpu);
56cf515b 9049 }
1e3c88bd 9050
630246a0 9051 update_sg_lb_stats(env, sg, sgs, &sg_status);
1e3c88bd 9052
b72ff13c
PZ
9053 if (local_group)
9054 goto next_group;
9055
1e3c88bd 9056
b72ff13c 9057 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
532cb4c4 9058 sds->busiest = sg;
56cf515b 9059 sds->busiest_stat = *sgs;
1e3c88bd
PZ
9060 }
9061
b72ff13c
PZ
9062next_group:
9063 /* Now, start updating sd_lb_stats */
9064 sds->total_load += sgs->group_load;
63b2ca30 9065 sds->total_capacity += sgs->group_capacity;
b72ff13c 9066
532cb4c4 9067 sg = sg->next;
bd939f45 9068 } while (sg != env->sd->groups);
0ec8aa00 9069
0b0695f2
VG
9070 /* Tag domain that child domain prefers tasks go to siblings first */
9071 sds->prefer_sibling = child && child->flags & SD_PREFER_SIBLING;
9072
f643ea22 9073
0ec8aa00
PZ
9074 if (env->sd->flags & SD_NUMA)
9075 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
4486edd1
TC
9076
9077 if (!env->sd->parent) {
2802bf3c
MR
9078 struct root_domain *rd = env->dst_rq->rd;
9079
4486edd1 9080 /* update overload indicator if we are at root domain */
2802bf3c
MR
9081 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
9082
9083 /* Update over-utilization (tipping point, U >= 0) indicator */
9084 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
f9f240f9 9085 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
2802bf3c 9086 } else if (sg_status & SG_OVERUTILIZED) {
f9f240f9
QY
9087 struct root_domain *rd = env->dst_rq->rd;
9088
9089 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
9090 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
4486edd1 9091 }
532cb4c4
MN
9092}
9093
abeae76a
MG
9094#define NUMA_IMBALANCE_MIN 2
9095
7d2b5dd0
MG
9096static inline long adjust_numa_imbalance(int imbalance,
9097 int dst_running, int dst_weight)
fb86f5b2 9098{
23e6082a
MG
9099 if (!allow_numa_imbalance(dst_running, dst_weight))
9100 return imbalance;
9101
fb86f5b2
MG
9102 /*
9103 * Allow a small imbalance based on a simple pair of communicating
7d2b5dd0 9104 * tasks that remain local when the destination is lightly loaded.
fb86f5b2 9105 */
23e6082a 9106 if (imbalance <= NUMA_IMBALANCE_MIN)
fb86f5b2
MG
9107 return 0;
9108
9109 return imbalance;
9110}
9111
1e3c88bd
PZ
9112/**
9113 * calculate_imbalance - Calculate the amount of imbalance present within the
9114 * groups of a given sched_domain during load balance.
bd939f45 9115 * @env: load balance environment
1e3c88bd 9116 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 9117 */
bd939f45 9118static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 9119{
56cf515b
JK
9120 struct sg_lb_stats *local, *busiest;
9121
9122 local = &sds->local_stat;
56cf515b 9123 busiest = &sds->busiest_stat;
dd5feea1 9124
0b0695f2
VG
9125 if (busiest->group_type == group_misfit_task) {
9126 /* Set imbalance to allow misfit tasks to be balanced. */
9127 env->migration_type = migrate_misfit;
c63be7be 9128 env->imbalance = 1;
0b0695f2
VG
9129 return;
9130 }
9131
9132 if (busiest->group_type == group_asym_packing) {
9133 /*
9134 * In case of asym capacity, we will try to migrate all load to
9135 * the preferred CPU.
9136 */
9137 env->migration_type = migrate_task;
9138 env->imbalance = busiest->sum_h_nr_running;
9139 return;
9140 }
9141
9142 if (busiest->group_type == group_imbalanced) {
9143 /*
9144 * In the group_imb case we cannot rely on group-wide averages
9145 * to ensure CPU-load equilibrium, try to move any task to fix
9146 * the imbalance. The next load balance will take care of
9147 * balancing back the system.
9148 */
9149 env->migration_type = migrate_task;
9150 env->imbalance = 1;
490ba971
VG
9151 return;
9152 }
9153
1e3c88bd 9154 /*
0b0695f2 9155 * Try to use spare capacity of local group without overloading it or
a9723389 9156 * emptying busiest.
1e3c88bd 9157 */
0b0695f2 9158 if (local->group_type == group_has_spare) {
16b0a7a1
VG
9159 if ((busiest->group_type > group_fully_busy) &&
9160 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
0b0695f2
VG
9161 /*
9162 * If busiest is overloaded, try to fill spare
9163 * capacity. This might end up creating spare capacity
9164 * in busiest or busiest still being overloaded but
9165 * there is no simple way to directly compute the
9166 * amount of load to migrate in order to balance the
9167 * system.
9168 */
9169 env->migration_type = migrate_util;
9170 env->imbalance = max(local->group_capacity, local->group_util) -
9171 local->group_util;
9172
9173 /*
9174 * In some cases, the group's utilization is max or even
9175 * higher than capacity because of migrations but the
9176 * local CPU is (newly) idle. There is at least one
9177 * waiting task in this overloaded busiest group. Let's
9178 * try to pull it.
9179 */
9180 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
9181 env->migration_type = migrate_task;
9182 env->imbalance = 1;
9183 }
9184
9185 return;
9186 }
9187
9188 if (busiest->group_weight == 1 || sds->prefer_sibling) {
5e23e474 9189 unsigned int nr_diff = busiest->sum_nr_running;
0b0695f2
VG
9190 /*
9191 * When prefer sibling, evenly spread running tasks on
9192 * groups.
9193 */
9194 env->migration_type = migrate_task;
5e23e474 9195 lsub_positive(&nr_diff, local->sum_nr_running);
0b0695f2 9196 env->imbalance = nr_diff >> 1;
b396f523 9197 } else {
0b0695f2 9198
b396f523
MG
9199 /*
9200 * If there is no overload, we just want to even the number of
9201 * idle cpus.
9202 */
9203 env->migration_type = migrate_task;
9204 env->imbalance = max_t(long, 0, (local->idle_cpus -
0b0695f2 9205 busiest->idle_cpus) >> 1);
b396f523
MG
9206 }
9207
9208 /* Consider allowing a small imbalance between NUMA groups */
7d2b5dd0 9209 if (env->sd->flags & SD_NUMA) {
fb86f5b2 9210 env->imbalance = adjust_numa_imbalance(env->imbalance,
7d2b5dd0
MG
9211 busiest->sum_nr_running, busiest->group_weight);
9212 }
b396f523 9213
fcf0553d 9214 return;
1e3c88bd
PZ
9215 }
9216
9a5d9ba6 9217 /*
0b0695f2
VG
9218 * Local is fully busy but has to take more load to relieve the
9219 * busiest group
9a5d9ba6 9220 */
0b0695f2
VG
9221 if (local->group_type < group_overloaded) {
9222 /*
9223 * Local will become overloaded so the avg_load metrics are
9224 * finally needed.
9225 */
9226
9227 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
9228 local->group_capacity;
9229
9230 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
9231 sds->total_capacity;
111688ca
AL
9232 /*
9233 * If the local group is more loaded than the selected
9234 * busiest group don't try to pull any tasks.
9235 */
9236 if (local->avg_load >= busiest->avg_load) {
9237 env->imbalance = 0;
9238 return;
9239 }
dd5feea1
SS
9240 }
9241
9242 /*
0b0695f2
VG
9243 * Both group are or will become overloaded and we're trying to get all
9244 * the CPUs to the average_load, so we don't want to push ourselves
9245 * above the average load, nor do we wish to reduce the max loaded CPU
9246 * below the average load. At the same time, we also don't want to
9247 * reduce the group load below the group capacity. Thus we look for
9248 * the minimum possible imbalance.
dd5feea1 9249 */
0b0695f2 9250 env->migration_type = migrate_load;
56cf515b 9251 env->imbalance = min(
0b0695f2 9252 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
63b2ca30 9253 (sds->avg_load - local->avg_load) * local->group_capacity
ca8ce3d0 9254 ) / SCHED_CAPACITY_SCALE;
1e3c88bd 9255}
fab47622 9256
1e3c88bd
PZ
9257/******* find_busiest_group() helpers end here *********************/
9258
0b0695f2
VG
9259/*
9260 * Decision matrix according to the local and busiest group type:
9261 *
9262 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
9263 * has_spare nr_idle balanced N/A N/A balanced balanced
9264 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
9265 * misfit_task force N/A N/A N/A force force
9266 * asym_packing force force N/A N/A force force
9267 * imbalanced force force N/A N/A force force
9268 * overloaded force force N/A N/A force avg_load
9269 *
9270 * N/A : Not Applicable because already filtered while updating
9271 * statistics.
9272 * balanced : The system is balanced for these 2 groups.
9273 * force : Calculate the imbalance as load migration is probably needed.
9274 * avg_load : Only if imbalance is significant enough.
9275 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
9276 * different in groups.
9277 */
9278
1e3c88bd
PZ
9279/**
9280 * find_busiest_group - Returns the busiest group within the sched_domain
0a9b23ce 9281 * if there is an imbalance.
1e3c88bd 9282 *
a3df0679 9283 * Also calculates the amount of runnable load which should be moved
1e3c88bd
PZ
9284 * to restore balance.
9285 *
cd96891d 9286 * @env: The load balancing environment.
1e3c88bd 9287 *
e69f6186 9288 * Return: - The busiest group if imbalance exists.
1e3c88bd 9289 */
56cf515b 9290static struct sched_group *find_busiest_group(struct lb_env *env)
1e3c88bd 9291{
56cf515b 9292 struct sg_lb_stats *local, *busiest;
1e3c88bd
PZ
9293 struct sd_lb_stats sds;
9294
147c5fc2 9295 init_sd_lb_stats(&sds);
1e3c88bd
PZ
9296
9297 /*
b0fb1eb4 9298 * Compute the various statistics relevant for load balancing at
1e3c88bd
PZ
9299 * this level.
9300 */
23f0d209 9301 update_sd_lb_stats(env, &sds);
2802bf3c 9302
f8a696f2 9303 if (sched_energy_enabled()) {
2802bf3c
MR
9304 struct root_domain *rd = env->dst_rq->rd;
9305
9306 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
9307 goto out_balanced;
9308 }
9309
56cf515b
JK
9310 local = &sds.local_stat;
9311 busiest = &sds.busiest_stat;
1e3c88bd 9312
cc57aa8f 9313 /* There is no busy sibling group to pull tasks from */
0b0695f2 9314 if (!sds.busiest)
1e3c88bd
PZ
9315 goto out_balanced;
9316
0b0695f2
VG
9317 /* Misfit tasks should be dealt with regardless of the avg load */
9318 if (busiest->group_type == group_misfit_task)
9319 goto force_balance;
9320
9321 /* ASYM feature bypasses nice load balance check */
9322 if (busiest->group_type == group_asym_packing)
9323 goto force_balance;
b0432d8f 9324
866ab43e
PZ
9325 /*
9326 * If the busiest group is imbalanced the below checks don't
30ce5dab 9327 * work because they assume all things are equal, which typically
3bd37062 9328 * isn't true due to cpus_ptr constraints and the like.
866ab43e 9329 */
caeb178c 9330 if (busiest->group_type == group_imbalanced)
866ab43e
PZ
9331 goto force_balance;
9332
cc57aa8f 9333 /*
9c58c79a 9334 * If the local group is busier than the selected busiest group
cc57aa8f
PZ
9335 * don't try and pull any tasks.
9336 */
0b0695f2 9337 if (local->group_type > busiest->group_type)
1e3c88bd
PZ
9338 goto out_balanced;
9339
cc57aa8f 9340 /*
0b0695f2
VG
9341 * When groups are overloaded, use the avg_load to ensure fairness
9342 * between tasks.
cc57aa8f 9343 */
0b0695f2
VG
9344 if (local->group_type == group_overloaded) {
9345 /*
9346 * If the local group is more loaded than the selected
9347 * busiest group don't try to pull any tasks.
9348 */
9349 if (local->avg_load >= busiest->avg_load)
9350 goto out_balanced;
9351
9352 /* XXX broken for overlapping NUMA groups */
9353 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
9354 sds.total_capacity;
1e3c88bd 9355
aae6d3dd 9356 /*
0b0695f2
VG
9357 * Don't pull any tasks if this group is already above the
9358 * domain average load.
aae6d3dd 9359 */
0b0695f2 9360 if (local->avg_load >= sds.avg_load)
aae6d3dd 9361 goto out_balanced;
0b0695f2 9362
c186fafe 9363 /*
0b0695f2
VG
9364 * If the busiest group is more loaded, use imbalance_pct to be
9365 * conservative.
c186fafe 9366 */
56cf515b
JK
9367 if (100 * busiest->avg_load <=
9368 env->sd->imbalance_pct * local->avg_load)
c186fafe 9369 goto out_balanced;
aae6d3dd 9370 }
1e3c88bd 9371
0b0695f2
VG
9372 /* Try to move all excess tasks to child's sibling domain */
9373 if (sds.prefer_sibling && local->group_type == group_has_spare &&
5e23e474 9374 busiest->sum_nr_running > local->sum_nr_running + 1)
0b0695f2
VG
9375 goto force_balance;
9376
2ab4092f
VG
9377 if (busiest->group_type != group_overloaded) {
9378 if (env->idle == CPU_NOT_IDLE)
9379 /*
9380 * If the busiest group is not overloaded (and as a
9381 * result the local one too) but this CPU is already
9382 * busy, let another idle CPU try to pull task.
9383 */
9384 goto out_balanced;
9385
9386 if (busiest->group_weight > 1 &&
9387 local->idle_cpus <= (busiest->idle_cpus + 1))
9388 /*
9389 * If the busiest group is not overloaded
9390 * and there is no imbalance between this and busiest
9391 * group wrt idle CPUs, it is balanced. The imbalance
9392 * becomes significant if the diff is greater than 1
9393 * otherwise we might end up to just move the imbalance
9394 * on another group. Of course this applies only if
9395 * there is more than 1 CPU per group.
9396 */
9397 goto out_balanced;
9398
9399 if (busiest->sum_h_nr_running == 1)
9400 /*
9401 * busiest doesn't have any tasks waiting to run
9402 */
9403 goto out_balanced;
9404 }
0b0695f2 9405
fab47622 9406force_balance:
1e3c88bd 9407 /* Looks like there is an imbalance. Compute it */
bd939f45 9408 calculate_imbalance(env, &sds);
bb3485c8 9409 return env->imbalance ? sds.busiest : NULL;
1e3c88bd
PZ
9410
9411out_balanced:
bd939f45 9412 env->imbalance = 0;
1e3c88bd
PZ
9413 return NULL;
9414}
9415
9416/*
97fb7a0a 9417 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
1e3c88bd 9418 */
bd939f45 9419static struct rq *find_busiest_queue(struct lb_env *env,
b9403130 9420 struct sched_group *group)
1e3c88bd
PZ
9421{
9422 struct rq *busiest = NULL, *rq;
0b0695f2
VG
9423 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
9424 unsigned int busiest_nr = 0;
1e3c88bd
PZ
9425 int i;
9426
ae4df9d6 9427 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
0b0695f2
VG
9428 unsigned long capacity, load, util;
9429 unsigned int nr_running;
0ec8aa00
PZ
9430 enum fbq_type rt;
9431
9432 rq = cpu_rq(i);
9433 rt = fbq_classify_rq(rq);
1e3c88bd 9434
0ec8aa00
PZ
9435 /*
9436 * We classify groups/runqueues into three groups:
9437 * - regular: there are !numa tasks
9438 * - remote: there are numa tasks that run on the 'wrong' node
9439 * - all: there is no distinction
9440 *
9441 * In order to avoid migrating ideally placed numa tasks,
9442 * ignore those when there's better options.
9443 *
9444 * If we ignore the actual busiest queue to migrate another
9445 * task, the next balance pass can still reduce the busiest
9446 * queue by moving tasks around inside the node.
9447 *
9448 * If we cannot move enough load due to this classification
9449 * the next pass will adjust the group classification and
9450 * allow migration of more tasks.
9451 *
9452 * Both cases only affect the total convergence complexity.
9453 */
9454 if (rt > env->fbq_type)
9455 continue;
9456
0b0695f2 9457 nr_running = rq->cfs.h_nr_running;
fc488ffd
VG
9458 if (!nr_running)
9459 continue;
9460
9461 capacity = capacity_of(i);
9d5efe05 9462
4ad3831a
CR
9463 /*
9464 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
9465 * eventually lead to active_balancing high->low capacity.
9466 * Higher per-CPU capacity is considered better than balancing
9467 * average load.
9468 */
9469 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
4aed8aa4 9470 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
0b0695f2 9471 nr_running == 1)
4ad3831a
CR
9472 continue;
9473
0b0695f2
VG
9474 switch (env->migration_type) {
9475 case migrate_load:
9476 /*
b0fb1eb4
VG
9477 * When comparing with load imbalance, use cpu_load()
9478 * which is not scaled with the CPU capacity.
0b0695f2 9479 */
b0fb1eb4 9480 load = cpu_load(rq);
1e3c88bd 9481
0b0695f2
VG
9482 if (nr_running == 1 && load > env->imbalance &&
9483 !check_cpu_capacity(rq, env->sd))
9484 break;
ea67821b 9485
0b0695f2
VG
9486 /*
9487 * For the load comparisons with the other CPUs,
b0fb1eb4
VG
9488 * consider the cpu_load() scaled with the CPU
9489 * capacity, so that the load can be moved away
9490 * from the CPU that is potentially running at a
9491 * lower capacity.
0b0695f2
VG
9492 *
9493 * Thus we're looking for max(load_i / capacity_i),
9494 * crosswise multiplication to rid ourselves of the
9495 * division works out to:
9496 * load_i * capacity_j > load_j * capacity_i;
9497 * where j is our previous maximum.
9498 */
9499 if (load * busiest_capacity > busiest_load * capacity) {
9500 busiest_load = load;
9501 busiest_capacity = capacity;
9502 busiest = rq;
9503 }
9504 break;
9505
9506 case migrate_util:
9507 util = cpu_util(cpu_of(rq));
9508
c32b4308
VG
9509 /*
9510 * Don't try to pull utilization from a CPU with one
9511 * running task. Whatever its utilization, we will fail
9512 * detach the task.
9513 */
9514 if (nr_running <= 1)
9515 continue;
9516
0b0695f2
VG
9517 if (busiest_util < util) {
9518 busiest_util = util;
9519 busiest = rq;
9520 }
9521 break;
9522
9523 case migrate_task:
9524 if (busiest_nr < nr_running) {
9525 busiest_nr = nr_running;
9526 busiest = rq;
9527 }
9528 break;
9529
9530 case migrate_misfit:
9531 /*
9532 * For ASYM_CPUCAPACITY domains with misfit tasks we
9533 * simply seek the "biggest" misfit task.
9534 */
9535 if (rq->misfit_task_load > busiest_load) {
9536 busiest_load = rq->misfit_task_load;
9537 busiest = rq;
9538 }
9539
9540 break;
1e3c88bd 9541
1e3c88bd
PZ
9542 }
9543 }
9544
9545 return busiest;
9546}
9547
9548/*
9549 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
9550 * so long as it is large enough.
9551 */
9552#define MAX_PINNED_INTERVAL 512
9553
46a745d9
VG
9554static inline bool
9555asym_active_balance(struct lb_env *env)
1af3ed3d 9556{
46a745d9
VG
9557 /*
9558 * ASYM_PACKING needs to force migrate tasks from busy but
9559 * lower priority CPUs in order to pack all tasks in the
9560 * highest priority CPUs.
9561 */
9562 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
9563 sched_asym_prefer(env->dst_cpu, env->src_cpu);
9564}
bd939f45 9565
46a745d9 9566static inline bool
e9b9734b
VG
9567imbalanced_active_balance(struct lb_env *env)
9568{
9569 struct sched_domain *sd = env->sd;
9570
9571 /*
9572 * The imbalanced case includes the case of pinned tasks preventing a fair
9573 * distribution of the load on the system but also the even distribution of the
9574 * threads on a system with spare capacity
9575 */
9576 if ((env->migration_type == migrate_task) &&
9577 (sd->nr_balance_failed > sd->cache_nice_tries+2))
9578 return 1;
9579
9580 return 0;
9581}
9582
9583static int need_active_balance(struct lb_env *env)
46a745d9
VG
9584{
9585 struct sched_domain *sd = env->sd;
532cb4c4 9586
46a745d9
VG
9587 if (asym_active_balance(env))
9588 return 1;
1af3ed3d 9589
e9b9734b
VG
9590 if (imbalanced_active_balance(env))
9591 return 1;
9592
1aaf90a4
VG
9593 /*
9594 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
9595 * It's worth migrating the task if the src_cpu's capacity is reduced
9596 * because of other sched_class or IRQs if more capacity stays
9597 * available on dst_cpu.
9598 */
9599 if ((env->idle != CPU_NOT_IDLE) &&
9600 (env->src_rq->cfs.h_nr_running == 1)) {
9601 if ((check_cpu_capacity(env->src_rq, sd)) &&
9602 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
9603 return 1;
9604 }
9605
0b0695f2 9606 if (env->migration_type == migrate_misfit)
cad68e55
MR
9607 return 1;
9608
46a745d9
VG
9609 return 0;
9610}
9611
969c7921
TH
9612static int active_load_balance_cpu_stop(void *data);
9613
23f0d209
JK
9614static int should_we_balance(struct lb_env *env)
9615{
9616 struct sched_group *sg = env->sd->groups;
64297f2b 9617 int cpu;
23f0d209 9618
024c9d2f
PZ
9619 /*
9620 * Ensure the balancing environment is consistent; can happen
9621 * when the softirq triggers 'during' hotplug.
9622 */
9623 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
9624 return 0;
9625
23f0d209 9626 /*
97fb7a0a 9627 * In the newly idle case, we will allow all the CPUs
23f0d209
JK
9628 * to do the newly idle load balance.
9629 */
9630 if (env->idle == CPU_NEWLY_IDLE)
9631 return 1;
9632
97fb7a0a 9633 /* Try to find first idle CPU */
e5c14b1f 9634 for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
af218122 9635 if (!idle_cpu(cpu))
23f0d209
JK
9636 continue;
9637
64297f2b
PW
9638 /* Are we the first idle CPU? */
9639 return cpu == env->dst_cpu;
23f0d209
JK
9640 }
9641
64297f2b
PW
9642 /* Are we the first CPU of this group ? */
9643 return group_balance_cpu(sg) == env->dst_cpu;
23f0d209
JK
9644}
9645
1e3c88bd
PZ
9646/*
9647 * Check this_cpu to ensure it is balanced within domain. Attempt to move
9648 * tasks if there is an imbalance.
9649 */
9650static int load_balance(int this_cpu, struct rq *this_rq,
9651 struct sched_domain *sd, enum cpu_idle_type idle,
23f0d209 9652 int *continue_balancing)
1e3c88bd 9653{
88b8dac0 9654 int ld_moved, cur_ld_moved, active_balance = 0;
6263322c 9655 struct sched_domain *sd_parent = sd->parent;
1e3c88bd 9656 struct sched_group *group;
1e3c88bd 9657 struct rq *busiest;
8a8c69c3 9658 struct rq_flags rf;
4ba29684 9659 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
1e3c88bd 9660
8e45cb54
PZ
9661 struct lb_env env = {
9662 .sd = sd,
ddcdf6e7
PZ
9663 .dst_cpu = this_cpu,
9664 .dst_rq = this_rq,
ae4df9d6 9665 .dst_grpmask = sched_group_span(sd->groups),
8e45cb54 9666 .idle = idle,
eb95308e 9667 .loop_break = sched_nr_migrate_break,
b9403130 9668 .cpus = cpus,
0ec8aa00 9669 .fbq_type = all,
163122b7 9670 .tasks = LIST_HEAD_INIT(env.tasks),
8e45cb54
PZ
9671 };
9672
65a4433a 9673 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
1e3c88bd 9674
ae92882e 9675 schedstat_inc(sd->lb_count[idle]);
1e3c88bd
PZ
9676
9677redo:
23f0d209
JK
9678 if (!should_we_balance(&env)) {
9679 *continue_balancing = 0;
1e3c88bd 9680 goto out_balanced;
23f0d209 9681 }
1e3c88bd 9682
23f0d209 9683 group = find_busiest_group(&env);
1e3c88bd 9684 if (!group) {
ae92882e 9685 schedstat_inc(sd->lb_nobusyg[idle]);
1e3c88bd
PZ
9686 goto out_balanced;
9687 }
9688
b9403130 9689 busiest = find_busiest_queue(&env, group);
1e3c88bd 9690 if (!busiest) {
ae92882e 9691 schedstat_inc(sd->lb_nobusyq[idle]);
1e3c88bd
PZ
9692 goto out_balanced;
9693 }
9694
78feefc5 9695 BUG_ON(busiest == env.dst_rq);
1e3c88bd 9696
ae92882e 9697 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
1e3c88bd 9698
1aaf90a4
VG
9699 env.src_cpu = busiest->cpu;
9700 env.src_rq = busiest;
9701
1e3c88bd 9702 ld_moved = 0;
8a41dfcd
VG
9703 /* Clear this flag as soon as we find a pullable task */
9704 env.flags |= LBF_ALL_PINNED;
1e3c88bd
PZ
9705 if (busiest->nr_running > 1) {
9706 /*
9707 * Attempt to move tasks. If find_busiest_group has found
9708 * an imbalance but busiest->nr_running <= 1, the group is
9709 * still unbalanced. ld_moved simply stays zero, so it is
9710 * correctly treated as an imbalance.
9711 */
c82513e5 9712 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
8e45cb54 9713
5d6523eb 9714more_balance:
8a8c69c3 9715 rq_lock_irqsave(busiest, &rf);
3bed5e21 9716 update_rq_clock(busiest);
88b8dac0
SV
9717
9718 /*
9719 * cur_ld_moved - load moved in current iteration
9720 * ld_moved - cumulative load moved across iterations
9721 */
163122b7 9722 cur_ld_moved = detach_tasks(&env);
1e3c88bd
PZ
9723
9724 /*
163122b7
KT
9725 * We've detached some tasks from busiest_rq. Every
9726 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9727 * unlock busiest->lock, and we are able to be sure
9728 * that nobody can manipulate the tasks in parallel.
9729 * See task_rq_lock() family for the details.
1e3c88bd 9730 */
163122b7 9731
8a8c69c3 9732 rq_unlock(busiest, &rf);
163122b7
KT
9733
9734 if (cur_ld_moved) {
9735 attach_tasks(&env);
9736 ld_moved += cur_ld_moved;
9737 }
9738
8a8c69c3 9739 local_irq_restore(rf.flags);
88b8dac0 9740
f1cd0858
JK
9741 if (env.flags & LBF_NEED_BREAK) {
9742 env.flags &= ~LBF_NEED_BREAK;
9743 goto more_balance;
9744 }
9745
88b8dac0
SV
9746 /*
9747 * Revisit (affine) tasks on src_cpu that couldn't be moved to
9748 * us and move them to an alternate dst_cpu in our sched_group
9749 * where they can run. The upper limit on how many times we
97fb7a0a 9750 * iterate on same src_cpu is dependent on number of CPUs in our
88b8dac0
SV
9751 * sched_group.
9752 *
9753 * This changes load balance semantics a bit on who can move
9754 * load to a given_cpu. In addition to the given_cpu itself
9755 * (or a ilb_cpu acting on its behalf where given_cpu is
9756 * nohz-idle), we now have balance_cpu in a position to move
9757 * load to given_cpu. In rare situations, this may cause
9758 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
9759 * _independently_ and at _same_ time to move some load to
3b03706f 9760 * given_cpu) causing excess load to be moved to given_cpu.
88b8dac0
SV
9761 * This however should not happen so much in practice and
9762 * moreover subsequent load balance cycles should correct the
9763 * excess load moved.
9764 */
6263322c 9765 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
88b8dac0 9766
97fb7a0a 9767 /* Prevent to re-select dst_cpu via env's CPUs */
c89d92ed 9768 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
7aff2e3a 9769
78feefc5 9770 env.dst_rq = cpu_rq(env.new_dst_cpu);
88b8dac0 9771 env.dst_cpu = env.new_dst_cpu;
6263322c 9772 env.flags &= ~LBF_DST_PINNED;
88b8dac0
SV
9773 env.loop = 0;
9774 env.loop_break = sched_nr_migrate_break;
e02e60c1 9775
88b8dac0
SV
9776 /*
9777 * Go back to "more_balance" rather than "redo" since we
9778 * need to continue with same src_cpu.
9779 */
9780 goto more_balance;
9781 }
1e3c88bd 9782
6263322c
PZ
9783 /*
9784 * We failed to reach balance because of affinity.
9785 */
9786 if (sd_parent) {
63b2ca30 9787 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
6263322c 9788
afdeee05 9789 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
6263322c 9790 *group_imbalance = 1;
6263322c
PZ
9791 }
9792
1e3c88bd 9793 /* All tasks on this runqueue were pinned by CPU affinity */
8e45cb54 9794 if (unlikely(env.flags & LBF_ALL_PINNED)) {
c89d92ed 9795 __cpumask_clear_cpu(cpu_of(busiest), cpus);
65a4433a
JH
9796 /*
9797 * Attempting to continue load balancing at the current
9798 * sched_domain level only makes sense if there are
9799 * active CPUs remaining as possible busiest CPUs to
9800 * pull load from which are not contained within the
9801 * destination group that is receiving any migrated
9802 * load.
9803 */
9804 if (!cpumask_subset(cpus, env.dst_grpmask)) {
bbf18b19
PN
9805 env.loop = 0;
9806 env.loop_break = sched_nr_migrate_break;
1e3c88bd 9807 goto redo;
bbf18b19 9808 }
afdeee05 9809 goto out_all_pinned;
1e3c88bd
PZ
9810 }
9811 }
9812
9813 if (!ld_moved) {
ae92882e 9814 schedstat_inc(sd->lb_failed[idle]);
58b26c4c
VP
9815 /*
9816 * Increment the failure counter only on periodic balance.
9817 * We do not want newidle balance, which can be very
9818 * frequent, pollute the failure counter causing
9819 * excessive cache_hot migrations and active balances.
9820 */
9821 if (idle != CPU_NEWLY_IDLE)
9822 sd->nr_balance_failed++;
1e3c88bd 9823
bd939f45 9824 if (need_active_balance(&env)) {
8a8c69c3
PZ
9825 unsigned long flags;
9826
5cb9eaa3 9827 raw_spin_rq_lock_irqsave(busiest, flags);
1e3c88bd 9828
97fb7a0a
IM
9829 /*
9830 * Don't kick the active_load_balance_cpu_stop,
9831 * if the curr task on busiest CPU can't be
9832 * moved to this_cpu:
1e3c88bd 9833 */
3bd37062 9834 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
5cb9eaa3 9835 raw_spin_rq_unlock_irqrestore(busiest, flags);
1e3c88bd
PZ
9836 goto out_one_pinned;
9837 }
9838
8a41dfcd
VG
9839 /* Record that we found at least one task that could run on this_cpu */
9840 env.flags &= ~LBF_ALL_PINNED;
9841
969c7921
TH
9842 /*
9843 * ->active_balance synchronizes accesses to
9844 * ->active_balance_work. Once set, it's cleared
9845 * only after active load balance is finished.
9846 */
1e3c88bd
PZ
9847 if (!busiest->active_balance) {
9848 busiest->active_balance = 1;
9849 busiest->push_cpu = this_cpu;
9850 active_balance = 1;
9851 }
5cb9eaa3 9852 raw_spin_rq_unlock_irqrestore(busiest, flags);
969c7921 9853
bd939f45 9854 if (active_balance) {
969c7921
TH
9855 stop_one_cpu_nowait(cpu_of(busiest),
9856 active_load_balance_cpu_stop, busiest,
9857 &busiest->active_balance_work);
bd939f45 9858 }
1e3c88bd 9859 }
e9b9734b 9860 } else {
1e3c88bd 9861 sd->nr_balance_failed = 0;
e9b9734b 9862 }
1e3c88bd 9863
e9b9734b 9864 if (likely(!active_balance) || need_active_balance(&env)) {
1e3c88bd
PZ
9865 /* We were unbalanced, so reset the balancing interval */
9866 sd->balance_interval = sd->min_interval;
1e3c88bd
PZ
9867 }
9868
1e3c88bd
PZ
9869 goto out;
9870
9871out_balanced:
afdeee05
VG
9872 /*
9873 * We reach balance although we may have faced some affinity
f6cad8df
VG
9874 * constraints. Clear the imbalance flag only if other tasks got
9875 * a chance to move and fix the imbalance.
afdeee05 9876 */
f6cad8df 9877 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
afdeee05
VG
9878 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9879
9880 if (*group_imbalance)
9881 *group_imbalance = 0;
9882 }
9883
9884out_all_pinned:
9885 /*
9886 * We reach balance because all tasks are pinned at this level so
9887 * we can't migrate them. Let the imbalance flag set so parent level
9888 * can try to migrate them.
9889 */
ae92882e 9890 schedstat_inc(sd->lb_balanced[idle]);
1e3c88bd
PZ
9891
9892 sd->nr_balance_failed = 0;
9893
9894out_one_pinned:
3f130a37
VS
9895 ld_moved = 0;
9896
9897 /*
5ba553ef
PZ
9898 * newidle_balance() disregards balance intervals, so we could
9899 * repeatedly reach this code, which would lead to balance_interval
3b03706f 9900 * skyrocketing in a short amount of time. Skip the balance_interval
5ba553ef 9901 * increase logic to avoid that.
3f130a37
VS
9902 */
9903 if (env.idle == CPU_NEWLY_IDLE)
9904 goto out;
9905
1e3c88bd 9906 /* tune up the balancing interval */
47b7aee1
VS
9907 if ((env.flags & LBF_ALL_PINNED &&
9908 sd->balance_interval < MAX_PINNED_INTERVAL) ||
9909 sd->balance_interval < sd->max_interval)
1e3c88bd 9910 sd->balance_interval *= 2;
1e3c88bd 9911out:
1e3c88bd
PZ
9912 return ld_moved;
9913}
9914
52a08ef1
JL
9915static inline unsigned long
9916get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
9917{
9918 unsigned long interval = sd->balance_interval;
9919
9920 if (cpu_busy)
9921 interval *= sd->busy_factor;
9922
9923 /* scale ms to jiffies */
9924 interval = msecs_to_jiffies(interval);
e4d32e4d
VG
9925
9926 /*
9927 * Reduce likelihood of busy balancing at higher domains racing with
9928 * balancing at lower domains by preventing their balancing periods
9929 * from being multiples of each other.
9930 */
9931 if (cpu_busy)
9932 interval -= 1;
9933
52a08ef1
JL
9934 interval = clamp(interval, 1UL, max_load_balance_interval);
9935
9936 return interval;
9937}
9938
9939static inline void
31851a98 9940update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
52a08ef1
JL
9941{
9942 unsigned long interval, next;
9943
31851a98
LY
9944 /* used by idle balance, so cpu_busy = 0 */
9945 interval = get_sd_balance_interval(sd, 0);
52a08ef1
JL
9946 next = sd->last_balance + interval;
9947
9948 if (time_after(*next_balance, next))
9949 *next_balance = next;
9950}
9951
1e3c88bd 9952/*
97fb7a0a 9953 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
969c7921
TH
9954 * running tasks off the busiest CPU onto idle CPUs. It requires at
9955 * least 1 task to be running on each physical CPU where possible, and
9956 * avoids physical / logical imbalances.
1e3c88bd 9957 */
969c7921 9958static int active_load_balance_cpu_stop(void *data)
1e3c88bd 9959{
969c7921
TH
9960 struct rq *busiest_rq = data;
9961 int busiest_cpu = cpu_of(busiest_rq);
1e3c88bd 9962 int target_cpu = busiest_rq->push_cpu;
969c7921 9963 struct rq *target_rq = cpu_rq(target_cpu);
1e3c88bd 9964 struct sched_domain *sd;
e5673f28 9965 struct task_struct *p = NULL;
8a8c69c3 9966 struct rq_flags rf;
969c7921 9967
8a8c69c3 9968 rq_lock_irq(busiest_rq, &rf);
edd8e41d
PZ
9969 /*
9970 * Between queueing the stop-work and running it is a hole in which
9971 * CPUs can become inactive. We should not move tasks from or to
9972 * inactive CPUs.
9973 */
9974 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
9975 goto out_unlock;
969c7921 9976
97fb7a0a 9977 /* Make sure the requested CPU hasn't gone down in the meantime: */
969c7921
TH
9978 if (unlikely(busiest_cpu != smp_processor_id() ||
9979 !busiest_rq->active_balance))
9980 goto out_unlock;
1e3c88bd
PZ
9981
9982 /* Is there any task to move? */
9983 if (busiest_rq->nr_running <= 1)
969c7921 9984 goto out_unlock;
1e3c88bd
PZ
9985
9986 /*
9987 * This condition is "impossible", if it occurs
9988 * we need to fix it. Originally reported by
97fb7a0a 9989 * Bjorn Helgaas on a 128-CPU setup.
1e3c88bd
PZ
9990 */
9991 BUG_ON(busiest_rq == target_rq);
9992
1e3c88bd 9993 /* Search for an sd spanning us and the target CPU. */
dce840a0 9994 rcu_read_lock();
1e3c88bd 9995 for_each_domain(target_cpu, sd) {
e669ac8a
VS
9996 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
9997 break;
1e3c88bd
PZ
9998 }
9999
10000 if (likely(sd)) {
8e45cb54
PZ
10001 struct lb_env env = {
10002 .sd = sd,
ddcdf6e7
PZ
10003 .dst_cpu = target_cpu,
10004 .dst_rq = target_rq,
10005 .src_cpu = busiest_rq->cpu,
10006 .src_rq = busiest_rq,
8e45cb54 10007 .idle = CPU_IDLE,
23fb06d9 10008 .flags = LBF_ACTIVE_LB,
8e45cb54
PZ
10009 };
10010
ae92882e 10011 schedstat_inc(sd->alb_count);
3bed5e21 10012 update_rq_clock(busiest_rq);
1e3c88bd 10013
e5673f28 10014 p = detach_one_task(&env);
d02c0711 10015 if (p) {
ae92882e 10016 schedstat_inc(sd->alb_pushed);
d02c0711
SD
10017 /* Active balancing done, reset the failure counter. */
10018 sd->nr_balance_failed = 0;
10019 } else {
ae92882e 10020 schedstat_inc(sd->alb_failed);
d02c0711 10021 }
1e3c88bd 10022 }
dce840a0 10023 rcu_read_unlock();
969c7921
TH
10024out_unlock:
10025 busiest_rq->active_balance = 0;
8a8c69c3 10026 rq_unlock(busiest_rq, &rf);
e5673f28
KT
10027
10028 if (p)
10029 attach_one_task(target_rq, p);
10030
10031 local_irq_enable();
10032
969c7921 10033 return 0;
1e3c88bd
PZ
10034}
10035
af3fe03c
PZ
10036static DEFINE_SPINLOCK(balancing);
10037
10038/*
10039 * Scale the max load_balance interval with the number of CPUs in the system.
10040 * This trades load-balance latency on larger machines for less cross talk.
10041 */
10042void update_max_interval(void)
10043{
10044 max_load_balance_interval = HZ*num_online_cpus()/10;
10045}
10046
10047/*
10048 * It checks each scheduling domain to see if it is due to be balanced,
10049 * and initiates a balancing operation if so.
10050 *
10051 * Balancing parameters are set up in init_sched_domains.
10052 */
10053static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
10054{
10055 int continue_balancing = 1;
10056 int cpu = rq->cpu;
323af6de 10057 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
af3fe03c
PZ
10058 unsigned long interval;
10059 struct sched_domain *sd;
10060 /* Earliest time when we have to do rebalance again */
10061 unsigned long next_balance = jiffies + 60*HZ;
10062 int update_next_balance = 0;
10063 int need_serialize, need_decay = 0;
10064 u64 max_cost = 0;
10065
10066 rcu_read_lock();
10067 for_each_domain(cpu, sd) {
10068 /*
10069 * Decay the newidle max times here because this is a regular
10070 * visit to all the domains. Decay ~1% per second.
10071 */
10072 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
10073 sd->max_newidle_lb_cost =
10074 (sd->max_newidle_lb_cost * 253) / 256;
10075 sd->next_decay_max_lb_cost = jiffies + HZ;
10076 need_decay = 1;
10077 }
10078 max_cost += sd->max_newidle_lb_cost;
10079
af3fe03c
PZ
10080 /*
10081 * Stop the load balance at this level. There is another
10082 * CPU in our sched group which is doing load balancing more
10083 * actively.
10084 */
10085 if (!continue_balancing) {
10086 if (need_decay)
10087 continue;
10088 break;
10089 }
10090
323af6de 10091 interval = get_sd_balance_interval(sd, busy);
af3fe03c
PZ
10092
10093 need_serialize = sd->flags & SD_SERIALIZE;
10094 if (need_serialize) {
10095 if (!spin_trylock(&balancing))
10096 goto out;
10097 }
10098
10099 if (time_after_eq(jiffies, sd->last_balance + interval)) {
10100 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
10101 /*
10102 * The LBF_DST_PINNED logic could have changed
10103 * env->dst_cpu, so we can't know our idle
10104 * state even if we migrated tasks. Update it.
10105 */
10106 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
323af6de 10107 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
af3fe03c
PZ
10108 }
10109 sd->last_balance = jiffies;
323af6de 10110 interval = get_sd_balance_interval(sd, busy);
af3fe03c
PZ
10111 }
10112 if (need_serialize)
10113 spin_unlock(&balancing);
10114out:
10115 if (time_after(next_balance, sd->last_balance + interval)) {
10116 next_balance = sd->last_balance + interval;
10117 update_next_balance = 1;
10118 }
10119 }
10120 if (need_decay) {
10121 /*
10122 * Ensure the rq-wide value also decays but keep it at a
10123 * reasonable floor to avoid funnies with rq->avg_idle.
10124 */
10125 rq->max_idle_balance_cost =
10126 max((u64)sysctl_sched_migration_cost, max_cost);
10127 }
10128 rcu_read_unlock();
10129
10130 /*
10131 * next_balance will be updated only when there is a need.
10132 * When the cpu is attached to null domain for ex, it will not be
10133 * updated.
10134 */
7a82e5f5 10135 if (likely(update_next_balance))
af3fe03c
PZ
10136 rq->next_balance = next_balance;
10137
af3fe03c
PZ
10138}
10139
d987fc7f
MG
10140static inline int on_null_domain(struct rq *rq)
10141{
10142 return unlikely(!rcu_dereference_sched(rq->sd));
10143}
10144
3451d024 10145#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2
VP
10146/*
10147 * idle load balancing details
83cd4fe2
VP
10148 * - When one of the busy CPUs notice that there may be an idle rebalancing
10149 * needed, they will kick the idle load balancer, which then does idle
10150 * load balancing for all the idle CPUs.
9b019acb
NP
10151 * - HK_FLAG_MISC CPUs are used for this task, because HK_FLAG_SCHED not set
10152 * anywhere yet.
83cd4fe2 10153 */
1e3c88bd 10154
3dd0337d 10155static inline int find_new_ilb(void)
1e3c88bd 10156{
9b019acb 10157 int ilb;
1e3c88bd 10158
9b019acb
NP
10159 for_each_cpu_and(ilb, nohz.idle_cpus_mask,
10160 housekeeping_cpumask(HK_FLAG_MISC)) {
45da7a2b
PZ
10161
10162 if (ilb == smp_processor_id())
10163 continue;
10164
9b019acb
NP
10165 if (idle_cpu(ilb))
10166 return ilb;
10167 }
786d6dc7
SS
10168
10169 return nr_cpu_ids;
1e3c88bd 10170}
1e3c88bd 10171
83cd4fe2 10172/*
9b019acb
NP
10173 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
10174 * idle CPU in the HK_FLAG_MISC housekeeping set (if there is one).
83cd4fe2 10175 */
a4064fb6 10176static void kick_ilb(unsigned int flags)
83cd4fe2
VP
10177{
10178 int ilb_cpu;
10179
3ea2f097
VG
10180 /*
10181 * Increase nohz.next_balance only when if full ilb is triggered but
10182 * not if we only update stats.
10183 */
10184 if (flags & NOHZ_BALANCE_KICK)
10185 nohz.next_balance = jiffies+1;
83cd4fe2 10186
3dd0337d 10187 ilb_cpu = find_new_ilb();
83cd4fe2 10188
0b005cf5
SS
10189 if (ilb_cpu >= nr_cpu_ids)
10190 return;
83cd4fe2 10191
19a1f5ec
PZ
10192 /*
10193 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
10194 * the first flag owns it; cleared by nohz_csd_func().
10195 */
a4064fb6 10196 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
b7031a02 10197 if (flags & NOHZ_KICK_MASK)
1c792db7 10198 return;
4550487a 10199
1c792db7 10200 /*
90b5363a 10201 * This way we generate an IPI on the target CPU which
1c792db7
SS
10202 * is idle. And the softirq performing nohz idle load balance
10203 * will be run before returning from the IPI.
10204 */
90b5363a 10205 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
4550487a
PZ
10206}
10207
10208/*
9f132742
VS
10209 * Current decision point for kicking the idle load balancer in the presence
10210 * of idle CPUs in the system.
4550487a
PZ
10211 */
10212static void nohz_balancer_kick(struct rq *rq)
10213{
10214 unsigned long now = jiffies;
10215 struct sched_domain_shared *sds;
10216 struct sched_domain *sd;
10217 int nr_busy, i, cpu = rq->cpu;
a4064fb6 10218 unsigned int flags = 0;
4550487a
PZ
10219
10220 if (unlikely(rq->idle_balance))
10221 return;
10222
10223 /*
10224 * We may be recently in ticked or tickless idle mode. At the first
10225 * busy tick after returning from idle, we will update the busy stats.
10226 */
00357f5e 10227 nohz_balance_exit_idle(rq);
4550487a
PZ
10228
10229 /*
10230 * None are in tickless mode and hence no need for NOHZ idle load
10231 * balancing.
10232 */
10233 if (likely(!atomic_read(&nohz.nr_cpus)))
10234 return;
10235
f643ea22
VG
10236 if (READ_ONCE(nohz.has_blocked) &&
10237 time_after(now, READ_ONCE(nohz.next_blocked)))
a4064fb6
PZ
10238 flags = NOHZ_STATS_KICK;
10239
4550487a 10240 if (time_before(now, nohz.next_balance))
a4064fb6 10241 goto out;
4550487a 10242
a0fe2cf0 10243 if (rq->nr_running >= 2) {
a4064fb6 10244 flags = NOHZ_KICK_MASK;
4550487a
PZ
10245 goto out;
10246 }
10247
10248 rcu_read_lock();
4550487a
PZ
10249
10250 sd = rcu_dereference(rq->sd);
10251 if (sd) {
e25a7a94
VS
10252 /*
10253 * If there's a CFS task and the current CPU has reduced
10254 * capacity; kick the ILB to see if there's a better CPU to run
10255 * on.
10256 */
10257 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
a4064fb6 10258 flags = NOHZ_KICK_MASK;
4550487a
PZ
10259 goto unlock;
10260 }
10261 }
10262
011b27bb 10263 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
4550487a 10264 if (sd) {
b9a7b883
VS
10265 /*
10266 * When ASYM_PACKING; see if there's a more preferred CPU
10267 * currently idle; in which case, kick the ILB to move tasks
10268 * around.
10269 */
7edab78d 10270 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
4550487a 10271 if (sched_asym_prefer(i, cpu)) {
a4064fb6 10272 flags = NOHZ_KICK_MASK;
4550487a
PZ
10273 goto unlock;
10274 }
10275 }
10276 }
b9a7b883 10277
a0fe2cf0
VS
10278 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
10279 if (sd) {
10280 /*
10281 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
10282 * to run the misfit task on.
10283 */
10284 if (check_misfit_status(rq, sd)) {
10285 flags = NOHZ_KICK_MASK;
10286 goto unlock;
10287 }
b9a7b883
VS
10288
10289 /*
10290 * For asymmetric systems, we do not want to nicely balance
10291 * cache use, instead we want to embrace asymmetry and only
10292 * ensure tasks have enough CPU capacity.
10293 *
10294 * Skip the LLC logic because it's not relevant in that case.
10295 */
10296 goto unlock;
a0fe2cf0
VS
10297 }
10298
b9a7b883
VS
10299 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
10300 if (sds) {
e25a7a94 10301 /*
b9a7b883
VS
10302 * If there is an imbalance between LLC domains (IOW we could
10303 * increase the overall cache use), we need some less-loaded LLC
10304 * domain to pull some load. Likewise, we may need to spread
10305 * load within the current LLC domain (e.g. packed SMT cores but
10306 * other CPUs are idle). We can't really know from here how busy
10307 * the others are - so just get a nohz balance going if it looks
10308 * like this LLC domain has tasks we could move.
e25a7a94 10309 */
b9a7b883
VS
10310 nr_busy = atomic_read(&sds->nr_busy_cpus);
10311 if (nr_busy > 1) {
10312 flags = NOHZ_KICK_MASK;
10313 goto unlock;
4550487a
PZ
10314 }
10315 }
10316unlock:
10317 rcu_read_unlock();
10318out:
a4064fb6
PZ
10319 if (flags)
10320 kick_ilb(flags);
83cd4fe2
VP
10321}
10322
00357f5e 10323static void set_cpu_sd_state_busy(int cpu)
71325960 10324{
00357f5e 10325 struct sched_domain *sd;
a22e47a4 10326
00357f5e
PZ
10327 rcu_read_lock();
10328 sd = rcu_dereference(per_cpu(sd_llc, cpu));
a22e47a4 10329
00357f5e
PZ
10330 if (!sd || !sd->nohz_idle)
10331 goto unlock;
10332 sd->nohz_idle = 0;
10333
10334 atomic_inc(&sd->shared->nr_busy_cpus);
10335unlock:
10336 rcu_read_unlock();
71325960
SS
10337}
10338
00357f5e
PZ
10339void nohz_balance_exit_idle(struct rq *rq)
10340{
10341 SCHED_WARN_ON(rq != this_rq());
10342
10343 if (likely(!rq->nohz_tick_stopped))
10344 return;
10345
10346 rq->nohz_tick_stopped = 0;
10347 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
10348 atomic_dec(&nohz.nr_cpus);
10349
10350 set_cpu_sd_state_busy(rq->cpu);
10351}
10352
10353static void set_cpu_sd_state_idle(int cpu)
69e1e811
SS
10354{
10355 struct sched_domain *sd;
69e1e811 10356
69e1e811 10357 rcu_read_lock();
0e369d75 10358 sd = rcu_dereference(per_cpu(sd_llc, cpu));
25f55d9d
VG
10359
10360 if (!sd || sd->nohz_idle)
10361 goto unlock;
10362 sd->nohz_idle = 1;
10363
0e369d75 10364 atomic_dec(&sd->shared->nr_busy_cpus);
25f55d9d 10365unlock:
69e1e811
SS
10366 rcu_read_unlock();
10367}
10368
1e3c88bd 10369/*
97fb7a0a 10370 * This routine will record that the CPU is going idle with tick stopped.
0b005cf5 10371 * This info will be used in performing idle load balancing in the future.
1e3c88bd 10372 */
c1cc017c 10373void nohz_balance_enter_idle(int cpu)
1e3c88bd 10374{
00357f5e
PZ
10375 struct rq *rq = cpu_rq(cpu);
10376
10377 SCHED_WARN_ON(cpu != smp_processor_id());
10378
97fb7a0a 10379 /* If this CPU is going down, then nothing needs to be done: */
71325960
SS
10380 if (!cpu_active(cpu))
10381 return;
10382
387bc8b5 10383 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
de201559 10384 if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
387bc8b5
FW
10385 return;
10386
f643ea22
VG
10387 /*
10388 * Can be set safely without rq->lock held
10389 * If a clear happens, it will have evaluated last additions because
10390 * rq->lock is held during the check and the clear
10391 */
10392 rq->has_blocked_load = 1;
10393
10394 /*
10395 * The tick is still stopped but load could have been added in the
10396 * meantime. We set the nohz.has_blocked flag to trig a check of the
10397 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
10398 * of nohz.has_blocked can only happen after checking the new load
10399 */
00357f5e 10400 if (rq->nohz_tick_stopped)
f643ea22 10401 goto out;
1e3c88bd 10402
97fb7a0a 10403 /* If we're a completely isolated CPU, we don't play: */
00357f5e 10404 if (on_null_domain(rq))
d987fc7f
MG
10405 return;
10406
00357f5e
PZ
10407 rq->nohz_tick_stopped = 1;
10408
c1cc017c
AS
10409 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
10410 atomic_inc(&nohz.nr_cpus);
00357f5e 10411
f643ea22
VG
10412 /*
10413 * Ensures that if nohz_idle_balance() fails to observe our
10414 * @idle_cpus_mask store, it must observe the @has_blocked
10415 * store.
10416 */
10417 smp_mb__after_atomic();
10418
00357f5e 10419 set_cpu_sd_state_idle(cpu);
f643ea22
VG
10420
10421out:
10422 /*
10423 * Each time a cpu enter idle, we assume that it has blocked load and
10424 * enable the periodic update of the load of idle cpus
10425 */
10426 WRITE_ONCE(nohz.has_blocked, 1);
1e3c88bd 10427}
1e3c88bd 10428
3f5ad914
Y
10429static bool update_nohz_stats(struct rq *rq)
10430{
10431 unsigned int cpu = rq->cpu;
10432
10433 if (!rq->has_blocked_load)
10434 return false;
10435
10436 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
10437 return false;
10438
10439 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
10440 return true;
10441
10442 update_blocked_averages(cpu);
10443
10444 return rq->has_blocked_load;
10445}
10446
1e3c88bd 10447/*
31e77c93
VG
10448 * Internal function that runs load balance for all idle cpus. The load balance
10449 * can be a simple update of blocked load or a complete load balance with
10450 * tasks movement depending of flags.
1e3c88bd 10451 */
ab2dde5e 10452static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
31e77c93 10453 enum cpu_idle_type idle)
83cd4fe2 10454{
c5afb6a8 10455 /* Earliest time when we have to do rebalance again */
a4064fb6
PZ
10456 unsigned long now = jiffies;
10457 unsigned long next_balance = now + 60*HZ;
f643ea22 10458 bool has_blocked_load = false;
c5afb6a8 10459 int update_next_balance = 0;
b7031a02 10460 int this_cpu = this_rq->cpu;
b7031a02
PZ
10461 int balance_cpu;
10462 struct rq *rq;
83cd4fe2 10463
b7031a02 10464 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
83cd4fe2 10465
f643ea22
VG
10466 /*
10467 * We assume there will be no idle load after this update and clear
10468 * the has_blocked flag. If a cpu enters idle in the mean time, it will
10469 * set the has_blocked flag and trig another update of idle load.
10470 * Because a cpu that becomes idle, is added to idle_cpus_mask before
10471 * setting the flag, we are sure to not clear the state and not
10472 * check the load of an idle cpu.
10473 */
10474 WRITE_ONCE(nohz.has_blocked, 0);
10475
10476 /*
10477 * Ensures that if we miss the CPU, we must see the has_blocked
10478 * store from nohz_balance_enter_idle().
10479 */
10480 smp_mb();
10481
7a82e5f5
VG
10482 /*
10483 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
10484 * chance for other idle cpu to pull load.
10485 */
10486 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
10487 if (!idle_cpu(balance_cpu))
83cd4fe2
VP
10488 continue;
10489
10490 /*
97fb7a0a
IM
10491 * If this CPU gets work to do, stop the load balancing
10492 * work being done for other CPUs. Next load
83cd4fe2
VP
10493 * balancing owner will pick it up.
10494 */
f643ea22
VG
10495 if (need_resched()) {
10496 has_blocked_load = true;
10497 goto abort;
10498 }
83cd4fe2 10499
5ed4f1d9
VG
10500 rq = cpu_rq(balance_cpu);
10501
64f84f27 10502 has_blocked_load |= update_nohz_stats(rq);
f643ea22 10503
ed61bbc6
TC
10504 /*
10505 * If time for next balance is due,
10506 * do the balance.
10507 */
10508 if (time_after_eq(jiffies, rq->next_balance)) {
8a8c69c3
PZ
10509 struct rq_flags rf;
10510
31e77c93 10511 rq_lock_irqsave(rq, &rf);
ed61bbc6 10512 update_rq_clock(rq);
31e77c93 10513 rq_unlock_irqrestore(rq, &rf);
8a8c69c3 10514
b7031a02
PZ
10515 if (flags & NOHZ_BALANCE_KICK)
10516 rebalance_domains(rq, CPU_IDLE);
ed61bbc6 10517 }
83cd4fe2 10518
c5afb6a8
VG
10519 if (time_after(next_balance, rq->next_balance)) {
10520 next_balance = rq->next_balance;
10521 update_next_balance = 1;
10522 }
83cd4fe2 10523 }
c5afb6a8 10524
3ea2f097
VG
10525 /*
10526 * next_balance will be updated only when there is a need.
10527 * When the CPU is attached to null domain for ex, it will not be
10528 * updated.
10529 */
10530 if (likely(update_next_balance))
10531 nohz.next_balance = next_balance;
10532
f643ea22
VG
10533 WRITE_ONCE(nohz.next_blocked,
10534 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
10535
10536abort:
10537 /* There is still blocked load, enable periodic update */
10538 if (has_blocked_load)
10539 WRITE_ONCE(nohz.has_blocked, 1);
31e77c93
VG
10540}
10541
10542/*
10543 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
10544 * rebalancing for all the cpus for whom scheduler ticks are stopped.
10545 */
10546static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10547{
19a1f5ec 10548 unsigned int flags = this_rq->nohz_idle_balance;
31e77c93 10549
19a1f5ec 10550 if (!flags)
31e77c93
VG
10551 return false;
10552
19a1f5ec 10553 this_rq->nohz_idle_balance = 0;
31e77c93 10554
19a1f5ec 10555 if (idle != CPU_IDLE)
31e77c93
VG
10556 return false;
10557
10558 _nohz_idle_balance(this_rq, flags, idle);
10559
b7031a02 10560 return true;
83cd4fe2 10561}
31e77c93 10562
c6f88654
VG
10563/*
10564 * Check if we need to run the ILB for updating blocked load before entering
10565 * idle state.
10566 */
10567void nohz_run_idle_balance(int cpu)
10568{
10569 unsigned int flags;
10570
10571 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
10572
10573 /*
10574 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
10575 * (ie NOHZ_STATS_KICK set) and will do the same.
10576 */
10577 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
10578 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK, CPU_IDLE);
10579}
10580
31e77c93
VG
10581static void nohz_newidle_balance(struct rq *this_rq)
10582{
10583 int this_cpu = this_rq->cpu;
10584
10585 /*
10586 * This CPU doesn't want to be disturbed by scheduler
10587 * housekeeping
10588 */
10589 if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
10590 return;
10591
10592 /* Will wake up very soon. No time for doing anything else*/
10593 if (this_rq->avg_idle < sysctl_sched_migration_cost)
10594 return;
10595
10596 /* Don't need to update blocked load of idle CPUs*/
10597 if (!READ_ONCE(nohz.has_blocked) ||
10598 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
10599 return;
10600
31e77c93 10601 /*
c6f88654
VG
10602 * Set the need to trigger ILB in order to update blocked load
10603 * before entering idle state.
31e77c93 10604 */
c6f88654 10605 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
31e77c93
VG
10606}
10607
dd707247
PZ
10608#else /* !CONFIG_NO_HZ_COMMON */
10609static inline void nohz_balancer_kick(struct rq *rq) { }
10610
31e77c93 10611static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
b7031a02
PZ
10612{
10613 return false;
10614}
31e77c93
VG
10615
10616static inline void nohz_newidle_balance(struct rq *this_rq) { }
dd707247 10617#endif /* CONFIG_NO_HZ_COMMON */
83cd4fe2 10618
47ea5412 10619/*
5b78f2dc 10620 * newidle_balance is called by schedule() if this_cpu is about to become
47ea5412 10621 * idle. Attempts to pull tasks from other CPUs.
7277a34c
PZ
10622 *
10623 * Returns:
10624 * < 0 - we released the lock and there are !fair tasks present
10625 * 0 - failed, no new tasks
10626 * > 0 - success, new (fair) tasks present
47ea5412 10627 */
d91cecc1 10628static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
47ea5412
PZ
10629{
10630 unsigned long next_balance = jiffies + HZ;
10631 int this_cpu = this_rq->cpu;
10632 struct sched_domain *sd;
10633 int pulled_task = 0;
10634 u64 curr_cost = 0;
10635
5ba553ef 10636 update_misfit_status(NULL, this_rq);
e5e678e4
RR
10637
10638 /*
10639 * There is a task waiting to run. No need to search for one.
10640 * Return 0; the task will be enqueued when switching to idle.
10641 */
10642 if (this_rq->ttwu_pending)
10643 return 0;
10644
47ea5412
PZ
10645 /*
10646 * We must set idle_stamp _before_ calling idle_balance(), such that we
10647 * measure the duration of idle_balance() as idle time.
10648 */
10649 this_rq->idle_stamp = rq_clock(this_rq);
10650
10651 /*
10652 * Do not pull tasks towards !active CPUs...
10653 */
10654 if (!cpu_active(this_cpu))
10655 return 0;
10656
10657 /*
10658 * This is OK, because current is on_cpu, which avoids it being picked
10659 * for load-balance and preemption/IRQs are still disabled avoiding
10660 * further scheduler activity on it and we're being very careful to
10661 * re-start the picking loop.
10662 */
10663 rq_unpin_lock(this_rq, rf);
10664
10665 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
e90c8fe1 10666 !READ_ONCE(this_rq->rd->overload)) {
31e77c93 10667
47ea5412
PZ
10668 rcu_read_lock();
10669 sd = rcu_dereference_check_sched_domain(this_rq->sd);
10670 if (sd)
10671 update_next_balance(sd, &next_balance);
10672 rcu_read_unlock();
10673
10674 goto out;
10675 }
10676
5cb9eaa3 10677 raw_spin_rq_unlock(this_rq);
47ea5412
PZ
10678
10679 update_blocked_averages(this_cpu);
10680 rcu_read_lock();
10681 for_each_domain(this_cpu, sd) {
10682 int continue_balancing = 1;
10683 u64 t0, domain_cost;
10684
47ea5412
PZ
10685 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
10686 update_next_balance(sd, &next_balance);
10687 break;
10688 }
10689
10690 if (sd->flags & SD_BALANCE_NEWIDLE) {
10691 t0 = sched_clock_cpu(this_cpu);
10692
10693 pulled_task = load_balance(this_cpu, this_rq,
10694 sd, CPU_NEWLY_IDLE,
10695 &continue_balancing);
10696
10697 domain_cost = sched_clock_cpu(this_cpu) - t0;
10698 if (domain_cost > sd->max_newidle_lb_cost)
10699 sd->max_newidle_lb_cost = domain_cost;
10700
10701 curr_cost += domain_cost;
10702 }
10703
10704 update_next_balance(sd, &next_balance);
10705
10706 /*
10707 * Stop searching for tasks to pull if there are
10708 * now runnable tasks on this rq.
10709 */
e5e678e4
RR
10710 if (pulled_task || this_rq->nr_running > 0 ||
10711 this_rq->ttwu_pending)
47ea5412
PZ
10712 break;
10713 }
10714 rcu_read_unlock();
10715
5cb9eaa3 10716 raw_spin_rq_lock(this_rq);
47ea5412
PZ
10717
10718 if (curr_cost > this_rq->max_idle_balance_cost)
10719 this_rq->max_idle_balance_cost = curr_cost;
10720
10721 /*
10722 * While browsing the domains, we released the rq lock, a task could
10723 * have been enqueued in the meantime. Since we're not going idle,
10724 * pretend we pulled a task.
10725 */
10726 if (this_rq->cfs.h_nr_running && !pulled_task)
10727 pulled_task = 1;
10728
47ea5412
PZ
10729 /* Is there a task of a high priority class? */
10730 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
10731 pulled_task = -1;
10732
6553fc18
VG
10733out:
10734 /* Move the next balance forward */
10735 if (time_after(this_rq->next_balance, next_balance))
10736 this_rq->next_balance = next_balance;
10737
47ea5412
PZ
10738 if (pulled_task)
10739 this_rq->idle_stamp = 0;
0826530d
VG
10740 else
10741 nohz_newidle_balance(this_rq);
47ea5412
PZ
10742
10743 rq_repin_lock(this_rq, rf);
10744
10745 return pulled_task;
10746}
10747
83cd4fe2
VP
10748/*
10749 * run_rebalance_domains is triggered when needed from the scheduler tick.
10750 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
10751 */
0766f788 10752static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
1e3c88bd 10753{
208cb16b 10754 struct rq *this_rq = this_rq();
6eb57e0d 10755 enum cpu_idle_type idle = this_rq->idle_balance ?
1e3c88bd
PZ
10756 CPU_IDLE : CPU_NOT_IDLE;
10757
1e3c88bd 10758 /*
97fb7a0a
IM
10759 * If this CPU has a pending nohz_balance_kick, then do the
10760 * balancing on behalf of the other idle CPUs whose ticks are
d4573c3e 10761 * stopped. Do nohz_idle_balance *before* rebalance_domains to
97fb7a0a 10762 * give the idle CPUs a chance to load balance. Else we may
d4573c3e
PM
10763 * load balance only within the local sched_domain hierarchy
10764 * and abort nohz_idle_balance altogether if we pull some load.
1e3c88bd 10765 */
b7031a02
PZ
10766 if (nohz_idle_balance(this_rq, idle))
10767 return;
10768
10769 /* normal load balance */
10770 update_blocked_averages(this_rq->cpu);
d4573c3e 10771 rebalance_domains(this_rq, idle);
1e3c88bd
PZ
10772}
10773
1e3c88bd
PZ
10774/*
10775 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
1e3c88bd 10776 */
7caff66f 10777void trigger_load_balance(struct rq *rq)
1e3c88bd 10778{
e0b257c3
AMB
10779 /*
10780 * Don't need to rebalance while attached to NULL domain or
10781 * runqueue CPU is not active
10782 */
10783 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
c726099e
DL
10784 return;
10785
10786 if (time_after_eq(jiffies, rq->next_balance))
1e3c88bd 10787 raise_softirq(SCHED_SOFTIRQ);
4550487a
PZ
10788
10789 nohz_balancer_kick(rq);
1e3c88bd
PZ
10790}
10791
0bcdcf28
CE
10792static void rq_online_fair(struct rq *rq)
10793{
10794 update_sysctl();
0e59bdae
KT
10795
10796 update_runtime_enabled(rq);
0bcdcf28
CE
10797}
10798
10799static void rq_offline_fair(struct rq *rq)
10800{
10801 update_sysctl();
a4c96ae3
PB
10802
10803 /* Ensure any throttled groups are reachable by pick_next_task */
10804 unthrottle_offline_cfs_rqs(rq);
0bcdcf28
CE
10805}
10806
55e12e5e 10807#endif /* CONFIG_SMP */
e1d1484f 10808
8039e96f
VP
10809#ifdef CONFIG_SCHED_CORE
10810static inline bool
10811__entity_slice_used(struct sched_entity *se, int min_nr_tasks)
10812{
10813 u64 slice = sched_slice(cfs_rq_of(se), se);
10814 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
10815
10816 return (rtime * min_nr_tasks > slice);
10817}
10818
10819#define MIN_NR_TASKS_DURING_FORCEIDLE 2
10820static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
10821{
10822 if (!sched_core_enabled(rq))
10823 return;
10824
10825 /*
10826 * If runqueue has only one task which used up its slice and
10827 * if the sibling is forced idle, then trigger schedule to
10828 * give forced idle task a chance.
10829 *
10830 * sched_slice() considers only this active rq and it gets the
10831 * whole slice. But during force idle, we have siblings acting
10832 * like a single runqueue and hence we need to consider runnable
cc00c198 10833 * tasks on this CPU and the forced idle CPU. Ideally, we should
8039e96f 10834 * go through the forced idle rq, but that would be a perf hit.
cc00c198 10835 * We can assume that the forced idle CPU has at least
8039e96f 10836 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
cc00c198 10837 * if we need to give up the CPU.
8039e96f
VP
10838 */
10839 if (rq->core->core_forceidle && rq->cfs.nr_running == 1 &&
10840 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
10841 resched_curr(rq);
10842}
c6047c2e
JFG
10843
10844/*
10845 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
10846 */
10847static void se_fi_update(struct sched_entity *se, unsigned int fi_seq, bool forceidle)
10848{
10849 for_each_sched_entity(se) {
10850 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10851
10852 if (forceidle) {
10853 if (cfs_rq->forceidle_seq == fi_seq)
10854 break;
10855 cfs_rq->forceidle_seq = fi_seq;
10856 }
10857
10858 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
10859 }
10860}
10861
10862void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
10863{
10864 struct sched_entity *se = &p->se;
10865
10866 if (p->sched_class != &fair_sched_class)
10867 return;
10868
10869 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
10870}
10871
10872bool cfs_prio_less(struct task_struct *a, struct task_struct *b, bool in_fi)
10873{
10874 struct rq *rq = task_rq(a);
10875 struct sched_entity *sea = &a->se;
10876 struct sched_entity *seb = &b->se;
10877 struct cfs_rq *cfs_rqa;
10878 struct cfs_rq *cfs_rqb;
10879 s64 delta;
10880
10881 SCHED_WARN_ON(task_rq(b)->core != rq->core);
10882
10883#ifdef CONFIG_FAIR_GROUP_SCHED
10884 /*
10885 * Find an se in the hierarchy for tasks a and b, such that the se's
10886 * are immediate siblings.
10887 */
10888 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
10889 int sea_depth = sea->depth;
10890 int seb_depth = seb->depth;
10891
10892 if (sea_depth >= seb_depth)
10893 sea = parent_entity(sea);
10894 if (sea_depth <= seb_depth)
10895 seb = parent_entity(seb);
10896 }
10897
10898 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
10899 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
10900
10901 cfs_rqa = sea->cfs_rq;
10902 cfs_rqb = seb->cfs_rq;
10903#else
10904 cfs_rqa = &task_rq(a)->cfs;
10905 cfs_rqb = &task_rq(b)->cfs;
10906#endif
10907
10908 /*
10909 * Find delta after normalizing se's vruntime with its cfs_rq's
10910 * min_vruntime_fi, which would have been updated in prior calls
10911 * to se_fi_update().
10912 */
10913 delta = (s64)(sea->vruntime - seb->vruntime) +
10914 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
10915
10916 return delta > 0;
10917}
8039e96f
VP
10918#else
10919static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
10920#endif
10921
bf0f6f24 10922/*
d84b3131
FW
10923 * scheduler tick hitting a task of our scheduling class.
10924 *
10925 * NOTE: This function can be called remotely by the tick offload that
10926 * goes along full dynticks. Therefore no local assumption can be made
10927 * and everything must be accessed through the @rq and @curr passed in
10928 * parameters.
bf0f6f24 10929 */
8f4d37ec 10930static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
bf0f6f24
IM
10931{
10932 struct cfs_rq *cfs_rq;
10933 struct sched_entity *se = &curr->se;
10934
10935 for_each_sched_entity(se) {
10936 cfs_rq = cfs_rq_of(se);
8f4d37ec 10937 entity_tick(cfs_rq, se, queued);
bf0f6f24 10938 }
18bf2805 10939
b52da86e 10940 if (static_branch_unlikely(&sched_numa_balancing))
cbee9f88 10941 task_tick_numa(rq, curr);
3b1baa64
MR
10942
10943 update_misfit_status(curr, rq);
2802bf3c 10944 update_overutilized_status(task_rq(curr));
8039e96f
VP
10945
10946 task_tick_core(rq, curr);
bf0f6f24
IM
10947}
10948
10949/*
cd29fe6f
PZ
10950 * called on fork with the child task as argument from the parent's context
10951 * - child not yet on the tasklist
10952 * - preemption disabled
bf0f6f24 10953 */
cd29fe6f 10954static void task_fork_fair(struct task_struct *p)
bf0f6f24 10955{
4fc420c9
DN
10956 struct cfs_rq *cfs_rq;
10957 struct sched_entity *se = &p->se, *curr;
cd29fe6f 10958 struct rq *rq = this_rq();
8a8c69c3 10959 struct rq_flags rf;
bf0f6f24 10960
8a8c69c3 10961 rq_lock(rq, &rf);
861d034e
PZ
10962 update_rq_clock(rq);
10963
4fc420c9
DN
10964 cfs_rq = task_cfs_rq(current);
10965 curr = cfs_rq->curr;
e210bffd
PZ
10966 if (curr) {
10967 update_curr(cfs_rq);
b5d9d734 10968 se->vruntime = curr->vruntime;
e210bffd 10969 }
aeb73b04 10970 place_entity(cfs_rq, se, 1);
4d78e7b6 10971
cd29fe6f 10972 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
87fefa38 10973 /*
edcb60a3
IM
10974 * Upon rescheduling, sched_class::put_prev_task() will place
10975 * 'current' within the tree based on its new key value.
10976 */
4d78e7b6 10977 swap(curr->vruntime, se->vruntime);
8875125e 10978 resched_curr(rq);
4d78e7b6 10979 }
bf0f6f24 10980
88ec22d3 10981 se->vruntime -= cfs_rq->min_vruntime;
8a8c69c3 10982 rq_unlock(rq, &rf);
bf0f6f24
IM
10983}
10984
cb469845
SR
10985/*
10986 * Priority of the task has changed. Check to see if we preempt
10987 * the current task.
10988 */
da7a735e
PZ
10989static void
10990prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
cb469845 10991{
da0c1e65 10992 if (!task_on_rq_queued(p))
da7a735e
PZ
10993 return;
10994
7c2e8bbd
FW
10995 if (rq->cfs.nr_running == 1)
10996 return;
10997
cb469845
SR
10998 /*
10999 * Reschedule if we are currently running on this runqueue and
11000 * our priority decreased, or if we are not currently running on
11001 * this runqueue and our priority is higher than the current's
11002 */
65bcf072 11003 if (task_current(rq, p)) {
cb469845 11004 if (p->prio > oldprio)
8875125e 11005 resched_curr(rq);
cb469845 11006 } else
15afe09b 11007 check_preempt_curr(rq, p, 0);
cb469845
SR
11008}
11009
daa59407 11010static inline bool vruntime_normalized(struct task_struct *p)
da7a735e
PZ
11011{
11012 struct sched_entity *se = &p->se;
da7a735e
PZ
11013
11014 /*
daa59407
BP
11015 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
11016 * the dequeue_entity(.flags=0) will already have normalized the
11017 * vruntime.
11018 */
11019 if (p->on_rq)
11020 return true;
11021
11022 /*
11023 * When !on_rq, vruntime of the task has usually NOT been normalized.
11024 * But there are some cases where it has already been normalized:
da7a735e 11025 *
daa59407
BP
11026 * - A forked child which is waiting for being woken up by
11027 * wake_up_new_task().
11028 * - A task which has been woken up by try_to_wake_up() and
11029 * waiting for actually being woken up by sched_ttwu_pending().
da7a735e 11030 */
d0cdb3ce
SM
11031 if (!se->sum_exec_runtime ||
11032 (p->state == TASK_WAKING && p->sched_remote_wakeup))
daa59407
BP
11033 return true;
11034
11035 return false;
11036}
11037
09a43ace
VG
11038#ifdef CONFIG_FAIR_GROUP_SCHED
11039/*
11040 * Propagate the changes of the sched_entity across the tg tree to make it
11041 * visible to the root
11042 */
11043static void propagate_entity_cfs_rq(struct sched_entity *se)
11044{
11045 struct cfs_rq *cfs_rq;
11046
0258bdfa
OU
11047 list_add_leaf_cfs_rq(cfs_rq_of(se));
11048
09a43ace
VG
11049 /* Start to propagate at parent */
11050 se = se->parent;
11051
11052 for_each_sched_entity(se) {
11053 cfs_rq = cfs_rq_of(se);
11054
0258bdfa
OU
11055 if (!cfs_rq_throttled(cfs_rq)){
11056 update_load_avg(cfs_rq, se, UPDATE_TG);
11057 list_add_leaf_cfs_rq(cfs_rq);
11058 continue;
11059 }
09a43ace 11060
0258bdfa
OU
11061 if (list_add_leaf_cfs_rq(cfs_rq))
11062 break;
09a43ace
VG
11063 }
11064}
11065#else
11066static void propagate_entity_cfs_rq(struct sched_entity *se) { }
11067#endif
11068
df217913 11069static void detach_entity_cfs_rq(struct sched_entity *se)
daa59407 11070{
daa59407
BP
11071 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11072
9d89c257 11073 /* Catch up with the cfs_rq and remove our load when we leave */
88c0616e 11074 update_load_avg(cfs_rq, se, 0);
a05e8c51 11075 detach_entity_load_avg(cfs_rq, se);
fe749158 11076 update_tg_load_avg(cfs_rq);
09a43ace 11077 propagate_entity_cfs_rq(se);
da7a735e
PZ
11078}
11079
df217913 11080static void attach_entity_cfs_rq(struct sched_entity *se)
cb469845 11081{
daa59407 11082 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7855a35a
BP
11083
11084#ifdef CONFIG_FAIR_GROUP_SCHED
eb7a59b2
M
11085 /*
11086 * Since the real-depth could have been changed (only FAIR
11087 * class maintain depth value), reset depth properly.
11088 */
11089 se->depth = se->parent ? se->parent->depth + 1 : 0;
11090#endif
7855a35a 11091
df217913 11092 /* Synchronize entity with its cfs_rq */
88c0616e 11093 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
a4f9a0e5 11094 attach_entity_load_avg(cfs_rq, se);
fe749158 11095 update_tg_load_avg(cfs_rq);
09a43ace 11096 propagate_entity_cfs_rq(se);
df217913
VG
11097}
11098
11099static void detach_task_cfs_rq(struct task_struct *p)
11100{
11101 struct sched_entity *se = &p->se;
11102 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11103
11104 if (!vruntime_normalized(p)) {
11105 /*
11106 * Fix up our vruntime so that the current sleep doesn't
11107 * cause 'unlimited' sleep bonus.
11108 */
11109 place_entity(cfs_rq, se, 0);
11110 se->vruntime -= cfs_rq->min_vruntime;
11111 }
11112
11113 detach_entity_cfs_rq(se);
11114}
11115
11116static void attach_task_cfs_rq(struct task_struct *p)
11117{
11118 struct sched_entity *se = &p->se;
11119 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11120
11121 attach_entity_cfs_rq(se);
daa59407
BP
11122
11123 if (!vruntime_normalized(p))
11124 se->vruntime += cfs_rq->min_vruntime;
11125}
6efdb105 11126
daa59407
BP
11127static void switched_from_fair(struct rq *rq, struct task_struct *p)
11128{
11129 detach_task_cfs_rq(p);
11130}
11131
11132static void switched_to_fair(struct rq *rq, struct task_struct *p)
11133{
11134 attach_task_cfs_rq(p);
7855a35a 11135
daa59407 11136 if (task_on_rq_queued(p)) {
7855a35a 11137 /*
daa59407
BP
11138 * We were most likely switched from sched_rt, so
11139 * kick off the schedule if running, otherwise just see
11140 * if we can still preempt the current task.
7855a35a 11141 */
65bcf072 11142 if (task_current(rq, p))
daa59407
BP
11143 resched_curr(rq);
11144 else
11145 check_preempt_curr(rq, p, 0);
7855a35a 11146 }
cb469845
SR
11147}
11148
83b699ed
SV
11149/* Account for a task changing its policy or group.
11150 *
11151 * This routine is mostly called to set cfs_rq->curr field when a task
11152 * migrates between groups/classes.
11153 */
a0e813f2 11154static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
83b699ed 11155{
03b7fad1
PZ
11156 struct sched_entity *se = &p->se;
11157
11158#ifdef CONFIG_SMP
11159 if (task_on_rq_queued(p)) {
11160 /*
11161 * Move the next running task to the front of the list, so our
11162 * cfs_tasks list becomes MRU one.
11163 */
11164 list_move(&se->group_node, &rq->cfs_tasks);
11165 }
11166#endif
83b699ed 11167
ec12cb7f
PT
11168 for_each_sched_entity(se) {
11169 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11170
11171 set_next_entity(cfs_rq, se);
11172 /* ensure bandwidth has been allocated on our new cfs_rq */
11173 account_cfs_rq_runtime(cfs_rq, 0);
11174 }
83b699ed
SV
11175}
11176
029632fb
PZ
11177void init_cfs_rq(struct cfs_rq *cfs_rq)
11178{
bfb06889 11179 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
029632fb
PZ
11180 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
11181#ifndef CONFIG_64BIT
11182 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
11183#endif
141965c7 11184#ifdef CONFIG_SMP
2a2f5d4e 11185 raw_spin_lock_init(&cfs_rq->removed.lock);
9ee474f5 11186#endif
029632fb
PZ
11187}
11188
810b3817 11189#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
11190static void task_set_group_fair(struct task_struct *p)
11191{
11192 struct sched_entity *se = &p->se;
11193
11194 set_task_rq(p, task_cpu(p));
11195 se->depth = se->parent ? se->parent->depth + 1 : 0;
11196}
11197
bc54da21 11198static void task_move_group_fair(struct task_struct *p)
810b3817 11199{
daa59407 11200 detach_task_cfs_rq(p);
b2b5ce02 11201 set_task_rq(p, task_cpu(p));
6efdb105
BP
11202
11203#ifdef CONFIG_SMP
11204 /* Tell se's cfs_rq has been changed -- migrated */
11205 p->se.avg.last_update_time = 0;
11206#endif
daa59407 11207 attach_task_cfs_rq(p);
810b3817 11208}
029632fb 11209
ea86cb4b
VG
11210static void task_change_group_fair(struct task_struct *p, int type)
11211{
11212 switch (type) {
11213 case TASK_SET_GROUP:
11214 task_set_group_fair(p);
11215 break;
11216
11217 case TASK_MOVE_GROUP:
11218 task_move_group_fair(p);
11219 break;
11220 }
11221}
11222
029632fb
PZ
11223void free_fair_sched_group(struct task_group *tg)
11224{
11225 int i;
11226
11227 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
11228
11229 for_each_possible_cpu(i) {
11230 if (tg->cfs_rq)
11231 kfree(tg->cfs_rq[i]);
6fe1f348 11232 if (tg->se)
029632fb
PZ
11233 kfree(tg->se[i]);
11234 }
11235
11236 kfree(tg->cfs_rq);
11237 kfree(tg->se);
11238}
11239
11240int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11241{
029632fb 11242 struct sched_entity *se;
b7fa30c9 11243 struct cfs_rq *cfs_rq;
029632fb
PZ
11244 int i;
11245
6396bb22 11246 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
029632fb
PZ
11247 if (!tg->cfs_rq)
11248 goto err;
6396bb22 11249 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
029632fb
PZ
11250 if (!tg->se)
11251 goto err;
11252
11253 tg->shares = NICE_0_LOAD;
11254
11255 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
11256
11257 for_each_possible_cpu(i) {
11258 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
11259 GFP_KERNEL, cpu_to_node(i));
11260 if (!cfs_rq)
11261 goto err;
11262
11263 se = kzalloc_node(sizeof(struct sched_entity),
11264 GFP_KERNEL, cpu_to_node(i));
11265 if (!se)
11266 goto err_free_rq;
11267
11268 init_cfs_rq(cfs_rq);
11269 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
540247fb 11270 init_entity_runnable_average(se);
029632fb
PZ
11271 }
11272
11273 return 1;
11274
11275err_free_rq:
11276 kfree(cfs_rq);
11277err:
11278 return 0;
11279}
11280
8663e24d
PZ
11281void online_fair_sched_group(struct task_group *tg)
11282{
11283 struct sched_entity *se;
a46d14ec 11284 struct rq_flags rf;
8663e24d
PZ
11285 struct rq *rq;
11286 int i;
11287
11288 for_each_possible_cpu(i) {
11289 rq = cpu_rq(i);
11290 se = tg->se[i];
a46d14ec 11291 rq_lock_irq(rq, &rf);
4126bad6 11292 update_rq_clock(rq);
d0326691 11293 attach_entity_cfs_rq(se);
55e16d30 11294 sync_throttle(tg, i);
a46d14ec 11295 rq_unlock_irq(rq, &rf);
8663e24d
PZ
11296 }
11297}
11298
6fe1f348 11299void unregister_fair_sched_group(struct task_group *tg)
029632fb 11300{
029632fb 11301 unsigned long flags;
6fe1f348
PZ
11302 struct rq *rq;
11303 int cpu;
029632fb 11304
6fe1f348
PZ
11305 for_each_possible_cpu(cpu) {
11306 if (tg->se[cpu])
11307 remove_entity_load_avg(tg->se[cpu]);
029632fb 11308
6fe1f348
PZ
11309 /*
11310 * Only empty task groups can be destroyed; so we can speculatively
11311 * check on_list without danger of it being re-added.
11312 */
11313 if (!tg->cfs_rq[cpu]->on_list)
11314 continue;
11315
11316 rq = cpu_rq(cpu);
11317
5cb9eaa3 11318 raw_spin_rq_lock_irqsave(rq, flags);
6fe1f348 11319 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
5cb9eaa3 11320 raw_spin_rq_unlock_irqrestore(rq, flags);
6fe1f348 11321 }
029632fb
PZ
11322}
11323
11324void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
11325 struct sched_entity *se, int cpu,
11326 struct sched_entity *parent)
11327{
11328 struct rq *rq = cpu_rq(cpu);
11329
11330 cfs_rq->tg = tg;
11331 cfs_rq->rq = rq;
029632fb
PZ
11332 init_cfs_rq_runtime(cfs_rq);
11333
11334 tg->cfs_rq[cpu] = cfs_rq;
11335 tg->se[cpu] = se;
11336
11337 /* se could be NULL for root_task_group */
11338 if (!se)
11339 return;
11340
fed14d45 11341 if (!parent) {
029632fb 11342 se->cfs_rq = &rq->cfs;
fed14d45
PZ
11343 se->depth = 0;
11344 } else {
029632fb 11345 se->cfs_rq = parent->my_q;
fed14d45
PZ
11346 se->depth = parent->depth + 1;
11347 }
029632fb
PZ
11348
11349 se->my_q = cfs_rq;
0ac9b1c2
PT
11350 /* guarantee group entities always have weight */
11351 update_load_set(&se->load, NICE_0_LOAD);
029632fb
PZ
11352 se->parent = parent;
11353}
11354
11355static DEFINE_MUTEX(shares_mutex);
11356
11357int sched_group_set_shares(struct task_group *tg, unsigned long shares)
11358{
11359 int i;
029632fb
PZ
11360
11361 /*
11362 * We can't change the weight of the root cgroup.
11363 */
11364 if (!tg->se[0])
11365 return -EINVAL;
11366
11367 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
11368
11369 mutex_lock(&shares_mutex);
11370 if (tg->shares == shares)
11371 goto done;
11372
11373 tg->shares = shares;
11374 for_each_possible_cpu(i) {
11375 struct rq *rq = cpu_rq(i);
8a8c69c3
PZ
11376 struct sched_entity *se = tg->se[i];
11377 struct rq_flags rf;
029632fb 11378
029632fb 11379 /* Propagate contribution to hierarchy */
8a8c69c3 11380 rq_lock_irqsave(rq, &rf);
71b1da46 11381 update_rq_clock(rq);
89ee048f 11382 for_each_sched_entity(se) {
88c0616e 11383 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
1ea6c46a 11384 update_cfs_group(se);
89ee048f 11385 }
8a8c69c3 11386 rq_unlock_irqrestore(rq, &rf);
029632fb
PZ
11387 }
11388
11389done:
11390 mutex_unlock(&shares_mutex);
11391 return 0;
11392}
11393#else /* CONFIG_FAIR_GROUP_SCHED */
11394
11395void free_fair_sched_group(struct task_group *tg) { }
11396
11397int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11398{
11399 return 1;
11400}
11401
8663e24d
PZ
11402void online_fair_sched_group(struct task_group *tg) { }
11403
6fe1f348 11404void unregister_fair_sched_group(struct task_group *tg) { }
029632fb
PZ
11405
11406#endif /* CONFIG_FAIR_GROUP_SCHED */
11407
810b3817 11408
6d686f45 11409static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
0d721cea
PW
11410{
11411 struct sched_entity *se = &task->se;
0d721cea
PW
11412 unsigned int rr_interval = 0;
11413
11414 /*
11415 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11416 * idle runqueue:
11417 */
0d721cea 11418 if (rq->cfs.load.weight)
a59f4e07 11419 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
0d721cea
PW
11420
11421 return rr_interval;
11422}
11423
bf0f6f24
IM
11424/*
11425 * All the scheduling class methods:
11426 */
43c31ac0
PZ
11427DEFINE_SCHED_CLASS(fair) = {
11428
bf0f6f24
IM
11429 .enqueue_task = enqueue_task_fair,
11430 .dequeue_task = dequeue_task_fair,
11431 .yield_task = yield_task_fair,
d95f4122 11432 .yield_to_task = yield_to_task_fair,
bf0f6f24 11433
2e09bf55 11434 .check_preempt_curr = check_preempt_wakeup,
bf0f6f24 11435
98c2f700 11436 .pick_next_task = __pick_next_task_fair,
bf0f6f24 11437 .put_prev_task = put_prev_task_fair,
03b7fad1 11438 .set_next_task = set_next_task_fair,
bf0f6f24 11439
681f3e68 11440#ifdef CONFIG_SMP
6e2df058 11441 .balance = balance_fair,
21f56ffe 11442 .pick_task = pick_task_fair,
4ce72a2c 11443 .select_task_rq = select_task_rq_fair,
0a74bef8 11444 .migrate_task_rq = migrate_task_rq_fair,
141965c7 11445
0bcdcf28
CE
11446 .rq_online = rq_online_fair,
11447 .rq_offline = rq_offline_fair,
88ec22d3 11448
12695578 11449 .task_dead = task_dead_fair,
c5b28038 11450 .set_cpus_allowed = set_cpus_allowed_common,
681f3e68 11451#endif
bf0f6f24 11452
bf0f6f24 11453 .task_tick = task_tick_fair,
cd29fe6f 11454 .task_fork = task_fork_fair,
cb469845
SR
11455
11456 .prio_changed = prio_changed_fair,
da7a735e 11457 .switched_from = switched_from_fair,
cb469845 11458 .switched_to = switched_to_fair,
810b3817 11459
0d721cea
PW
11460 .get_rr_interval = get_rr_interval_fair,
11461
6e998916
SG
11462 .update_curr = update_curr_fair,
11463
810b3817 11464#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b 11465 .task_change_group = task_change_group_fair,
810b3817 11466#endif
982d9cdc
PB
11467
11468#ifdef CONFIG_UCLAMP_TASK
11469 .uclamp_enabled = 1,
11470#endif
bf0f6f24
IM
11471};
11472
11473#ifdef CONFIG_SCHED_DEBUG
029632fb 11474void print_cfs_stats(struct seq_file *m, int cpu)
bf0f6f24 11475{
039ae8bc 11476 struct cfs_rq *cfs_rq, *pos;
bf0f6f24 11477
5973e5b9 11478 rcu_read_lock();
039ae8bc 11479 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
5cef9eca 11480 print_cfs_rq(m, cpu, cfs_rq);
5973e5b9 11481 rcu_read_unlock();
bf0f6f24 11482}
397f2378
SD
11483
11484#ifdef CONFIG_NUMA_BALANCING
11485void show_numa_stats(struct task_struct *p, struct seq_file *m)
11486{
11487 int node;
11488 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
cb361d8c 11489 struct numa_group *ng;
397f2378 11490
cb361d8c
JH
11491 rcu_read_lock();
11492 ng = rcu_dereference(p->numa_group);
397f2378
SD
11493 for_each_online_node(node) {
11494 if (p->numa_faults) {
11495 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
11496 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
11497 }
cb361d8c
JH
11498 if (ng) {
11499 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
11500 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
397f2378
SD
11501 }
11502 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
11503 }
cb361d8c 11504 rcu_read_unlock();
397f2378
SD
11505}
11506#endif /* CONFIG_NUMA_BALANCING */
11507#endif /* CONFIG_SCHED_DEBUG */
029632fb
PZ
11508
11509__init void init_sched_fair_class(void)
11510{
11511#ifdef CONFIG_SMP
11512 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
11513
3451d024 11514#ifdef CONFIG_NO_HZ_COMMON
554cecaf 11515 nohz.next_balance = jiffies;
f643ea22 11516 nohz.next_blocked = jiffies;
029632fb 11517 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
029632fb
PZ
11518#endif
11519#endif /* SMP */
11520
11521}
3c93a0c0
QY
11522
11523/*
11524 * Helper functions to facilitate extracting info from tracepoints.
11525 */
11526
11527const struct sched_avg *sched_trace_cfs_rq_avg(struct cfs_rq *cfs_rq)
11528{
11529#ifdef CONFIG_SMP
11530 return cfs_rq ? &cfs_rq->avg : NULL;
11531#else
11532 return NULL;
11533#endif
11534}
11535EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_avg);
11536
11537char *sched_trace_cfs_rq_path(struct cfs_rq *cfs_rq, char *str, int len)
11538{
11539 if (!cfs_rq) {
11540 if (str)
11541 strlcpy(str, "(null)", len);
11542 else
11543 return NULL;
11544 }
11545
11546 cfs_rq_tg_path(cfs_rq, str, len);
11547 return str;
11548}
11549EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_path);
11550
11551int sched_trace_cfs_rq_cpu(struct cfs_rq *cfs_rq)
11552{
11553 return cfs_rq ? cpu_of(rq_of(cfs_rq)) : -1;
11554}
11555EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_cpu);
11556
11557const struct sched_avg *sched_trace_rq_avg_rt(struct rq *rq)
11558{
11559#ifdef CONFIG_SMP
11560 return rq ? &rq->avg_rt : NULL;
11561#else
11562 return NULL;
11563#endif
11564}
11565EXPORT_SYMBOL_GPL(sched_trace_rq_avg_rt);
11566
11567const struct sched_avg *sched_trace_rq_avg_dl(struct rq *rq)
11568{
11569#ifdef CONFIG_SMP
11570 return rq ? &rq->avg_dl : NULL;
11571#else
11572 return NULL;
11573#endif
11574}
11575EXPORT_SYMBOL_GPL(sched_trace_rq_avg_dl);
11576
11577const struct sched_avg *sched_trace_rq_avg_irq(struct rq *rq)
11578{
11579#if defined(CONFIG_SMP) && defined(CONFIG_HAVE_SCHED_AVG_IRQ)
11580 return rq ? &rq->avg_irq : NULL;
11581#else
11582 return NULL;
11583#endif
11584}
11585EXPORT_SYMBOL_GPL(sched_trace_rq_avg_irq);
11586
11587int sched_trace_rq_cpu(struct rq *rq)
11588{
11589 return rq ? cpu_of(rq) : -1;
11590}
11591EXPORT_SYMBOL_GPL(sched_trace_rq_cpu);
11592
51cf18c9
VD
11593int sched_trace_rq_cpu_capacity(struct rq *rq)
11594{
11595 return rq ?
11596#ifdef CONFIG_SMP
11597 rq->cpu_capacity
11598#else
11599 SCHED_CAPACITY_SCALE
11600#endif
11601 : -1;
11602}
11603EXPORT_SYMBOL_GPL(sched_trace_rq_cpu_capacity);
11604
3c93a0c0
QY
11605const struct cpumask *sched_trace_rd_span(struct root_domain *rd)
11606{
11607#ifdef CONFIG_SMP
11608 return rd ? rd->span : NULL;
11609#else
11610 return NULL;
11611#endif
11612}
11613EXPORT_SYMBOL_GPL(sched_trace_rd_span);
9d246053
PA
11614
11615int sched_trace_rq_nr_running(struct rq *rq)
11616{
11617 return rq ? rq->nr_running : -1;
11618}
11619EXPORT_SYMBOL_GPL(sched_trace_rq_nr_running);