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