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