1 // SPDX-License-Identifier: GPL-2.0
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, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
19 *
20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22 */
23 #include <linux/energy_model.h>
24 #include <linux/mmap_lock.h>
25 #include <linux/hugetlb_inline.h>
26 #include <linux/jiffies.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/hrtimer.h>
30 #include <linux/hrtimer_bases.h>
31 #include <linux/spinlock_api.h>
32 #include <linux/cpumask_api.h>
33 #include <linux/lockdep_api.h>
34 #include <linux/softirq.h>
35 #include <linux/refcount_api.h>
36 #include <linux/topology.h>
37 #include <linux/sched/clock.h>
38 #include <linux/sched/cond_resched.h>
39 #include <linux/sched/cputime.h>
40 #include <linux/sched/isolation.h>
41 #include <linux/sched/nohz.h>
42 #include <linux/sched/prio.h>
43 #include <linux/static_call.h>
44
45 #include <linux/cpuidle.h>
46 #include <linux/interrupt.h>
47 #include <linux/memory-tiers.h>
48 #include <linux/mempolicy.h>
49 #include <linux/mutex_api.h>
50 #include <linux/profile.h>
51 #include <linux/psi.h>
52 #include <linux/ratelimit.h>
53 #include <linux/task_work.h>
54 #include <linux/rbtree_augmented.h>
55
56 #include <asm/switch_to.h>
57
58 #include <uapi/linux/sched/types.h>
59
60 #include "sched.h"
61 #include "stats.h"
62 #include "autogroup.h"
63
64 /*
65 * The initial- and re-scaling of tunables is configurable
66 *
67 * Options are:
68 *
69 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
70 * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
71 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
72 *
73 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
74 */
75 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
76
77 /*
78 * Default base time slice (request size r_i) for SCHED_NORMAL/SCHED_BATCH:
79 *
80 * Under EEVDF this is the request size used to compute the virtual
81 * deadline; see update_deadline().
82 *
83 * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
84 */
85 unsigned int sysctl_sched_base_slice = 700000ULL;
86 static unsigned int normalized_sysctl_sched_base_slice = 700000ULL;
87
88 __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL;
89
setup_sched_thermal_decay_shift(char * str)90 static int __init setup_sched_thermal_decay_shift(char *str)
91 {
92 pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
93 return 1;
94 }
95 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
96
97 /*
98 * For asym packing, by default the lower numbered CPU has higher priority.
99 */
arch_asym_cpu_priority(int cpu)100 int __weak arch_asym_cpu_priority(int cpu)
101 {
102 return -cpu;
103 }
104
105 /*
106 * The margin used when comparing utilization with CPU capacity.
107 *
108 * (default: ~20%)
109 */
110 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
111
112 /*
113 * The margin used when comparing CPU capacities.
114 * is 'cap1' noticeably greater than 'cap2'
115 *
116 * (default: ~5%)
117 */
118 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
119
120 #ifdef CONFIG_CFS_BANDWIDTH
121 /*
122 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
123 * each time a cfs_rq requests quota.
124 *
125 * Note: in the case that the slice exceeds the runtime remaining (either due
126 * to consumption or the quota being specified to be smaller than the slice)
127 * we will always only issue the remaining available time.
128 *
129 * (default: 5 msec, units: microseconds)
130 */
131 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
132 #endif
133
134 #ifdef CONFIG_NUMA_BALANCING
135 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
136 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
137 #endif
138
139 #ifdef CONFIG_SYSCTL
140 static const struct ctl_table sched_fair_sysctls[] = {
141 #ifdef CONFIG_CFS_BANDWIDTH
142 {
143 .procname = "sched_cfs_bandwidth_slice_us",
144 .data = &sysctl_sched_cfs_bandwidth_slice,
145 .maxlen = sizeof(unsigned int),
146 .mode = 0644,
147 .proc_handler = proc_dointvec_minmax,
148 .extra1 = SYSCTL_ONE,
149 },
150 #endif
151 #ifdef CONFIG_NUMA_BALANCING
152 {
153 .procname = "numa_balancing_promote_rate_limit_MBps",
154 .data = &sysctl_numa_balancing_promote_rate_limit,
155 .maxlen = sizeof(unsigned int),
156 .mode = 0644,
157 .proc_handler = proc_dointvec_minmax,
158 .extra1 = SYSCTL_ZERO,
159 },
160 #endif /* CONFIG_NUMA_BALANCING */
161 };
162
sched_fair_sysctl_init(void)163 static int __init sched_fair_sysctl_init(void)
164 {
165 register_sysctl_init("kernel", sched_fair_sysctls);
166 return 0;
167 }
168 late_initcall(sched_fair_sysctl_init);
169 #endif /* CONFIG_SYSCTL */
170
update_load_add(struct load_weight * lw,unsigned long inc)171 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
172 {
173 lw->weight += inc;
174 lw->inv_weight = 0;
175 }
176
update_load_sub(struct load_weight * lw,unsigned long dec)177 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
178 {
179 lw->weight -= dec;
180 lw->inv_weight = 0;
181 }
182
update_load_set(struct load_weight * lw,unsigned long w)183 static inline void update_load_set(struct load_weight *lw, unsigned long w)
184 {
185 lw->weight = w;
186 lw->inv_weight = 0;
187 }
188
189 /*
190 * Increase the granularity value when there are more CPUs,
191 * because with more CPUs the 'effective latency' as visible
192 * to users decreases. But the relationship is not linear,
193 * so pick a second-best guess by going with the log2 of the
194 * number of CPUs.
195 *
196 * This idea comes from the SD scheduler of Con Kolivas:
197 */
get_update_sysctl_factor(void)198 static unsigned int get_update_sysctl_factor(void)
199 {
200 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
201 unsigned int factor;
202
203 switch (sysctl_sched_tunable_scaling) {
204 case SCHED_TUNABLESCALING_NONE:
205 factor = 1;
206 break;
207 case SCHED_TUNABLESCALING_LINEAR:
208 factor = cpus;
209 break;
210 case SCHED_TUNABLESCALING_LOG:
211 default:
212 factor = 1 + ilog2(cpus);
213 break;
214 }
215
216 return factor;
217 }
218
update_sysctl(void)219 static void update_sysctl(void)
220 {
221 unsigned int factor = get_update_sysctl_factor();
222
223 #define SET_SYSCTL(name) \
224 (sysctl_##name = (factor) * normalized_sysctl_##name)
225 SET_SYSCTL(sched_base_slice);
226 #undef SET_SYSCTL
227 }
228
sched_init_granularity(void)229 void __init sched_init_granularity(void)
230 {
231 update_sysctl();
232 }
233
234 #ifndef CONFIG_64BIT
235 #define WMULT_CONST (~0U)
236 #define WMULT_SHIFT 32
237
__update_inv_weight(struct load_weight * lw)238 static void __update_inv_weight(struct load_weight *lw)
239 {
240 unsigned long w;
241
242 if (likely(lw->inv_weight))
243 return;
244
245 w = scale_load_down(lw->weight);
246
247 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
248 lw->inv_weight = 1;
249 else if (unlikely(!w))
250 lw->inv_weight = WMULT_CONST;
251 else
252 lw->inv_weight = WMULT_CONST / w;
253 }
254
255 /*
256 * delta_exec * weight / lw.weight
257 * OR
258 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
259 *
260 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
261 * we're guaranteed shift stays positive because inv_weight is guaranteed to
262 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
263 *
264 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
265 * weight/lw.weight <= 1, and therefore our shift will also be positive.
266 */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)267 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
268 {
269 u64 fact = scale_load_down(weight);
270 u32 fact_hi = (u32)(fact >> 32);
271 int shift = WMULT_SHIFT;
272 int fs;
273
274 __update_inv_weight(lw);
275
276 if (unlikely(fact_hi)) {
277 fs = fls(fact_hi);
278 shift -= fs;
279 fact >>= fs;
280 }
281
282 fact = mul_u32_u32(fact, lw->inv_weight);
283
284 fact_hi = (u32)(fact >> 32);
285 if (fact_hi) {
286 fs = fls(fact_hi);
287 shift -= fs;
288 fact >>= fs;
289 }
290
291 return mul_u64_u32_shr(delta_exec, fact, shift);
292 }
293 #else
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)294 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
295 {
296 return (delta_exec * weight) / lw->weight;
297 }
298 #endif
299
300 /*
301 * delta /= w
302 */
calc_delta_fair(u64 delta,struct sched_entity * se)303 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
304 {
305 if (se->h_load.weight != NICE_0_LOAD)
306 delta = __calc_delta(delta, NICE_0_LOAD, &se->h_load);
307
308 return delta;
309 }
310
311 const struct sched_class fair_sched_class;
312
313 /**************************************************************
314 * CFS operations on generic schedulable entities:
315 */
316
317 #ifdef CONFIG_FAIR_GROUP_SCHED
318
319 /* Walk up scheduling entities hierarchy */
320 #define for_each_sched_entity(se) \
321 for (; se; se = se->parent)
322
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)323 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
324 {
325 struct rq *rq = rq_of(cfs_rq);
326 int cpu = cpu_of(rq);
327
328 if (cfs_rq->on_list)
329 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
330
331 cfs_rq->on_list = 1;
332
333 /*
334 * Ensure we either appear before our parent (if already
335 * enqueued) or force our parent to appear after us when it is
336 * enqueued. The fact that we always enqueue bottom-up
337 * reduces this to two cases and a special case for the root
338 * cfs_rq. Furthermore, it also means that we will always reset
339 * tmp_alone_branch either when the branch is connected
340 * to a tree or when we reach the top of the tree
341 */
342 if (cfs_rq->tg->parent &&
343 tg_cfs_rq(cfs_rq->tg->parent, cpu)->on_list) {
344 /*
345 * If parent is already on the list, we add the child
346 * just before. Thanks to circular linked property of
347 * the list, this means to put the child at the tail
348 * of the list that starts by parent.
349 */
350 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
351 &(tg_cfs_rq(cfs_rq->tg->parent, cpu)->leaf_cfs_rq_list));
352 /*
353 * The branch is now connected to its tree so we can
354 * reset tmp_alone_branch to the beginning of the
355 * list.
356 */
357 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
358 return true;
359 }
360
361 if (!cfs_rq->tg->parent) {
362 /*
363 * cfs rq without parent should be put
364 * at the tail of the list.
365 */
366 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
367 &rq->leaf_cfs_rq_list);
368 /*
369 * We have reach the top of a tree so we can reset
370 * tmp_alone_branch to the beginning of the list.
371 */
372 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
373 return true;
374 }
375
376 /*
377 * The parent has not already been added so we want to
378 * make sure that it will be put after us.
379 * tmp_alone_branch points to the begin of the branch
380 * where we will add parent.
381 */
382 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
383 /*
384 * update tmp_alone_branch to points to the new begin
385 * of the branch
386 */
387 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
388 return false;
389 }
390
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)391 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
392 {
393 if (cfs_rq->on_list) {
394 struct rq *rq = rq_of(cfs_rq);
395
396 /*
397 * With cfs_rq being unthrottled/throttled during an enqueue,
398 * it can happen the tmp_alone_branch points to the leaf that
399 * we finally want to delete. In this case, tmp_alone_branch moves
400 * to the prev element but it will point to rq->leaf_cfs_rq_list
401 * at the end of the enqueue.
402 */
403 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
404 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
405
406 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
407 cfs_rq->on_list = 0;
408 }
409 }
410
assert_list_leaf_cfs_rq(struct rq * rq)411 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
412 {
413 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
414 }
415
416 /* Iterate through all leaf cfs_rq's on a runqueue */
417 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
418 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
419 leaf_cfs_rq_list)
420
421 /* Do the two (enqueued) entities belong to the same group ? */
422 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)423 is_same_group(struct sched_entity *se, struct sched_entity *pse)
424 {
425 if (se->cfs_rq == pse->cfs_rq)
426 return se->cfs_rq;
427
428 return NULL;
429 }
430
parent_entity(const struct sched_entity * se)431 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
432 {
433 return se->parent;
434 }
435
tg_is_idle(struct task_group * tg)436 static int tg_is_idle(struct task_group *tg)
437 {
438 return tg->idle > 0;
439 }
440
cfs_rq_is_idle(struct cfs_rq * cfs_rq)441 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
442 {
443 return cfs_rq->idle > 0;
444 }
445
se_is_idle(struct sched_entity * se)446 static int se_is_idle(struct sched_entity *se)
447 {
448 if (entity_is_task(se))
449 return task_has_idle_policy(task_of(se));
450 return cfs_rq_is_idle(group_cfs_rq(se));
451 }
452
453 #else /* !CONFIG_FAIR_GROUP_SCHED: */
454
455 #define for_each_sched_entity(se) \
456 for (; se; se = NULL)
457
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)458 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
459 {
460 return true;
461 }
462
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)463 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
464 {
465 }
466
assert_list_leaf_cfs_rq(struct rq * rq)467 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
468 {
469 }
470
471 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
472 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
473
parent_entity(struct sched_entity * se)474 static inline struct sched_entity *parent_entity(struct sched_entity *se)
475 {
476 return NULL;
477 }
478
tg_is_idle(struct task_group * tg)479 static inline int tg_is_idle(struct task_group *tg)
480 {
481 return 0;
482 }
483
cfs_rq_is_idle(struct cfs_rq * cfs_rq)484 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
485 {
486 return 0;
487 }
488
se_is_idle(struct sched_entity * se)489 static int se_is_idle(struct sched_entity *se)
490 {
491 return task_has_idle_policy(task_of(se));
492 }
493
494 #endif /* !CONFIG_FAIR_GROUP_SCHED */
495
496 static __always_inline
497 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
498
499 /**************************************************************
500 * Scheduling class tree data structure manipulation methods:
501 */
502
503 extern void __BUILD_BUG_vruntime_cmp(void);
504
505 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */
506
507 #define vruntime_cmp(A, CMP_STR, B) ({ \
508 int __res = 0; \
509 \
510 if (!__builtin_strcmp(CMP_STR, "<")) { \
511 __res = ((s64)((A)-(B)) < 0); \
512 } else if (!__builtin_strcmp(CMP_STR, "<=")) { \
513 __res = ((s64)((A)-(B)) <= 0); \
514 } else if (!__builtin_strcmp(CMP_STR, ">")) { \
515 __res = ((s64)((A)-(B)) > 0); \
516 } else if (!__builtin_strcmp(CMP_STR, ">=")) { \
517 __res = ((s64)((A)-(B)) >= 0); \
518 } else { \
519 /* Unknown operator throws linker error: */ \
520 __BUILD_BUG_vruntime_cmp(); \
521 } \
522 \
523 __res; \
524 })
525
526 extern void __BUILD_BUG_vruntime_op(void);
527
528 #define vruntime_op(A, OP_STR, B) ({ \
529 s64 __res = 0; \
530 \
531 if (!__builtin_strcmp(OP_STR, "-")) { \
532 __res = (s64)((A)-(B)); \
533 } else { \
534 /* Unknown operator throws linker error: */ \
535 __BUILD_BUG_vruntime_op(); \
536 } \
537 \
538 __res; \
539 })
540
541
max_vruntime(u64 max_vruntime,u64 vruntime)542 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
543 {
544 if (vruntime_cmp(vruntime, ">", max_vruntime))
545 max_vruntime = vruntime;
546
547 return max_vruntime;
548 }
549
min_vruntime(u64 min_vruntime,u64 vruntime)550 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
551 {
552 if (vruntime_cmp(vruntime, "<", min_vruntime))
553 min_vruntime = vruntime;
554
555 return min_vruntime;
556 }
557
entity_before(const struct sched_entity * a,const struct sched_entity * b)558 static inline bool entity_before(const struct sched_entity *a,
559 const struct sched_entity *b)
560 {
561 /*
562 * Tiebreak on vruntime seems unnecessary since it can
563 * hardly happen.
564 */
565 return vruntime_cmp(a->deadline, "<", b->deadline);
566 }
567
568 /*
569 * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale
570 * and this value should be no more than two lag bounds. Which puts it in the
571 * general order of:
572 *
573 * (slice + TICK_NSEC) << NICE_0_LOAD_SHIFT
574 *
575 * which is around 44 bits in size (on 64bit); that is 20 for
576 * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for
577 * however many msec the actual slice+tick ends up begin.
578 *
579 * (disregarding the actual divide-by-weight part makes for the worst case
580 * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually
581 * being the zero-lag point).
582 */
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)583 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
584 {
585 return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime);
586 }
587
588 #define __node_2_se(node) \
589 rb_entry((node), struct sched_entity, run_node)
590
591 /*
592 * Compute virtual time from the per-task service numbers:
593 *
594 * Fair schedulers conserve lag:
595 *
596 * \Sum lag_i = 0
597 *
598 * Where lag_i is given by:
599 *
600 * lag_i = S - s_i = w_i * (V - v_i)
601 *
602 * Where S is the ideal service time and V is it's virtual time counterpart.
603 * Therefore:
604 *
605 * \Sum lag_i = 0
606 * \Sum w_i * (V - v_i) = 0
607 * \Sum (w_i * V - w_i * v_i) = 0
608 *
609 * From which we can solve an expression for V in v_i (which we have in
610 * se->vruntime):
611 *
612 * \Sum v_i * w_i \Sum v_i * w_i
613 * V = -------------- = --------------
614 * \Sum w_i W
615 *
616 * Specifically, this is the weighted average of all entity virtual runtimes.
617 *
618 * [[ NOTE: this is only equal to the ideal scheduler under the condition
619 * that join/leave operations happen at lag_i = 0, otherwise the
620 * virtual time has non-contiguous motion equivalent to:
621 *
622 * V +-= lag_i / W
623 *
624 * Also see the comment in place_entity() that deals with this. ]]
625 *
626 * However, since v_i is u64, and the multiplication could easily overflow
627 * transform it into a relative form that uses smaller quantities:
628 *
629 * Substitute: v_i == (v_i - v0) + v0
630 *
631 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
632 * V = ---------------------------- = --------------------- + v0
633 * W W
634 *
635 * Which we track using:
636 *
637 * v0 := cfs_rq->zero_vruntime
638 * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime
639 * \Sum w_i := cfs_rq->sum_weight
640 *
641 * Since zero_vruntime closely tracks the per-task service, these
642 * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag
643 * induced in the system due to quantisation.
644 */
avg_vruntime_weight(struct cfs_rq * cfs_rq,unsigned long w)645 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w)
646 {
647 #ifdef CONFIG_64BIT
648 if (cfs_rq->sum_shift)
649 w = max(2UL, w >> cfs_rq->sum_shift);
650 #endif
651 return w;
652 }
653
654 static inline void
__sum_w_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)655 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
656 {
657 unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
658 s64 w_vruntime, key = entity_key(cfs_rq, se);
659
660 w_vruntime = key * weight;
661 WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62));
662
663 cfs_rq->sum_w_vruntime += w_vruntime;
664 cfs_rq->sum_weight += weight;
665 }
666
667 static void
sum_w_vruntime_add_paranoid(struct cfs_rq * cfs_rq,struct sched_entity * se)668 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se)
669 {
670 unsigned long weight;
671 s64 key, tmp;
672
673 again:
674 weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
675 key = entity_key(cfs_rq, se);
676
677 if (check_mul_overflow(key, weight, &key))
678 goto overflow;
679
680 if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp))
681 goto overflow;
682
683 cfs_rq->sum_w_vruntime = tmp;
684 cfs_rq->sum_weight += weight;
685 return;
686
687 overflow:
688 /*
689 * There's gotta be a limit -- if we're still failing at this point
690 * there's really nothing much to be done about things.
691 */
692 BUG_ON(cfs_rq->sum_shift >= 10);
693 cfs_rq->sum_shift++;
694
695 /*
696 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1
697 */
698 cfs_rq->sum_w_vruntime = 0;
699 cfs_rq->sum_weight = 0;
700
701 for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost;
702 node; node = rb_next(node))
703 __sum_w_vruntime_add(cfs_rq, __node_2_se(node));
704
705 goto again;
706 }
707
708 static void
sum_w_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)709 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
710 {
711 if (sched_feat(PARANOID_AVG))
712 return sum_w_vruntime_add_paranoid(cfs_rq, se);
713
714 __sum_w_vruntime_add(cfs_rq, se);
715 }
716
717 static void
sum_w_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)718 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
719 {
720 unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
721 s64 key = entity_key(cfs_rq, se);
722
723 cfs_rq->sum_w_vruntime -= key * weight;
724 cfs_rq->sum_weight -= weight;
725 }
726
727 static inline
update_zero_vruntime(struct cfs_rq * cfs_rq,s64 delta)728 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta)
729 {
730 /*
731 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight
732 */
733 cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta;
734 cfs_rq->zero_vruntime += delta;
735 }
736
737 /*
738 * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true
739 * For this to be so, the result of this function must have a left bias.
740 *
741 * Called in:
742 * - place_entity() -- before enqueue
743 * - update_entity_lag() -- before dequeue
744 * - update_deadline() -- slice expiration
745 *
746 * This means it is one entry 'behind' but that puts it close enough to where
747 * the bound on entity_key() is at most two lag bounds.
748 */
avg_vruntime(struct cfs_rq * cfs_rq)749 u64 avg_vruntime(struct cfs_rq *cfs_rq)
750 {
751 struct sched_entity *curr = cfs_rq->curr;
752 long weight = cfs_rq->sum_weight;
753 s64 delta = 0;
754
755 if (curr && !curr->on_rq)
756 curr = NULL;
757
758 if (weight) {
759 s64 runtime = cfs_rq->sum_w_vruntime;
760
761 if (curr) {
762 unsigned long w = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
763
764 runtime += entity_key(cfs_rq, curr) * w;
765 weight += w;
766 }
767
768 /* sign flips effective floor / ceiling */
769 if (runtime < 0)
770 runtime -= (weight - 1);
771
772 delta = div64_long(runtime, weight);
773 } else if (curr) {
774 /*
775 * When there is but one element, it is the average.
776 */
777 delta = curr->vruntime - cfs_rq->zero_vruntime;
778 }
779
780 update_zero_vruntime(cfs_rq, delta);
781
782 return cfs_rq->zero_vruntime;
783 }
784
785 /*
786 * \Sum (v_i - v0)*w_i
787 * V = ------------------- + v0
788 * \Sum w_i
789 *
790 * Let W = \Sum w_i, and move v_j such that 'v_j == V', thus:
791 *
792 * V = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0
793 *
794 * v_j = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0
795 *
796 * v_j = 1/W * (v_j - v0)*w_j + 1/W * \Sum_i!=j (v_i - v0)*w_i + v0
797 *
798 * v_j - 1/W * (v_j - v0)*w_j = 1/W * \Sum_i!=j (v_i - v0)*w_i + v0
799 *
800 * v_j*W - (v_j - v0)*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
801 *
802 * v_j*(W - w_j) + v0*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W
803 *
804 * v_j*(W - w_j) = \Sum_i!=j (v_i - v0)*w_i + v0*(W - w_j)
805 *
806 * \Sum_i!=j (v_i - v0)*w_i
807 * v_j = ------------------------ + v0
808 * W - w_j
809 *
810 * When v_j happens to be curr, then '\Sum_i!=j (v_i - v0)*w_i'
811 * is cfs_rq->sum_w_runtime, and 'W - w_j' is cfs_rq->sum_weight, since curr
812 * is not included in the sum.
813 */
ineligible_vruntime(struct cfs_rq * cfs_rq)814 static u64 ineligible_vruntime(struct cfs_rq *cfs_rq)
815 {
816 struct sched_entity *curr = cfs_rq->curr;
817 long weight = cfs_rq->sum_weight;
818 s64 delta = 0;
819
820 if (curr && !curr->on_rq)
821 curr = NULL;
822
823 /*
824 * This is called from set_next_task_fair(.first=true) /
825 * set_protect_slice() so curr had better be set and on_rq.
826 */
827 WARN_ON_ONCE(!curr);
828
829 if (weight) {
830 s64 runtime = cfs_rq->sum_w_vruntime;
831
832 /*
833 * Do not add @curr to obtain the effective '- w_j' terms.
834 */
835
836 /* sign flips effective floor / ceiling */
837 if (runtime < 0)
838 runtime -= (weight - 1);
839
840 delta = div64_long(runtime, weight);
841 }
842
843 return cfs_rq->zero_vruntime + delta + 1;
844 }
845
846 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq);
847
848 /*
849 * lag_i = S - s_i = w_i * (V - v_i)
850 *
851 * However, since V is approximated by the weighted average of all entities it
852 * is possible -- by addition/removal/reweight to the tree -- to move V around
853 * and end up with a larger lag than we started with.
854 *
855 * Limit this to either double the slice length with a minimum of TICK_NSEC
856 * since that is the timing granularity.
857 *
858 * EEVDF gives the following limit for a steady state system:
859 *
860 * -r_max < lag < max(r_max, q)
861 */
entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se,u64 avruntime)862 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime)
863 {
864 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC;
865 s64 vlag, limit;
866
867 vlag = avruntime - se->vruntime;
868 limit = calc_delta_fair(max_slice, se);
869
870 return clamp(vlag, -limit, limit);
871 }
872
873 /*
874 * Delayed dequeue aims to reduce the negative lag of a dequeued task. While
875 * updating the lag of an entity, check that negative lag didn't increase
876 * during the delayed dequeue period which would be unfair.
877 * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO
878 * is set.
879 *
880 * Return true if the vlag has been modified. Specifically:
881 *
882 * se->vlag != avg_vruntime() - se->vruntime
883 *
884 * This can be due to clamping in entity_lag() or clamping due to
885 * sched_delayed. Either way, when vlag is modified and the entity is
886 * retained, the tree needs to be adjusted.
887 */
888 static __always_inline
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)889 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
890 {
891 u64 avruntime = avg_vruntime(cfs_rq);
892 s64 vlag = entity_lag(cfs_rq, se, avruntime);
893
894 if (se->sched_delayed) {
895 /* previous vlag < 0 otherwise se would not be delayed */
896 vlag = max(vlag, se->vlag);
897 if (sched_feat(DELAY_ZERO))
898 vlag = min(vlag, 0);
899 }
900 se->vlag = vlag;
901
902 return avruntime - vlag != se->vruntime;
903 }
904
905 /*
906 * Entity is eligible once it received less service than it ought to have,
907 * eg. lag >= 0.
908 *
909 * lag_i = S - s_i = w_i*(V - v_i)
910 *
911 * lag_i >= 0 -> V >= v_i
912 *
913 * \Sum (v_i - v0)*w_i
914 * V = ------------------- + v0
915 * \Sum w_i
916 *
917 * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i)
918 *
919 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
920 * to the loss in precision caused by the division.
921 */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)922 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
923 {
924 struct sched_entity *curr = cfs_rq->curr;
925 s64 key, avg = cfs_rq->sum_w_vruntime;
926 long load = cfs_rq->sum_weight;
927
928 if (curr && curr->on_rq) {
929 unsigned long weight = avg_vruntime_weight(cfs_rq, curr->h_load.weight);
930
931 avg += entity_key(cfs_rq, curr) * weight;
932 load += weight;
933 }
934
935 key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime);
936
937 /*
938 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD'
939 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24
940 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise.
941 *
942 * This gives that on 64bit the product will be at least 64bit which
943 * overflows s64, while on 32bit it will only be 44bits and should fit
944 * comfortably.
945 */
946 #ifdef CONFIG_64BIT
947 #ifdef CONFIG_ARCH_SUPPORTS_INT128
948 /* This often results in simpler code than __builtin_mul_overflow(). */
949 return avg >= (__int128)key * load;
950 #else
951 s64 rhs;
952 /*
953 * On overflow, the sign of key tells us the correct answer: a large
954 * positive key means vruntime >> V, so not eligible; a large negative
955 * key means vruntime << V, so eligible.
956 */
957 if (check_mul_overflow(key, load, &rhs))
958 return key <= 0;
959
960 return avg >= rhs;
961 #endif
962 #else /* 32bit */
963 return avg >= key * load;
964 #endif
965 }
966
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)967 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
968 {
969 return vruntime_eligible(cfs_rq, se->vruntime);
970 }
971
cfs_rq_min_slice(struct cfs_rq * cfs_rq)972 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
973 {
974 struct sched_entity *root = __pick_root_entity(cfs_rq);
975 struct sched_entity *curr = cfs_rq->curr;
976 u64 min_slice = ~0ULL;
977
978 if (curr && curr->on_rq)
979 min_slice = curr->slice;
980
981 if (root)
982 min_slice = min(min_slice, root->min_slice);
983
984 return min_slice;
985 }
986
cfs_rq_max_slice(struct cfs_rq * cfs_rq)987 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq)
988 {
989 struct sched_entity *root = __pick_root_entity(cfs_rq);
990 struct sched_entity *curr = cfs_rq->curr;
991 u64 max_slice = 0ULL;
992
993 if (curr && curr->on_rq)
994 max_slice = curr->slice;
995
996 if (root)
997 max_slice = max(max_slice, root->max_slice);
998
999 return max_slice;
1000 }
1001
__entity_less(struct rb_node * a,const struct rb_node * b)1002 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
1003 {
1004 return entity_before(__node_2_se(a), __node_2_se(b));
1005 }
1006
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)1007 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
1008 {
1009 if (node) {
1010 struct sched_entity *rse = __node_2_se(node);
1011
1012 if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime))
1013 se->min_vruntime = rse->min_vruntime;
1014 }
1015 }
1016
__min_slice_update(struct sched_entity * se,struct rb_node * node)1017 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
1018 {
1019 if (node) {
1020 struct sched_entity *rse = __node_2_se(node);
1021 if (rse->min_slice < se->min_slice)
1022 se->min_slice = rse->min_slice;
1023 }
1024 }
1025
__max_slice_update(struct sched_entity * se,struct rb_node * node)1026 static inline void __max_slice_update(struct sched_entity *se, struct rb_node *node)
1027 {
1028 if (node) {
1029 struct sched_entity *rse = __node_2_se(node);
1030 if (rse->max_slice > se->max_slice)
1031 se->max_slice = rse->max_slice;
1032 }
1033 }
1034
min_vruntime_copy(struct sched_entity * new,struct sched_entity * old)1035 static inline void min_vruntime_copy(struct sched_entity *new, struct sched_entity *old)
1036 {
1037 new->min_vruntime = old->min_vruntime;
1038 new->min_slice = old->min_slice;
1039 new->max_slice = old->max_slice;
1040 }
1041
1042 /*
1043 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
1044 */
min_vruntime_update(struct sched_entity * se,bool exit)1045 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
1046 {
1047 u64 old_min_vruntime = se->min_vruntime;
1048 u64 old_min_slice = se->min_slice;
1049 u64 old_max_slice = se->max_slice;
1050 struct rb_node *node = &se->run_node;
1051
1052 se->min_vruntime = se->vruntime;
1053 __min_vruntime_update(se, node->rb_right);
1054 __min_vruntime_update(se, node->rb_left);
1055
1056 se->min_slice = se->slice;
1057 __min_slice_update(se, node->rb_right);
1058 __min_slice_update(se, node->rb_left);
1059
1060 se->max_slice = se->slice;
1061 __max_slice_update(se, node->rb_right);
1062 __max_slice_update(se, node->rb_left);
1063
1064 return se->min_vruntime == old_min_vruntime &&
1065 se->min_slice == old_min_slice &&
1066 se->max_slice == old_max_slice;
1067 }
1068
1069
1070 RB_DECLARE_CALLBACKS_MULTI(static, min_vruntime_cb, struct sched_entity,
1071 run_node, min_vruntime_copy, min_vruntime_update);
1072
1073 /*
1074 * Enqueue an entity into the rb-tree:
1075 */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)1076 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1077 {
1078 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1079 WARN_ON_ONCE(!entity_is_task(se));
1080
1081 sum_w_vruntime_add(cfs_rq, se);
1082 se->min_vruntime = se->vruntime;
1083 se->min_slice = se->slice;
1084 se->max_slice = se->slice;
1085
1086 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1087 __entity_less, &min_vruntime_cb);
1088 }
1089
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)1090 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1091 {
1092 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq);
1093 WARN_ON_ONCE(!entity_is_task(se));
1094
1095 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1096 &min_vruntime_cb);
1097 sum_w_vruntime_sub(cfs_rq, se);
1098 }
1099
__pick_root_entity(struct cfs_rq * cfs_rq)1100 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
1101 {
1102 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
1103
1104 if (!root)
1105 return NULL;
1106
1107 return __node_2_se(root);
1108 }
1109
__pick_first_entity(struct cfs_rq * cfs_rq)1110 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
1111 {
1112 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
1113
1114 if (!left)
1115 return NULL;
1116
1117 return __node_2_se(left);
1118 }
1119
1120 /*
1121 * Set the vruntime up to which an entity can run before looking
1122 * for another entity to pick.
1123 * In case of run to parity, we use the shortest slice of the enqueued
1124 * entities to set the protected period.
1125 * When run to parity is disabled, we give a minimum quantum to the running
1126 * entity to ensure progress.
1127 */
set_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)1128 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1129 {
1130 u64 slice = normalized_sysctl_sched_base_slice;
1131 u64 vprot = se->deadline;
1132
1133 if (sched_feat(RUN_TO_PARITY))
1134 slice = cfs_rq_min_slice(cfs_rq);
1135
1136 slice = min(slice, se->slice);
1137
1138 /* If there are shorter slices than se's one */
1139 if (slice != se->slice) {
1140 if (sched_feat(PREEMPT_SHORT))
1141 vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq));
1142 else
1143 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
1144 }
1145
1146 se->vprot = vprot;
1147 }
1148
update_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)1149 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1150 {
1151 u64 slice = cfs_rq_min_slice(cfs_rq);
1152 u64 vruntime = min_vruntime(se->vruntime, avg_vruntime(cfs_rq));
1153
1154 se->vprot = min_vruntime(se->vprot, vruntime + calc_delta_fair(slice, se));
1155 }
1156
protect_slice(struct sched_entity * se)1157 static inline bool protect_slice(struct sched_entity *se)
1158 {
1159 return vruntime_cmp(se->vruntime, "<", se->vprot);
1160 }
1161
cancel_protect_slice(struct sched_entity * se)1162 static inline void cancel_protect_slice(struct sched_entity *se)
1163 {
1164 if (protect_slice(se))
1165 se->vprot = se->vruntime;
1166 }
1167
1168 /*
1169 * Earliest Eligible Virtual Deadline First
1170 *
1171 * In order to provide latency guarantees for different request sizes
1172 * EEVDF selects the best runnable task from two criteria:
1173 *
1174 * 1) the task must be eligible (must be owed service)
1175 *
1176 * 2) from those tasks that meet 1), we select the one
1177 * with the earliest virtual deadline.
1178 *
1179 * We can do this in O(log n) time due to an augmented RB-tree. The
1180 * tree keeps the entries sorted on deadline, but also functions as a
1181 * heap based on the vruntime by keeping:
1182 *
1183 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
1184 *
1185 * Which allows tree pruning through eligibility.
1186 */
pick_eevdf(struct cfs_rq * cfs_rq,bool protect)1187 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
1188 {
1189 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
1190 struct sched_entity *se = __pick_first_entity(cfs_rq);
1191 struct sched_entity *curr = cfs_rq->curr;
1192 struct sched_entity *best = NULL;
1193
1194 /*
1195 * We can safely skip eligibility check if there is only one entity
1196 * in this cfs_rq, saving some cycles.
1197 */
1198 if (cfs_rq->h_nr_queued == 1)
1199 return curr && curr->on_rq ? curr : se;
1200
1201 /*
1202 * Picking the ->next buddy will affect latency but not fairness.
1203 */
1204 if (sched_feat(PICK_BUDDY) && protect &&
1205 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
1206 /* ->next will never be delayed */
1207 WARN_ON_ONCE(cfs_rq->next->sched_delayed);
1208 return cfs_rq->next;
1209 }
1210
1211 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
1212 curr = NULL;
1213
1214 if (curr && protect && protect_slice(curr))
1215 return curr;
1216
1217 /* Pick the leftmost entity if it's eligible */
1218 if (se && entity_eligible(cfs_rq, se)) {
1219 best = se;
1220 goto found;
1221 }
1222
1223 /* Heap search for the EEVD entity */
1224 while (node) {
1225 struct rb_node *left = node->rb_left;
1226
1227 /*
1228 * Eligible entities in left subtree are always better
1229 * choices, since they have earlier deadlines.
1230 */
1231 if (left && vruntime_eligible(cfs_rq,
1232 __node_2_se(left)->min_vruntime)) {
1233 node = left;
1234 continue;
1235 }
1236
1237 se = __node_2_se(node);
1238
1239 /*
1240 * The left subtree either is empty or has no eligible
1241 * entity, so check the current node since it is the one
1242 * with earliest deadline that might be eligible.
1243 */
1244 if (entity_eligible(cfs_rq, se)) {
1245 best = se;
1246 break;
1247 }
1248
1249 node = node->rb_right;
1250 }
1251 found:
1252 if (!best || (curr && entity_before(curr, best)))
1253 best = curr;
1254
1255 return best;
1256 }
1257
__pick_last_entity(struct cfs_rq * cfs_rq)1258 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1259 {
1260 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1261
1262 if (!last)
1263 return NULL;
1264
1265 return __node_2_se(last);
1266 }
1267
1268 /**************************************************************
1269 * Scheduling class statistics methods:
1270 */
sched_update_scaling(void)1271 int sched_update_scaling(void)
1272 {
1273 unsigned int factor = get_update_sysctl_factor();
1274
1275 #define WRT_SYSCTL(name) \
1276 (normalized_sysctl_##name = sysctl_##name / (factor))
1277 WRT_SYSCTL(sched_base_slice);
1278 #undef WRT_SYSCTL
1279
1280 return 0;
1281 }
1282
1283 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1284
1285 /*
1286 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1287 * this is probably good enough.
1288 */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1289 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1290 {
1291 if (vruntime_cmp(se->vruntime, "<", se->deadline))
1292 return false;
1293
1294 /*
1295 * For EEVDF the virtual time slope is determined by w_i (iow.
1296 * nice) while the request time r_i is determined by
1297 * sysctl_sched_base_slice.
1298 */
1299 if (!se->custom_slice)
1300 se->slice = sysctl_sched_base_slice;
1301
1302 /*
1303 * EEVDF: vd_i = ve_i + r_i / w_i
1304 */
1305 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1306 avg_vruntime(cfs_rq);
1307
1308 /*
1309 * The task has consumed its request, reschedule.
1310 */
1311 return true;
1312 }
1313
1314 #include "pelt.h"
1315
1316 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1317 static unsigned long task_h_load(struct task_struct *p);
1318 static unsigned long capacity_of(int cpu);
1319
1320 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1321 void init_entity_runnable_average(struct sched_entity *se)
1322 {
1323 struct sched_avg *sa = &se->avg;
1324
1325 memset(sa, 0, sizeof(*sa));
1326
1327 /*
1328 * Tasks are initialized with full load to be seen as heavy tasks until
1329 * they get a chance to stabilize to their real load level.
1330 * Group entities are initialized with zero load to reflect the fact that
1331 * nothing has been attached to the task group yet.
1332 */
1333 if (entity_is_task(se))
1334 sa->load_avg = scale_load_down(se->load.weight);
1335
1336 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1337 }
1338
1339 /*
1340 * With new tasks being created, their initial util_avgs are extrapolated
1341 * based on the cfs_rq's current util_avg:
1342 *
1343 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1344 * * se_weight(se)
1345 *
1346 * However, in many cases, the above util_avg does not give a desired
1347 * value. Moreover, the sum of the util_avgs may be divergent, such
1348 * as when the series is a harmonic series.
1349 *
1350 * To solve this problem, we also cap the util_avg of successive tasks to
1351 * only 1/2 of the left utilization budget:
1352 *
1353 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1354 *
1355 * where n denotes the nth task and cpu_scale the CPU capacity.
1356 *
1357 * For example, for a CPU with 1024 of capacity, a simplest series from
1358 * the beginning would be like:
1359 *
1360 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1361 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1362 *
1363 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1364 * if util_avg > util_avg_cap.
1365 */
post_init_entity_util_avg(struct task_struct * p)1366 void post_init_entity_util_avg(struct task_struct *p)
1367 {
1368 struct sched_entity *se = &p->se;
1369 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1370 struct sched_avg *sa = &se->avg;
1371 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1372 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1373
1374 if (p->sched_class != &fair_sched_class) {
1375 /*
1376 * For !fair tasks do:
1377 *
1378 update_cfs_rq_load_avg(now, cfs_rq);
1379 attach_entity_load_avg(cfs_rq, se);
1380 switched_from_fair(rq, p);
1381 *
1382 * such that the next switched_to_fair() has the
1383 * expected state.
1384 */
1385 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1386 return;
1387 }
1388
1389 if (cap > 0) {
1390 if (cfs_rq->avg.util_avg != 0) {
1391 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se);
1392 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1393
1394 if (sa->util_avg > cap)
1395 sa->util_avg = cap;
1396 } else {
1397 sa->util_avg = cap;
1398 }
1399 }
1400
1401 sa->runnable_avg = sa->util_avg;
1402 }
1403
1404 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec);
1405
update_se(struct rq * rq,struct sched_entity * se)1406 static s64 update_se(struct rq *rq, struct sched_entity *se)
1407 {
1408 u64 now = rq_clock_task(rq);
1409 s64 delta_exec;
1410
1411 delta_exec = now - se->exec_start;
1412 if (unlikely(delta_exec <= 0))
1413 return delta_exec;
1414
1415 se->exec_start = now;
1416 if (entity_is_task(se)) {
1417 struct task_struct *running = rq->curr;
1418 /*
1419 * If se is a task, we account the time against the running
1420 * task, as w/ proxy-exec they may not be the same.
1421 */
1422 running->se.exec_start = now;
1423 running->se.sum_exec_runtime += delta_exec;
1424
1425 trace_sched_stat_runtime(running, delta_exec);
1426 account_group_exec_runtime(running, delta_exec);
1427 account_mm_sched(rq, running, delta_exec);
1428
1429 cgroup_account_cputime(running, delta_exec);
1430 } else {
1431 /* If not task, account the time against donor se */
1432 se->sum_exec_runtime += delta_exec;
1433 }
1434
1435 if (schedstat_enabled()) {
1436 struct sched_statistics *stats;
1437
1438 stats = __schedstats_from_se(se);
1439 __schedstat_set(stats->exec_max,
1440 max(delta_exec, stats->exec_max));
1441 }
1442
1443 return delta_exec;
1444 }
1445
1446 #ifdef CONFIG_SCHED_CACHE
1447
1448 /*
1449 * XXX numbers come from a place the sun don't shine -- probably wants to be SD
1450 * tunable or so.
1451 */
1452 #define EPOCH_PERIOD (HZ / 100) /* 10 ms */
1453 #define EPOCH_LLC_AFFINITY_TIMEOUT 5 /* 50 ms */
1454 __read_mostly unsigned int llc_aggr_tolerance = 1;
1455 __read_mostly unsigned int llc_epoch_period = EPOCH_PERIOD;
1456 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT;
1457 __read_mostly unsigned int llc_imb_pct = 20;
1458 __read_mostly unsigned int llc_overaggr_pct = 50;
1459
llc_id(int cpu)1460 static int llc_id(int cpu)
1461 {
1462 if (cpu < 0)
1463 return -1;
1464
1465 return per_cpu(sd_llc_id, cpu);
1466 }
1467
get_sched_cache_scale(int mul)1468 static inline int get_sched_cache_scale(int mul)
1469 {
1470 unsigned int tol = READ_ONCE(llc_aggr_tolerance);
1471
1472 if (!tol)
1473 return 0;
1474
1475 if (tol >= 100)
1476 return INT_MAX;
1477
1478 return (1 + (tol - 1) * mul);
1479 }
1480
exceed_llc_capacity(struct mm_struct * mm,int cpu)1481 static bool exceed_llc_capacity(struct mm_struct *mm, int cpu)
1482 {
1483 #ifdef CONFIG_NUMA_BALANCING
1484 unsigned long llc, footprint;
1485 struct sched_domain *sd;
1486 int scale;
1487
1488 guard(rcu)();
1489
1490 sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd);
1491 if (!sd)
1492 return true;
1493
1494 if (static_branch_likely(&sched_numa_balancing)) {
1495 /*
1496 * TBD: RDT exclusive LLC ways reserved should be
1497 * excluded.
1498 */
1499 llc = sd->llc_bytes;
1500 footprint = READ_ONCE(mm->sc_stat.footprint);
1501
1502 /*
1503 * Scale the LLC size by 256*llc_aggr_tolerance
1504 * and compare it to the task's footprint.
1505 *
1506 * Suppose the L3 size is 32MB. If the
1507 * llc_aggr_tolerance is 1:
1508 * When the footprint is larger than 32MB, the
1509 * process is regarded as exceeding the LLC
1510 * capacity. If the llc_aggr_tolerance is 99:
1511 * When the footprint is larger than 784GB, the
1512 * process is regarded as exceeding the LLC
1513 * capacity:
1514 * 784GB = (1 + (99 - 1) * 256) * 32MB
1515 * If the llc_aggr_tolerance is 100:
1516 * ignore the footprint and do the aggregation
1517 * anyway.
1518 */
1519 scale = get_sched_cache_scale(256);
1520 if (scale == INT_MAX)
1521 return false;
1522
1523 return ((llc * (u64)scale) < (footprint * PAGE_SIZE));
1524 }
1525 #endif
1526 return false;
1527 }
1528
invalid_llc_nr(struct mm_struct * mm,struct task_struct * p,int cpu)1529 static bool invalid_llc_nr(struct mm_struct *mm, struct task_struct *p,
1530 int cpu)
1531 {
1532 int scale;
1533
1534 if (get_nr_threads(p) <= 1)
1535 return true;
1536
1537 /*
1538 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance
1539 * and compare it to the task's active threads.
1540 */
1541 scale = get_sched_cache_scale(1);
1542 if (scale == INT_MAX)
1543 return false;
1544
1545 return !fits_capacity((mm->sc_stat.nr_running_avg * cpu_smt_num_threads),
1546 (scale * per_cpu(sd_llc_size, cpu)));
1547 }
1548
account_llc_enqueue(struct rq * rq,struct task_struct * p)1549 static void account_llc_enqueue(struct rq *rq, struct task_struct *p)
1550 {
1551 int pref_llc, pref_llc_queued;
1552 struct sched_domain *sd;
1553
1554 pref_llc = p->preferred_llc;
1555 if (pref_llc < 0)
1556 return;
1557
1558 pref_llc_queued = (pref_llc == task_llc(p));
1559 rq->nr_llc_running++;
1560 rq->nr_pref_llc_running += pref_llc_queued;
1561
1562 /*
1563 * Record whether p is enqueued on its preferred
1564 * LLC, in order to pair with account_llc_dequeue()
1565 * to maintain a consistent nr_pref_llc_running per
1566 * runqueue.
1567 * This is necessary because a race condition exists:
1568 * after a task is enqueued on a runqueue, task_llc(p)
1569 * may change due to CPU hotplug. Therefore, checking
1570 * task_llc(p) to determine whether the task is being
1571 * dequeued from its preferred LLC is unreliable and
1572 * can cause inconsistent values - checking the
1573 * p->pref_llc_queued in account_llc_dequeue() would
1574 * be reliable.
1575 */
1576 p->pref_llc_queued = pref_llc_queued;
1577
1578 sd = rcu_dereference_all(rq->sd);
1579 if (sd && (unsigned int)pref_llc < sd->llc_max)
1580 sd->llc_counts[pref_llc]++;
1581 }
1582
account_llc_dequeue(struct rq * rq,struct task_struct * p)1583 static void account_llc_dequeue(struct rq *rq, struct task_struct *p)
1584 {
1585 struct sched_domain *sd;
1586 int pref_llc;
1587
1588 pref_llc = p->preferred_llc;
1589 if (pref_llc < 0)
1590 return;
1591
1592 rq->nr_llc_running--;
1593 if (p->pref_llc_queued) {
1594 rq->nr_pref_llc_running--;
1595 /*
1596 * Update the status in case
1597 * other logic might query
1598 * this.
1599 */
1600 p->pref_llc_queued = 0;
1601 }
1602
1603 sd = rcu_dereference_all(rq->sd);
1604 if (sd && (unsigned int)pref_llc < sd->llc_max) {
1605 /*
1606 * There is a race condition between dequeue
1607 * and CPU hotplug. After a task has been enqueued
1608 * on CPUx, a CPU hotplug event occurs, and all online
1609 * CPUs (including CPUx) rebuild their sched_domains
1610 * and reset statistics to zero(including sd->llc_counts).
1611 * This can cause temporary undercount and we have to
1612 * check for such underflow in sd->llc_counts.
1613 *
1614 * This undercount is temporary and accurate accounting
1615 * will resume once the rq has a chance to be idle.
1616 */
1617 if (sd->llc_counts[pref_llc])
1618 sd->llc_counts[pref_llc]--;
1619 }
1620 }
1621
mm_init_sched(struct mm_struct * mm,struct sched_cache_time __percpu * _pcpu_sched)1622 void mm_init_sched(struct mm_struct *mm,
1623 struct sched_cache_time __percpu *_pcpu_sched)
1624 {
1625 unsigned long epoch = 0;
1626 int i;
1627
1628 for_each_possible_cpu(i) {
1629 struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i);
1630 struct rq *rq = cpu_rq(i);
1631
1632 pcpu_sched->runtime = 0;
1633 /* a slightly stale cpu epoch is acceptible */
1634 pcpu_sched->epoch = rq->cpu_epoch;
1635 epoch = rq->cpu_epoch;
1636 }
1637
1638 raw_spin_lock_init(&mm->sc_stat.lock);
1639 mm->sc_stat.epoch = epoch;
1640 mm->sc_stat.cpu = -1;
1641 mm->sc_stat.next_scan = jiffies;
1642 mm->sc_stat.nr_running_avg = 0;
1643 mm->sc_stat.footprint = 0;
1644 /*
1645 * The update to mm->sc_stat should not be reordered
1646 * before initialization to mm's other fields, in case
1647 * the readers may get invalid mm_sched_epoch, etc.
1648 */
1649 smp_store_release(&mm->sc_stat.pcpu_sched, _pcpu_sched);
1650 }
1651
1652 /* because why would C be fully specified */
__shr_u64(u64 * val,unsigned int n)1653 static __always_inline void __shr_u64(u64 *val, unsigned int n)
1654 {
1655 if (n >= 64) {
1656 *val = 0;
1657 return;
1658 }
1659 *val >>= n;
1660 }
1661
__update_mm_sched(struct rq * rq,struct sched_cache_time * pcpu_sched)1662 static inline void __update_mm_sched(struct rq *rq,
1663 struct sched_cache_time *pcpu_sched)
1664 {
1665 lockdep_assert_held(&rq->cpu_epoch_lock);
1666
1667 unsigned int period = max(READ_ONCE(llc_epoch_period), 1U);
1668 unsigned long n, now = jiffies;
1669 long delta = now - rq->cpu_epoch_next;
1670
1671 if (delta > 0) {
1672 n = (delta + period - 1) / period;
1673 rq->cpu_epoch += n;
1674 rq->cpu_epoch_next += n * period;
1675 __shr_u64(&rq->cpu_runtime, n);
1676 }
1677
1678 n = rq->cpu_epoch - pcpu_sched->epoch;
1679 if (n) {
1680 pcpu_sched->epoch += n;
1681 __shr_u64(&pcpu_sched->runtime, n);
1682 }
1683 }
1684
fraction_mm_sched(struct rq * rq,struct sched_cache_time * pcpu_sched)1685 static unsigned long fraction_mm_sched(struct rq *rq,
1686 struct sched_cache_time *pcpu_sched)
1687 {
1688 guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock);
1689
1690 __update_mm_sched(rq, pcpu_sched);
1691
1692 /*
1693 * Runtime is a geometric series (r=0.5) and as such will sum to twice
1694 * the accumulation period, this means the multiplcation here should
1695 * not overflow.
1696 */
1697 return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1);
1698 }
1699
get_pref_llc(struct task_struct * p,struct mm_struct * mm)1700 static int get_pref_llc(struct task_struct *p, struct mm_struct *mm)
1701 {
1702 int mm_sched_llc = -1, mm_sched_cpu;
1703
1704 if (!mm)
1705 return -1;
1706
1707 mm_sched_cpu = READ_ONCE(mm->sc_stat.cpu);
1708 if (mm_sched_cpu != -1) {
1709 mm_sched_llc = llc_id(mm_sched_cpu);
1710
1711 #ifdef CONFIG_NUMA_BALANCING
1712 /*
1713 * Don't assign preferred LLC if it
1714 * conflicts with NUMA balancing.
1715 * This can happen when sched_setnuma() gets
1716 * called, however it is not much of an issue
1717 * because we expect account_mm_sched() to get
1718 * called fairly regularly -- at a higher rate
1719 * than sched_setnuma() at least -- and thus the
1720 * conflict only exists for a short period of time.
1721 */
1722 if (static_branch_likely(&sched_numa_balancing) &&
1723 p->numa_preferred_nid >= 0 &&
1724 cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid)
1725 mm_sched_llc = -1;
1726 #endif
1727 }
1728
1729 return mm_sched_llc;
1730 }
1731
1732 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p);
1733
1734 static inline
account_mm_sched(struct rq * rq,struct task_struct * p,s64 delta_exec)1735 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
1736 {
1737 struct sched_cache_time *pcpu_sched;
1738 struct mm_struct *mm = p->mm;
1739 int mm_sched_llc = -1;
1740 unsigned long epoch;
1741
1742 if (!sched_cache_enabled())
1743 return;
1744
1745 if (p->sched_class != &fair_sched_class)
1746 return;
1747 /*
1748 * init_task, kthreads and user thread created
1749 * by user_mode_thread() don't have mm.
1750 */
1751 if (!mm || !mm->sc_stat.pcpu_sched)
1752 return;
1753
1754 pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, cpu_of(rq));
1755
1756 scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) {
1757 __update_mm_sched(rq, pcpu_sched);
1758 pcpu_sched->runtime += delta_exec;
1759 rq->cpu_runtime += delta_exec;
1760 epoch = rq->cpu_epoch;
1761 }
1762
1763 /*
1764 * If this process hasn't hit task_cache_work() for a while invalidate
1765 * its preferred state.
1766 */
1767 if ((long)(epoch - READ_ONCE(mm->sc_stat.epoch)) > llc_epoch_affinity_timeout ||
1768 invalid_llc_nr(mm, p, cpu_of(rq)) ||
1769 exceed_llc_capacity(mm, cpu_of(rq))) {
1770 if (READ_ONCE(mm->sc_stat.cpu) != -1)
1771 WRITE_ONCE(mm->sc_stat.cpu, -1);
1772 }
1773
1774 mm_sched_llc = get_pref_llc(p, mm);
1775
1776 /* task not on rq accounted later in account_entity_enqueue() */
1777 if (task_running_on_cpu(rq->cpu, p) &&
1778 READ_ONCE(p->preferred_llc) != mm_sched_llc) {
1779 account_llc_dequeue(rq, p);
1780 WRITE_ONCE(p->preferred_llc, mm_sched_llc);
1781 account_llc_enqueue(rq, p);
1782 }
1783 }
1784
task_tick_cache(struct rq * rq,struct task_struct * p)1785 static void task_tick_cache(struct rq *rq, struct task_struct *p)
1786 {
1787 struct callback_head *work = &p->cache_work;
1788 struct mm_struct *mm = p->mm;
1789 unsigned long epoch;
1790
1791 if (!sched_cache_enabled())
1792 return;
1793
1794 if (!mm || p->flags & PF_KTHREAD ||
1795 !mm->sc_stat.pcpu_sched)
1796 return;
1797
1798 epoch = rq->cpu_epoch;
1799 /* avoid moving backwards */
1800 if (time_after_eq(mm->sc_stat.epoch, epoch))
1801 return;
1802
1803 guard(raw_spinlock)(&mm->sc_stat.lock);
1804
1805 if (work->next == work) {
1806 task_work_add(p, work, TWA_RESUME);
1807 WRITE_ONCE(mm->sc_stat.epoch, epoch);
1808 }
1809 }
1810
get_scan_cpumasks(cpumask_var_t cpus,struct task_struct * p)1811 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p)
1812 {
1813 #ifdef CONFIG_NUMA_BALANCING
1814 int cpu, curr_cpu, nid, pref_nid;
1815
1816 if (!static_branch_likely(&sched_numa_balancing))
1817 goto out;
1818
1819 cpu = READ_ONCE(p->mm->sc_stat.cpu);
1820 if (cpu != -1)
1821 nid = cpu_to_node(cpu);
1822 curr_cpu = task_cpu(p);
1823
1824 /*
1825 * Scanning in the preferred NUMA node is ideal. However, the NUMA
1826 * preferred node is per-task rather than per-process. It is possible
1827 * for different threads of the process to have distinct preferred
1828 * nodes; consequently, the process-wide preferred LLC may bounce
1829 * between different nodes. As a workaround, maintain the scan
1830 * CPU mask to also cover the process's current preferred LLC and the
1831 * current running node to mitigate the bouncing risk.
1832 * TBD: numa_group should be considered during task aggregation.
1833 */
1834 pref_nid = p->numa_preferred_nid;
1835 /* honor the task's preferred node */
1836 if (pref_nid == NUMA_NO_NODE)
1837 goto out;
1838
1839 cpumask_or(cpus, cpus, cpumask_of_node(pref_nid));
1840
1841 /* honor the task's preferred LLC CPU */
1842 if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE)
1843 cpumask_or(cpus, cpus, cpumask_of_node(nid));
1844
1845 /* make sure the task's current running node is included */
1846 if (!cpumask_test_cpu(curr_cpu, cpus))
1847 cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu)));
1848
1849 return;
1850
1851 out:
1852 #endif
1853 cpumask_copy(cpus, cpu_online_mask);
1854 }
1855
update_avg_scale(u64 * avg,u64 sample)1856 static inline void update_avg_scale(u64 *avg, u64 sample)
1857 {
1858 int factor = per_cpu(sd_llc_size, raw_smp_processor_id());
1859 s64 diff = sample - *avg;
1860 u32 divisor;
1861
1862 /*
1863 * Scale the divisor based on the number of CPUs contained
1864 * in the LLC. This scaling ensures smaller LLC domains use
1865 * a smaller divisor to achieve more precise sensitivity to
1866 * changes in nr_running, while larger LLC domains are capped
1867 * at a maximum divisor of 8 which is the default smoothing
1868 * factor of EWMA in update_avg().
1869 */
1870 divisor = clamp_t(u32, (factor >> 2), 2, 8);
1871 *avg += div64_s64(diff, divisor);
1872 }
1873
task_cache_work(struct callback_head * work)1874 static void task_cache_work(struct callback_head *work)
1875 {
1876 int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu;
1877 unsigned long next_scan, now = jiffies;
1878 struct task_struct *p = current, *cur;
1879 unsigned long curr_m_a_occ = 0;
1880 struct mm_struct *mm = p->mm;
1881 unsigned long m_a_occ = 0;
1882 cpumask_var_t cpus;
1883
1884 WARN_ON_ONCE(work != &p->cache_work);
1885
1886 work->next = work;
1887
1888 if (p->flags & PF_EXITING)
1889 return;
1890
1891 next_scan = READ_ONCE(mm->sc_stat.next_scan);
1892 if (time_before(now, next_scan))
1893 return;
1894
1895 /* only 1 thread is allowed to scan */
1896 if (!try_cmpxchg(&mm->sc_stat.next_scan, &next_scan,
1897 now + max_t(unsigned long,
1898 READ_ONCE(llc_epoch_period), 1)))
1899 return;
1900
1901 curr_cpu = task_cpu(p);
1902 if (invalid_llc_nr(mm, p, curr_cpu) ||
1903 exceed_llc_capacity(mm, curr_cpu)) {
1904 if (READ_ONCE(mm->sc_stat.cpu) != -1)
1905 WRITE_ONCE(mm->sc_stat.cpu, -1);
1906
1907 return;
1908 }
1909
1910 if (!zalloc_cpumask_var(&cpus, GFP_KERNEL))
1911 return;
1912
1913 scoped_guard (cpus_read_lock) {
1914 guard(rcu)();
1915
1916 get_scan_cpumasks(cpus, p);
1917
1918 for_each_cpu(cpu, cpus) {
1919 /* XXX sched_cluster_active */
1920 struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
1921 unsigned long occ, m_occ = 0, a_occ = 0;
1922 int m_cpu = -1, i;
1923
1924 if (!sd)
1925 continue;
1926
1927 for_each_cpu(i, sched_domain_span(sd)) {
1928 occ = fraction_mm_sched(cpu_rq(i),
1929 per_cpu_ptr(mm->sc_stat.pcpu_sched, i));
1930 a_occ += occ;
1931 if (occ > m_occ) {
1932 m_occ = occ;
1933 m_cpu = i;
1934 }
1935
1936 cur = rcu_dereference_all(cpu_rq(i)->curr);
1937 if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) &&
1938 cur->mm == mm)
1939 nr_running++;
1940 }
1941
1942 /*
1943 * Compare the accumulated occupancy of each LLC. The
1944 * reason for using accumulated occupancy rather than average
1945 * per CPU occupancy is that it works better in asymmetric LLC
1946 * scenarios.
1947 * For example, if there are 2 threads in a 4CPU LLC and 3
1948 * threads in an 8CPU LLC, it might be better to choose the one
1949 * with 3 threads. However, this would not be the case if the
1950 * occupancy is divided by the number of CPUs in an LLC (i.e.,
1951 * if average per CPU occupancy is used).
1952 * Besides, NUMA balancing fault statistics behave similarly:
1953 * the total number of faults per node is compared rather than
1954 * the average number of faults per CPU. This strategy is also
1955 * followed here.
1956 */
1957 if (a_occ > m_a_occ) {
1958 m_a_occ = a_occ;
1959 m_a_cpu = m_cpu;
1960 }
1961
1962 if (llc_id(cpu) == llc_id(READ_ONCE(mm->sc_stat.cpu)))
1963 curr_m_a_occ = a_occ;
1964
1965 cpumask_andnot(cpus, cpus, sched_domain_span(sd));
1966 }
1967 }
1968
1969 if (m_a_occ > (2 * curr_m_a_occ)) {
1970 /*
1971 * Avoid switching sc_stat.cpu too fast.
1972 * The reason to choose 2X is because:
1973 * 1. It is better to keep the preferred LLC stable,
1974 * rather than changing it frequently and cause migrations
1975 * 2. 2X means the new preferred LLC has at least 1 more
1976 * busy CPU than the old one(200% vs 100%, eg)
1977 * 3. 2X is chosen based on test results, as it delivers
1978 * the optimal performance gain so far.
1979 */
1980 WRITE_ONCE(mm->sc_stat.cpu, m_a_cpu);
1981 }
1982
1983 update_avg_scale(&mm->sc_stat.nr_running_avg, nr_running);
1984 free_cpumask_var(cpus);
1985 }
1986
init_sched_mm(struct task_struct * p)1987 void init_sched_mm(struct task_struct *p)
1988 {
1989 struct callback_head *work = &p->cache_work;
1990
1991 init_task_work(work, task_cache_work);
1992 work->next = work;
1993 /*
1994 * Reset new task's preference to avoid
1995 * polluting account_llc_enqueue().
1996 */
1997 p->preferred_llc = -1;
1998 }
1999
2000 #else /* CONFIG_SCHED_CACHE */
2001
account_mm_sched(struct rq * rq,struct task_struct * p,s64 delta_exec)2002 static inline void account_mm_sched(struct rq *rq, struct task_struct *p,
2003 s64 delta_exec) { }
2004
init_sched_mm(struct task_struct * p)2005 void init_sched_mm(struct task_struct *p) { }
2006
task_tick_cache(struct rq * rq,struct task_struct * p)2007 static void task_tick_cache(struct rq *rq, struct task_struct *p) { }
2008
get_pref_llc(struct task_struct * p,struct mm_struct * mm)2009 static inline int get_pref_llc(struct task_struct *p,
2010 struct mm_struct *mm)
2011 {
2012 return -1;
2013 }
2014
account_llc_enqueue(struct rq * rq,struct task_struct * p)2015 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {}
2016
account_llc_dequeue(struct rq * rq,struct task_struct * p)2017 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {}
2018
2019 #endif /* CONFIG_SCHED_CACHE */
2020
2021 /*
2022 * Used by other classes to account runtime.
2023 */
update_curr_common(struct rq * rq)2024 s64 update_curr_common(struct rq *rq)
2025 {
2026 return update_se(rq, &rq->donor->se);
2027 }
2028
2029 /*
2030 * Update the current task's runtime statistics.
2031 */
update_curr(struct cfs_rq * cfs_rq)2032 static void update_curr(struct cfs_rq *cfs_rq)
2033 {
2034 /*
2035 * Note: cfs_rq->curr corresponds to the task picked to
2036 * run (ie: rq->donor.se) which due to proxy-exec may
2037 * not necessarily be the actual task running
2038 * (rq->curr.se). This is easy to confuse!
2039 */
2040 struct sched_entity *curr = cfs_rq->h_curr;
2041 struct rq *rq = rq_of(cfs_rq);
2042 s64 delta_exec;
2043 bool resched;
2044
2045 if (unlikely(!curr))
2046 return;
2047
2048 delta_exec = update_se(rq, curr);
2049 if (unlikely(delta_exec <= 0))
2050 return;
2051
2052 account_cfs_rq_runtime(cfs_rq, delta_exec);
2053
2054 if (!entity_is_task(curr))
2055 return;
2056
2057 cfs_rq = &rq->cfs;
2058
2059 curr->vruntime += calc_delta_fair(delta_exec, curr);
2060 resched = update_deadline(cfs_rq, curr);
2061
2062 /*
2063 * If the fair_server is active, we need to account for the
2064 * fair_server time whether or not the task is running on
2065 * behalf of fair_server or not:
2066 * - If the task is running on behalf of fair_server, we need
2067 * to limit its time based on the assigned runtime.
2068 * - Fair task that runs outside of fair_server should account
2069 * against fair_server such that it can account for this time
2070 * and possibly avoid running this period.
2071 */
2072 dl_server_update(&rq->fair_server, delta_exec);
2073
2074 if (cfs_rq->h_nr_queued == 1)
2075 return;
2076
2077 if (resched || !protect_slice(curr)) {
2078 resched_curr_lazy(rq);
2079 clear_buddies(cfs_rq, curr);
2080 }
2081 }
2082
update_curr_fair(struct rq * rq)2083 static void update_curr_fair(struct rq *rq)
2084 {
2085 struct sched_entity *se = &rq->donor->se;
2086
2087 for_each_sched_entity(se)
2088 update_curr(cfs_rq_of(se));
2089 }
2090
2091 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)2092 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2093 {
2094 struct sched_statistics *stats;
2095 struct task_struct *p = NULL;
2096
2097 if (!schedstat_enabled())
2098 return;
2099
2100 stats = __schedstats_from_se(se);
2101
2102 if (entity_is_task(se))
2103 p = task_of(se);
2104
2105 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
2106 }
2107
2108 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)2109 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2110 {
2111 struct sched_statistics *stats;
2112 struct task_struct *p = NULL;
2113
2114 if (!schedstat_enabled())
2115 return;
2116
2117 stats = __schedstats_from_se(se);
2118
2119 /*
2120 * When the sched_schedstat changes from 0 to 1, some sched se
2121 * maybe already in the runqueue, the se->statistics.wait_start
2122 * will be 0.So it will let the delta wrong. We need to avoid this
2123 * scenario.
2124 */
2125 if (unlikely(!schedstat_val(stats->wait_start)))
2126 return;
2127
2128 if (entity_is_task(se))
2129 p = task_of(se);
2130
2131 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
2132 }
2133
2134 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)2135 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
2136 {
2137 struct sched_statistics *stats;
2138 struct task_struct *tsk = NULL;
2139
2140 if (!schedstat_enabled())
2141 return;
2142
2143 stats = __schedstats_from_se(se);
2144
2145 if (entity_is_task(se))
2146 tsk = task_of(se);
2147
2148 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
2149 }
2150
2151 /*
2152 * Task is being enqueued - update stats:
2153 */
2154 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)2155 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2156 {
2157 if (!schedstat_enabled())
2158 return;
2159
2160 /*
2161 * Are we enqueueing a waiting task? (for current tasks
2162 * a dequeue/enqueue event is a NOP)
2163 */
2164 if (se != cfs_rq->h_curr)
2165 update_stats_wait_start_fair(cfs_rq, se);
2166
2167 if (flags & ENQUEUE_WAKEUP)
2168 update_stats_enqueue_sleeper_fair(cfs_rq, se);
2169 }
2170
2171 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)2172 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2173 {
2174
2175 if (!schedstat_enabled())
2176 return;
2177
2178 /*
2179 * Mark the end of the wait period if dequeueing a
2180 * waiting task:
2181 */
2182 if (se != cfs_rq->h_curr)
2183 update_stats_wait_end_fair(cfs_rq, se);
2184
2185 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
2186 struct task_struct *tsk = task_of(se);
2187 unsigned int state;
2188
2189 /* XXX racy against TTWU */
2190 state = READ_ONCE(tsk->__state);
2191 if (state & TASK_INTERRUPTIBLE)
2192 __schedstat_set(tsk->stats.sleep_start,
2193 rq_clock(rq_of(cfs_rq)));
2194 if (state & TASK_UNINTERRUPTIBLE)
2195 __schedstat_set(tsk->stats.block_start,
2196 rq_clock(rq_of(cfs_rq)));
2197 }
2198 }
2199
2200 /*
2201 * We are picking a new current task - update its stats:
2202 */
2203 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)2204 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
2205 {
2206 /*
2207 * We are starting a new run period:
2208 */
2209 se->exec_start = rq_clock_task(rq_of(cfs_rq));
2210 }
2211
2212 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */
is_core_idle(int cpu)2213 static inline bool is_core_idle(int cpu)
2214 {
2215 int sibling;
2216
2217 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
2218 if (cpu == sibling)
2219 continue;
2220
2221 if (!idle_cpu(sibling))
2222 return false;
2223 }
2224
2225 return true;
2226 }
2227
2228 #ifdef CONFIG_NUMA
2229 #define NUMA_IMBALANCE_MIN 2
2230
2231 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)2232 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
2233 {
2234 /*
2235 * Allow a NUMA imbalance if busy CPUs is less than the maximum
2236 * threshold. Above this threshold, individual tasks may be contending
2237 * for both memory bandwidth and any shared HT resources. This is an
2238 * approximation as the number of running tasks may not be related to
2239 * the number of busy CPUs due to sched_setaffinity.
2240 */
2241 if (dst_running > imb_numa_nr)
2242 return imbalance;
2243
2244 /*
2245 * Allow a small imbalance based on a simple pair of communicating
2246 * tasks that remain local when the destination is lightly loaded.
2247 */
2248 if (imbalance <= NUMA_IMBALANCE_MIN)
2249 return 0;
2250
2251 return imbalance;
2252 }
2253 #endif /* CONFIG_NUMA */
2254
2255 #ifdef CONFIG_NUMA_BALANCING
2256 /*
2257 * Approximate time to scan a full NUMA task in ms. The task scan period is
2258 * calculated based on the tasks virtual memory size and
2259 * numa_balancing_scan_size.
2260 */
2261 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
2262 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
2263
2264 /* Portion of address space to scan in MB */
2265 unsigned int sysctl_numa_balancing_scan_size = 256;
2266
2267 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
2268 unsigned int sysctl_numa_balancing_scan_delay = 1000;
2269
2270 /* The page with hint page fault latency < threshold in ms is considered hot */
2271 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
2272
2273 struct numa_group {
2274 refcount_t refcount;
2275
2276 spinlock_t lock; /* nr_tasks, tasks */
2277 int nr_tasks;
2278 pid_t gid;
2279 int active_nodes;
2280
2281 struct rcu_head rcu;
2282 unsigned long total_faults;
2283 unsigned long max_faults_cpu;
2284 /*
2285 * faults[] array is split into two regions: faults_mem and faults_cpu.
2286 *
2287 * Faults_cpu is used to decide whether memory should move
2288 * towards the CPU. As a consequence, these stats are weighted
2289 * more by CPU use than by memory faults.
2290 */
2291 unsigned long faults[];
2292 };
2293
2294 /*
2295 * For functions that can be called in multiple contexts that permit reading
2296 * ->numa_group (see struct task_struct for locking rules).
2297 */
deref_task_numa_group(struct task_struct * p)2298 static struct numa_group *deref_task_numa_group(struct task_struct *p)
2299 {
2300 return rcu_dereference_check(p->numa_group, p == current ||
2301 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
2302 }
2303
deref_curr_numa_group(struct task_struct * p)2304 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
2305 {
2306 return rcu_dereference_protected(p->numa_group, p == current);
2307 }
2308
2309 static inline unsigned long group_faults_priv(struct numa_group *ng);
2310 static inline unsigned long group_faults_shared(struct numa_group *ng);
2311
task_nr_scan_windows(struct task_struct * p)2312 static unsigned int task_nr_scan_windows(struct task_struct *p)
2313 {
2314 unsigned long rss = 0;
2315 unsigned long nr_scan_pages;
2316
2317 /*
2318 * Calculations based on RSS as non-present and empty pages are skipped
2319 * by the PTE scanner and NUMA hinting faults should be trapped based
2320 * on resident pages
2321 */
2322 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
2323 rss = get_mm_rss(p->mm);
2324 if (!rss)
2325 rss = nr_scan_pages;
2326
2327 rss = round_up(rss, nr_scan_pages);
2328 return rss / nr_scan_pages;
2329 }
2330
2331 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
2332 #define MAX_SCAN_WINDOW 2560
2333
task_scan_min(struct task_struct * p)2334 static unsigned int task_scan_min(struct task_struct *p)
2335 {
2336 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
2337 unsigned int scan, floor;
2338 unsigned int windows = 1;
2339
2340 if (scan_size < MAX_SCAN_WINDOW)
2341 windows = MAX_SCAN_WINDOW / scan_size;
2342 floor = 1000 / windows;
2343
2344 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
2345 return max_t(unsigned int, floor, scan);
2346 }
2347
task_scan_start(struct task_struct * p)2348 static unsigned int task_scan_start(struct task_struct *p)
2349 {
2350 unsigned long smin = task_scan_min(p);
2351 unsigned long period = smin;
2352 struct numa_group *ng;
2353
2354 /* Scale the maximum scan period with the amount of shared memory. */
2355 rcu_read_lock();
2356 ng = rcu_dereference_all(p->numa_group);
2357 if (ng) {
2358 unsigned long shared = group_faults_shared(ng);
2359 unsigned long private = group_faults_priv(ng);
2360
2361 period *= refcount_read(&ng->refcount);
2362 period *= shared + 1;
2363 period /= private + shared + 1;
2364 }
2365 rcu_read_unlock();
2366
2367 return max(smin, period);
2368 }
2369
task_scan_max(struct task_struct * p)2370 static unsigned int task_scan_max(struct task_struct *p)
2371 {
2372 unsigned long smin = task_scan_min(p);
2373 unsigned long smax;
2374 struct numa_group *ng;
2375
2376 /* Watch for min being lower than max due to floor calculations */
2377 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
2378
2379 /* Scale the maximum scan period with the amount of shared memory. */
2380 ng = deref_curr_numa_group(p);
2381 if (ng) {
2382 unsigned long shared = group_faults_shared(ng);
2383 unsigned long private = group_faults_priv(ng);
2384 unsigned long period = smax;
2385
2386 period *= refcount_read(&ng->refcount);
2387 period *= shared + 1;
2388 period /= private + shared + 1;
2389
2390 smax = max(smax, period);
2391 }
2392
2393 return max(smin, smax);
2394 }
2395
account_numa_enqueue(struct rq * rq,struct task_struct * p)2396 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2397 {
2398 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
2399 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
2400 }
2401
account_numa_dequeue(struct rq * rq,struct task_struct * p)2402 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2403 {
2404 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
2405 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
2406 }
2407
2408 /* Shared or private faults. */
2409 #define NR_NUMA_HINT_FAULT_TYPES 2
2410
2411 /* Memory and CPU locality */
2412 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
2413
2414 /* Averaged statistics, and temporary buffers. */
2415 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
2416
task_numa_group_id(struct task_struct * p)2417 pid_t task_numa_group_id(struct task_struct *p)
2418 {
2419 struct numa_group *ng;
2420 pid_t gid = 0;
2421
2422 rcu_read_lock();
2423 ng = rcu_dereference_all(p->numa_group);
2424 if (ng)
2425 gid = ng->gid;
2426 rcu_read_unlock();
2427
2428 return gid;
2429 }
2430
2431 /*
2432 * The averaged statistics, shared & private, memory & CPU,
2433 * occupy the first half of the array. The second half of the
2434 * array is for current counters, which are averaged into the
2435 * first set by task_numa_placement.
2436 */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)2437 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
2438 {
2439 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
2440 }
2441
task_faults(struct task_struct * p,int nid)2442 static inline unsigned long task_faults(struct task_struct *p, int nid)
2443 {
2444 if (!p->numa_faults)
2445 return 0;
2446
2447 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2448 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
2449 }
2450
group_faults(struct task_struct * p,int nid)2451 static inline unsigned long group_faults(struct task_struct *p, int nid)
2452 {
2453 struct numa_group *ng = deref_task_numa_group(p);
2454
2455 if (!ng)
2456 return 0;
2457
2458 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
2459 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
2460 }
2461
group_faults_cpu(struct numa_group * group,int nid)2462 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
2463 {
2464 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
2465 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
2466 }
2467
group_faults_priv(struct numa_group * ng)2468 static inline unsigned long group_faults_priv(struct numa_group *ng)
2469 {
2470 unsigned long faults = 0;
2471 int node;
2472
2473 for_each_online_node(node) {
2474 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
2475 }
2476
2477 return faults;
2478 }
2479
group_faults_shared(struct numa_group * ng)2480 static inline unsigned long group_faults_shared(struct numa_group *ng)
2481 {
2482 unsigned long faults = 0;
2483 int node;
2484
2485 for_each_online_node(node) {
2486 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
2487 }
2488
2489 return faults;
2490 }
2491
2492 /*
2493 * A node triggering more than 1/3 as many NUMA faults as the maximum is
2494 * considered part of a numa group's pseudo-interleaving set. Migrations
2495 * between these nodes are slowed down, to allow things to settle down.
2496 */
2497 #define ACTIVE_NODE_FRACTION 3
2498
numa_is_active_node(int nid,struct numa_group * ng)2499 static bool numa_is_active_node(int nid, struct numa_group *ng)
2500 {
2501 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
2502 }
2503
2504 /* Handle placement on systems where not all nodes are directly connected. */
score_nearby_nodes(struct task_struct * p,int nid,int lim_dist,bool task)2505 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
2506 int lim_dist, bool task)
2507 {
2508 unsigned long score = 0;
2509 int node, max_dist;
2510
2511 /*
2512 * All nodes are directly connected, and the same distance
2513 * from each other. No need for fancy placement algorithms.
2514 */
2515 if (sched_numa_topology_type == NUMA_DIRECT)
2516 return 0;
2517
2518 /* sched_max_numa_distance may be changed in parallel. */
2519 max_dist = READ_ONCE(sched_max_numa_distance);
2520 /*
2521 * This code is called for each node, introducing N^2 complexity,
2522 * which should be OK given the number of nodes rarely exceeds 8.
2523 */
2524 for_each_online_node(node) {
2525 unsigned long faults;
2526 int dist = node_distance(nid, node);
2527
2528 /*
2529 * The furthest away nodes in the system are not interesting
2530 * for placement; nid was already counted.
2531 */
2532 if (dist >= max_dist || node == nid)
2533 continue;
2534
2535 /*
2536 * On systems with a backplane NUMA topology, compare groups
2537 * of nodes, and move tasks towards the group with the most
2538 * memory accesses. When comparing two nodes at distance
2539 * "hoplimit", only nodes closer by than "hoplimit" are part
2540 * of each group. Skip other nodes.
2541 */
2542 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
2543 continue;
2544
2545 /* Add up the faults from nearby nodes. */
2546 if (task)
2547 faults = task_faults(p, node);
2548 else
2549 faults = group_faults(p, node);
2550
2551 /*
2552 * On systems with a glueless mesh NUMA topology, there are
2553 * no fixed "groups of nodes". Instead, nodes that are not
2554 * directly connected bounce traffic through intermediate
2555 * nodes; a numa_group can occupy any set of nodes.
2556 * The further away a node is, the less the faults count.
2557 * This seems to result in good task placement.
2558 */
2559 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2560 faults *= (max_dist - dist);
2561 faults /= (max_dist - LOCAL_DISTANCE);
2562 }
2563
2564 score += faults;
2565 }
2566
2567 return score;
2568 }
2569
2570 /*
2571 * These return the fraction of accesses done by a particular task, or
2572 * task group, on a particular numa node. The group weight is given a
2573 * larger multiplier, in order to group tasks together that are almost
2574 * evenly spread out between numa nodes.
2575 */
task_weight(struct task_struct * p,int nid,int dist)2576 static inline unsigned long task_weight(struct task_struct *p, int nid,
2577 int dist)
2578 {
2579 unsigned long faults, total_faults;
2580
2581 if (!p->numa_faults)
2582 return 0;
2583
2584 total_faults = p->total_numa_faults;
2585
2586 if (!total_faults)
2587 return 0;
2588
2589 faults = task_faults(p, nid);
2590 faults += score_nearby_nodes(p, nid, dist, true);
2591
2592 return 1000 * faults / total_faults;
2593 }
2594
group_weight(struct task_struct * p,int nid,int dist)2595 static inline unsigned long group_weight(struct task_struct *p, int nid,
2596 int dist)
2597 {
2598 struct numa_group *ng = deref_task_numa_group(p);
2599 unsigned long faults, total_faults;
2600
2601 if (!ng)
2602 return 0;
2603
2604 total_faults = ng->total_faults;
2605
2606 if (!total_faults)
2607 return 0;
2608
2609 faults = group_faults(p, nid);
2610 faults += score_nearby_nodes(p, nid, dist, false);
2611
2612 return 1000 * faults / total_faults;
2613 }
2614
2615 /*
2616 * If memory tiering mode is enabled, cpupid of slow memory page is
2617 * used to record scan time instead of CPU and PID. When tiering mode
2618 * is disabled at run time, the scan time (in cpupid) will be
2619 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
2620 * access out of array bound.
2621 */
cpupid_valid(int cpupid)2622 static inline bool cpupid_valid(int cpupid)
2623 {
2624 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
2625 }
2626
2627 /*
2628 * For memory tiering mode, if there are enough free pages (more than
2629 * enough watermark defined here) in fast memory node, to take full
2630 * advantage of fast memory capacity, all recently accessed slow
2631 * memory pages will be migrated to fast memory node without
2632 * considering hot threshold.
2633 */
pgdat_free_space_enough(struct pglist_data * pgdat)2634 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
2635 {
2636 int z;
2637 unsigned long enough_wmark;
2638
2639 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
2640 pgdat->node_present_pages >> 4);
2641 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
2642 struct zone *zone = pgdat->node_zones + z;
2643
2644 if (!populated_zone(zone))
2645 continue;
2646
2647 if (zone_watermark_ok(zone, 0,
2648 promo_wmark_pages(zone) + enough_wmark,
2649 ZONE_MOVABLE, 0))
2650 return true;
2651 }
2652 return false;
2653 }
2654
2655 /*
2656 * For memory tiering mode, when page tables are scanned, the scan
2657 * time will be recorded in struct page in addition to make page
2658 * PROT_NONE for slow memory page. So when the page is accessed, in
2659 * hint page fault handler, the hint page fault latency is calculated
2660 * via,
2661 *
2662 * hint page fault latency = hint page fault time - scan time
2663 *
2664 * The smaller the hint page fault latency, the higher the possibility
2665 * for the page to be hot.
2666 */
numa_hint_fault_latency(struct folio * folio)2667 static int numa_hint_fault_latency(struct folio *folio)
2668 {
2669 int last_time, time;
2670
2671 time = jiffies_to_msecs(jiffies);
2672 last_time = folio_xchg_access_time(folio, time);
2673
2674 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
2675 }
2676
2677 /*
2678 * For memory tiering mode, too high promotion/demotion throughput may
2679 * hurt application latency. So we provide a mechanism to rate limit
2680 * the number of pages that are tried to be promoted.
2681 */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)2682 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
2683 unsigned long rate_limit, int nr)
2684 {
2685 unsigned long nr_cand;
2686 unsigned int now, start;
2687
2688 now = jiffies_to_msecs(jiffies);
2689 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
2690 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2691 start = pgdat->nbp_rl_start;
2692 if (now - start > MSEC_PER_SEC &&
2693 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
2694 pgdat->nbp_rl_nr_cand = nr_cand;
2695 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
2696 return true;
2697 return false;
2698 }
2699
2700 #define NUMA_MIGRATION_ADJUST_STEPS 16
2701
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)2702 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
2703 unsigned long rate_limit,
2704 unsigned int ref_th)
2705 {
2706 unsigned int now, start, th_period, unit_th, th;
2707 unsigned long nr_cand, ref_cand, diff_cand;
2708
2709 now = jiffies_to_msecs(jiffies);
2710 th_period = sysctl_numa_balancing_scan_period_max;
2711 start = pgdat->nbp_th_start;
2712 if (now - start > th_period &&
2713 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
2714 ref_cand = rate_limit *
2715 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
2716 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2717 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
2718 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
2719 th = pgdat->nbp_threshold ? : ref_th;
2720 if (diff_cand > ref_cand * 11 / 10)
2721 th = max(th - unit_th, unit_th);
2722 else if (diff_cand < ref_cand * 9 / 10)
2723 th = min(th + unit_th, ref_th * 2);
2724 pgdat->nbp_th_nr_cand = nr_cand;
2725 pgdat->nbp_threshold = th;
2726 }
2727 }
2728
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)2729 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
2730 int src_nid, int dst_cpu)
2731 {
2732 struct numa_group *ng = deref_curr_numa_group(p);
2733 int dst_nid = cpu_to_node(dst_cpu);
2734 int last_cpupid, this_cpupid;
2735
2736 /*
2737 * Cannot migrate to memoryless nodes.
2738 */
2739 if (!node_state(dst_nid, N_MEMORY))
2740 return false;
2741
2742 /*
2743 * The pages in slow memory node should be migrated according
2744 * to hot/cold instead of private/shared.
2745 */
2746 if (folio_use_access_time(folio)) {
2747 struct pglist_data *pgdat;
2748 unsigned long rate_limit;
2749 unsigned int latency, th, def_th;
2750 long nr = folio_nr_pages(folio);
2751
2752 pgdat = NODE_DATA(dst_nid);
2753 if (pgdat_free_space_enough(pgdat)) {
2754 /* workload changed, reset hot threshold */
2755 pgdat->nbp_threshold = 0;
2756 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
2757 return true;
2758 }
2759
2760 def_th = sysctl_numa_balancing_hot_threshold;
2761 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
2762 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
2763
2764 th = pgdat->nbp_threshold ? : def_th;
2765 latency = numa_hint_fault_latency(folio);
2766 if (latency >= th)
2767 return false;
2768
2769 return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
2770 }
2771
2772 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
2773 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
2774
2775 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
2776 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
2777 return false;
2778
2779 /*
2780 * Allow first faults or private faults to migrate immediately early in
2781 * the lifetime of a task. The magic number 4 is based on waiting for
2782 * two full passes of the "multi-stage node selection" test that is
2783 * executed below.
2784 */
2785 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
2786 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
2787 return true;
2788
2789 /*
2790 * Multi-stage node selection is used in conjunction with a periodic
2791 * migration fault to build a temporal task<->page relation. By using
2792 * a two-stage filter we remove short/unlikely relations.
2793 *
2794 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2795 * a task's usage of a particular page (n_p) per total usage of this
2796 * page (n_t) (in a given time-span) to a probability.
2797 *
2798 * Our periodic faults will sample this probability and getting the
2799 * same result twice in a row, given these samples are fully
2800 * independent, is then given by P(n)^2, provided our sample period
2801 * is sufficiently short compared to the usage pattern.
2802 *
2803 * This quadric squishes small probabilities, making it less likely we
2804 * act on an unlikely task<->page relation.
2805 */
2806 if (!cpupid_pid_unset(last_cpupid) &&
2807 cpupid_to_nid(last_cpupid) != dst_nid)
2808 return false;
2809
2810 /* Always allow migrate on private faults */
2811 if (cpupid_match_pid(p, last_cpupid))
2812 return true;
2813
2814 /* A shared fault, but p->numa_group has not been set up yet. */
2815 if (!ng)
2816 return true;
2817
2818 /*
2819 * Destination node is much more heavily used than the source
2820 * node? Allow migration.
2821 */
2822 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2823 ACTIVE_NODE_FRACTION)
2824 return true;
2825
2826 /*
2827 * Distribute memory according to CPU & memory use on each node,
2828 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2829 *
2830 * faults_cpu(dst) 3 faults_cpu(src)
2831 * --------------- * - > ---------------
2832 * faults_mem(dst) 4 faults_mem(src)
2833 */
2834 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2835 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2836 }
2837
2838 /*
2839 * 'numa_type' describes the node at the moment of load balancing.
2840 */
2841 enum numa_type {
2842 /* The node has spare capacity that can be used to run more tasks. */
2843 node_has_spare = 0,
2844 /*
2845 * The node is fully used and the tasks don't compete for more CPU
2846 * cycles. Nevertheless, some tasks might wait before running.
2847 */
2848 node_fully_busy,
2849 /*
2850 * The node is overloaded and can't provide expected CPU cycles to all
2851 * tasks.
2852 */
2853 node_overloaded
2854 };
2855
2856 /* Cached statistics for all CPUs within a node */
2857 struct numa_stats {
2858 unsigned long load;
2859 unsigned long runnable;
2860 unsigned long util;
2861 /* Total compute capacity of CPUs on a node */
2862 unsigned long compute_capacity;
2863 unsigned int nr_running;
2864 unsigned int weight;
2865 enum numa_type node_type;
2866 int idle_cpu;
2867 };
2868
2869 struct task_numa_env {
2870 struct task_struct *p;
2871
2872 int src_cpu, src_nid;
2873 int dst_cpu, dst_nid;
2874 int imb_numa_nr;
2875
2876 struct numa_stats src_stats, dst_stats;
2877
2878 int imbalance_pct;
2879 int dist;
2880
2881 struct task_struct *best_task;
2882 long best_imp;
2883 int best_cpu;
2884 };
2885
2886 static unsigned long cpu_load(struct rq *rq);
2887 static unsigned long cpu_runnable(struct rq *rq);
2888
2889 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2890 numa_type numa_classify(unsigned int imbalance_pct,
2891 struct numa_stats *ns)
2892 {
2893 if ((ns->nr_running > ns->weight) &&
2894 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2895 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2896 return node_overloaded;
2897
2898 if ((ns->nr_running < ns->weight) ||
2899 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2900 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2901 return node_has_spare;
2902
2903 return node_fully_busy;
2904 }
2905
2906 /* Forward declarations of select_idle_sibling helpers */
2907 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2908 static inline int numa_idle_core(int idle_core, int cpu)
2909 {
2910 if (!sched_smt_active() ||
2911 idle_core >= 0 || !test_idle_cores(cpu))
2912 return idle_core;
2913
2914 /*
2915 * Prefer cores instead of packing HT siblings
2916 * and triggering future load balancing.
2917 */
2918 if (is_core_idle(cpu))
2919 idle_core = cpu;
2920
2921 return idle_core;
2922 }
2923
2924 /*
2925 * Gather all necessary information to make NUMA balancing placement
2926 * decisions that are compatible with standard load balancer. This
2927 * borrows code and logic from update_sg_lb_stats but sharing a
2928 * common implementation is impractical.
2929 */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2930 static void update_numa_stats(struct task_numa_env *env,
2931 struct numa_stats *ns, int nid,
2932 bool find_idle)
2933 {
2934 int cpu, idle_core = -1;
2935
2936 memset(ns, 0, sizeof(*ns));
2937 ns->idle_cpu = -1;
2938
2939 rcu_read_lock();
2940 for_each_cpu(cpu, cpumask_of_node(nid)) {
2941 struct rq *rq = cpu_rq(cpu);
2942
2943 ns->load += cpu_load(rq);
2944 ns->runnable += cpu_runnable(rq);
2945 ns->util += cpu_util_cfs(cpu);
2946 ns->nr_running += rq->cfs.h_nr_runnable;
2947 ns->compute_capacity += capacity_of(cpu);
2948
2949 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2950 if (READ_ONCE(rq->numa_migrate_on) ||
2951 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2952 continue;
2953
2954 if (ns->idle_cpu == -1)
2955 ns->idle_cpu = cpu;
2956
2957 idle_core = numa_idle_core(idle_core, cpu);
2958 }
2959 }
2960 rcu_read_unlock();
2961
2962 ns->weight = cpumask_weight(cpumask_of_node(nid));
2963
2964 ns->node_type = numa_classify(env->imbalance_pct, ns);
2965
2966 if (idle_core >= 0)
2967 ns->idle_cpu = idle_core;
2968 }
2969
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2970 static void task_numa_assign(struct task_numa_env *env,
2971 struct task_struct *p, long imp)
2972 {
2973 struct rq *rq = cpu_rq(env->dst_cpu);
2974
2975 /* Check if run-queue part of active NUMA balance. */
2976 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2977 int cpu;
2978 int start = env->dst_cpu;
2979
2980 /* Find alternative idle CPU. */
2981 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2982 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2983 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2984 continue;
2985 }
2986
2987 env->dst_cpu = cpu;
2988 rq = cpu_rq(env->dst_cpu);
2989 if (!xchg(&rq->numa_migrate_on, 1))
2990 goto assign;
2991 }
2992
2993 /* Failed to find an alternative idle CPU */
2994 return;
2995 }
2996
2997 assign:
2998 /*
2999 * Clear previous best_cpu/rq numa-migrate flag, since task now
3000 * found a better CPU to move/swap.
3001 */
3002 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
3003 rq = cpu_rq(env->best_cpu);
3004 WRITE_ONCE(rq->numa_migrate_on, 0);
3005 }
3006
3007 if (env->best_task)
3008 put_task_struct(env->best_task);
3009 if (p)
3010 get_task_struct(p);
3011
3012 env->best_task = p;
3013 env->best_imp = imp;
3014 env->best_cpu = env->dst_cpu;
3015 }
3016
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)3017 static bool load_too_imbalanced(long src_load, long dst_load,
3018 struct task_numa_env *env)
3019 {
3020 long imb, old_imb;
3021 long orig_src_load, orig_dst_load;
3022 long src_capacity, dst_capacity;
3023
3024 /*
3025 * The load is corrected for the CPU capacity available on each node.
3026 *
3027 * src_load dst_load
3028 * ------------ vs ---------
3029 * src_capacity dst_capacity
3030 */
3031 src_capacity = env->src_stats.compute_capacity;
3032 dst_capacity = env->dst_stats.compute_capacity;
3033
3034 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
3035
3036 orig_src_load = env->src_stats.load;
3037 orig_dst_load = env->dst_stats.load;
3038
3039 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
3040
3041 /* Would this change make things worse? */
3042 return (imb > old_imb);
3043 }
3044
3045 /*
3046 * Maximum NUMA importance can be 1998 (2*999);
3047 * SMALLIMP @ 30 would be close to 1998/64.
3048 * Used to deter task migration.
3049 */
3050 #define SMALLIMP 30
3051
3052 /*
3053 * This checks if the overall compute and NUMA accesses of the system would
3054 * be improved if the source tasks was migrated to the target dst_cpu taking
3055 * into account that it might be best if task running on the dst_cpu should
3056 * be exchanged with the source task
3057 */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)3058 static bool task_numa_compare(struct task_numa_env *env,
3059 long taskimp, long groupimp, bool maymove)
3060 {
3061 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
3062 struct rq *dst_rq = cpu_rq(env->dst_cpu);
3063 long imp = p_ng ? groupimp : taskimp;
3064 struct task_struct *cur;
3065 long src_load, dst_load;
3066 int dist = env->dist;
3067 long moveimp = imp;
3068 long load;
3069 bool stopsearch = false;
3070
3071 if (READ_ONCE(dst_rq->numa_migrate_on))
3072 return false;
3073
3074 rcu_read_lock();
3075 cur = rcu_dereference_all(dst_rq->curr);
3076 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
3077 !cur->mm))
3078 cur = NULL;
3079
3080 /*
3081 * Because we have preemption enabled we can get migrated around and
3082 * end try selecting ourselves (current == env->p) as a swap candidate.
3083 */
3084 if (cur == env->p) {
3085 stopsearch = true;
3086 goto unlock;
3087 }
3088
3089 if (!cur) {
3090 if (maymove && moveimp >= env->best_imp)
3091 goto assign;
3092 else
3093 goto unlock;
3094 }
3095
3096 /* Skip this swap candidate if cannot move to the source cpu. */
3097 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
3098 goto unlock;
3099
3100 /*
3101 * Skip this swap candidate if it is not moving to its preferred
3102 * node and the best task is.
3103 */
3104 if (env->best_task &&
3105 env->best_task->numa_preferred_nid == env->src_nid &&
3106 cur->numa_preferred_nid != env->src_nid) {
3107 goto unlock;
3108 }
3109
3110 /*
3111 * "imp" is the fault differential for the source task between the
3112 * source and destination node. Calculate the total differential for
3113 * the source task and potential destination task. The more negative
3114 * the value is, the more remote accesses that would be expected to
3115 * be incurred if the tasks were swapped.
3116 *
3117 * If dst and source tasks are in the same NUMA group, or not
3118 * in any group then look only at task weights.
3119 */
3120 cur_ng = rcu_dereference_all(cur->numa_group);
3121 if (cur_ng == p_ng) {
3122 /*
3123 * Do not swap within a group or between tasks that have
3124 * no group if there is spare capacity. Swapping does
3125 * not address the load imbalance and helps one task at
3126 * the cost of punishing another.
3127 */
3128 if (env->dst_stats.node_type == node_has_spare)
3129 goto unlock;
3130
3131 imp = taskimp + task_weight(cur, env->src_nid, dist) -
3132 task_weight(cur, env->dst_nid, dist);
3133 /*
3134 * Add some hysteresis to prevent swapping the
3135 * tasks within a group over tiny differences.
3136 */
3137 if (cur_ng)
3138 imp -= imp / 16;
3139 } else {
3140 /*
3141 * Compare the group weights. If a task is all by itself
3142 * (not part of a group), use the task weight instead.
3143 */
3144 if (cur_ng && p_ng)
3145 imp += group_weight(cur, env->src_nid, dist) -
3146 group_weight(cur, env->dst_nid, dist);
3147 else
3148 imp += task_weight(cur, env->src_nid, dist) -
3149 task_weight(cur, env->dst_nid, dist);
3150 }
3151
3152 /* Discourage picking a task already on its preferred node */
3153 if (cur->numa_preferred_nid == env->dst_nid)
3154 imp -= imp / 16;
3155
3156 /*
3157 * Encourage picking a task that moves to its preferred node.
3158 * This potentially makes imp larger than it's maximum of
3159 * 1998 (see SMALLIMP and task_weight for why) but in this
3160 * case, it does not matter.
3161 */
3162 if (cur->numa_preferred_nid == env->src_nid)
3163 imp += imp / 8;
3164
3165 if (maymove && moveimp > imp && moveimp > env->best_imp) {
3166 imp = moveimp;
3167 cur = NULL;
3168 goto assign;
3169 }
3170
3171 /*
3172 * Prefer swapping with a task moving to its preferred node over a
3173 * task that is not.
3174 */
3175 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
3176 env->best_task->numa_preferred_nid != env->src_nid) {
3177 goto assign;
3178 }
3179
3180 /*
3181 * If the NUMA importance is less than SMALLIMP,
3182 * task migration might only result in ping pong
3183 * of tasks and also hurt performance due to cache
3184 * misses.
3185 */
3186 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
3187 goto unlock;
3188
3189 /*
3190 * In the overloaded case, try and keep the load balanced.
3191 */
3192 load = task_h_load(env->p) - task_h_load(cur);
3193 if (!load)
3194 goto assign;
3195
3196 dst_load = env->dst_stats.load + load;
3197 src_load = env->src_stats.load - load;
3198
3199 if (load_too_imbalanced(src_load, dst_load, env))
3200 goto unlock;
3201
3202 assign:
3203 /* Evaluate an idle CPU for a task numa move. */
3204 if (!cur) {
3205 int cpu = env->dst_stats.idle_cpu;
3206
3207 /* Nothing cached so current CPU went idle since the search. */
3208 if (cpu < 0)
3209 cpu = env->dst_cpu;
3210
3211 /*
3212 * If the CPU is no longer truly idle and the previous best CPU
3213 * is, keep using it.
3214 */
3215 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
3216 idle_cpu(env->best_cpu)) {
3217 cpu = env->best_cpu;
3218 }
3219
3220 env->dst_cpu = cpu;
3221 }
3222
3223 task_numa_assign(env, cur, imp);
3224
3225 /*
3226 * If a move to idle is allowed because there is capacity or load
3227 * balance improves then stop the search. While a better swap
3228 * candidate may exist, a search is not free.
3229 */
3230 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
3231 stopsearch = true;
3232
3233 /*
3234 * If a swap candidate must be identified and the current best task
3235 * moves its preferred node then stop the search.
3236 */
3237 if (!maymove && env->best_task &&
3238 env->best_task->numa_preferred_nid == env->src_nid) {
3239 stopsearch = true;
3240 }
3241 unlock:
3242 rcu_read_unlock();
3243
3244 return stopsearch;
3245 }
3246
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)3247 static void task_numa_find_cpu(struct task_numa_env *env,
3248 long taskimp, long groupimp)
3249 {
3250 bool maymove = false;
3251 int cpu;
3252
3253 /*
3254 * If dst node has spare capacity, then check if there is an
3255 * imbalance that would be overruled by the load balancer.
3256 */
3257 if (env->dst_stats.node_type == node_has_spare) {
3258 unsigned int imbalance;
3259 int src_running, dst_running;
3260
3261 /*
3262 * Would movement cause an imbalance? Note that if src has
3263 * more running tasks that the imbalance is ignored as the
3264 * move improves the imbalance from the perspective of the
3265 * CPU load balancer.
3266 * */
3267 src_running = env->src_stats.nr_running - 1;
3268 dst_running = env->dst_stats.nr_running + 1;
3269 imbalance = max(0, dst_running - src_running);
3270 imbalance = adjust_numa_imbalance(imbalance, dst_running,
3271 env->imb_numa_nr);
3272
3273 /* Use idle CPU if there is no imbalance */
3274 if (!imbalance) {
3275 maymove = true;
3276 if (env->dst_stats.idle_cpu >= 0) {
3277 env->dst_cpu = env->dst_stats.idle_cpu;
3278 task_numa_assign(env, NULL, 0);
3279 return;
3280 }
3281 }
3282 } else {
3283 long src_load, dst_load, load;
3284 /*
3285 * If the improvement from just moving env->p direction is better
3286 * than swapping tasks around, check if a move is possible.
3287 */
3288 load = task_h_load(env->p);
3289 dst_load = env->dst_stats.load + load;
3290 src_load = env->src_stats.load - load;
3291 maymove = !load_too_imbalanced(src_load, dst_load, env);
3292 }
3293
3294 /* Skip CPUs if the source task cannot migrate */
3295 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) {
3296 env->dst_cpu = cpu;
3297 if (task_numa_compare(env, taskimp, groupimp, maymove))
3298 break;
3299 }
3300 }
3301
task_numa_migrate(struct task_struct * p)3302 static int task_numa_migrate(struct task_struct *p)
3303 {
3304 struct task_numa_env env = {
3305 .p = p,
3306
3307 .src_cpu = task_cpu(p),
3308 .src_nid = task_node(p),
3309
3310 .imbalance_pct = 112,
3311
3312 .best_task = NULL,
3313 .best_imp = 0,
3314 .best_cpu = -1,
3315 };
3316 unsigned long taskweight, groupweight;
3317 struct sched_domain *sd;
3318 long taskimp, groupimp;
3319 struct numa_group *ng;
3320 struct rq *best_rq;
3321 int nid, ret, dist;
3322
3323 /*
3324 * Pick the lowest SD_NUMA domain, as that would have the smallest
3325 * imbalance and would be the first to start moving tasks about.
3326 *
3327 * And we want to avoid any moving of tasks about, as that would create
3328 * random movement of tasks -- counter the numa conditions we're trying
3329 * to satisfy here.
3330 */
3331 rcu_read_lock();
3332 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu));
3333 if (sd) {
3334 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
3335 env.imb_numa_nr = sd->imb_numa_nr;
3336 }
3337 rcu_read_unlock();
3338
3339 /*
3340 * Cpusets can break the scheduler domain tree into smaller
3341 * balance domains, some of which do not cross NUMA boundaries.
3342 * Tasks that are "trapped" in such domains cannot be migrated
3343 * elsewhere, so there is no point in (re)trying.
3344 */
3345 if (unlikely(!sd)) {
3346 sched_setnuma(p, task_node(p));
3347 return -EINVAL;
3348 }
3349
3350 env.dst_nid = p->numa_preferred_nid;
3351 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
3352 taskweight = task_weight(p, env.src_nid, dist);
3353 groupweight = group_weight(p, env.src_nid, dist);
3354 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
3355 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
3356 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
3357 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3358
3359 /* Try to find a spot on the preferred nid. */
3360 task_numa_find_cpu(&env, taskimp, groupimp);
3361
3362 /*
3363 * Look at other nodes in these cases:
3364 * - there is no space available on the preferred_nid
3365 * - the task is part of a numa_group that is interleaved across
3366 * multiple NUMA nodes; in order to better consolidate the group,
3367 * we need to check other locations.
3368 */
3369 ng = deref_curr_numa_group(p);
3370 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
3371 for_each_node_state(nid, N_CPU) {
3372 if (nid == env.src_nid || nid == p->numa_preferred_nid)
3373 continue;
3374
3375 dist = node_distance(env.src_nid, env.dst_nid);
3376 if (sched_numa_topology_type == NUMA_BACKPLANE &&
3377 dist != env.dist) {
3378 taskweight = task_weight(p, env.src_nid, dist);
3379 groupweight = group_weight(p, env.src_nid, dist);
3380 }
3381
3382 /* Only consider nodes where both task and groups benefit */
3383 taskimp = task_weight(p, nid, dist) - taskweight;
3384 groupimp = group_weight(p, nid, dist) - groupweight;
3385 if (taskimp < 0 && groupimp < 0)
3386 continue;
3387
3388 env.dist = dist;
3389 env.dst_nid = nid;
3390 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
3391 task_numa_find_cpu(&env, taskimp, groupimp);
3392 }
3393 }
3394
3395 /*
3396 * If the task is part of a workload that spans multiple NUMA nodes,
3397 * and is migrating into one of the workload's active nodes, remember
3398 * this node as the task's preferred numa node, so the workload can
3399 * settle down.
3400 * A task that migrated to a second choice node will be better off
3401 * trying for a better one later. Do not set the preferred node here.
3402 */
3403 if (ng) {
3404 if (env.best_cpu == -1)
3405 nid = env.src_nid;
3406 else
3407 nid = cpu_to_node(env.best_cpu);
3408
3409 if (nid != p->numa_preferred_nid)
3410 sched_setnuma(p, nid);
3411 }
3412
3413 /* No better CPU than the current one was found. */
3414 if (env.best_cpu == -1) {
3415 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
3416 return -EAGAIN;
3417 }
3418
3419 best_rq = cpu_rq(env.best_cpu);
3420 if (env.best_task == NULL) {
3421 ret = migrate_task_to(p, env.best_cpu);
3422 WRITE_ONCE(best_rq->numa_migrate_on, 0);
3423 if (ret != 0)
3424 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
3425 return ret;
3426 }
3427
3428 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
3429 WRITE_ONCE(best_rq->numa_migrate_on, 0);
3430
3431 if (ret != 0)
3432 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
3433 put_task_struct(env.best_task);
3434 return ret;
3435 }
3436
3437 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)3438 static void numa_migrate_preferred(struct task_struct *p)
3439 {
3440 unsigned long interval = HZ;
3441
3442 /* This task has no NUMA fault statistics yet */
3443 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
3444 return;
3445
3446 /* Periodically retry migrating the task to the preferred node */
3447 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
3448 p->numa_migrate_retry = jiffies + interval;
3449
3450 /* Success if task is already running on preferred CPU */
3451 if (task_node(p) == p->numa_preferred_nid)
3452 return;
3453
3454 /* Otherwise, try migrate to a CPU on the preferred node */
3455 task_numa_migrate(p);
3456 }
3457
3458 /*
3459 * Find out how many nodes the workload is actively running on. Do this by
3460 * tracking the nodes from which NUMA hinting faults are triggered. This can
3461 * be different from the set of nodes where the workload's memory is currently
3462 * located.
3463 */
numa_group_count_active_nodes(struct numa_group * numa_group)3464 static void numa_group_count_active_nodes(struct numa_group *numa_group)
3465 {
3466 unsigned long faults, max_faults = 0;
3467 int nid, active_nodes = 0;
3468
3469 for_each_node_state(nid, N_CPU) {
3470 faults = group_faults_cpu(numa_group, nid);
3471 if (faults > max_faults)
3472 max_faults = faults;
3473 }
3474
3475 for_each_node_state(nid, N_CPU) {
3476 faults = group_faults_cpu(numa_group, nid);
3477 if (faults * ACTIVE_NODE_FRACTION > max_faults)
3478 active_nodes++;
3479 }
3480
3481 numa_group->max_faults_cpu = max_faults;
3482 numa_group->active_nodes = active_nodes;
3483 }
3484
3485 /*
3486 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
3487 * increments. The more local the fault statistics are, the higher the scan
3488 * period will be for the next scan window. If local/(local+remote) ratio is
3489 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
3490 * the scan period will decrease. Aim for 70% local accesses.
3491 */
3492 #define NUMA_PERIOD_SLOTS 10
3493 #define NUMA_PERIOD_THRESHOLD 7
3494
3495 /*
3496 * Increase the scan period (slow down scanning) if the majority of
3497 * our memory is already on our local node, or if the majority of
3498 * the page accesses are shared with other processes.
3499 * Otherwise, decrease the scan period.
3500 */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)3501 static void update_task_scan_period(struct task_struct *p,
3502 unsigned long shared, unsigned long private)
3503 {
3504 unsigned int period_slot;
3505 int lr_ratio, ps_ratio;
3506 int diff;
3507
3508 unsigned long remote = p->numa_faults_locality[0];
3509 unsigned long local = p->numa_faults_locality[1];
3510
3511 /*
3512 * If there were no record hinting faults then either the task is
3513 * completely idle or all activity is in areas that are not of interest
3514 * to automatic numa balancing. Related to that, if there were failed
3515 * migration then it implies we are migrating too quickly or the local
3516 * node is overloaded. In either case, scan slower
3517 */
3518 if (local + shared == 0 || p->numa_faults_locality[2]) {
3519 p->numa_scan_period = min(p->numa_scan_period_max,
3520 p->numa_scan_period << 1);
3521
3522 p->mm->numa_next_scan = jiffies +
3523 msecs_to_jiffies(p->numa_scan_period);
3524
3525 return;
3526 }
3527
3528 /*
3529 * Prepare to scale scan period relative to the current period.
3530 * == NUMA_PERIOD_THRESHOLD scan period stays the same
3531 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
3532 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
3533 */
3534 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
3535 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
3536 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
3537
3538 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
3539 /*
3540 * Most memory accesses are local. There is no need to
3541 * do fast NUMA scanning, since memory is already local.
3542 */
3543 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
3544 if (!slot)
3545 slot = 1;
3546 diff = slot * period_slot;
3547 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
3548 /*
3549 * Most memory accesses are shared with other tasks.
3550 * There is no point in continuing fast NUMA scanning,
3551 * since other tasks may just move the memory elsewhere.
3552 */
3553 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
3554 if (!slot)
3555 slot = 1;
3556 diff = slot * period_slot;
3557 } else {
3558 /*
3559 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
3560 * yet they are not on the local NUMA node. Speed up
3561 * NUMA scanning to get the memory moved over.
3562 */
3563 int ratio = max(lr_ratio, ps_ratio);
3564 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
3565 }
3566
3567 p->numa_scan_period = clamp(p->numa_scan_period + diff,
3568 task_scan_min(p), task_scan_max(p));
3569 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3570 }
3571
3572 /*
3573 * Get the fraction of time the task has been running since the last
3574 * NUMA placement cycle. The scheduler keeps similar statistics, but
3575 * decays those on a 32ms period, which is orders of magnitude off
3576 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
3577 * stats only if the task is so new there are no NUMA statistics yet.
3578 */
numa_get_avg_runtime(struct task_struct * p,u64 * period)3579 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
3580 {
3581 u64 runtime, delta, now;
3582 /* Use the start of this time slice to avoid calculations. */
3583 now = p->se.exec_start;
3584 runtime = p->se.sum_exec_runtime;
3585
3586 if (p->last_task_numa_placement) {
3587 delta = runtime - p->last_sum_exec_runtime;
3588 *period = now - p->last_task_numa_placement;
3589
3590 /* Avoid time going backwards, prevent potential divide error: */
3591 if (unlikely((s64)*period < 0))
3592 *period = 0;
3593 } else {
3594 delta = p->se.avg.load_sum;
3595 *period = LOAD_AVG_MAX;
3596 }
3597
3598 p->last_sum_exec_runtime = runtime;
3599 p->last_task_numa_placement = now;
3600
3601 return delta;
3602 }
3603
3604 /*
3605 * Determine the preferred nid for a task in a numa_group. This needs to
3606 * be done in a way that produces consistent results with group_weight,
3607 * otherwise workloads might not converge.
3608 */
preferred_group_nid(struct task_struct * p,int nid)3609 static int preferred_group_nid(struct task_struct *p, int nid)
3610 {
3611 nodemask_t nodes;
3612 int dist;
3613
3614 /* Direct connections between all NUMA nodes. */
3615 if (sched_numa_topology_type == NUMA_DIRECT)
3616 return nid;
3617
3618 /*
3619 * On a system with glueless mesh NUMA topology, group_weight
3620 * scores nodes according to the number of NUMA hinting faults on
3621 * both the node itself, and on nearby nodes.
3622 */
3623 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
3624 unsigned long score, max_score = 0;
3625 int node, max_node = nid;
3626
3627 dist = sched_max_numa_distance;
3628
3629 for_each_node_state(node, N_CPU) {
3630 score = group_weight(p, node, dist);
3631 if (score > max_score) {
3632 max_score = score;
3633 max_node = node;
3634 }
3635 }
3636 return max_node;
3637 }
3638
3639 /*
3640 * Finding the preferred nid in a system with NUMA backplane
3641 * interconnect topology is more involved. The goal is to locate
3642 * tasks from numa_groups near each other in the system, and
3643 * untangle workloads from different sides of the system. This requires
3644 * searching down the hierarchy of node groups, recursively searching
3645 * inside the highest scoring group of nodes. The nodemask tricks
3646 * keep the complexity of the search down.
3647 */
3648 nodes = node_states[N_CPU];
3649 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
3650 unsigned long max_faults = 0;
3651 nodemask_t max_group = NODE_MASK_NONE;
3652 int a, b;
3653
3654 /* Are there nodes at this distance from each other? */
3655 if (!find_numa_distance(dist))
3656 continue;
3657
3658 for_each_node_mask(a, nodes) {
3659 unsigned long faults = 0;
3660 nodemask_t this_group;
3661 nodes_clear(this_group);
3662
3663 /* Sum group's NUMA faults; includes a==b case. */
3664 for_each_node_mask(b, nodes) {
3665 if (node_distance(a, b) < dist) {
3666 faults += group_faults(p, b);
3667 node_set(b, this_group);
3668 node_clear(b, nodes);
3669 }
3670 }
3671
3672 /* Remember the top group. */
3673 if (faults > max_faults) {
3674 max_faults = faults;
3675 max_group = this_group;
3676 /*
3677 * subtle: at the smallest distance there is
3678 * just one node left in each "group", the
3679 * winner is the preferred nid.
3680 */
3681 nid = a;
3682 }
3683 }
3684 /* Next round, evaluate the nodes within max_group. */
3685 if (!max_faults)
3686 break;
3687 nodes = max_group;
3688 }
3689 return nid;
3690 }
3691
task_numa_placement(struct task_struct * p)3692 static void task_numa_placement(struct task_struct *p)
3693 __context_unsafe(/* conditional locking */)
3694 {
3695 int seq, nid, max_nid = NUMA_NO_NODE;
3696 unsigned long max_faults = 0;
3697 unsigned long fault_types[2] = { 0, 0 };
3698 unsigned long total_faults;
3699 u64 runtime, period;
3700 spinlock_t *group_lock = NULL;
3701 long __maybe_unused new_fp;
3702 struct numa_group *ng;
3703
3704 /*
3705 * The p->mm->numa_scan_seq field gets updated without
3706 * exclusive access. Use READ_ONCE() here to ensure
3707 * that the field is read in a single access:
3708 */
3709 seq = READ_ONCE(p->mm->numa_scan_seq);
3710 if (p->numa_scan_seq == seq)
3711 return;
3712 p->numa_scan_seq = seq;
3713 p->numa_scan_period_max = task_scan_max(p);
3714
3715 total_faults = p->numa_faults_locality[0] +
3716 p->numa_faults_locality[1];
3717 runtime = numa_get_avg_runtime(p, &period);
3718
3719 /* If the task is part of a group prevent parallel updates to group stats */
3720 ng = deref_curr_numa_group(p);
3721 if (ng) {
3722 group_lock = &ng->lock;
3723 spin_lock_irq(group_lock);
3724 }
3725
3726 /* Find the node with the highest number of faults */
3727 for_each_online_node(nid) {
3728 /* Keep track of the offsets in numa_faults array */
3729 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
3730 unsigned long faults = 0, group_faults = 0;
3731 int priv;
3732
3733 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
3734 long diff, f_diff, f_weight;
3735
3736 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
3737 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
3738 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
3739 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
3740
3741 /* Decay existing window, copy faults since last scan */
3742 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
3743 fault_types[priv] += p->numa_faults[membuf_idx];
3744 p->numa_faults[membuf_idx] = 0;
3745
3746 /*
3747 * Normalize the faults_from, so all tasks in a group
3748 * count according to CPU use, instead of by the raw
3749 * number of faults. Tasks with little runtime have
3750 * little over-all impact on throughput, and thus their
3751 * faults are less important.
3752 */
3753 f_weight = div64_u64(runtime << 16, period + 1);
3754 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
3755 (total_faults + 1);
3756 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
3757 p->numa_faults[cpubuf_idx] = 0;
3758
3759 p->numa_faults[mem_idx] += diff;
3760 p->numa_faults[cpu_idx] += f_diff;
3761 faults += p->numa_faults[mem_idx];
3762 p->total_numa_faults += diff;
3763 if (ng) {
3764 /*
3765 * safe because we can only change our own group
3766 *
3767 * mem_idx represents the offset for a given
3768 * nid and priv in a specific region because it
3769 * is at the beginning of the numa_faults array.
3770 */
3771 ng->faults[mem_idx] += diff;
3772 ng->faults[cpu_idx] += f_diff;
3773 ng->total_faults += diff;
3774 group_faults += ng->faults[mem_idx];
3775 }
3776 #ifdef CONFIG_SCHED_CACHE
3777 /*
3778 * Per task p->numa_faults[mem_idx] converges,
3779 * so the accumulation of each task's faults
3780 * converges too - Given the number of threads,
3781 * it cannot overflow an unsigned long.
3782 * Racy with concurrent updates from other threads
3783 * sharing this mm. Acceptable since footprint is a
3784 * heuristic and occasional lost updates are tolerable.
3785 *
3786 * If a task exits, its corresponding footprint must
3787 * be subtracted from the mm->sc_stat.footprint, otherwise
3788 * the mm->sc_stat.footprint will not converge:
3789 * the exiting thread's footprint remains unchanged/undecayed
3790 * in mm->sc_stat.footprint. See exit_mm().
3791 *
3792 * Lost updates and unsynchronized subtraction
3793 * in exit_mm() can cause footprint + diff to
3794 * go negative. Clamp to zero to prevent the
3795 * unsigned footprint from wrapping.
3796 */
3797 new_fp = (long)READ_ONCE(p->mm->sc_stat.footprint) + diff;
3798 WRITE_ONCE(p->mm->sc_stat.footprint,
3799 max(new_fp, 0L));
3800 #endif
3801 }
3802
3803 if (!ng) {
3804 if (faults > max_faults) {
3805 max_faults = faults;
3806 max_nid = nid;
3807 }
3808 } else if (group_faults > max_faults) {
3809 max_faults = group_faults;
3810 max_nid = nid;
3811 }
3812 }
3813
3814 /* Cannot migrate task to CPU-less node */
3815 max_nid = numa_nearest_node(max_nid, N_CPU);
3816
3817 if (ng) {
3818 numa_group_count_active_nodes(ng);
3819 spin_unlock_irq(group_lock);
3820 max_nid = preferred_group_nid(p, max_nid);
3821 }
3822
3823 if (max_faults) {
3824 /* Set the new preferred node */
3825 if (max_nid != p->numa_preferred_nid)
3826 sched_setnuma(p, max_nid);
3827 }
3828
3829 update_task_scan_period(p, fault_types[0], fault_types[1]);
3830 }
3831
get_numa_group(struct numa_group * grp)3832 static inline int get_numa_group(struct numa_group *grp)
3833 {
3834 return refcount_inc_not_zero(&grp->refcount);
3835 }
3836
put_numa_group(struct numa_group * grp)3837 static inline void put_numa_group(struct numa_group *grp)
3838 {
3839 if (refcount_dec_and_test(&grp->refcount))
3840 kfree_rcu(grp, rcu);
3841 }
3842
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)3843 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3844 int *priv)
3845 {
3846 struct numa_group *grp, *my_grp;
3847 struct task_struct *tsk;
3848 bool join = false;
3849 int cpu = cpupid_to_cpu(cpupid);
3850 int i;
3851
3852 if (unlikely(!deref_curr_numa_group(p))) {
3853 unsigned int size = sizeof(struct numa_group) +
3854 NR_NUMA_HINT_FAULT_STATS *
3855 nr_node_ids * sizeof(unsigned long);
3856
3857 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3858 if (!grp)
3859 return;
3860
3861 refcount_set(&grp->refcount, 1);
3862 grp->active_nodes = 1;
3863 grp->max_faults_cpu = 0;
3864 spin_lock_init(&grp->lock);
3865 grp->gid = p->pid;
3866
3867 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3868 grp->faults[i] = p->numa_faults[i];
3869
3870 grp->total_faults = p->total_numa_faults;
3871
3872 grp->nr_tasks++;
3873 rcu_assign_pointer(p->numa_group, grp);
3874 }
3875
3876 rcu_read_lock();
3877 tsk = READ_ONCE(cpu_rq(cpu)->curr);
3878
3879 if (!cpupid_match_pid(tsk, cpupid))
3880 goto no_join;
3881
3882 grp = rcu_dereference_all(tsk->numa_group);
3883 if (!grp)
3884 goto no_join;
3885
3886 my_grp = deref_curr_numa_group(p);
3887 if (grp == my_grp)
3888 goto no_join;
3889
3890 /*
3891 * Only join the other group if its bigger; if we're the bigger group,
3892 * the other task will join us.
3893 */
3894 if (my_grp->nr_tasks > grp->nr_tasks)
3895 goto no_join;
3896
3897 /*
3898 * Tie-break on the grp address.
3899 */
3900 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3901 goto no_join;
3902
3903 /* Always join threads in the same process. */
3904 if (tsk->mm == current->mm)
3905 join = true;
3906
3907 /* Simple filter to avoid false positives due to PID collisions */
3908 if (flags & TNF_SHARED)
3909 join = true;
3910
3911 /* Update priv based on whether false sharing was detected */
3912 *priv = !join;
3913
3914 if (join && !get_numa_group(grp))
3915 goto no_join;
3916
3917 rcu_read_unlock();
3918
3919 if (!join)
3920 return;
3921
3922 WARN_ON_ONCE(irqs_disabled());
3923 double_lock_irq(&my_grp->lock, &grp->lock);
3924
3925 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3926 my_grp->faults[i] -= p->numa_faults[i];
3927 grp->faults[i] += p->numa_faults[i];
3928 }
3929 my_grp->total_faults -= p->total_numa_faults;
3930 grp->total_faults += p->total_numa_faults;
3931
3932 my_grp->nr_tasks--;
3933 grp->nr_tasks++;
3934
3935 spin_unlock(&my_grp->lock);
3936 spin_unlock_irq(&grp->lock);
3937
3938 rcu_assign_pointer(p->numa_group, grp);
3939
3940 put_numa_group(my_grp);
3941 return;
3942
3943 no_join:
3944 rcu_read_unlock();
3945 return;
3946 }
3947
3948 /*
3949 * Get rid of NUMA statistics associated with a task (either current or dead).
3950 * If @final is set, the task is dead and has reached refcount zero, so we can
3951 * safely free all relevant data structures. Otherwise, there might be
3952 * concurrent reads from places like load balancing and procfs, and we should
3953 * reset the data back to default state without freeing ->numa_faults.
3954 */
task_numa_free(struct task_struct * p,bool final)3955 void task_numa_free(struct task_struct *p, bool final)
3956 {
3957 /* safe: p either is current or is being freed by current */
3958 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3959 unsigned long *numa_faults = p->numa_faults;
3960 unsigned long flags;
3961 int i;
3962
3963 if (!numa_faults)
3964 return;
3965
3966 if (grp) {
3967 spin_lock_irqsave(&grp->lock, flags);
3968 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3969 grp->faults[i] -= p->numa_faults[i];
3970 grp->total_faults -= p->total_numa_faults;
3971
3972 grp->nr_tasks--;
3973 spin_unlock_irqrestore(&grp->lock, flags);
3974 RCU_INIT_POINTER(p->numa_group, NULL);
3975 put_numa_group(grp);
3976 }
3977
3978 if (final) {
3979 p->numa_faults = NULL;
3980 kfree(numa_faults);
3981 } else {
3982 p->total_numa_faults = 0;
3983 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3984 numa_faults[i] = 0;
3985 }
3986 }
3987
3988 /*
3989 * Got a PROT_NONE fault for a page on @node.
3990 */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3991 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3992 {
3993 struct task_struct *p = current;
3994 bool migrated = flags & TNF_MIGRATED;
3995 int cpu_node = task_node(current);
3996 int local = !!(flags & TNF_FAULT_LOCAL);
3997 struct numa_group *ng;
3998 int priv;
3999
4000 if (!static_branch_likely(&sched_numa_balancing))
4001 return;
4002
4003 /* for example, ksmd faulting in a user's mm */
4004 if (!p->mm)
4005 return;
4006
4007 /*
4008 * NUMA faults statistics are unnecessary for the slow memory
4009 * node for memory tiering mode.
4010 */
4011 if (!node_is_toptier(mem_node) &&
4012 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
4013 !cpupid_valid(last_cpupid)))
4014 return;
4015
4016 /* Allocate buffer to track faults on a per-node basis */
4017 if (unlikely(!p->numa_faults)) {
4018 int size = sizeof(*p->numa_faults) *
4019 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
4020
4021 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
4022 if (!p->numa_faults)
4023 return;
4024
4025 p->total_numa_faults = 0;
4026 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
4027 }
4028
4029 /*
4030 * First accesses are treated as private, otherwise consider accesses
4031 * to be private if the accessing pid has not changed
4032 */
4033 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
4034 priv = 1;
4035 } else {
4036 priv = cpupid_match_pid(p, last_cpupid);
4037 if (!priv && !(flags & TNF_NO_GROUP))
4038 task_numa_group(p, last_cpupid, flags, &priv);
4039 }
4040
4041 /*
4042 * If a workload spans multiple NUMA nodes, a shared fault that
4043 * occurs wholly within the set of nodes that the workload is
4044 * actively using should be counted as local. This allows the
4045 * scan rate to slow down when a workload has settled down.
4046 */
4047 ng = deref_curr_numa_group(p);
4048 if (!priv && !local && ng && ng->active_nodes > 1 &&
4049 numa_is_active_node(cpu_node, ng) &&
4050 numa_is_active_node(mem_node, ng))
4051 local = 1;
4052
4053 /*
4054 * Retry to migrate task to preferred node periodically, in case it
4055 * previously failed, or the scheduler moved us.
4056 */
4057 if (time_after(jiffies, p->numa_migrate_retry)) {
4058 task_numa_placement(p);
4059 numa_migrate_preferred(p);
4060 }
4061
4062 if (migrated)
4063 p->numa_pages_migrated += pages;
4064 if (flags & TNF_MIGRATE_FAIL)
4065 p->numa_faults_locality[2] += pages;
4066
4067 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
4068 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
4069 p->numa_faults_locality[local] += pages;
4070 }
4071
reset_ptenuma_scan(struct task_struct * p)4072 static void reset_ptenuma_scan(struct task_struct *p)
4073 {
4074 /*
4075 * We only did a read acquisition of the mmap sem, so
4076 * p->mm->numa_scan_seq is written to without exclusive access
4077 * and the update is not guaranteed to be atomic. That's not
4078 * much of an issue though, since this is just used for
4079 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
4080 * expensive, to avoid any form of compiler optimizations:
4081 */
4082 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
4083 p->mm->numa_scan_offset = 0;
4084 }
4085
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)4086 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
4087 {
4088 unsigned long pids;
4089 /*
4090 * Allow unconditional access first two times, so that all the (pages)
4091 * of VMAs get prot_none fault introduced irrespective of accesses.
4092 * This is also done to avoid any side effect of task scanning
4093 * amplifying the unfairness of disjoint set of VMAs' access.
4094 */
4095 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
4096 return true;
4097
4098 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
4099 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
4100 return true;
4101
4102 /*
4103 * Complete a scan that has already started regardless of PID access, or
4104 * some VMAs may never be scanned in multi-threaded applications:
4105 */
4106 if (mm->numa_scan_offset > vma->vm_start) {
4107 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
4108 return true;
4109 }
4110
4111 /*
4112 * This vma has not been accessed for a while, and if the number
4113 * the threads in the same process is low, which means no other
4114 * threads can help scan this vma, force a vma scan.
4115 */
4116 if (READ_ONCE(mm->numa_scan_seq) >
4117 (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
4118 return true;
4119
4120 return false;
4121 }
4122
4123 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
4124
4125 /*
4126 * The expensive part of numa migration is done from task_work context.
4127 * Triggered from task_tick_numa().
4128 */
task_numa_work(struct callback_head * work)4129 static void task_numa_work(struct callback_head *work)
4130 {
4131 unsigned long migrate, next_scan, now = jiffies;
4132 struct task_struct *p = current;
4133 struct mm_struct *mm = p->mm;
4134 u64 runtime = p->se.sum_exec_runtime;
4135 struct vm_area_struct *vma;
4136 unsigned long start, end;
4137 unsigned long nr_pte_updates = 0;
4138 long pages, virtpages;
4139 struct vma_iterator vmi;
4140 bool vma_pids_skipped;
4141 bool vma_pids_forced = false;
4142
4143 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
4144
4145 work->next = work;
4146 /*
4147 * Who cares about NUMA placement when they're dying.
4148 *
4149 * NOTE: make sure not to dereference p->mm before this check,
4150 * exit_task_work() happens _after_ exit_mm() so we could be called
4151 * without p->mm even though we still had it when we enqueued this
4152 * work.
4153 */
4154 if (p->flags & PF_EXITING)
4155 return;
4156
4157 /*
4158 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
4159 * no page can be migrated.
4160 */
4161 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
4162 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
4163 return;
4164 }
4165
4166 if (!mm->numa_next_scan) {
4167 mm->numa_next_scan = now +
4168 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4169 }
4170
4171 /*
4172 * Enforce maximal scan/migration frequency..
4173 */
4174 migrate = mm->numa_next_scan;
4175 if (time_before(now, migrate))
4176 return;
4177
4178 if (p->numa_scan_period == 0) {
4179 p->numa_scan_period_max = task_scan_max(p);
4180 p->numa_scan_period = task_scan_start(p);
4181 }
4182
4183 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
4184 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
4185 return;
4186
4187 /*
4188 * Delay this task enough that another task of this mm will likely win
4189 * the next time around.
4190 */
4191 p->node_stamp += 2 * TICK_NSEC;
4192
4193 pages = sysctl_numa_balancing_scan_size;
4194 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
4195 virtpages = pages * 8; /* Scan up to this much virtual space */
4196 if (!pages)
4197 return;
4198
4199
4200 if (!mmap_read_trylock(mm))
4201 return;
4202
4203 /*
4204 * VMAs are skipped if the current PID has not trapped a fault within
4205 * the VMA recently. Allow scanning to be forced if there is no
4206 * suitable VMA remaining.
4207 */
4208 vma_pids_skipped = false;
4209
4210 retry_pids:
4211 start = mm->numa_scan_offset;
4212 vma_iter_init(&vmi, mm, start);
4213 vma = vma_next(&vmi);
4214 if (!vma) {
4215 reset_ptenuma_scan(p);
4216 start = 0;
4217 vma_iter_set(&vmi, start);
4218 vma = vma_next(&vmi);
4219 }
4220
4221 for (; vma; vma = vma_next(&vmi)) {
4222 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
4223 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
4224 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
4225 continue;
4226 }
4227
4228 /*
4229 * Shared library pages mapped by multiple processes are not
4230 * migrated as it is expected they are cache replicated. Avoid
4231 * hinting faults in read-only file-backed mappings or the vDSO
4232 * as migrating the pages will be of marginal benefit.
4233 */
4234 if (!vma->vm_mm ||
4235 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
4236 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
4237 continue;
4238 }
4239
4240 /*
4241 * Skip inaccessible VMAs to avoid any confusion between
4242 * PROT_NONE and NUMA hinting PTEs
4243 */
4244 if (!vma_is_accessible(vma)) {
4245 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
4246 continue;
4247 }
4248
4249 /* Initialise new per-VMA NUMAB state. */
4250 if (!vma->numab_state) {
4251 struct vma_numab_state *ptr;
4252
4253 ptr = kzalloc_obj(*ptr);
4254 if (!ptr)
4255 continue;
4256
4257 if (cmpxchg(&vma->numab_state, NULL, ptr)) {
4258 kfree(ptr);
4259 continue;
4260 }
4261
4262 vma->numab_state->start_scan_seq = mm->numa_scan_seq;
4263
4264 vma->numab_state->next_scan = now +
4265 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4266
4267 /* Reset happens after 4 times scan delay of scan start */
4268 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
4269 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4270
4271 /*
4272 * Ensure prev_scan_seq does not match numa_scan_seq,
4273 * to prevent VMAs being skipped prematurely on the
4274 * first scan:
4275 */
4276 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
4277 }
4278
4279 /*
4280 * Scanning the VMAs of short lived tasks add more overhead. So
4281 * delay the scan for new VMAs.
4282 */
4283 if (mm->numa_scan_seq && time_before(jiffies,
4284 vma->numab_state->next_scan)) {
4285 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
4286 continue;
4287 }
4288
4289 /* RESET access PIDs regularly for old VMAs. */
4290 if (mm->numa_scan_seq &&
4291 time_after(jiffies, vma->numab_state->pids_active_reset)) {
4292 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
4293 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
4294 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
4295 vma->numab_state->pids_active[1] = 0;
4296 }
4297
4298 /* Do not rescan VMAs twice within the same sequence. */
4299 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
4300 mm->numa_scan_offset = vma->vm_end;
4301 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
4302 continue;
4303 }
4304
4305 /*
4306 * Do not scan the VMA if task has not accessed it, unless no other
4307 * VMA candidate exists.
4308 */
4309 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
4310 vma_pids_skipped = true;
4311 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
4312 continue;
4313 }
4314
4315 do {
4316 start = max(start, vma->vm_start);
4317 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
4318 end = min(end, vma->vm_end);
4319 nr_pte_updates = change_prot_numa(vma, start, end);
4320
4321 /*
4322 * Try to scan sysctl_numa_balancing_size worth of
4323 * hpages that have at least one present PTE that
4324 * is not already PTE-numa. If the VMA contains
4325 * areas that are unused or already full of prot_numa
4326 * PTEs, scan up to virtpages, to skip through those
4327 * areas faster.
4328 */
4329 if (nr_pte_updates)
4330 pages -= (end - start) >> PAGE_SHIFT;
4331 virtpages -= (end - start) >> PAGE_SHIFT;
4332
4333 start = end;
4334 if (pages <= 0 || virtpages <= 0)
4335 goto out;
4336
4337 cond_resched();
4338 } while (end != vma->vm_end);
4339
4340 /* VMA scan is complete, do not scan until next sequence. */
4341 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
4342
4343 /*
4344 * Only force scan within one VMA at a time, to limit the
4345 * cost of scanning a potentially uninteresting VMA.
4346 */
4347 if (vma_pids_forced)
4348 break;
4349 }
4350
4351 /*
4352 * If no VMAs are remaining and VMAs were skipped due to the PID
4353 * not accessing the VMA previously, then force a scan to ensure
4354 * forward progress:
4355 */
4356 if (!vma && !vma_pids_forced && vma_pids_skipped) {
4357 vma_pids_forced = true;
4358 goto retry_pids;
4359 }
4360
4361 out:
4362 /*
4363 * It is possible to reach the end of the VMA list but the last few
4364 * VMAs are not guaranteed to the vma_migratable. If they are not, we
4365 * would find the !migratable VMA on the next scan but not reset the
4366 * scanner to the start so check it now.
4367 */
4368 if (vma)
4369 mm->numa_scan_offset = start;
4370 else
4371 reset_ptenuma_scan(p);
4372 mmap_read_unlock(mm);
4373
4374 /*
4375 * Make sure tasks use at least 32x as much time to run other code
4376 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
4377 * Usually update_task_scan_period slows down scanning enough; on an
4378 * overloaded system we need to limit overhead on a per task basis.
4379 */
4380 if (unlikely(p->se.sum_exec_runtime != runtime)) {
4381 u64 diff = p->se.sum_exec_runtime - runtime;
4382 p->node_stamp += 32 * diff;
4383 }
4384 }
4385
init_numa_balancing(u64 clone_flags,struct task_struct * p)4386 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
4387 {
4388 int mm_users = 0;
4389 struct mm_struct *mm = p->mm;
4390
4391 if (mm) {
4392 mm_users = atomic_read(&mm->mm_users);
4393 if (mm_users == 1) {
4394 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
4395 mm->numa_scan_seq = 0;
4396 }
4397 }
4398 p->node_stamp = 0;
4399 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
4400 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
4401 p->numa_migrate_retry = 0;
4402 /* Protect against double add, see task_tick_numa and task_numa_work */
4403 p->numa_work.next = &p->numa_work;
4404 p->numa_faults = NULL;
4405 p->numa_pages_migrated = 0;
4406 p->total_numa_faults = 0;
4407 RCU_INIT_POINTER(p->numa_group, NULL);
4408 p->last_task_numa_placement = 0;
4409 p->last_sum_exec_runtime = 0;
4410
4411 init_task_work(&p->numa_work, task_numa_work);
4412
4413 /* New address space, reset the preferred nid */
4414 if (!(clone_flags & CLONE_VM)) {
4415 p->numa_preferred_nid = NUMA_NO_NODE;
4416 return;
4417 }
4418
4419 /*
4420 * New thread, keep existing numa_preferred_nid which should be copied
4421 * already by arch_dup_task_struct but stagger when scans start.
4422 */
4423 if (mm) {
4424 unsigned int delay;
4425
4426 delay = min_t(unsigned int, task_scan_max(current),
4427 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
4428 delay += 2 * TICK_NSEC;
4429 p->node_stamp = delay;
4430 }
4431 }
4432
4433 /*
4434 * Drive the periodic memory faults..
4435 */
task_tick_numa(struct rq * rq,struct task_struct * curr)4436 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4437 {
4438 struct callback_head *work = &curr->numa_work;
4439 u64 period, now;
4440
4441 /*
4442 * We don't care about NUMA placement if we don't have memory.
4443 */
4444 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
4445 return;
4446
4447 /*
4448 * Using runtime rather than walltime has the dual advantage that
4449 * we (mostly) drive the selection from busy threads and that the
4450 * task needs to have done some actual work before we bother with
4451 * NUMA placement.
4452 */
4453 now = curr->se.sum_exec_runtime;
4454 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
4455
4456 if (now > curr->node_stamp + period) {
4457 if (!curr->node_stamp)
4458 curr->numa_scan_period = task_scan_start(curr);
4459 curr->node_stamp += period;
4460
4461 if (!time_before(jiffies, curr->mm->numa_next_scan))
4462 task_work_add(curr, work, TWA_RESUME);
4463 }
4464 }
4465
update_scan_period(struct task_struct * p,int new_cpu)4466 static void update_scan_period(struct task_struct *p, int new_cpu)
4467 {
4468 int src_nid = cpu_to_node(task_cpu(p));
4469 int dst_nid = cpu_to_node(new_cpu);
4470
4471 if (!static_branch_likely(&sched_numa_balancing))
4472 return;
4473
4474 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
4475 return;
4476
4477 if (src_nid == dst_nid)
4478 return;
4479
4480 /*
4481 * Allow resets if faults have been trapped before one scan
4482 * has completed. This is most likely due to a new task that
4483 * is pulled cross-node due to wakeups or load balancing.
4484 */
4485 if (p->numa_scan_seq) {
4486 /*
4487 * Avoid scan adjustments if moving to the preferred
4488 * node or if the task was not previously running on
4489 * the preferred node.
4490 */
4491 if (dst_nid == p->numa_preferred_nid ||
4492 (p->numa_preferred_nid != NUMA_NO_NODE &&
4493 src_nid != p->numa_preferred_nid))
4494 return;
4495 }
4496
4497 p->numa_scan_period = task_scan_start(p);
4498 }
4499
4500 #else /* !CONFIG_NUMA_BALANCING: */
4501
task_tick_numa(struct rq * rq,struct task_struct * curr)4502 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
4503 {
4504 }
4505
account_numa_enqueue(struct rq * rq,struct task_struct * p)4506 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
4507 {
4508 }
4509
account_numa_dequeue(struct rq * rq,struct task_struct * p)4510 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
4511 {
4512 }
4513
update_scan_period(struct task_struct * p,int new_cpu)4514 static inline void update_scan_period(struct task_struct *p, int new_cpu)
4515 {
4516 }
4517
4518 #endif /* !CONFIG_NUMA_BALANCING */
4519
4520 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)4521 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4522 {
4523 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4524 update_load_add(&cfs_rq->load, se->load.weight);
4525 if (entity_is_task(se)) {
4526 struct task_struct *p = task_of(se);
4527 struct rq *rq = rq_of(cfs_rq);
4528
4529 account_numa_enqueue(rq, p);
4530 account_llc_enqueue(rq, p);
4531 list_add(&se->group_node, &rq->cfs_tasks);
4532 }
4533 cfs_rq->nr_queued++;
4534 }
4535
4536 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)4537 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
4538 {
4539 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4540 update_load_sub(&cfs_rq->load, se->load.weight);
4541 if (entity_is_task(se)) {
4542 struct task_struct *p = task_of(se);
4543 struct rq *rq = rq_of(cfs_rq);
4544
4545 account_numa_dequeue(rq, p);
4546 account_llc_dequeue(rq, p);
4547 list_del_init(&se->group_node);
4548 }
4549 cfs_rq->nr_queued--;
4550 }
4551
4552 /*
4553 * Signed add and clamp on underflow.
4554 *
4555 * Explicitly do a load-store to ensure the intermediate value never hits
4556 * memory. This allows lockless observations without ever seeing the negative
4557 * values.
4558 */
4559 #define add_positive(_ptr, _val) do { \
4560 typeof(_ptr) ptr = (_ptr); \
4561 __signed_scalar_typeof(*ptr) val = (_val); \
4562 typeof(*ptr) res, var = READ_ONCE(*ptr); \
4563 \
4564 res = var + val; \
4565 \
4566 if (val < 0 && res > var) \
4567 res = 0; \
4568 \
4569 WRITE_ONCE(*ptr, res); \
4570 } while (0)
4571
4572 /*
4573 * Remove and clamp on negative, from a local variable.
4574 *
4575 * A variant of sub_positive(), which does not use explicit load-store
4576 * and is thus optimized for local variable updates.
4577 */
4578 #define lsub_positive(_ptr, _val) do { \
4579 typeof(_ptr) ptr = (_ptr); \
4580 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
4581 } while (0)
4582
4583
4584 /*
4585 * Because of rounding, se->util_sum might ends up being +1 more than
4586 * cfs->util_sum. Although this is not a problem by itself, detaching
4587 * a lot of tasks with the rounding problem between 2 updates of
4588 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4589 * cfs_util_avg is not.
4590 *
4591 * Check that util_sum is still above its lower bound for the new
4592 * util_avg. Given that period_contrib might have moved since the last
4593 * sync, we are only sure that util_sum must be above or equal to
4594 * util_avg * minimum possible divider
4595 */
4596 #define __update_sa(sa, name, delta_avg, delta_sum) do { \
4597 add_positive(&(sa)->name##_avg, delta_avg); \
4598 add_positive(&(sa)->name##_sum, delta_sum); \
4599 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \
4600 (sa)->name##_sum, \
4601 (sa)->name##_avg * PELT_MIN_DIVIDER); \
4602 } while (0)
4603
4604 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4605 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4606 {
4607 __update_sa(&cfs_rq->avg, load, se->avg.load_avg,
4608 se_weight(se) * se->avg.load_sum);
4609 }
4610
4611 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4612 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4613 {
4614 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg,
4615 se_weight(se) * -se->avg.load_sum);
4616 }
4617
4618 static void
rescale_entity(struct sched_entity * se,unsigned long weight,bool rel_vprot)4619 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot)
4620 {
4621 long old_weight = se->h_load.weight;
4622
4623 /*
4624 * VRUNTIME
4625 * --------
4626 *
4627 * COROLLARY #1: The virtual runtime of the entity needs to be
4628 * adjusted if re-weight at !0-lag point.
4629 *
4630 * Proof: For contradiction assume this is not true, so we can
4631 * re-weight without changing vruntime at !0-lag point.
4632 *
4633 * Weight VRuntime Avg-VRuntime
4634 * before w v V
4635 * after w' v' V'
4636 *
4637 * Since lag needs to be preserved through re-weight:
4638 *
4639 * lag = (V - v)*w = (V'- v')*w', where v = v'
4640 * ==> V' = (V - v)*w/w' + v (1)
4641 *
4642 * Let W be the total weight of the entities before reweight,
4643 * since V' is the new weighted average of entities:
4644 *
4645 * V' = (WV + w'v - wv) / (W + w' - w) (2)
4646 *
4647 * by using (1) & (2) we obtain:
4648 *
4649 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
4650 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
4651 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
4652 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
4653 *
4654 * Since we are doing at !0-lag point which means V != v, we
4655 * can simplify (3):
4656 *
4657 * ==> W / (W + w' - w) = w / w'
4658 * ==> Ww' = Ww + ww' - ww
4659 * ==> W * (w' - w) = w * (w' - w)
4660 * ==> W = w (re-weight indicates w' != w)
4661 *
4662 * So the cfs_rq contains only one entity, hence vruntime of
4663 * the entity @v should always equal to the cfs_rq's weighted
4664 * average vruntime @V, which means we will always re-weight
4665 * at 0-lag point, thus breach assumption. Proof completed.
4666 *
4667 *
4668 * COROLLARY #2: Re-weight does NOT affect weighted average
4669 * vruntime of all the entities.
4670 *
4671 * Proof: According to corollary #1, Eq. (1) should be:
4672 *
4673 * (V - v)*w = (V' - v')*w'
4674 * ==> v' = V' - (V - v)*w/w' (4)
4675 *
4676 * According to the weighted average formula, we have:
4677 *
4678 * V' = (WV - wv + w'v') / (W - w + w')
4679 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
4680 * = (WV - wv + w'V' - Vw + wv) / (W - w + w')
4681 * = (WV + w'V' - Vw) / (W - w + w')
4682 *
4683 * ==> V'*(W - w + w') = WV + w'V' - Vw
4684 * ==> V' * (W - w) = (W - w) * V (5)
4685 *
4686 * If the entity is the only one in the cfs_rq, then reweight
4687 * always occurs at 0-lag point, so V won't change. Or else
4688 * there are other entities, hence W != w, then Eq. (5) turns
4689 * into V' = V. So V won't change in either case, proof done.
4690 *
4691 *
4692 * So according to corollary #1 & #2, the effect of re-weight
4693 * on vruntime should be:
4694 *
4695 * v' = V' - (V - v) * w / w' (4)
4696 * = V - (V - v) * w / w'
4697 * = V - vl * w / w'
4698 * = V - vl'
4699 */
4700 se->vlag = div64_long(se->vlag * old_weight, weight);
4701
4702 /*
4703 * DEADLINE
4704 * --------
4705 *
4706 * When the weight changes, the virtual time slope changes and
4707 * we should adjust the relative virtual deadline accordingly.
4708 *
4709 * d' = v' + (d - v)*w/w'
4710 * = V' - (V - v)*w/w' + (d - v)*w/w'
4711 * = V - (V - v)*w/w' + (d - v)*w/w'
4712 * = V + (d - V)*w/w'
4713 */
4714 if (se->rel_deadline)
4715 se->deadline = div64_long(se->deadline * old_weight, weight);
4716
4717 if (rel_vprot)
4718 se->vprot = div64_long(se->vprot * old_weight, weight);
4719 }
4720
reweight_eevdf(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight,bool on_rq)4721 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se,
4722 unsigned long weight, bool on_rq)
4723 {
4724 bool curr = cfs_rq->curr == se;
4725 bool rel_vprot = false;
4726 u64 avruntime = 0;
4727
4728 if (se->h_load.weight == weight)
4729 return;
4730
4731 if (on_rq) {
4732 avruntime = avg_vruntime(cfs_rq);
4733 se->vlag = entity_lag(cfs_rq, se, avruntime);
4734 se->deadline -= avruntime;
4735 se->rel_deadline = 1;
4736 if (curr && protect_slice(se)) {
4737 se->vprot -= avruntime;
4738 rel_vprot = true;
4739 }
4740
4741 cfs_rq->h_nr_queued--;
4742 if (!curr)
4743 __dequeue_entity(cfs_rq, se);
4744 }
4745
4746 rescale_entity(se, weight, rel_vprot);
4747
4748 update_load_set(&se->h_load, weight);
4749
4750 if (on_rq) {
4751 if (rel_vprot)
4752 se->vprot += avruntime;
4753 se->deadline += avruntime;
4754 se->rel_deadline = 0;
4755 se->vruntime = avruntime - se->vlag;
4756
4757 if (!curr)
4758 __enqueue_entity(cfs_rq, se);
4759 cfs_rq->h_nr_queued++;
4760 }
4761 }
4762
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)4763 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
4764 unsigned long weight)
4765 {
4766 if (se->load.weight == weight)
4767 return;
4768
4769 if (se->on_rq) {
4770 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se));
4771 update_load_sub(&cfs_rq->load, se->load.weight);
4772 }
4773 dequeue_load_avg(cfs_rq, se);
4774
4775 update_load_set(&se->load, weight);
4776
4777 do {
4778 u32 divider = get_pelt_divider(&se->avg);
4779 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
4780 } while (0);
4781
4782 enqueue_load_avg(cfs_rq, se);
4783
4784 if (se->on_rq)
4785 update_load_add(&cfs_rq->load, se->load.weight);
4786 }
4787
4788 /*
4789 * weight = NICE_0_LOAD;
4790 * for_each_entity_se(se)
4791 * weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4792 */
4793 static __always_inline
__calc_prop_weight(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)4794 unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se,
4795 unsigned long weight)
4796 {
4797 weight *= se->load.weight;
4798 if (parent_entity(se))
4799 weight /= cfs_rq->load.weight;
4800 else
4801 weight /= NICE_0_LOAD;
4802
4803 return max(weight, MIN_SHARES);
4804 }
4805
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)4806 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
4807 const struct load_weight *lw)
4808 {
4809 struct sched_entity *se = &p->se;
4810 unsigned long weight = NICE_0_LOAD;
4811
4812 if (se->on_rq)
4813 update_curr_fair(rq);
4814
4815 reweight_entity(cfs_rq_of(se), se, lw->weight);
4816 se->load.inv_weight = lw->inv_weight;
4817
4818 if (!se->on_rq)
4819 return;
4820
4821 for_each_sched_entity(se)
4822 weight = __calc_prop_weight(cfs_rq_of(se), se, weight);
4823
4824 reweight_eevdf(&rq->cfs, &p->se, weight, p->se.on_rq);
4825 }
4826
4827 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
4828
4829 #ifdef CONFIG_FAIR_GROUP_SCHED
4830 /*
4831 * All this does is approximate the hierarchical proportion which includes that
4832 * global sum we all love to hate.
4833 *
4834 * That is, the weight of a group entity, is the proportional share of the
4835 * group weight based on the group runqueue weights. That is:
4836 *
4837 * tg->weight * grq->load.weight
4838 * ge->load.weight = ----------------------------- (1)
4839 * \Sum grq->load.weight
4840 *
4841 * Now, because computing that sum is prohibitively expensive to compute (been
4842 * there, done that) we approximate it with this average stuff. The average
4843 * moves slower and therefore the approximation is cheaper and more stable.
4844 *
4845 * So instead of the above, we substitute:
4846 *
4847 * grq->load.weight -> grq->avg.load_avg (2)
4848 *
4849 * which yields the following:
4850 *
4851 * tg->weight * grq->avg.load_avg
4852 * ge->load.weight = ------------------------------ (3)
4853 * tg->load_avg
4854 *
4855 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
4856 *
4857 * That is shares_avg, and it is right (given the approximation (2)).
4858 *
4859 * The problem with it is that because the average is slow -- it was designed
4860 * to be exactly that of course -- this leads to transients in boundary
4861 * conditions. In specific, the case where the group was idle and we start the
4862 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
4863 * yielding bad latency etc..
4864 *
4865 * Now, in that special case (1) reduces to:
4866 *
4867 * tg->weight * grq->load.weight
4868 * ge->load.weight = ----------------------------- = tg->weight (4)
4869 * grp->load.weight
4870 *
4871 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
4872 *
4873 * So what we do is modify our approximation (3) to approach (4) in the (near)
4874 * UP case, like:
4875 *
4876 * ge->load.weight =
4877 *
4878 * tg->weight * grq->load.weight
4879 * --------------------------------------------------- (5)
4880 * tg->load_avg - grq->avg.load_avg + grq->load.weight
4881 *
4882 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
4883 * we need to use grq->avg.load_avg as its lower bound, which then gives:
4884 *
4885 *
4886 * tg->weight * grq->load.weight
4887 * ge->load.weight = ----------------------------- (6)
4888 * tg_load_avg'
4889 *
4890 * Where:
4891 *
4892 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
4893 * max(grq->load.weight, grq->avg.load_avg)
4894 *
4895 * And that is shares_weight and is icky. In the (near) UP case it approaches
4896 * (4) while in the normal case it approaches (3). It consistently
4897 * overestimates the ge->load.weight and therefore:
4898 *
4899 * \Sum ge->load.weight >= tg->weight
4900 *
4901 * hence icky!
4902 */
__calc_smp_shares(struct cfs_rq * cfs_rq,long tg_shares,long shares_max)4903 static long __calc_smp_shares(struct cfs_rq *cfs_rq, long tg_shares, long shares_max)
4904 {
4905 struct task_group *tg = cfs_rq->tg;
4906 long tg_weight, load, shares;
4907
4908 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
4909
4910 tg_weight = atomic_long_read(&tg->load_avg);
4911
4912 /* Ensure tg_weight >= load */
4913 tg_weight -= cfs_rq->tg_load_avg_contrib;
4914 tg_weight += load;
4915
4916 shares = (tg_shares * load);
4917 if (tg_weight)
4918 shares /= tg_weight;
4919
4920 /*
4921 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
4922 * of a group with small tg->shares value. It is a floor value which is
4923 * assigned as a minimum load.weight to the sched_entity representing
4924 * the group on a CPU.
4925 *
4926 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
4927 * on an 8-core system with 8 tasks each runnable on one CPU shares has
4928 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
4929 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
4930 * instead of 0.
4931 */
4932 return clamp_t(long, shares, MIN_SHARES, shares_max);
4933 }
4934
tg_cpus(struct task_group * tg)4935 static int tg_cpus(struct task_group *tg)
4936 {
4937 int nr = num_online_cpus();
4938
4939 if (cpusets_enabled()) {
4940 struct cgroup *cgrp = tg->css.cgroup;
4941 if (cgrp)
4942 nr = cpuset_num_cpus(cgrp);
4943 }
4944
4945 /*
4946 * An empty cpuset would propagate a 0 shares_max into
4947 * __calc_smp_shares(), where clamp() yields hi when hi < lo and so
4948 * defeats the MIN_SHARES floor. Match tg_tasks(), which floors at 1.
4949 */
4950 return max(nr, 1);
4951 }
4952
tg_tasks(struct task_group * tg)4953 static inline int tg_tasks(struct task_group *tg)
4954 {
4955 return max(1, atomic_long_read(&tg->runnable_avg) >> SCHED_CAPACITY_SHIFT);
4956 }
4957
4958 /*
4959 * Func: fraction(nr_tasks * tg->shares)
4960 *
4961 * Scale tg->shares by the number of tasks.
4962 */
calc_tasks_shares(struct cfs_rq * cfs_rq)4963 static long calc_tasks_shares(struct cfs_rq *cfs_rq)
4964 {
4965 struct task_group *tg = cfs_rq->tg;
4966 int nr = tg_tasks(tg);
4967 long tg_shares = READ_ONCE(tg->shares);
4968 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
4969 }
4970
4971 /*
4972 * Func: min(fraction(nr_cpus * tg->shares), nice -20)
4973 *
4974 * Scale tg->shares by the maximal number of CPUs; but clip the max shares at
4975 * nice -20, otherwise a single spinner on a 512 CPU machine would result in
4976 * 512*NICE_0_LOAD, which is also crazy.
4977 */
calc_max_shares(struct cfs_rq * cfs_rq)4978 static long calc_max_shares(struct cfs_rq *cfs_rq)
4979 {
4980 struct task_group *tg = cfs_rq->tg;
4981 int nr = tg_cpus(tg);
4982 long tg_shares = READ_ONCE(tg->shares);
4983 long max_shares = scale_load(sched_prio_to_weight[0]);
4984 return __calc_smp_shares(cfs_rq, tg_shares * nr, max_shares);
4985 }
4986
4987 /*
4988 * Func: fraction(nr * tg->shares); nr = min(nr_tasks, nr_cpus)
4989 *
4990 * Scales between "smp" and "max" in a natural way. No longer needs clipping
4991 * since there are no unnatural inflations like with "max".
4992 */
calc_concur_shares(struct cfs_rq * cfs_rq)4993 static long calc_concur_shares(struct cfs_rq *cfs_rq)
4994 {
4995 struct task_group *tg = cfs_rq->tg;
4996 int nr = min(tg_tasks(tg), tg_cpus(tg));
4997 long tg_shares = READ_ONCE(tg->shares);
4998 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares);
4999 }
5000
5001 /*
5002 * Func: fraction(tg->shares)
5003 *
5004 * This infamously results in tiny shares when you have many CPUs.
5005 */
calc_smp_shares(struct cfs_rq * cfs_rq)5006 static long calc_smp_shares(struct cfs_rq *cfs_rq)
5007 {
5008 struct task_group *tg = cfs_rq->tg;
5009 long tg_shares = READ_ONCE(tg->shares);
5010 return __calc_smp_shares(cfs_rq, tg_shares, tg_shares);
5011 }
5012
5013 /*
5014 * Ignore this pesky SMP stuff, use (4).
5015 */
calc_up_shares(struct cfs_rq * cfs_rq)5016 static long calc_up_shares(struct cfs_rq *cfs_rq)
5017 {
5018 struct task_group *tg = cfs_rq->tg;
5019 return READ_ONCE(tg->shares);
5020 }
5021
5022 DEFINE_STATIC_CALL(calc_group_shares, calc_concur_shares);
5023
__sched_cgroup_mode_update(int mode)5024 void __sched_cgroup_mode_update(int mode)
5025 {
5026 long (*func)(struct cfs_rq *);
5027 switch (mode) {
5028 case 0:
5029 func = &calc_up_shares;
5030 break;
5031 case 1:
5032 func = &calc_smp_shares;
5033 break;
5034 case 2:
5035 default:
5036 func = &calc_concur_shares;
5037 break;
5038 case 3:
5039 func = &calc_max_shares;
5040 break;
5041 case 4:
5042 func = &calc_tasks_shares;
5043 break;
5044 }
5045 static_call_update(calc_group_shares, func);
5046 }
5047
5048 /*
5049 * Recomputes the group entity based on the current state of its group
5050 * runqueue.
5051 */
update_cfs_group(struct sched_entity * se)5052 static void update_cfs_group(struct sched_entity *se)
5053 {
5054 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5055 long shares;
5056
5057 /*
5058 * When a group becomes empty, preserve its weight. This matters for
5059 * DELAY_DEQUEUE.
5060 */
5061 if (!gcfs_rq || !gcfs_rq->load.weight)
5062 return;
5063
5064 shares = static_call(calc_group_shares)(gcfs_rq);
5065 reweight_entity(cfs_rq_of(se), se, shares);
5066 }
5067
5068 #else /* !CONFIG_FAIR_GROUP_SCHED: */
update_cfs_group(struct sched_entity * se)5069 static inline void update_cfs_group(struct sched_entity *se)
5070 {
5071 }
5072 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5073
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)5074 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
5075 {
5076 struct rq *rq = rq_of(cfs_rq);
5077
5078 if (&rq->cfs == cfs_rq) {
5079 /*
5080 * There are a few boundary cases this might miss but it should
5081 * get called often enough that that should (hopefully) not be
5082 * a real problem.
5083 *
5084 * It will not get called when we go idle, because the idle
5085 * thread is a different class (!fair), nor will the utilization
5086 * number include things like RT tasks.
5087 *
5088 * As is, the util number is not freq-invariant (we'd have to
5089 * implement arch_scale_freq_capacity() for that).
5090 *
5091 * See cpu_util_cfs().
5092 */
5093 cpufreq_update_util(rq, flags);
5094 }
5095 }
5096
load_avg_is_decayed(struct sched_avg * sa)5097 static inline bool load_avg_is_decayed(struct sched_avg *sa)
5098 {
5099 if (sa->load_sum)
5100 return false;
5101
5102 if (sa->util_sum)
5103 return false;
5104
5105 if (sa->runnable_sum)
5106 return false;
5107
5108 /*
5109 * _avg must be null when _sum are null because _avg = _sum / divider
5110 * Make sure that rounding and/or propagation of PELT values never
5111 * break this.
5112 */
5113 WARN_ON_ONCE(sa->load_avg ||
5114 sa->util_avg ||
5115 sa->runnable_avg);
5116
5117 return true;
5118 }
5119
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)5120 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
5121 {
5122 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
5123 cfs_rq->last_update_time_copy);
5124 }
5125 #ifdef CONFIG_FAIR_GROUP_SCHED
5126 /*
5127 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
5128 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
5129 * bottom-up, we only have to test whether the cfs_rq before us on the list
5130 * is our child.
5131 * If cfs_rq is not on the list, test whether a child needs its to be added to
5132 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
5133 */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)5134 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
5135 {
5136 struct cfs_rq *prev_cfs_rq;
5137 struct list_head *prev;
5138 struct rq *rq = rq_of(cfs_rq);
5139
5140 if (cfs_rq->on_list) {
5141 prev = cfs_rq->leaf_cfs_rq_list.prev;
5142 } else {
5143 prev = rq->tmp_alone_branch;
5144 }
5145
5146 if (prev == &rq->leaf_cfs_rq_list)
5147 return false;
5148
5149 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
5150
5151 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
5152 }
5153
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)5154 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5155 {
5156 if (cfs_rq->load.weight)
5157 return false;
5158
5159 if (!load_avg_is_decayed(&cfs_rq->avg))
5160 return false;
5161
5162 if (child_cfs_rq_on_list(cfs_rq))
5163 return false;
5164
5165 if (cfs_rq->tg_load_avg_contrib)
5166 return false;
5167
5168 return true;
5169 }
5170
5171 /**
5172 * update_tg_load_avg - update the tg's load avg
5173 * @cfs_rq: the cfs_rq whose avg changed
5174 *
5175 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
5176 * However, because tg->load_avg is a global value there are performance
5177 * considerations.
5178 *
5179 * In order to avoid having to look at the other cfs_rq's, we use a
5180 * differential update where we store the last value we propagated. This in
5181 * turn allows skipping updates if the differential is 'small'.
5182 *
5183 * Updating tg's load_avg is necessary before update_cfs_group().
5184 */
update_tg_load_avg(struct cfs_rq * cfs_rq)5185 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
5186 {
5187 long dl, dr;
5188 u64 now;
5189
5190 /*
5191 * No need to update load_avg for root_task_group as it is not used.
5192 */
5193 if (cfs_rq->tg == &root_task_group)
5194 return;
5195
5196 /* rq has been offline and doesn't contribute to the share anymore: */
5197 if (!cpu_active(cpu_of(rq_of(cfs_rq))))
5198 return;
5199
5200 /*
5201 * For migration heavy workloads, access to tg->load_avg can be
5202 * unbound. Limit the update rate to at most once per ms.
5203 */
5204 now = rq_clock(rq_of(cfs_rq));
5205 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
5206 return;
5207
5208 dl = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
5209 dr = cfs_rq->avg.runnable_avg - cfs_rq->tg_runnable_avg_contrib;
5210 if (abs(dl) > cfs_rq->tg_load_avg_contrib / 64 ||
5211 abs(dr) > cfs_rq->tg_runnable_avg_contrib / 64) {
5212 atomic_long_add(dl, &cfs_rq->tg->load_avg);
5213 atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5214 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
5215 cfs_rq->tg_runnable_avg_contrib = cfs_rq->avg.runnable_avg;
5216 cfs_rq->last_update_tg_load_avg = now;
5217 }
5218 }
5219
clear_tg_load_avg(struct cfs_rq * cfs_rq)5220 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
5221 {
5222 long dl, dr;
5223 u64 now;
5224
5225 /*
5226 * No need to update load_avg for root_task_group, as it is not used.
5227 */
5228 if (cfs_rq->tg == &root_task_group)
5229 return;
5230
5231 now = rq_clock(rq_of(cfs_rq));
5232 dl = 0 - cfs_rq->tg_load_avg_contrib;
5233 dr = 0 - cfs_rq->tg_runnable_avg_contrib;
5234 atomic_long_add(dl, &cfs_rq->tg->load_avg);
5235 atomic_long_add(dr, &cfs_rq->tg->runnable_avg);
5236 cfs_rq->tg_load_avg_contrib = 0;
5237 cfs_rq->tg_runnable_avg_contrib = 0;
5238 cfs_rq->last_update_tg_load_avg = now;
5239 }
5240
5241 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)5242 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
5243 {
5244 struct task_group *tg;
5245
5246 lockdep_assert_rq_held(rq);
5247
5248 /*
5249 * The rq clock has already been updated in
5250 * set_rq_offline(), so we should skip updating
5251 * the rq clock again in unthrottle_cfs_rq().
5252 */
5253 rq_clock_start_loop_update(rq);
5254
5255 guard(rcu)();
5256
5257 list_for_each_entry_rcu(tg, &task_groups, list) {
5258 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
5259
5260 clear_tg_load_avg(cfs_rq);
5261 }
5262
5263 rq_clock_stop_loop_update(rq);
5264 }
5265
5266 /*
5267 * Called within set_task_rq() right before setting a task's CPU. The
5268 * caller only guarantees p->pi_lock is held; no other assumptions,
5269 * including the state of rq->lock, should be made.
5270 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)5271 void set_task_rq_fair(struct sched_entity *se,
5272 struct cfs_rq *prev, struct cfs_rq *next)
5273 {
5274 u64 p_last_update_time;
5275 u64 n_last_update_time;
5276
5277 if (!sched_feat(ATTACH_AGE_LOAD))
5278 return;
5279
5280 /*
5281 * We are supposed to update the task to "current" time, then its up to
5282 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
5283 * getting what current time is, so simply throw away the out-of-date
5284 * time. This will result in the wakee task is less decayed, but giving
5285 * the wakee more load sounds not bad.
5286 */
5287 if (!(se->avg.last_update_time && prev))
5288 return;
5289
5290 p_last_update_time = cfs_rq_last_update_time(prev);
5291 n_last_update_time = cfs_rq_last_update_time(next);
5292
5293 __update_load_avg_blocked_se(p_last_update_time, se);
5294 se->avg.last_update_time = n_last_update_time;
5295 }
5296
5297 /*
5298 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
5299 * propagate its contribution. The key to this propagation is the invariant
5300 * that for each group:
5301 *
5302 * ge->avg == grq->avg (1)
5303 *
5304 * _IFF_ we look at the pure running and runnable sums. Because they
5305 * represent the very same entity, just at different points in the hierarchy.
5306 *
5307 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
5308 * and simply copies the running/runnable sum over (but still wrong, because
5309 * the group entity and group rq do not have their PELT windows aligned).
5310 *
5311 * However, update_tg_cfs_load() is more complex. So we have:
5312 *
5313 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
5314 *
5315 * And since, like util, the runnable part should be directly transferable,
5316 * the following would _appear_ to be the straight forward approach:
5317 *
5318 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
5319 *
5320 * And per (1) we have:
5321 *
5322 * ge->avg.runnable_avg == grq->avg.runnable_avg
5323 *
5324 * Which gives:
5325 *
5326 * ge->load.weight * grq->avg.load_avg
5327 * ge->avg.load_avg = ----------------------------------- (4)
5328 * grq->load.weight
5329 *
5330 * Except that is wrong!
5331 *
5332 * Because while for entities historical weight is not important and we
5333 * really only care about our future and therefore can consider a pure
5334 * runnable sum, runqueues can NOT do this.
5335 *
5336 * We specifically want runqueues to have a load_avg that includes
5337 * historical weights. Those represent the blocked load, the load we expect
5338 * to (shortly) return to us. This only works by keeping the weights as
5339 * integral part of the sum. We therefore cannot decompose as per (3).
5340 *
5341 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
5342 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
5343 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
5344 * runnable section of these tasks overlap (or not). If they were to perfectly
5345 * align the rq as a whole would be runnable 2/3 of the time. If however we
5346 * always have at least 1 runnable task, the rq as a whole is always runnable.
5347 *
5348 * So we'll have to approximate.. :/
5349 *
5350 * Given the constraint:
5351 *
5352 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
5353 *
5354 * We can construct a rule that adds runnable to a rq by assuming minimal
5355 * overlap.
5356 *
5357 * On removal, we'll assume each task is equally runnable; which yields:
5358 *
5359 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
5360 *
5361 * XXX: only do this for the part of runnable > running ?
5362 *
5363 */
5364 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)5365 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5366 {
5367 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
5368 u32 new_sum, divider;
5369
5370 /* Nothing to update */
5371 if (!delta_avg)
5372 return;
5373
5374 /*
5375 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5376 * See ___update_load_avg() for details.
5377 */
5378 divider = get_pelt_divider(&cfs_rq->avg);
5379
5380 /* Set new sched_entity's utilization */
5381 se->avg.util_avg = gcfs_rq->avg.util_avg;
5382 new_sum = se->avg.util_avg * divider;
5383 delta_sum = (long)new_sum - (long)se->avg.util_sum;
5384 se->avg.util_sum = new_sum;
5385
5386 /* Update parent cfs_rq utilization */
5387 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum);
5388 }
5389
5390 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)5391 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5392 {
5393 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
5394 u64 new_sum;
5395 u32 divider;
5396
5397 /* Nothing to update */
5398 if (!delta_avg)
5399 return;
5400
5401 /*
5402 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5403 * See ___update_load_avg() for details.
5404 */
5405 divider = get_pelt_divider(&cfs_rq->avg);
5406
5407 /* Set new sched_entity's runnable */
5408 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
5409 new_sum = (u64)se->avg.runnable_avg * divider;
5410 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
5411 se->avg.runnable_sum = new_sum;
5412
5413 /* Update parent cfs_rq runnable */
5414 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum);
5415 }
5416
5417 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)5418 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
5419 {
5420 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
5421 unsigned long load_avg;
5422 u64 load_sum = 0;
5423 s64 delta_sum;
5424 u32 divider;
5425
5426 if (!runnable_sum)
5427 return;
5428
5429 gcfs_rq->prop_runnable_sum = 0;
5430
5431 /*
5432 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5433 * See ___update_load_avg() for details.
5434 */
5435 divider = get_pelt_divider(&cfs_rq->avg);
5436
5437 if (runnable_sum >= 0) {
5438 /*
5439 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
5440 * the CPU is saturated running == runnable.
5441 */
5442 runnable_sum += se->avg.load_sum;
5443 runnable_sum = min_t(long, runnable_sum, divider);
5444 } else {
5445 /*
5446 * Estimate the new unweighted runnable_sum of the gcfs_rq by
5447 * assuming all tasks are equally runnable.
5448 */
5449 if (scale_load_down(gcfs_rq->load.weight)) {
5450 load_sum = div_u64(gcfs_rq->avg.load_sum,
5451 scale_load_down(gcfs_rq->load.weight));
5452 }
5453
5454 /* But make sure to not inflate se's runnable */
5455 runnable_sum = min(se->avg.load_sum, load_sum);
5456 }
5457
5458 /*
5459 * runnable_sum can't be lower than running_sum
5460 * Rescale running sum to be in the same range as runnable sum
5461 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
5462 * runnable_sum is in [0 : LOAD_AVG_MAX]
5463 */
5464 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
5465 runnable_sum = max(runnable_sum, running_sum);
5466
5467 load_sum = se_weight(se) * runnable_sum;
5468 load_avg = div_u64(load_sum, divider);
5469
5470 delta_avg = load_avg - se->avg.load_avg;
5471 if (!delta_avg)
5472 return;
5473
5474 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
5475
5476 se->avg.load_sum = runnable_sum;
5477 se->avg.load_avg = load_avg;
5478 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum);
5479 }
5480
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)5481 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
5482 {
5483 cfs_rq->propagate = 1;
5484 cfs_rq->prop_runnable_sum += runnable_sum;
5485 }
5486
5487 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)5488 static inline int propagate_entity_load_avg(struct sched_entity *se)
5489 {
5490 struct cfs_rq *cfs_rq, *gcfs_rq;
5491
5492 if (entity_is_task(se))
5493 return 0;
5494
5495 gcfs_rq = group_cfs_rq(se);
5496 if (!gcfs_rq->propagate)
5497 return 0;
5498
5499 gcfs_rq->propagate = 0;
5500
5501 cfs_rq = cfs_rq_of(se);
5502
5503 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
5504
5505 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
5506 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
5507 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
5508
5509 trace_pelt_cfs_tp(cfs_rq);
5510 trace_pelt_se_tp(se);
5511
5512 return 1;
5513 }
5514
5515 /*
5516 * Check if we need to update the load and the utilization of a blocked
5517 * group_entity:
5518 */
skip_blocked_update(struct sched_entity * se)5519 static inline bool skip_blocked_update(struct sched_entity *se)
5520 {
5521 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
5522
5523 /*
5524 * If sched_entity still have not zero load or utilization, we have to
5525 * decay it:
5526 */
5527 if (se->avg.load_avg || se->avg.util_avg)
5528 return false;
5529
5530 /*
5531 * If there is a pending propagation, we have to update the load and
5532 * the utilization of the sched_entity:
5533 */
5534 if (gcfs_rq->propagate)
5535 return false;
5536
5537 /*
5538 * Otherwise, the load and the utilization of the sched_entity is
5539 * already zero and there is no pending propagation, so it will be a
5540 * waste of time to try to decay it:
5541 */
5542 return true;
5543 }
5544
5545 #else /* !CONFIG_FAIR_GROUP_SCHED: */
5546
update_tg_load_avg(struct cfs_rq * cfs_rq)5547 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
5548
clear_tg_offline_cfs_rqs(struct rq * rq)5549 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
5550
propagate_entity_load_avg(struct sched_entity * se)5551 static inline int propagate_entity_load_avg(struct sched_entity *se)
5552 {
5553 return 0;
5554 }
5555
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)5556 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
5557
5558 #endif /* !CONFIG_FAIR_GROUP_SCHED */
5559
5560 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)5561 static inline void migrate_se_pelt_lag(struct sched_entity *se)
5562 {
5563 u64 throttled = 0, now, lut;
5564 struct cfs_rq *cfs_rq;
5565 struct rq *rq;
5566 bool is_idle;
5567
5568 if (load_avg_is_decayed(&se->avg))
5569 return;
5570
5571 cfs_rq = cfs_rq_of(se);
5572 rq = rq_of(cfs_rq);
5573
5574 rcu_read_lock();
5575 is_idle = is_idle_task(rcu_dereference_all(rq->curr));
5576 rcu_read_unlock();
5577
5578 /*
5579 * The lag estimation comes with a cost we don't want to pay all the
5580 * time. Hence, limiting to the case where the source CPU is idle and
5581 * we know we are at the greatest risk to have an outdated clock.
5582 */
5583 if (!is_idle)
5584 return;
5585
5586 /*
5587 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
5588 *
5589 * last_update_time (the cfs_rq's last_update_time)
5590 * = cfs_rq_clock_pelt()@cfs_rq_idle
5591 * = rq_clock_pelt()@cfs_rq_idle
5592 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
5593 *
5594 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
5595 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
5596 *
5597 * rq_idle_lag (delta between now and rq's update)
5598 * = sched_clock_cpu() - rq_clock()@rq_idle
5599 *
5600 * We can then write:
5601 *
5602 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
5603 * sched_clock_cpu() - rq_clock()@rq_idle
5604 * Where:
5605 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
5606 * rq_clock()@rq_idle is rq->clock_idle
5607 * cfs->throttled_clock_pelt_time@cfs_rq_idle
5608 * is cfs_rq->throttled_pelt_idle
5609 */
5610
5611 #ifdef CONFIG_CFS_BANDWIDTH
5612 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
5613 /* The clock has been stopped for throttling */
5614 if (throttled == U64_MAX)
5615 return;
5616 #endif
5617 now = u64_u32_load(rq->clock_pelt_idle);
5618 /*
5619 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
5620 * is observed the old clock_pelt_idle value and the new clock_idle,
5621 * which lead to an underestimation. The opposite would lead to an
5622 * overestimation.
5623 */
5624 smp_rmb();
5625 lut = cfs_rq_last_update_time(cfs_rq);
5626
5627 now -= throttled;
5628 if (now < lut)
5629 /*
5630 * cfs_rq->avg.last_update_time is more recent than our
5631 * estimation, let's use it.
5632 */
5633 now = lut;
5634 else
5635 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
5636
5637 __update_load_avg_blocked_se(now, se);
5638 }
5639 #else /* !CONFIG_NO_HZ_COMMON: */
migrate_se_pelt_lag(struct sched_entity * se)5640 static void migrate_se_pelt_lag(struct sched_entity *se) {}
5641 #endif /* !CONFIG_NO_HZ_COMMON */
5642
5643 /**
5644 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
5645 * @now: current time, as per cfs_rq_clock_pelt()
5646 * @cfs_rq: cfs_rq to update
5647 *
5648 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
5649 * avg. The immediate corollary is that all (fair) tasks must be attached.
5650 *
5651 * cfs_rq->avg is used for task_h_load() and update_cfs_group() for example.
5652 *
5653 * Return: true if the load decayed or we removed load.
5654 *
5655 * Since both these conditions indicate a changed cfs_rq->avg.load we should
5656 * call update_tg_load_avg() when this function returns true.
5657 */
5658 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)5659 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
5660 {
5661 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
5662 struct sched_avg *sa = &cfs_rq->avg;
5663 int decayed = 0;
5664
5665 if (cfs_rq->removed.nr) {
5666 unsigned long r;
5667 u32 divider = get_pelt_divider(&cfs_rq->avg);
5668
5669 raw_spin_lock(&cfs_rq->removed.lock);
5670 swap(cfs_rq->removed.util_avg, removed_util);
5671 swap(cfs_rq->removed.load_avg, removed_load);
5672 swap(cfs_rq->removed.runnable_avg, removed_runnable);
5673 cfs_rq->removed.nr = 0;
5674 raw_spin_unlock(&cfs_rq->removed.lock);
5675
5676 r = removed_load;
5677 __update_sa(sa, load, -r, -r*divider);
5678
5679 r = removed_util;
5680 __update_sa(sa, util, -r, -r*divider);
5681
5682 r = removed_runnable;
5683 __update_sa(sa, runnable, -r, -r*divider);
5684
5685 /*
5686 * removed_runnable is the unweighted version of removed_load so we
5687 * can use it to estimate removed_load_sum.
5688 */
5689 add_tg_cfs_propagate(cfs_rq,
5690 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
5691
5692 decayed = 1;
5693 }
5694
5695 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
5696 u64_u32_store_copy(sa->last_update_time,
5697 cfs_rq->last_update_time_copy,
5698 sa->last_update_time);
5699 return decayed;
5700 }
5701
5702 /**
5703 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
5704 * @cfs_rq: cfs_rq to attach to
5705 * @se: sched_entity to attach
5706 *
5707 * Must call update_cfs_rq_load_avg() before this, since we rely on
5708 * cfs_rq->avg.last_update_time being current.
5709 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5710 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5711 {
5712 /*
5713 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
5714 * See ___update_load_avg() for details.
5715 */
5716 u32 divider = get_pelt_divider(&cfs_rq->avg);
5717
5718 /*
5719 * When we attach the @se to the @cfs_rq, we must align the decay
5720 * window because without that, really weird and wonderful things can
5721 * happen.
5722 *
5723 * XXX illustrate
5724 */
5725 se->avg.last_update_time = cfs_rq->avg.last_update_time;
5726 se->avg.period_contrib = cfs_rq->avg.period_contrib;
5727
5728 /*
5729 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
5730 * period_contrib. This isn't strictly correct, but since we're
5731 * entirely outside of the PELT hierarchy, nobody cares if we truncate
5732 * _sum a little.
5733 */
5734 se->avg.util_sum = se->avg.util_avg * divider;
5735
5736 se->avg.runnable_sum = se->avg.runnable_avg * divider;
5737
5738 se->avg.load_sum = se->avg.load_avg * divider;
5739 if (se_weight(se) < se->avg.load_sum)
5740 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
5741 else
5742 se->avg.load_sum = 1;
5743
5744 enqueue_load_avg(cfs_rq, se);
5745 cfs_rq->avg.util_avg += se->avg.util_avg;
5746 cfs_rq->avg.util_sum += se->avg.util_sum;
5747 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
5748 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
5749
5750 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
5751
5752 cfs_rq_util_change(cfs_rq, 0);
5753
5754 trace_pelt_cfs_tp(cfs_rq);
5755 }
5756
5757 /**
5758 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
5759 * @cfs_rq: cfs_rq to detach from
5760 * @se: sched_entity to detach
5761 *
5762 * Must call update_cfs_rq_load_avg() before this, since we rely on
5763 * cfs_rq->avg.last_update_time being current.
5764 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5765 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
5766 {
5767 dequeue_load_avg(cfs_rq, se);
5768 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum);
5769 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum);
5770
5771 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
5772
5773 cfs_rq_util_change(cfs_rq, 0);
5774
5775 trace_pelt_cfs_tp(cfs_rq);
5776 }
5777
5778 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
5779
util_est_update(struct sched_entity * se)5780 static inline void util_est_update(struct sched_entity *se)
5781 {
5782 unsigned int ewma, dequeued, last_ewma_diff;
5783
5784 if (!sched_feat(UTIL_EST))
5785 return;
5786
5787 /* Get current estimate of utilization */
5788 ewma = READ_ONCE(se->avg.util_est);
5789
5790 /*
5791 * If the PELT values haven't changed since enqueue time,
5792 * skip the util_est update.
5793 */
5794 if (ewma & UTIL_AVG_UNCHANGED)
5795 return;
5796
5797 /* Get utilization at dequeue */
5798 dequeued = READ_ONCE(se->avg.util_avg);
5799
5800 /*
5801 * Reset EWMA on utilization increases, the moving average is used only
5802 * to smooth utilization decreases.
5803 */
5804 if (ewma <= dequeued) {
5805 ewma = dequeued;
5806 goto done;
5807 }
5808
5809 /*
5810 * Skip update of task's estimated utilization when its members are
5811 * already ~1% close to its last activation value.
5812 */
5813 last_ewma_diff = ewma - dequeued;
5814 if (last_ewma_diff < UTIL_EST_MARGIN)
5815 goto done;
5816
5817 /*
5818 * To avoid underestimate of task utilization, skip updates of EWMA if
5819 * we cannot grant that thread got all CPU time it wanted.
5820 */
5821 if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg))
5822 goto done;
5823
5824 /*
5825 * Update Task's estimated utilization
5826 *
5827 * When *p completes an activation we can consolidate another sample
5828 * of the task size. This is done by using this value to update the
5829 * Exponential Weighted Moving Average (EWMA):
5830 *
5831 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
5832 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
5833 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
5834 * = w * ( -last_ewma_diff ) + ewma(t-1)
5835 * = w * (-last_ewma_diff + ewma(t-1) / w)
5836 *
5837 * Where 'w' is the weight of new samples, which is configured to be
5838 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5839 */
5840 ewma <<= UTIL_EST_WEIGHT_SHIFT;
5841 ewma -= last_ewma_diff;
5842 ewma >>= UTIL_EST_WEIGHT_SHIFT;
5843 done:
5844 ewma |= UTIL_AVG_UNCHANGED;
5845 WRITE_ONCE(se->avg.util_est, ewma);
5846
5847 trace_sched_util_est_se_tp(se);
5848 }
5849
5850 /*
5851 * Optional action to be done while updating the load average
5852 */
5853 #define UPDATE_TG 0x01
5854 #define SKIP_AGE_LOAD 0x02
5855 #define DO_ATTACH 0x04
5856 #define DO_DETACH 0x08
5857 #define UPDATE_UTIL_EST 0x10
5858
5859 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5860 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5861 {
5862 u64 now = cfs_rq_clock_pelt(cfs_rq);
5863 int decayed;
5864
5865 /*
5866 * Track task load average for carrying it to new CPU after migrated, and
5867 * track group sched_entity load average for task_h_load calculation in migration
5868 */
5869 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
5870 __update_load_avg_se(now, cfs_rq, se);
5871
5872 decayed = update_cfs_rq_load_avg(now, cfs_rq);
5873 decayed |= propagate_entity_load_avg(se);
5874
5875 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
5876
5877 /*
5878 * DO_ATTACH means we're here from enqueue_entity().
5879 * !last_update_time means we've passed through
5880 * migrate_task_rq_fair() indicating we migrated.
5881 *
5882 * IOW we're enqueueing a task on a new CPU.
5883 */
5884 attach_entity_load_avg(cfs_rq, se);
5885 update_tg_load_avg(cfs_rq);
5886
5887 } else if (flags & DO_DETACH) {
5888 /*
5889 * DO_DETACH means we're here from dequeue_entity()
5890 * and we are migrating task out of the CPU.
5891 */
5892 detach_entity_load_avg(cfs_rq, se);
5893 update_tg_load_avg(cfs_rq);
5894 } else if (decayed) {
5895 cfs_rq_util_change(cfs_rq, 0);
5896
5897 if (flags & UPDATE_TG)
5898 update_tg_load_avg(cfs_rq);
5899 }
5900
5901 if (flags & UPDATE_UTIL_EST)
5902 util_est_update(se);
5903 }
5904
5905 /*
5906 * Synchronize entity load avg of dequeued entity without locking
5907 * the previous rq.
5908 */
sync_entity_load_avg(struct sched_entity * se)5909 static void sync_entity_load_avg(struct sched_entity *se)
5910 {
5911 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5912 u64 last_update_time;
5913
5914 last_update_time = cfs_rq_last_update_time(cfs_rq);
5915 __update_load_avg_blocked_se(last_update_time, se);
5916 }
5917
5918 /*
5919 * Task first catches up with cfs_rq, and then subtract
5920 * itself from the cfs_rq (task must be off the queue now).
5921 */
remove_entity_load_avg(struct sched_entity * se)5922 static void remove_entity_load_avg(struct sched_entity *se)
5923 {
5924 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5925 unsigned long flags;
5926
5927 /*
5928 * tasks cannot exit without having gone through wake_up_new_task() ->
5929 * enqueue_task_fair() which will have added things to the cfs_rq,
5930 * so we can remove unconditionally.
5931 */
5932
5933 sync_entity_load_avg(se);
5934
5935 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
5936 ++cfs_rq->removed.nr;
5937 cfs_rq->removed.util_avg += se->avg.util_avg;
5938 cfs_rq->removed.load_avg += se->avg.load_avg;
5939 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
5940 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
5941 }
5942
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)5943 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
5944 {
5945 return cfs_rq->avg.runnable_avg;
5946 }
5947
cfs_rq_load_avg(struct cfs_rq * cfs_rq)5948 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
5949 {
5950 return cfs_rq->avg.load_avg;
5951 }
5952
5953 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
5954 __must_hold(__rq_lockp(this_rq));
5955
task_util(struct task_struct * p)5956 static inline unsigned long task_util(struct task_struct *p)
5957 {
5958 return READ_ONCE(p->se.avg.util_avg);
5959 }
5960
_task_util_est(struct task_struct * p)5961 static inline unsigned long _task_util_est(struct task_struct *p)
5962 {
5963 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
5964 }
5965
task_util_est(struct task_struct * p)5966 static inline unsigned long task_util_est(struct task_struct *p)
5967 {
5968 return max(task_util(p), _task_util_est(p));
5969 }
5970
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5971 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
5972 struct task_struct *p)
5973 {
5974 unsigned int enqueued;
5975
5976 if (!sched_feat(UTIL_EST))
5977 return;
5978
5979 /* Update root cfs_rq's estimated utilization */
5980 enqueued = cfs_rq->avg.util_est;
5981 enqueued += _task_util_est(p);
5982 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5983
5984 trace_sched_util_est_cfs_tp(cfs_rq);
5985 }
5986
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5987 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
5988 struct task_struct *p)
5989 {
5990 unsigned int enqueued;
5991
5992 if (!sched_feat(UTIL_EST))
5993 return;
5994
5995 /* Update root cfs_rq's estimated utilization */
5996 enqueued = cfs_rq->avg.util_est;
5997 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
5998 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5999
6000 trace_sched_util_est_cfs_tp(cfs_rq);
6001 }
6002
get_actual_cpu_capacity(int cpu)6003 static inline unsigned long get_actual_cpu_capacity(int cpu)
6004 {
6005 unsigned long capacity = arch_scale_cpu_capacity(cpu);
6006
6007 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
6008
6009 return capacity;
6010 }
6011
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)6012 static inline int util_fits_cpu(unsigned long util,
6013 unsigned long uclamp_min,
6014 unsigned long uclamp_max,
6015 int cpu)
6016 {
6017 unsigned long capacity = capacity_of(cpu);
6018 unsigned long capacity_orig;
6019 bool fits, uclamp_max_fits;
6020
6021 /*
6022 * Check if the real util fits without any uclamp boost/cap applied.
6023 */
6024 fits = fits_capacity(util, capacity);
6025
6026 if (!uclamp_is_used())
6027 return fits;
6028
6029 /*
6030 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
6031 * uclamp_max. We only care about capacity pressure (by using
6032 * capacity_of()) for comparing against the real util.
6033 *
6034 * If a task is boosted to 1024 for example, we don't want a tiny
6035 * pressure to skew the check whether it fits a CPU or not.
6036 *
6037 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
6038 * should fit a little cpu even if there's some pressure.
6039 *
6040 * Only exception is for HW or cpufreq pressure since it has a direct impact
6041 * on available OPP of the system.
6042 *
6043 * We honour it for uclamp_min only as a drop in performance level
6044 * could result in not getting the requested minimum performance level.
6045 *
6046 * For uclamp_max, we can tolerate a drop in performance level as the
6047 * goal is to cap the task. So it's okay if it's getting less.
6048 */
6049 capacity_orig = arch_scale_cpu_capacity(cpu);
6050
6051 /*
6052 * We want to force a task to fit a cpu as implied by uclamp_max.
6053 * But we do have some corner cases to cater for..
6054 *
6055 *
6056 * C=z
6057 * | ___
6058 * | C=y | |
6059 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
6060 * | C=x | | | |
6061 * | ___ | | | |
6062 * | | | | | | | (util somewhere in this region)
6063 * | | | | | | |
6064 * | | | | | | |
6065 * +----------------------------------------
6066 * CPU0 CPU1 CPU2
6067 *
6068 * In the above example if a task is capped to a specific performance
6069 * point, y, then when:
6070 *
6071 * * util = 80% of x then it does not fit on CPU0 and should migrate
6072 * to CPU1
6073 * * util = 80% of y then it is forced to fit on CPU1 to honour
6074 * uclamp_max request.
6075 *
6076 * which is what we're enforcing here. A task always fits if
6077 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
6078 * the normal upmigration rules should withhold still.
6079 *
6080 * Only exception is when we are on max capacity, then we need to be
6081 * careful not to block overutilized state. This is so because:
6082 *
6083 * 1. There's no concept of capping at max_capacity! We can't go
6084 * beyond this performance level anyway.
6085 * 2. The system is being saturated when we're operating near
6086 * max capacity, it doesn't make sense to block overutilized.
6087 */
6088 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
6089 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
6090 fits = fits || uclamp_max_fits;
6091
6092 /*
6093 *
6094 * C=z
6095 * | ___ (region a, capped, util >= uclamp_max)
6096 * | C=y | |
6097 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
6098 * | C=x | | | |
6099 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
6100 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
6101 * | | | | | | |
6102 * | | | | | | | (region c, boosted, util < uclamp_min)
6103 * +----------------------------------------
6104 * CPU0 CPU1 CPU2
6105 *
6106 * a) If util > uclamp_max, then we're capped, we don't care about
6107 * actual fitness value here. We only care if uclamp_max fits
6108 * capacity without taking margin/pressure into account.
6109 * See comment above.
6110 *
6111 * b) If uclamp_min <= util <= uclamp_max, then the normal
6112 * fits_capacity() rules apply. Except we need to ensure that we
6113 * enforce we remain within uclamp_max, see comment above.
6114 *
6115 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
6116 * need to take into account the boosted value fits the CPU without
6117 * taking margin/pressure into account.
6118 *
6119 * Cases (a) and (b) are handled in the 'fits' variable already. We
6120 * just need to consider an extra check for case (c) after ensuring we
6121 * handle the case uclamp_min > uclamp_max.
6122 */
6123 uclamp_min = min(uclamp_min, uclamp_max);
6124 if (fits && (util < uclamp_min) &&
6125 (uclamp_min > get_actual_cpu_capacity(cpu)))
6126 return -1;
6127
6128 return fits;
6129 }
6130
task_fits_cpu(struct task_struct * p,int cpu)6131 static inline int task_fits_cpu(struct task_struct *p, int cpu)
6132 {
6133 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
6134 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
6135 unsigned long util = task_util_est(p);
6136 /*
6137 * Return true only if the cpu fully fits the task requirements, which
6138 * include the utilization but also the performance hints.
6139 */
6140 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
6141 }
6142
update_misfit_status(struct task_struct * p,struct rq * rq)6143 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
6144 {
6145 int cpu = cpu_of(rq);
6146
6147 if (!sched_asym_cpucap_active())
6148 return;
6149
6150 /*
6151 * Affinity allows us to go somewhere higher? Or are we on biggest
6152 * available CPU already? Or do we fit into this CPU ?
6153 */
6154 if (!p || (p->nr_cpus_allowed == 1) ||
6155 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
6156 task_fits_cpu(p, cpu)) {
6157
6158 rq->misfit_task_load = 0;
6159 return;
6160 }
6161
6162 /*
6163 * Make sure that misfit_task_load will not be null even if
6164 * task_h_load() returns 0.
6165 */
6166 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
6167 }
6168
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)6169 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
6170 {
6171 struct sched_entity *se = &p->se;
6172
6173 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
6174 if (attr->sched_runtime) {
6175 se->custom_slice = 1;
6176 se->slice = clamp_t(u64, attr->sched_runtime,
6177 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */
6178 NSEC_PER_MSEC*100); /* HZ=100 / 10 */
6179 } else {
6180 se->custom_slice = 0;
6181 se->slice = sysctl_sched_base_slice;
6182 }
6183 }
6184
6185 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)6186 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6187 {
6188 u64 vslice, vruntime = avg_vruntime(cfs_rq);
6189 unsigned int nr_queued = cfs_rq->h_nr_queued;
6190 bool update_zero = false;
6191 s64 lag = 0;
6192
6193 if (!se->custom_slice)
6194 se->slice = sysctl_sched_base_slice;
6195 vslice = calc_delta_fair(se->slice, se);
6196
6197 if (flags & ENQUEUE_QUEUED)
6198 nr_queued -= 1;
6199
6200 /*
6201 * Due to how V is constructed as the weighted average of entities,
6202 * adding tasks with positive lag, or removing tasks with negative lag
6203 * will move 'time' backwards, this can screw around with the lag of
6204 * other tasks.
6205 *
6206 * EEVDF: placement strategy #1 / #2
6207 */
6208 if (sched_feat(PLACE_LAG) && nr_queued && se->vlag) {
6209 struct sched_entity *curr = cfs_rq->curr;
6210 long load, weight;
6211
6212 lag = se->vlag;
6213
6214 /*
6215 * If we want to place a task and preserve lag, we have to
6216 * consider the effect of the new entity on the weighted
6217 * average and compensate for this, otherwise lag can quickly
6218 * evaporate.
6219 *
6220 * Lag is defined as:
6221 *
6222 * lag_i = S - s_i = w_i * (V - v_i)
6223 *
6224 * To avoid the 'w_i' term all over the place, we only track
6225 * the virtual lag:
6226 *
6227 * vl_i = V - v_i <=> v_i = V - vl_i
6228 *
6229 * And we take V to be the weighted average of all v:
6230 *
6231 * V = (\Sum w_j*v_j) / W
6232 *
6233 * Where W is: \Sum w_j
6234 *
6235 * Then, the weighted average after adding an entity with lag
6236 * vl_i is given by:
6237 *
6238 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
6239 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
6240 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
6241 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
6242 * = V - w_i*vl_i / (W + w_i)
6243 *
6244 * And the actual lag after adding an entity with vl_i is:
6245 *
6246 * vl'_i = V' - v_i
6247 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
6248 * = vl_i - w_i*vl_i / (W + w_i)
6249 *
6250 * Which is strictly less than vl_i. So in order to preserve lag
6251 * we should inflate the lag before placement such that the
6252 * effective lag after placement comes out right.
6253 *
6254 * As such, invert the above relation for vl'_i to get the vl_i
6255 * we need to use such that the lag after placement is the lag
6256 * we computed before dequeue.
6257 *
6258 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
6259 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
6260 *
6261 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
6262 * = W*vl_i
6263 *
6264 * vl_i = (W + w_i)*vl'_i / W
6265 */
6266 load = cfs_rq->sum_weight;
6267 if (curr && curr->on_rq)
6268 load += avg_vruntime_weight(cfs_rq, curr->h_load.weight);
6269
6270 weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
6271 lag *= load + weight;
6272 if (WARN_ON_ONCE(!load))
6273 load = 1;
6274 lag = div64_long(lag, load);
6275
6276 /*
6277 * A heavy entity (relative to the tree) will pull the
6278 * avg_vruntime close to its vruntime position on enqueue. But
6279 * the zero_vruntime point is only updated at the next
6280 * update_deadline()/place_entity()/update_entity_lag().
6281 *
6282 * Specifically (see the comment near avg_vruntime_weight()):
6283 *
6284 * sum_w_vruntime = \Sum (v_i - v0) * w_i
6285 *
6286 * Note that if v0 is near a light entity, both terms will be
6287 * small for the light entity, while in that case both terms
6288 * are large for the heavy entity, leading to risk of
6289 * overflow.
6290 *
6291 * OTOH if v0 is near the heavy entity, then the difference is
6292 * larger for the light entity, but the factor is small, while
6293 * for the heavy entity the difference is small but the factor
6294 * is large. Avoiding the multiplication overflow.
6295 */
6296 if (weight > load)
6297 update_zero = true;
6298 }
6299
6300 se->vruntime = vruntime - lag;
6301
6302 if (update_zero)
6303 update_zero_vruntime(cfs_rq, -lag);
6304
6305 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
6306 se->deadline += se->vruntime;
6307 se->rel_deadline = 0;
6308 return;
6309 }
6310
6311 /*
6312 * When joining the competition; the existing tasks will be,
6313 * on average, halfway through their slice, as such start tasks
6314 * off with half a slice to ease into the competition.
6315 */
6316 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
6317 vslice /= 2;
6318
6319 /*
6320 * EEVDF: vd_i = ve_i + r_i/w_i
6321 */
6322 se->deadline = se->vruntime + vslice;
6323 }
6324
6325 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
6326 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
6327
6328 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)6329 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6330 {
6331 /*
6332 * When enqueuing a sched_entity, we must:
6333 * - Update loads to have both entity and cfs_rq synced with now.
6334 * - For group_entity, update its runnable_weight to reflect the new
6335 * h_nr_runnable of its group cfs_rq.
6336 * - For group_entity, update its weight to reflect the new share of
6337 * its group cfs_rq
6338 * - Add its new weight to cfs_rq->load.weight
6339 */
6340 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
6341 se_update_runnable(se);
6342 /*
6343 * XXX update_load_avg() above will have attached us to the pelt sum;
6344 * but update_cfs_group() here will re-adjust the weight and have to
6345 * undo/redo all that. Seems wasteful.
6346 */
6347 update_cfs_group(se);
6348
6349 account_entity_enqueue(cfs_rq, se);
6350
6351 /* Entity has migrated, no longer consider this task hot */
6352 if (flags & ENQUEUE_MIGRATED)
6353 se->exec_start = 0;
6354
6355 check_schedstat_required();
6356 update_stats_enqueue_fair(cfs_rq, se, flags);
6357 se->on_rq = 1;
6358
6359 if (cfs_rq->nr_queued == 1) {
6360 check_enqueue_throttle(cfs_rq);
6361 list_add_leaf_cfs_rq(cfs_rq);
6362 #ifdef CONFIG_CFS_BANDWIDTH
6363 if (cfs_rq->pelt_clock_throttled) {
6364 struct rq *rq = rq_of(cfs_rq);
6365
6366 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6367 cfs_rq->throttled_clock_pelt;
6368 cfs_rq->pelt_clock_throttled = 0;
6369 }
6370 #endif
6371 }
6372 }
6373
set_next_buddy(struct cfs_rq * cfs_rq,struct sched_entity * se)6374 static void set_next_buddy(struct cfs_rq *cfs_rq, struct sched_entity *se)
6375 {
6376 if (WARN_ON_ONCE(!se->on_rq || se->sched_delayed))
6377 return;
6378 if (se_is_idle(se))
6379 return;
6380 cfs_rq->next = se;
6381 }
6382
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)6383 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
6384 {
6385 if (cfs_rq->next == se)
6386 cfs_rq->next = NULL;
6387 }
6388
6389 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
6390
set_delayed(struct sched_entity * se)6391 static void set_delayed(struct sched_entity *se)
6392 {
6393 se->sched_delayed = 1;
6394
6395 /*
6396 * Delayed se of cfs_rq have no tasks queued on them.
6397 * Do not adjust h_nr_runnable since __dequeue_task()
6398 * will account it for blocked tasks.
6399 */
6400 if (!entity_is_task(se))
6401 return;
6402
6403 for_each_sched_entity(se) {
6404 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6405
6406 cfs_rq->h_nr_runnable--;
6407 }
6408 }
6409
clear_delayed(struct sched_entity * se)6410 static void clear_delayed(struct sched_entity *se)
6411 {
6412 se->sched_delayed = 0;
6413
6414 /*
6415 * Delayed se of cfs_rq have no tasks queued on them.
6416 * Do not adjust h_nr_runnable since a dequeue has
6417 * already accounted for it or an enqueue of a task
6418 * below it will account for it in enqueue_task_fair().
6419 */
6420 if (!entity_is_task(se))
6421 return;
6422
6423 for_each_sched_entity(se) {
6424 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6425
6426 cfs_rq->h_nr_runnable++;
6427 }
6428 }
6429
6430 static void
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)6431 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6432 {
6433 int action = UPDATE_TG;
6434
6435 if (entity_is_task(se)) {
6436 if (task_on_rq_migrating(task_of(se)))
6437 action |= DO_DETACH;
6438
6439 if ((flags & DEQUEUE_SLEEP) && !(flags & DEQUEUE_DELAYED))
6440 action |= UPDATE_UTIL_EST;
6441 }
6442
6443 /*
6444 * When dequeuing a sched_entity, we must:
6445 * - Update loads to have both entity and cfs_rq synced with now.
6446 * - For group_entity, update its runnable_weight to reflect the new
6447 * h_nr_runnable of its group cfs_rq.
6448 * - Subtract its previous weight from cfs_rq->load.weight.
6449 * - For group entity, update its weight to reflect the new share
6450 * of its group cfs_rq.
6451 */
6452 update_load_avg(cfs_rq, se, action);
6453 se_update_runnable(se);
6454
6455 update_stats_dequeue_fair(cfs_rq, se, flags);
6456
6457 se->on_rq = 0;
6458 account_entity_dequeue(cfs_rq, se);
6459
6460 /* return excess runtime on last dequeue */
6461 return_cfs_rq_runtime(cfs_rq);
6462
6463 update_cfs_group(se);
6464
6465 if (cfs_rq->nr_queued == 0) {
6466 update_idle_cfs_rq_clock_pelt(cfs_rq);
6467 #ifdef CONFIG_CFS_BANDWIDTH
6468 if (throttled_hierarchy(cfs_rq)) {
6469 struct rq *rq = rq_of(cfs_rq);
6470
6471 list_del_leaf_cfs_rq(cfs_rq);
6472 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6473 cfs_rq->pelt_clock_throttled = 1;
6474 }
6475 #endif
6476 }
6477 }
6478
6479 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)6480 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
6481 {
6482 /* 'current' is not kept within the tree. */
6483 if (se->on_rq) {
6484 /*
6485 * Any task has to be enqueued before it get to execute on
6486 * a CPU. So account for the time it spent waiting on the
6487 * runqueue.
6488 */
6489 update_stats_wait_end_fair(cfs_rq, se);
6490 update_load_avg(cfs_rq, se, UPDATE_TG);
6491 }
6492
6493 update_stats_curr_start(cfs_rq, se);
6494 WARN_ON_ONCE(cfs_rq->h_curr);
6495 cfs_rq->h_curr = se;
6496
6497 /*
6498 * Track our maximum slice length, if the CPU's load is at
6499 * least twice that of our own weight (i.e. don't track it
6500 * when there are only lesser-weight tasks around):
6501 */
6502 if (schedstat_enabled() &&
6503 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
6504 struct sched_statistics *stats;
6505
6506 stats = __schedstats_from_se(se);
6507 __schedstat_set(stats->slice_max,
6508 max((u64)stats->slice_max,
6509 se->sum_exec_runtime - se->prev_sum_exec_runtime));
6510 }
6511
6512 se->prev_sum_exec_runtime = se->sum_exec_runtime;
6513 }
6514
6515 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags);
6516
6517 static struct sched_entity *
pick_next_entity(struct rq * rq,bool protect)6518 pick_next_entity(struct rq *rq, bool protect)
6519 {
6520 struct cfs_rq *cfs_rq = &rq->cfs;
6521 struct sched_entity *se;
6522
6523 se = pick_eevdf(cfs_rq, protect);
6524 if (se->sched_delayed) {
6525 __dequeue_task(rq, task_of(se), DEQUEUE_SLEEP | DEQUEUE_DELAYED);
6526 /*
6527 * Must not reference @se again, see __block_task().
6528 */
6529 return NULL;
6530 }
6531 return se;
6532 }
6533
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)6534 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
6535 {
6536 /*
6537 * If still on the runqueue then deactivate_task()
6538 * was not called and update_curr() has to be done:
6539 */
6540 if (prev->on_rq)
6541 update_curr(cfs_rq);
6542
6543 if (prev->on_rq) {
6544 update_stats_wait_start_fair(cfs_rq, prev);
6545 /* in !on_rq case, update occurred at dequeue */
6546 update_load_avg(cfs_rq, prev, 0);
6547 }
6548 WARN_ON_ONCE(cfs_rq->h_curr != prev);
6549 cfs_rq->h_curr = NULL;
6550 }
6551
6552 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)6553 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
6554 {
6555 /*
6556 * Update run-time statistics of the 'current'.
6557 */
6558 update_curr(cfs_rq);
6559
6560 /*
6561 * Ensure that runnable average is periodically updated.
6562 */
6563 update_load_avg(cfs_rq, curr, UPDATE_TG);
6564 update_cfs_group(curr);
6565
6566 #ifdef CONFIG_SCHED_HRTICK
6567 /*
6568 * queued ticks are scheduled to match the slice, so don't bother
6569 * validating it and just reschedule.
6570 */
6571 if (queued) {
6572 resched_curr(rq_of(cfs_rq));
6573 return;
6574 }
6575 #endif
6576 }
6577
6578
6579 /**************************************************
6580 * CFS bandwidth control machinery
6581 */
6582
6583 #ifdef CONFIG_CFS_BANDWIDTH
6584
6585 #ifdef CONFIG_JUMP_LABEL
6586 static struct static_key __cfs_bandwidth_used;
6587
cfs_bandwidth_used(void)6588 static inline bool cfs_bandwidth_used(void)
6589 {
6590 return static_key_false(&__cfs_bandwidth_used);
6591 }
6592
cfs_bandwidth_usage_inc(void)6593 void cfs_bandwidth_usage_inc(void)
6594 {
6595 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
6596 }
6597
cfs_bandwidth_usage_dec(void)6598 void cfs_bandwidth_usage_dec(void)
6599 {
6600 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
6601 }
6602 #else /* !CONFIG_JUMP_LABEL: */
cfs_bandwidth_used(void)6603 static bool cfs_bandwidth_used(void)
6604 {
6605 return true;
6606 }
6607
cfs_bandwidth_usage_inc(void)6608 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)6609 void cfs_bandwidth_usage_dec(void) {}
6610 #endif /* !CONFIG_JUMP_LABEL */
6611
sched_cfs_bandwidth_slice(void)6612 static inline u64 sched_cfs_bandwidth_slice(void)
6613 {
6614 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
6615 }
6616
6617 /*
6618 * Replenish runtime according to assigned quota. We use sched_clock_cpu
6619 * directly instead of rq->clock to avoid adding additional synchronization
6620 * around rq->lock.
6621 *
6622 * requires cfs_b->lock
6623 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)6624 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
6625 {
6626 s64 runtime;
6627
6628 if (unlikely(cfs_b->quota == RUNTIME_INF))
6629 return;
6630
6631 cfs_b->runtime += cfs_b->quota;
6632 runtime = cfs_b->runtime_snap - cfs_b->runtime;
6633 if (runtime > 0) {
6634 cfs_b->burst_time += runtime;
6635 cfs_b->nr_burst++;
6636 }
6637
6638 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
6639 cfs_b->runtime_snap = cfs_b->runtime;
6640 }
6641
tg_cfs_bandwidth(struct task_group * tg)6642 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6643 {
6644 return &tg->cfs_bandwidth;
6645 }
6646
6647 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)6648 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
6649 struct cfs_rq *cfs_rq, u64 target_runtime)
6650 {
6651 u64 min_amount, amount = 0;
6652
6653 lockdep_assert_held(&cfs_b->lock);
6654
6655 /* note: this is a positive sum as runtime_remaining <= 0 */
6656 min_amount = target_runtime - cfs_rq->runtime_remaining;
6657
6658 if (cfs_b->quota == RUNTIME_INF)
6659 amount = min_amount;
6660 else {
6661 start_cfs_bandwidth(cfs_b);
6662
6663 if (cfs_b->runtime > 0) {
6664 amount = min(cfs_b->runtime, min_amount);
6665 cfs_b->runtime -= amount;
6666 cfs_b->idle = 0;
6667 }
6668 }
6669
6670 cfs_rq->runtime_remaining += amount;
6671
6672 return cfs_rq->runtime_remaining > 0;
6673 }
6674
6675 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq);
6676
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6677 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6678 {
6679 /* dock delta_exec before expiring quota (as it could span periods) */
6680 cfs_rq->runtime_remaining -= delta_exec;
6681
6682 if (likely(cfs_rq->runtime_remaining > 0))
6683 return false;
6684
6685 if (cfs_rq->throttled)
6686 return true;
6687 /*
6688 * throttle_cfs_rq() will try to extend the runtime first
6689 * before throttling the hierarchy.
6690 */
6691 return throttle_cfs_rq(cfs_rq);
6692 }
6693
6694 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6695 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
6696 {
6697 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
6698 return false;
6699
6700 return __account_cfs_rq_runtime(cfs_rq, delta_exec);
6701 }
6702
cfs_rq_throttled(struct cfs_rq * cfs_rq)6703 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6704 {
6705 return cfs_bandwidth_used() && cfs_rq->throttled;
6706 }
6707
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)6708 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6709 {
6710 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
6711 }
6712
6713 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)6714 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6715 {
6716 return cfs_bandwidth_used() && cfs_rq->throttle_count;
6717 }
6718
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)6719 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6720 {
6721 return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu));
6722 }
6723
task_is_throttled(struct task_struct * p)6724 static inline bool task_is_throttled(struct task_struct *p)
6725 {
6726 return cfs_bandwidth_used() && p->throttled;
6727 }
6728
6729 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
throttle_cfs_rq_work(struct callback_head * work)6730 static void throttle_cfs_rq_work(struct callback_head *work)
6731 {
6732 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
6733 struct sched_entity *se;
6734 struct cfs_rq *cfs_rq;
6735 struct rq *rq;
6736
6737 WARN_ON_ONCE(p != current);
6738 p->sched_throttle_work.next = &p->sched_throttle_work;
6739
6740 /*
6741 * If task is exiting, then there won't be a return to userspace, so we
6742 * don't have to bother with any of this.
6743 */
6744 if ((p->flags & PF_EXITING))
6745 return;
6746
6747 scoped_guard(task_rq_lock, p) {
6748 se = &p->se;
6749 cfs_rq = cfs_rq_of(se);
6750
6751 /* Raced, forget */
6752 if (p->sched_class != &fair_sched_class)
6753 return;
6754
6755 /*
6756 * If not in limbo, then either replenish has happened or this
6757 * task got migrated out of the throttled cfs_rq, move along.
6758 */
6759 if (!cfs_rq->throttle_count)
6760 return;
6761 rq = scope.rq;
6762 update_rq_clock(rq);
6763 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
6764 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
6765 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6766 /*
6767 * Must not set throttled before dequeue or dequeue will
6768 * mistakenly regard this task as an already throttled one.
6769 */
6770 p->throttled = true;
6771 resched_curr(rq);
6772 }
6773 }
6774
init_cfs_throttle_work(struct task_struct * p)6775 void init_cfs_throttle_work(struct task_struct *p)
6776 {
6777 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
6778 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
6779 p->sched_throttle_work.next = &p->sched_throttle_work;
6780 INIT_LIST_HEAD(&p->throttle_node);
6781 }
6782
6783 /*
6784 * Task is throttled and someone wants to dequeue it again:
6785 * it could be sched/core when core needs to do things like
6786 * task affinity change, task group change, task sched class
6787 * change etc. and in these cases, DEQUEUE_SLEEP is not set;
6788 * or the task is blocked after throttled due to freezer etc.
6789 * and in these cases, DEQUEUE_SLEEP is set.
6790 */
6791 static void detach_task_cfs_rq(struct task_struct *p);
dequeue_throttled_task(struct task_struct * p,int flags)6792 static void dequeue_throttled_task(struct task_struct *p, int flags)
6793 {
6794 WARN_ON_ONCE(p->se.on_rq);
6795 list_del_init(&p->throttle_node);
6796
6797 /* task blocked after throttled */
6798 if (flags & DEQUEUE_SLEEP) {
6799 p->throttled = false;
6800 return;
6801 }
6802
6803 /*
6804 * task is migrating off its old cfs_rq, detach
6805 * the task's load from its old cfs_rq.
6806 */
6807 if (task_on_rq_migrating(p))
6808 detach_task_cfs_rq(p);
6809 }
6810
enqueue_throttled_task(struct task_struct * p)6811 static bool enqueue_throttled_task(struct task_struct *p)
6812 {
6813 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
6814
6815 /* @p should have gone through dequeue_throttled_task() first */
6816 WARN_ON_ONCE(!list_empty(&p->throttle_node));
6817
6818 /*
6819 * If the throttled task @p is enqueued to a throttled cfs_rq,
6820 * take the fast path by directly putting the task on the
6821 * target cfs_rq's limbo list.
6822 *
6823 * Do not do that when @p is current because the following race can
6824 * cause @p's group_node to be incorectly re-insterted in its rq's
6825 * cfs_tasks list, despite being throttled:
6826 *
6827 * cpuX cpuY
6828 * p ret2user
6829 * throttle_cfs_rq_work() sched_move_task(p)
6830 * LOCK task_rq_lock
6831 * dequeue_task_fair(p)
6832 * UNLOCK task_rq_lock
6833 * LOCK task_rq_lock
6834 * task_current_donor(p) == true
6835 * task_on_rq_queued(p) == true
6836 * dequeue_task(p)
6837 * put_prev_task(p)
6838 * sched_change_group()
6839 * enqueue_task(p) -> p's new cfs_rq
6840 * is throttled, go
6841 * fast path and skip
6842 * actual enqueue
6843 * set_next_task(p)
6844 * list_move(&se->group_node, &rq->cfs_tasks); // bug
6845 * schedule()
6846 *
6847 * In the above race case, @p current cfs_rq is in the same rq as
6848 * its previous cfs_rq because sched_move_task() only moves a task
6849 * to a different group from the same rq, so we can use its current
6850 * cfs_rq to derive rq and test if the task is current.
6851 */
6852 if (throttled_hierarchy(cfs_rq) &&
6853 !task_current_donor(rq_of(cfs_rq), p)) {
6854 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6855 return true;
6856 }
6857
6858 /* we can't take the fast path, do an actual enqueue*/
6859 p->throttled = false;
6860 return false;
6861 }
6862
6863 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
tg_unthrottle_up(struct task_group * tg,void * data)6864 static int tg_unthrottle_up(struct task_group *tg, void *data)
6865 {
6866 struct rq *rq = data;
6867 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
6868 struct task_struct *p, *tmp;
6869 LIST_HEAD(throttled_tasks);
6870
6871 /*
6872 * If cfs_rq->curr is set, the cfs_rq might not have caught up
6873 * since the last clock update. Do it now before we begin
6874 * queueing task onto it to save the need for unnecessarily
6875 * unthrottle the hierarchy for this cfs_rq to be throttled
6876 * right back again.
6877 */
6878 update_curr(cfs_rq);
6879
6880 if (--cfs_rq->throttle_count)
6881 return 0;
6882
6883 if (cfs_rq->pelt_clock_throttled) {
6884 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6885 cfs_rq->throttled_clock_pelt;
6886 cfs_rq->pelt_clock_throttled = 0;
6887 }
6888
6889 if (cfs_rq->throttled_clock_self) {
6890 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
6891
6892 cfs_rq->throttled_clock_self = 0;
6893
6894 if (WARN_ON_ONCE((s64)delta < 0))
6895 delta = 0;
6896
6897 cfs_rq->throttled_clock_self_time += delta;
6898 }
6899
6900 /*
6901 * Move the tasks to a local list since an update_curr() during
6902 * enqueue_task_fair() can throttle a higher cfs_rq, and it can
6903 * see the "throttled_limbo_list" being non-empty in
6904 * tg_throttle_down() if throttle_count turned 0 above.
6905 */
6906 list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks);
6907
6908 /* Re-enqueue the tasks that have been throttled at this level. */
6909 list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) {
6910 /*
6911 * Back to being throttled! Break out and put the remaining
6912 * tasks back onto the limbo_list to prevent running them
6913 * unnecessarily.
6914 */
6915 if (cfs_rq->throttle_count)
6916 break;
6917
6918 list_del_init(&p->throttle_node);
6919 p->throttled = false;
6920 enqueue_task_fair(rq, p, ENQUEUE_WAKEUP);
6921 }
6922
6923 list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list);
6924
6925 /* Add cfs_rq with load or one or more already running entities to the list */
6926 if (!cfs_rq_is_decayed(cfs_rq))
6927 list_add_leaf_cfs_rq(cfs_rq);
6928
6929 return 0;
6930 }
6931
task_has_throttle_work(struct task_struct * p)6932 static inline bool task_has_throttle_work(struct task_struct *p)
6933 {
6934 return p->sched_throttle_work.next != &p->sched_throttle_work;
6935 }
6936
task_throttle_setup_work(struct task_struct * p)6937 static inline void task_throttle_setup_work(struct task_struct *p)
6938 {
6939 if (task_has_throttle_work(p))
6940 return;
6941
6942 /*
6943 * Kthreads and exiting tasks don't return to userspace, so adding the
6944 * work is pointless
6945 */
6946 if ((p->flags & (PF_EXITING | PF_KTHREAD)))
6947 return;
6948
6949 task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
6950 }
6951
record_throttle_clock(struct cfs_rq * cfs_rq)6952 static void record_throttle_clock(struct cfs_rq *cfs_rq)
6953 {
6954 struct rq *rq = rq_of(cfs_rq);
6955
6956 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
6957 cfs_rq->throttled_clock = rq_clock(rq);
6958
6959 if (!cfs_rq->throttled_clock_self)
6960 cfs_rq->throttled_clock_self = rq_clock(rq);
6961 }
6962
tg_throttle_down(struct task_group * tg,void * data)6963 static int tg_throttle_down(struct task_group *tg, void *data)
6964 {
6965 struct rq *rq = data;
6966 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
6967
6968 if (cfs_rq->throttle_count++)
6969 return 0;
6970
6971 /*
6972 * For cfs_rqs that still have entities enqueued, PELT clock
6973 * stop happens at dequeue time when all entities are dequeued.
6974 */
6975 if (!cfs_rq->nr_queued) {
6976 list_del_leaf_cfs_rq(cfs_rq);
6977 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6978 cfs_rq->pelt_clock_throttled = 1;
6979 }
6980
6981 WARN_ON_ONCE(cfs_rq->throttled_clock_self);
6982 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
6983 return 0;
6984 }
6985
throttle_cfs_rq(struct cfs_rq * cfs_rq)6986 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
6987 {
6988 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6989 struct sched_entity *curr = cfs_rq->h_curr;
6990 struct rq *rq = rq_of(cfs_rq);
6991
6992 scoped_guard(raw_spinlock, &cfs_b->lock) {
6993 u64 target_runtime = 1;
6994
6995 /*
6996 * If cfs_rq->h_curr is still runnable, we are here from an
6997 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice
6998 * worth of bandwidth to continue running.
6999 *
7000 * If the curr is not runnable, just request enough bandwidth
7001 * to be runnable next time the pick selects this cfs_rq.
7002 */
7003 if (curr && curr->on_rq)
7004 target_runtime = sched_cfs_bandwidth_slice();
7005
7006 /*
7007 * Check if We have raced with bandwidth becoming available. If
7008 * we actually throttled the timer might not unthrottle us for
7009 * an entire period. We additionally needed to make sure that
7010 * any subsequent check_cfs_rq_runtime calls agree not to
7011 * throttle us, as we may commit to do cfs put_prev+pick_next,
7012 * so we ask for 1ns of runtime rather than just check cfs_b.
7013 *
7014 * This will start the period timer if necessary.
7015 */
7016 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime))
7017 return false;
7018
7019 /*
7020 * No bandwidth available; Add ourselves on the list to be
7021 * unthrottled later.
7022 */
7023 list_add_tail_rcu(&cfs_rq->throttled_list,
7024 &cfs_b->throttled_cfs_rq);
7025 }
7026
7027 /* freeze hierarchy runnable averages while throttled */
7028 scoped_guard(rcu)
7029 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
7030
7031 /*
7032 * Note: distribution will already see us throttled via the
7033 * throttled-list. rq->lock protects completion.
7034 */
7035 cfs_rq->throttled = 1;
7036 WARN_ON_ONCE(cfs_rq->throttled_clock);
7037
7038 /*
7039 * If current hierarchy was throttled, add throttle work to the
7040 * current donor. In case of proxy-execution, the execution
7041 * context cannot exit to the userspace while holding a mutex
7042 * and the rule of throttle deferral to only throttle the
7043 * throttled context at exit to userspace is still preserved.
7044 */
7045 if (curr && curr->on_rq)
7046 task_throttle_setup_work(rq->donor);
7047
7048 return true;
7049 }
7050
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)7051 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
7052 {
7053 struct rq *rq = rq_of(cfs_rq);
7054 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7055 struct sched_entity *se = cfs_rq_se(cfs_rq);
7056
7057 /*
7058 * It's possible we are called with runtime_remaining < 0 due to things
7059 * like async unthrottled us with a positive runtime_remaining but other
7060 * still running entities consumed those runtime before we reached here.
7061 *
7062 * We can't unthrottle this cfs_rq without any runtime remaining because
7063 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
7064 * which is not supposed to happen on unthrottle path.
7065 *
7066 * Catch up on the remaining runtime since last clock update before
7067 * checking runtime remaining.
7068 */
7069 update_curr(cfs_rq);
7070 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
7071 return;
7072
7073 cfs_rq->throttled = 0;
7074
7075 scoped_guard(raw_spinlock, &cfs_b->lock) {
7076 list_del_rcu(&cfs_rq->throttled_list);
7077
7078 if (!cfs_rq->throttled_clock)
7079 break;
7080
7081 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
7082 cfs_rq->throttled_clock = 0;
7083 }
7084
7085 /* update hierarchical throttle state */
7086 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
7087
7088 if (!cfs_rq->load.weight) {
7089 if (!cfs_rq->on_list)
7090 return;
7091 /*
7092 * Nothing to run but something to decay (on_list)?
7093 * Complete the branch.
7094 */
7095 for_each_sched_entity(se) {
7096 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
7097 break;
7098 }
7099 }
7100
7101 assert_list_leaf_cfs_rq(rq);
7102
7103 /* Determine whether we need to wake up potentially idle CPU: */
7104 if (rq->curr == rq->idle && rq->cfs.h_nr_queued)
7105 resched_curr(rq);
7106 }
7107
__cfsb_csd_unthrottle(void * arg)7108 static void __cfsb_csd_unthrottle(void *arg)
7109 {
7110 struct cfs_rq *cursor, *tmp;
7111 struct rq *rq = arg;
7112
7113 guard(rq_lock)(rq);
7114
7115 /*
7116 * Iterating over the list can trigger several call to
7117 * update_rq_clock() in unthrottle_cfs_rq().
7118 * Do it once and skip the potential next ones.
7119 */
7120 update_rq_clock(rq);
7121 rq_clock_start_loop_update(rq);
7122
7123 /*
7124 * Since we hold rq lock we're safe from concurrent manipulation of
7125 * the CSD list. However, this RCU critical section annotates the
7126 * fact that we pair with sched_free_group_rcu(), so that we cannot
7127 * race with group being freed in the window between removing it
7128 * from the list and advancing to the next entry in the list.
7129 */
7130 guard(rcu)();
7131
7132 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
7133 throttled_csd_list) {
7134 list_del_init(&cursor->throttled_csd_list);
7135
7136 if (cfs_rq_throttled(cursor))
7137 unthrottle_cfs_rq(cursor);
7138 }
7139
7140 rq_clock_stop_loop_update(rq);
7141 }
7142
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)7143 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7144 {
7145 struct rq *rq = rq_of(cfs_rq);
7146 bool first;
7147
7148 if (rq == this_rq()) {
7149 update_rq_clock(rq);
7150 unthrottle_cfs_rq(cfs_rq);
7151 return;
7152 }
7153
7154 /* Already enqueued */
7155 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
7156 return;
7157
7158 first = list_empty(&rq->cfsb_csd_list);
7159 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7160 if (first)
7161 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
7162 }
7163
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)7164 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
7165 {
7166 lockdep_assert_rq_held(rq_of(cfs_rq));
7167
7168 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
7169 cfs_rq->runtime_remaining <= 0))
7170 return;
7171
7172 __unthrottle_cfs_rq_async(cfs_rq);
7173 }
7174
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)7175 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
7176 {
7177 bool throttled = false, unthrottle_local = false;
7178 int this_cpu = smp_processor_id();
7179 u64 runtime, remaining = 1;
7180 struct cfs_rq *cfs_rq;
7181 struct rq *rq;
7182
7183 guard(rcu)();
7184
7185 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
7186 throttled_list) {
7187 rq = rq_of(cfs_rq);
7188
7189 if (!remaining) {
7190 throttled = true;
7191 break;
7192 }
7193
7194 guard(rq_lock_irqsave)(rq);
7195
7196 if (!cfs_rq_throttled(cfs_rq))
7197 continue;
7198
7199 /* Already queued for async unthrottle */
7200 if (!list_empty(&cfs_rq->throttled_csd_list))
7201 continue;
7202
7203 if (cfs_rq->h_curr) {
7204 update_rq_clock(rq);
7205 update_curr(cfs_rq);
7206 }
7207
7208 /* By the above checks, this should never be true */
7209 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
7210
7211 scoped_guard(raw_spinlock, &cfs_b->lock) {
7212 runtime = -cfs_rq->runtime_remaining + 1;
7213 if (runtime > cfs_b->runtime)
7214 runtime = cfs_b->runtime;
7215 cfs_b->runtime -= runtime;
7216 remaining = cfs_b->runtime;
7217 }
7218
7219 cfs_rq->runtime_remaining += runtime;
7220
7221 /*
7222 * Ran out of bandwidth during distribution!
7223 * Indicate throttled entities and break early.
7224 */
7225 if (cfs_rq->runtime_remaining <= 0) {
7226 throttled = true;
7227 break;
7228 }
7229
7230 /* we check whether we're throttled above */
7231 if (cpu_of(rq) != this_cpu) {
7232 unthrottle_cfs_rq_async(cfs_rq);
7233 continue;
7234 }
7235
7236 /*
7237 * Allow a parallel async unthrottle to unthrottle
7238 * this cfs_rq too via __cfsb_csd_unthrottle().
7239 * If we are first, do it ourselves at the end and
7240 * save on an IPI from remote CPUs.
7241 */
7242 unthrottle_local = list_empty(&rq->cfsb_csd_list);
7243 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
7244 }
7245
7246 if (unthrottle_local) {
7247 /*
7248 * Protect against an IPI that is also trying to flush
7249 * the unthrottled cfs_rq(s) from this CPU's csd_list.
7250 */
7251 scoped_guard(irqsave)
7252 __cfsb_csd_unthrottle(cpu_rq(this_cpu));
7253 }
7254
7255 return throttled;
7256 }
7257
7258 /*
7259 * Responsible for refilling a task_group's bandwidth and unthrottling its
7260 * cfs_rqs as appropriate. If there has been no activity within the last
7261 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
7262 * used to track this state.
7263 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)7264 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
7265 __must_hold(&cfs_b->lock)
7266 {
7267 int throttled;
7268
7269 /* no need to continue the timer with no bandwidth constraint */
7270 if (cfs_b->quota == RUNTIME_INF)
7271 goto out_deactivate;
7272
7273 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
7274 cfs_b->nr_periods += overrun;
7275
7276 /* Refill extra burst quota even if cfs_b->idle */
7277 __refill_cfs_bandwidth_runtime(cfs_b);
7278
7279 /*
7280 * idle depends on !throttled (for the case of a large deficit), and if
7281 * we're going inactive then everything else can be deferred
7282 */
7283 if (cfs_b->idle && !throttled)
7284 goto out_deactivate;
7285
7286 if (!throttled) {
7287 /* mark as potentially idle for the upcoming period */
7288 cfs_b->idle = 1;
7289 return 0;
7290 }
7291
7292 /* account preceding periods in which throttling occurred */
7293 cfs_b->nr_throttled += overrun;
7294
7295 /*
7296 * This check is repeated as we release cfs_b->lock while we unthrottle.
7297 */
7298 while (throttled && cfs_b->runtime > 0) {
7299 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
7300 /* we can't nest cfs_b->lock while distributing bandwidth */
7301 throttled = distribute_cfs_runtime(cfs_b);
7302 raw_spin_lock_irqsave(&cfs_b->lock, flags);
7303 }
7304
7305 /*
7306 * While we are ensured activity in the period following an
7307 * unthrottle, this also covers the case in which the new bandwidth is
7308 * insufficient to cover the existing bandwidth deficit. (Forcing the
7309 * timer to remain active while there are any throttled entities.)
7310 */
7311 cfs_b->idle = 0;
7312
7313 return 0;
7314
7315 out_deactivate:
7316 return 1;
7317 }
7318
7319 /* a cfs_rq won't donate quota below this amount */
7320 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
7321 /* minimum remaining period time to redistribute slack quota */
7322 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
7323 /* how long we wait to gather additional slack before distributing */
7324 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
7325
7326 /*
7327 * Are we near the end of the current quota period?
7328 *
7329 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
7330 * hrtimer base being cleared by hrtimer_start. In the case of
7331 * migrate_hrtimers, base is never cleared, so we are fine.
7332 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)7333 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
7334 {
7335 struct hrtimer *refresh_timer = &cfs_b->period_timer;
7336 s64 remaining;
7337
7338 /* if the call-back is running a quota refresh is already occurring */
7339 if (hrtimer_callback_running(refresh_timer))
7340 return 1;
7341
7342 /* is a quota refresh about to occur? */
7343 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
7344 if (remaining < (s64)min_expire)
7345 return 1;
7346
7347 return 0;
7348 }
7349
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)7350 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
7351 {
7352 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
7353
7354 /* if there's a quota refresh soon don't bother with slack */
7355 if (runtime_refresh_within(cfs_b, min_left))
7356 return;
7357
7358 /* don't push forwards an existing deferred unthrottle */
7359 if (cfs_b->slack_started)
7360 return;
7361 cfs_b->slack_started = true;
7362
7363 hrtimer_start(&cfs_b->slack_timer,
7364 ns_to_ktime(cfs_bandwidth_slack_period),
7365 HRTIMER_MODE_REL);
7366 }
7367
7368 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)7369 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7370 {
7371 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
7372 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
7373
7374 if (slack_runtime <= 0)
7375 return;
7376
7377 guard(raw_spinlock)(&cfs_b->lock);
7378
7379 if (cfs_b->quota != RUNTIME_INF) {
7380 cfs_b->runtime += slack_runtime;
7381
7382 /* we are under rq->lock, defer unthrottling using a timer */
7383 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
7384 !list_empty(&cfs_b->throttled_cfs_rq))
7385 start_cfs_slack_bandwidth(cfs_b);
7386 }
7387
7388 /* even if it's not valid for return we don't want to try again */
7389 cfs_rq->runtime_remaining -= slack_runtime;
7390 }
7391
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)7392 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7393 {
7394 if (!cfs_bandwidth_used())
7395 return;
7396
7397 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
7398 return;
7399
7400 __return_cfs_rq_runtime(cfs_rq);
7401 }
7402
7403 /*
7404 * This is done with a timer (instead of inline with bandwidth return) since
7405 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
7406 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)7407 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
7408 {
7409 /* confirm we're still not at a refresh boundary */
7410 scoped_guard(raw_spinlock_irqsave, &cfs_b->lock) {
7411 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
7412
7413 cfs_b->slack_started = false;
7414
7415 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
7416 return;
7417
7418 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
7419 runtime = cfs_b->runtime;
7420
7421 if (!runtime)
7422 return;
7423 }
7424
7425 distribute_cfs_runtime(cfs_b);
7426 }
7427
7428 /*
7429 * When a group wakes up we want to make sure that its quota is not already
7430 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
7431 * runtime as update_curr() throttling can not trigger until it's on-rq.
7432 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)7433 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
7434 {
7435 if (!cfs_bandwidth_used())
7436 return;
7437
7438 /* an active group must be handled by the update_curr() path */
7439 if (!cfs_rq->runtime_enabled || cfs_rq->h_curr)
7440 return;
7441
7442 /* ensure the group is not already throttled */
7443 if (cfs_rq_throttled(cfs_rq))
7444 return;
7445
7446 /* update runtime allocation */
7447 account_cfs_rq_runtime(cfs_rq, 0);
7448 }
7449
sync_throttle(struct task_group * tg,int cpu)7450 static void sync_throttle(struct task_group *tg, int cpu)
7451 {
7452 struct cfs_rq *pcfs_rq, *cfs_rq;
7453
7454 if (!cfs_bandwidth_used())
7455 return;
7456
7457 if (!tg->parent)
7458 return;
7459
7460 cfs_rq = tg_cfs_rq(tg, cpu);
7461 pcfs_rq = tg_cfs_rq(tg->parent, cpu);
7462
7463 cfs_rq->throttle_count = pcfs_rq->throttle_count;
7464 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
7465
7466 /*
7467 * It is not enough to sync the "pelt_clock_throttled" indicator
7468 * with the parent cfs_rq when the hierarchy is not queued.
7469 * Always join a throttled hierarchy with PELT clock throttled
7470 * and leaf it to the first enqueue, or distribution to
7471 * unthrottle the PELT clock.
7472 */
7473 if (cfs_rq->throttle_count)
7474 cfs_rq->pelt_clock_throttled = 1;
7475 }
7476
sched_cfs_slack_timer(struct hrtimer * timer)7477 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
7478 {
7479 struct cfs_bandwidth *cfs_b =
7480 container_of(timer, struct cfs_bandwidth, slack_timer);
7481
7482 do_sched_cfs_slack_timer(cfs_b);
7483
7484 return HRTIMER_NORESTART;
7485 }
7486
sched_cfs_period_timer(struct hrtimer * timer)7487 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
7488 {
7489 struct cfs_bandwidth *cfs_b =
7490 container_of(timer, struct cfs_bandwidth, period_timer);
7491 int overrun;
7492 int idle = 0;
7493 int count = 0;
7494
7495 CLASS(raw_spinlock_irqsave, cfsb_guard)(&cfs_b->lock);
7496
7497 for (;;) {
7498 overrun = hrtimer_forward_now(timer, cfs_b->period);
7499 if (!overrun)
7500 break;
7501
7502 idle = do_sched_cfs_period_timer(cfs_b, overrun, cfsb_guard.flags);
7503
7504 if (++count > 3) {
7505 u64 new, old = ktime_to_ns(cfs_b->period);
7506
7507 /*
7508 * Grow period by a factor of 2 to avoid losing precision.
7509 * Precision loss in the quota/period ratio can cause __cfs_schedulable
7510 * to fail.
7511 */
7512 new = old * 2;
7513 if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
7514 cfs_b->period = ns_to_ktime(new);
7515 cfs_b->quota *= 2;
7516 cfs_b->burst *= 2;
7517
7518 pr_warn_ratelimited(
7519 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7520 smp_processor_id(),
7521 div_u64(new, NSEC_PER_USEC),
7522 div_u64(cfs_b->quota, NSEC_PER_USEC));
7523 } else {
7524 pr_warn_ratelimited(
7525 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
7526 smp_processor_id(),
7527 div_u64(old, NSEC_PER_USEC),
7528 div_u64(cfs_b->quota, NSEC_PER_USEC));
7529 }
7530
7531 /* reset count so we don't come right back in here */
7532 count = 0;
7533 }
7534 }
7535
7536 if (idle) {
7537 cfs_b->period_active = 0;
7538 return HRTIMER_NORESTART;
7539 }
7540
7541 return HRTIMER_RESTART;
7542 }
7543
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)7544 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
7545 {
7546 raw_spin_lock_init(&cfs_b->lock);
7547 cfs_b->runtime = 0;
7548 cfs_b->quota = RUNTIME_INF;
7549 cfs_b->period = us_to_ktime(default_bw_period_us());
7550 cfs_b->burst = 0;
7551 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
7552
7553 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
7554 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
7555 HRTIMER_MODE_ABS_PINNED);
7556
7557 /* Add a random offset so that timers interleave */
7558 hrtimer_set_expires(&cfs_b->period_timer,
7559 get_random_u32_below(cfs_b->period));
7560 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
7561 HRTIMER_MODE_REL);
7562 cfs_b->slack_started = false;
7563 }
7564
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)7565 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
7566 {
7567 cfs_rq->runtime_enabled = 0;
7568 INIT_LIST_HEAD(&cfs_rq->throttled_list);
7569 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
7570 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
7571 }
7572
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)7573 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7574 {
7575 lockdep_assert_held(&cfs_b->lock);
7576
7577 if (cfs_b->period_active)
7578 return;
7579
7580 cfs_b->period_active = 1;
7581 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
7582 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
7583 }
7584
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)7585 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
7586 {
7587 int __maybe_unused i;
7588
7589 /* init_cfs_bandwidth() was not called */
7590 if (!cfs_b->throttled_cfs_rq.next)
7591 return;
7592
7593 hrtimer_cancel(&cfs_b->period_timer);
7594 hrtimer_cancel(&cfs_b->slack_timer);
7595
7596 /*
7597 * It is possible that we still have some cfs_rq's pending on a CSD
7598 * list, though this race is very rare. In order for this to occur, we
7599 * must have raced with the last task leaving the group while there
7600 * exist throttled cfs_rq(s), and the period_timer must have queued the
7601 * CSD item but the remote cpu has not yet processed it. To handle this,
7602 * we can simply flush all pending CSD work inline here. We're
7603 * guaranteed at this point that no additional cfs_rq of this group can
7604 * join a CSD list.
7605 */
7606 for_each_possible_cpu(i) {
7607 struct rq *rq = cpu_rq(i);
7608
7609 if (list_empty(&rq->cfsb_csd_list))
7610 continue;
7611
7612 scoped_guard(irqsave)
7613 __cfsb_csd_unthrottle(rq);
7614 }
7615 }
7616
7617 /*
7618 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
7619 *
7620 * The race is harmless, since modifying bandwidth settings of unhooked group
7621 * bits doesn't do much.
7622 */
7623
7624 /* cpu online callback */
update_runtime_enabled(struct rq * rq)7625 static void __maybe_unused update_runtime_enabled(struct rq *rq)
7626 {
7627 struct task_group *tg;
7628
7629 lockdep_assert_rq_held(rq);
7630
7631 guard(rcu)();
7632
7633 list_for_each_entry_rcu(tg, &task_groups, list) {
7634 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7635 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7636
7637 scoped_guard(raw_spinlock, &cfs_b->lock)
7638 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
7639 }
7640 }
7641
7642 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)7643 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
7644 {
7645 struct task_group *tg;
7646
7647 lockdep_assert_rq_held(rq);
7648
7649 // Do not unthrottle for an active CPU
7650 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
7651 return;
7652
7653 /*
7654 * The rq clock has already been updated in the
7655 * set_rq_offline(), so we should skip updating
7656 * the rq clock again in unthrottle_cfs_rq().
7657 */
7658 rq_clock_start_loop_update(rq);
7659
7660 guard(rcu)();
7661
7662 list_for_each_entry_rcu(tg, &task_groups, list) {
7663 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
7664
7665 if (!cfs_rq->runtime_enabled)
7666 continue;
7667
7668 /*
7669 * Offline rq is schedulable till CPU is completely disabled
7670 * in take_cpu_down(), so we prevent new cfs throttling here.
7671 */
7672 cfs_rq->runtime_enabled = 0;
7673
7674 if (!cfs_rq_throttled(cfs_rq))
7675 continue;
7676
7677 /*
7678 * clock_task is not advancing so we just need to make sure
7679 * there's some valid quota amount
7680 */
7681 cfs_rq->runtime_remaining = 1;
7682 unthrottle_cfs_rq(cfs_rq);
7683 }
7684
7685 rq_clock_stop_loop_update(rq);
7686 }
7687
cfs_task_bw_constrained(struct task_struct * p)7688 bool cfs_task_bw_constrained(struct task_struct *p)
7689 {
7690 struct cfs_rq *cfs_rq = task_cfs_rq(p);
7691
7692 if (!cfs_bandwidth_used())
7693 return false;
7694
7695 if (cfs_rq->runtime_enabled ||
7696 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
7697 return true;
7698
7699 return false;
7700 }
7701
7702 #ifdef CONFIG_NO_HZ_FULL
7703 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)7704 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
7705 {
7706 int cpu = cpu_of(rq);
7707
7708 if (!cfs_bandwidth_used())
7709 return;
7710
7711 if (!tick_nohz_full_cpu(cpu))
7712 return;
7713
7714 if (rq->nr_running != 1)
7715 return;
7716
7717 /*
7718 * We know there is only one task runnable and we've just picked it. The
7719 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
7720 * be otherwise able to stop the tick. Just need to check if we are using
7721 * bandwidth control.
7722 */
7723 if (cfs_task_bw_constrained(p))
7724 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
7725 }
7726 #endif /* CONFIG_NO_HZ_FULL */
7727
7728 #else /* !CONFIG_CFS_BANDWIDTH: */
7729
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)7730 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)7731 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)7732 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)7733 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
task_throttle_setup_work(struct task_struct * p)7734 static void task_throttle_setup_work(struct task_struct *p) {}
task_is_throttled(struct task_struct * p)7735 static bool task_is_throttled(struct task_struct *p) { return false; }
dequeue_throttled_task(struct task_struct * p,int flags)7736 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
enqueue_throttled_task(struct task_struct * p)7737 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
record_throttle_clock(struct cfs_rq * cfs_rq)7738 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
7739
cfs_rq_throttled(struct cfs_rq * cfs_rq)7740 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
7741 {
7742 return 0;
7743 }
7744
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)7745 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
7746 {
7747 return false;
7748 }
7749
throttled_hierarchy(struct cfs_rq * cfs_rq)7750 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
7751 {
7752 return 0;
7753 }
7754
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)7755 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
7756 {
7757 return 0;
7758 }
7759
7760 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)7761 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)7762 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
7763 #endif
7764
tg_cfs_bandwidth(struct task_group * tg)7765 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
7766 {
7767 return NULL;
7768 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)7769 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)7770 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)7771 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
7772 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)7773 bool cfs_task_bw_constrained(struct task_struct *p)
7774 {
7775 return false;
7776 }
7777 #endif
7778 #endif /* !CONFIG_CFS_BANDWIDTH */
7779
7780 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)7781 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
7782 #endif
7783
7784 /**************************************************
7785 * CFS operations on tasks:
7786 */
7787
7788 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)7789 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
7790 {
7791 struct sched_entity *se = &p->se;
7792 unsigned long scale = 1024;
7793 unsigned long util = 0;
7794 u64 vdelta;
7795 u64 delta;
7796
7797 WARN_ON_ONCE(task_rq(p) != rq);
7798
7799 if (rq->cfs.h_nr_queued <= 1)
7800 return;
7801
7802 /*
7803 * Compute time until virtual deadline
7804 */
7805 vdelta = se->deadline - se->vruntime;
7806 if ((s64)vdelta < 0) {
7807 if (task_current_donor(rq, p))
7808 resched_curr(rq);
7809 return;
7810 }
7811 delta = (se->h_load.weight * vdelta) / NICE_0_LOAD;
7812
7813 /*
7814 * Correct for instantaneous load of other classes.
7815 */
7816 util += cpu_util_irq(rq);
7817 if (util && util < 1024) {
7818 scale *= 1024;
7819 scale /= (1024 - util);
7820 }
7821
7822 hrtick_start(rq, (scale * delta) / 1024);
7823 }
7824
7825 /*
7826 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1.
7827 */
hrtick_update(struct rq * rq)7828 static void hrtick_update(struct rq *rq)
7829 {
7830 struct task_struct *donor = rq->donor;
7831
7832 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
7833 return;
7834
7835 if (hrtick_active(rq))
7836 return;
7837
7838 hrtick_start_fair(rq, donor);
7839 }
7840 #else /* !CONFIG_SCHED_HRTICK: */
7841 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)7842 hrtick_start_fair(struct rq *rq, struct task_struct *p)
7843 {
7844 }
7845
hrtick_update(struct rq * rq)7846 static inline void hrtick_update(struct rq *rq)
7847 {
7848 }
7849 #endif /* !CONFIG_SCHED_HRTICK */
7850
cpu_overutilized(int cpu)7851 static inline bool cpu_overutilized(int cpu)
7852 {
7853 unsigned long rq_util_max;
7854
7855 if (!sched_energy_enabled())
7856 return false;
7857
7858 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
7859
7860 /* Return true only if the utilization doesn't fit CPU's capacity */
7861 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu);
7862 }
7863
7864 /*
7865 * overutilized value make sense only if EAS is enabled
7866 */
is_rd_overutilized(struct root_domain * rd)7867 static inline bool is_rd_overutilized(struct root_domain *rd)
7868 {
7869 return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
7870 }
7871
set_rd_overutilized(struct root_domain * rd,bool flag)7872 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
7873 {
7874 if (!sched_energy_enabled())
7875 return;
7876
7877 WRITE_ONCE(rd->overutilized, flag);
7878 trace_sched_overutilized_tp(rd, flag);
7879 }
7880
check_update_overutilized_status(struct rq * rq)7881 static inline void check_update_overutilized_status(struct rq *rq)
7882 {
7883 /*
7884 * overutilized field is used for load balancing decisions only
7885 * if energy aware scheduler is being used
7886 */
7887
7888 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
7889 set_rd_overutilized(rq->rd, 1);
7890 }
7891
7892 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)7893 static int sched_idle_rq(struct rq *rq)
7894 {
7895 return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
7896 rq->nr_running);
7897 }
7898
choose_sched_idle_rq(struct rq * rq,struct task_struct * p)7899 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p)
7900 {
7901 return sched_idle_rq(rq) && !task_has_idle_policy(p);
7902 }
7903
choose_idle_cpu(int cpu,struct task_struct * p)7904 static int choose_idle_cpu(int cpu, struct task_struct *p)
7905 {
7906 return available_idle_cpu(cpu) ||
7907 choose_sched_idle_rq(cpu_rq(cpu), p);
7908 }
7909
7910 static void
requeue_delayed_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)7911 requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
7912 {
7913 /*
7914 * se->sched_delayed should imply: se->on_rq == 1.
7915 * Because a delayed entity is one that is still on
7916 * the runqueue competing until elegibility.
7917 */
7918 WARN_ON_ONCE(!se->sched_delayed);
7919 WARN_ON_ONCE(!se->on_rq);
7920
7921 if (update_entity_lag(cfs_rq, se)) {
7922 cfs_rq->h_nr_queued--;
7923 if (se != cfs_rq->curr)
7924 __dequeue_entity(cfs_rq, se);
7925 place_entity(cfs_rq, se, 0);
7926 if (se != cfs_rq->curr)
7927 __enqueue_entity(cfs_rq, se);
7928 cfs_rq->h_nr_queued++;
7929 }
7930
7931 update_load_avg(cfs_rq, se, 0);
7932 clear_delayed(se);
7933 }
7934
enqueue_hierarchy(struct task_struct * p,int flags)7935 static unsigned long enqueue_hierarchy(struct task_struct *p, int flags)
7936 {
7937 unsigned long weight = NICE_0_LOAD;
7938 int task_new = !(flags & ENQUEUE_WAKEUP);
7939 struct sched_entity *se = &p->se;
7940 int h_nr_idle = task_has_idle_policy(p);
7941 int h_nr_runnable = 1;
7942
7943 if (task_new && se->sched_delayed)
7944 h_nr_runnable = 0;
7945
7946 for_each_sched_entity(se) {
7947 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7948
7949 update_curr(cfs_rq);
7950
7951 if (!se->on_rq) {
7952 enqueue_entity(cfs_rq, se, flags);
7953 } else {
7954 update_load_avg(cfs_rq, se, UPDATE_TG);
7955 se_update_runnable(se);
7956 update_cfs_group(se);
7957 }
7958
7959 cfs_rq->h_nr_runnable += h_nr_runnable;
7960 cfs_rq->h_nr_queued++;
7961 cfs_rq->h_nr_idle += h_nr_idle;
7962
7963 if (cfs_rq_is_idle(cfs_rq))
7964 h_nr_idle = 1;
7965
7966 weight = __calc_prop_weight(cfs_rq, se, weight);
7967
7968 flags = ENQUEUE_WAKEUP;
7969 }
7970
7971 return weight;
7972 }
7973
7974 /* Update curr's vruntime before placing entity or updating lag */
update_curr_eevdf(struct cfs_rq * cfs_rq)7975 static inline void update_curr_eevdf(struct cfs_rq *cfs_rq)
7976 {
7977 if (!cfs_rq->curr)
7978 return;
7979
7980 update_curr(cfs_rq_of(cfs_rq->curr));
7981 }
7982
7983 /*
7984 * The enqueue_task method is called before nr_running is
7985 * increased. Here we update the fair scheduling stats and
7986 * then put the task into the rbtree:
7987 */
7988 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)7989 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7990 {
7991 int rq_h_nr_queued = rq->cfs.h_nr_queued;
7992 int task_new = !(flags & ENQUEUE_WAKEUP);
7993 struct sched_entity *se = &p->se;
7994 struct cfs_rq *cfs_rq = &rq->cfs;
7995 unsigned long weight;
7996 bool curr;
7997
7998 if (task_is_throttled(p) && enqueue_throttled_task(p))
7999 return;
8000
8001 /*
8002 * The code below (indirectly) updates schedutil which looks at
8003 * the cfs_rq utilization to select a frequency.
8004 * Let's add the task's estimated utilization to the cfs_rq's
8005 * estimated utilization, before we update schedutil.
8006 */
8007 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
8008 util_est_enqueue(cfs_rq, p);
8009
8010 update_curr_eevdf(cfs_rq);
8011
8012 if (flags & ENQUEUE_DELAYED) {
8013 requeue_delayed_entity(cfs_rq, se);
8014 return;
8015 }
8016
8017 /*
8018 * If in_iowait is set, the code below may not trigger any cpufreq
8019 * utilization updates, so do it here explicitly with the IOWAIT flag
8020 * passed.
8021 */
8022 if (p->in_iowait)
8023 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
8024
8025 /*
8026 * XXX comment on the curr thing
8027 */
8028 curr = (cfs_rq->curr == se);
8029 if (curr)
8030 place_entity(cfs_rq, se, flags);
8031
8032 if (se->on_rq && se->sched_delayed)
8033 requeue_delayed_entity(cfs_rq, se);
8034
8035 weight = enqueue_hierarchy(p, flags);
8036
8037 if (!curr) {
8038 reweight_eevdf(cfs_rq, se, weight, false);
8039 place_entity(cfs_rq, se, flags | ENQUEUE_QUEUED);
8040 __enqueue_entity(cfs_rq, se);
8041 }
8042
8043 if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
8044 dl_server_start(&rq->fair_server);
8045
8046 /* At this point se is NULL and we are at root level*/
8047 add_nr_running(rq, 1);
8048
8049 /*
8050 * Since new tasks are assigned an initial util_avg equal to
8051 * half of the spare capacity of their CPU, tiny tasks have the
8052 * ability to cross the overutilized threshold, which will
8053 * result in the load balancer ruining all the task placement
8054 * done by EAS. As a way to mitigate that effect, do not account
8055 * for the first enqueue operation of new tasks during the
8056 * overutilized flag detection.
8057 *
8058 * A better way of solving this problem would be to wait for
8059 * the PELT signals of tasks to converge before taking them
8060 * into account, but that is not straightforward to implement,
8061 * and the following generally works well enough in practice.
8062 */
8063 if (!task_new)
8064 check_update_overutilized_status(rq);
8065
8066 assert_list_leaf_cfs_rq(rq);
8067
8068 hrtick_update(rq);
8069 }
8070
dequeue_hierarchy(struct task_struct * p,int flags)8071 static void dequeue_hierarchy(struct task_struct *p, int flags)
8072 {
8073 struct sched_entity *se = &p->se;
8074 bool task_sleep = flags & DEQUEUE_SLEEP;
8075 bool task_delayed = flags & DEQUEUE_DELAYED;
8076 bool task_throttled = flags & DEQUEUE_THROTTLE;
8077 int h_nr_runnable = 0;
8078 int h_nr_idle = task_has_idle_policy(p);
8079 bool dequeue = true;
8080
8081 if (task_sleep || task_delayed || !se->sched_delayed)
8082 h_nr_runnable = 1;
8083
8084 for_each_sched_entity(se) {
8085 struct cfs_rq *cfs_rq = cfs_rq_of(se);
8086
8087 update_curr(cfs_rq);
8088
8089 if (dequeue) {
8090 dequeue_entity(cfs_rq, se, flags);
8091 /* Don't dequeue parent if it has other entities besides us */
8092 if (cfs_rq->load.weight)
8093 dequeue = false;
8094 } else {
8095 update_load_avg(cfs_rq, se, UPDATE_TG);
8096 se_update_runnable(se);
8097 update_cfs_group(se);
8098 }
8099
8100 cfs_rq->h_nr_runnable -= h_nr_runnable;
8101 cfs_rq->h_nr_queued--;
8102 cfs_rq->h_nr_idle -= h_nr_idle;
8103
8104 if (cfs_rq_is_idle(cfs_rq))
8105 h_nr_idle = 1;
8106
8107 if (throttled_hierarchy(cfs_rq) && task_throttled)
8108 record_throttle_clock(cfs_rq);
8109
8110 flags |= DEQUEUE_SLEEP;
8111 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
8112 }
8113 }
8114
8115 /*
8116 * The part of dequeue_task_fair() that is needed to dequeue delayed tasks.
8117 *
8118 * Returns:
8119 * true - dequeued
8120 * false - delayed
8121 */
__dequeue_task(struct rq * rq,struct task_struct * p,int flags)8122 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags)
8123 {
8124 struct sched_entity *se = &p->se;
8125 struct cfs_rq *cfs_rq = &rq->cfs;
8126 bool was_sched_idle = sched_idle_rq(rq);
8127 bool task_sleep = flags & DEQUEUE_SLEEP;
8128 bool task_delayed = flags & DEQUEUE_DELAYED;
8129
8130 clear_buddies(cfs_rq, se);
8131
8132 update_curr_eevdf(cfs_rq);
8133 update_entity_lag(cfs_rq, se);
8134
8135 if (flags & DEQUEUE_DELAYED) {
8136 WARN_ON_ONCE(!se->sched_delayed);
8137 } else {
8138 bool delay = task_sleep;
8139 /*
8140 * DELAY_DEQUEUE relies on spurious wakeups, special task
8141 * states must not suffer spurious wakeups, excempt them.
8142 */
8143 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
8144 delay = false;
8145
8146 WARN_ON_ONCE(delay && se->sched_delayed);
8147
8148 if (sched_feat(DELAY_DEQUEUE) && delay &&
8149 !entity_eligible(cfs_rq, se)) {
8150 update_load_avg(cfs_rq_of(se), se, UPDATE_UTIL_EST);
8151 set_delayed(se);
8152 return false;
8153 }
8154 }
8155
8156 dequeue_hierarchy(p, flags);
8157
8158 if (sched_feat(PLACE_REL_DEADLINE) && !task_sleep) {
8159 se->deadline -= se->vruntime;
8160 se->rel_deadline = 1;
8161 }
8162 if (se != cfs_rq->curr)
8163 __dequeue_entity(cfs_rq, se);
8164
8165 sub_nr_running(rq, 1);
8166
8167 /* balance early to pull high priority tasks */
8168 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
8169 rq->next_balance = jiffies;
8170
8171 if (task_delayed) {
8172 clear_delayed(se);
8173
8174 WARN_ON_ONCE(!task_sleep);
8175 WARN_ON_ONCE(p->on_rq != 1);
8176
8177 /*
8178 * Fix-up what block_task() skipped.
8179 *
8180 * Must be last, @p might not be valid after this.
8181 */
8182 __block_task(rq, p);
8183 }
8184
8185 return true;
8186 }
8187
8188 /*
8189 * The dequeue_task method is called before nr_running is
8190 * decreased. We remove the task from the rbtree and
8191 * update the fair scheduling stats:
8192 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)8193 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
8194 {
8195 if (task_is_throttled(p)) {
8196 dequeue_throttled_task(p, flags);
8197 return true;
8198 }
8199
8200 if (!p->se.sched_delayed)
8201 util_est_dequeue(&rq->cfs, p);
8202
8203 if (!__dequeue_task(rq, p, flags))
8204 return false;
8205
8206 /*
8207 * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED).
8208 */
8209 return true;
8210 }
8211
cfs_h_nr_delayed(struct rq * rq)8212 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
8213 {
8214 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
8215 }
8216
8217 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
8218 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
8219 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
8220 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
8221
8222 #ifdef CONFIG_NO_HZ_COMMON
8223
8224 static struct {
8225 cpumask_var_t idle_cpus_mask;
8226 int has_blocked_load; /* Idle CPUS has blocked load */
8227 int needs_update; /* Newly idle CPUs need their next_balance collated */
8228 unsigned long next_balance; /* in jiffy units */
8229 unsigned long next_blocked; /* Next update of blocked load in jiffies */
8230 } nohz ____cacheline_aligned;
8231
8232 #endif /* CONFIG_NO_HZ_COMMON */
8233
cpu_load(struct rq * rq)8234 static unsigned long cpu_load(struct rq *rq)
8235 {
8236 return cfs_rq_load_avg(&rq->cfs);
8237 }
8238
8239 /*
8240 * cpu_load_without - compute CPU load without any contributions from *p
8241 * @cpu: the CPU which load is requested
8242 * @p: the task which load should be discounted
8243 *
8244 * The load of a CPU is defined by the load of tasks currently enqueued on that
8245 * CPU as well as tasks which are currently sleeping after an execution on that
8246 * CPU.
8247 *
8248 * This method returns the load of the specified CPU by discounting the load of
8249 * the specified task, whenever the task is currently contributing to the CPU
8250 * load.
8251 */
cpu_load_without(struct rq * rq,struct task_struct * p)8252 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
8253 {
8254 struct cfs_rq *cfs_rq;
8255 unsigned int load;
8256
8257 /* Task has no contribution or is new */
8258 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8259 return cpu_load(rq);
8260
8261 cfs_rq = &rq->cfs;
8262 load = READ_ONCE(cfs_rq->avg.load_avg);
8263
8264 /* Discount task's util from CPU's util */
8265 lsub_positive(&load, task_h_load(p));
8266
8267 return load;
8268 }
8269
cpu_runnable(struct rq * rq)8270 static unsigned long cpu_runnable(struct rq *rq)
8271 {
8272 return cfs_rq_runnable_avg(&rq->cfs);
8273 }
8274
cpu_runnable_without(struct rq * rq,struct task_struct * p)8275 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
8276 {
8277 struct cfs_rq *cfs_rq;
8278 unsigned int runnable;
8279
8280 /* Task has no contribution or is new */
8281 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8282 return cpu_runnable(rq);
8283
8284 cfs_rq = &rq->cfs;
8285 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
8286
8287 /* Discount task's runnable from CPU's runnable */
8288 lsub_positive(&runnable, p->se.avg.runnable_avg);
8289
8290 return runnable;
8291 }
8292
capacity_of(int cpu)8293 static unsigned long capacity_of(int cpu)
8294 {
8295 return cpu_rq(cpu)->cpu_capacity;
8296 }
8297
record_wakee(struct task_struct * p)8298 static void record_wakee(struct task_struct *p)
8299 {
8300 /*
8301 * Only decay a single time; tasks that have less then 1 wakeup per
8302 * jiffy will not have built up many flips.
8303 */
8304 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
8305 current->wakee_flips >>= 1;
8306 current->wakee_flip_decay_ts = jiffies;
8307 }
8308
8309 if (current->last_wakee != p) {
8310 current->last_wakee = p;
8311 current->wakee_flips++;
8312 }
8313 }
8314
8315 /*
8316 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
8317 *
8318 * A waker of many should wake a different task than the one last awakened
8319 * at a frequency roughly N times higher than one of its wakees.
8320 *
8321 * In order to determine whether we should let the load spread vs consolidating
8322 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
8323 * partner, and a factor of lls_size higher frequency in the other.
8324 *
8325 * With both conditions met, we can be relatively sure that the relationship is
8326 * non-monogamous, with partner count exceeding socket size.
8327 *
8328 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
8329 * whatever is irrelevant, spread criteria is apparent partner count exceeds
8330 * socket size.
8331 */
wake_wide(struct task_struct * p)8332 static int wake_wide(struct task_struct *p)
8333 {
8334 unsigned int master = current->wakee_flips;
8335 unsigned int slave = p->wakee_flips;
8336 int factor = __this_cpu_read(sd_llc_size);
8337
8338 if (master < slave)
8339 swap(master, slave);
8340 if (slave < factor || master < slave * factor)
8341 return 0;
8342 return 1;
8343 }
8344
8345 /*
8346 * The purpose of wake_affine() is to quickly determine on which CPU we can run
8347 * soonest. For the purpose of speed we only consider the waking and previous
8348 * CPU.
8349 *
8350 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
8351 * cache-affine and is (or will be) idle.
8352 *
8353 * wake_affine_weight() - considers the weight to reflect the average
8354 * scheduling latency of the CPUs. This seems to work
8355 * for the overloaded case.
8356 */
8357 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)8358 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
8359 {
8360 /*
8361 * If this_cpu is idle, it implies the wakeup is from interrupt
8362 * context. Only allow the move if cache is shared. Otherwise an
8363 * interrupt intensive workload could force all tasks onto one
8364 * node depending on the IO topology or IRQ affinity settings.
8365 *
8366 * If the prev_cpu is idle and cache affine then avoid a migration.
8367 * There is no guarantee that the cache hot data from an interrupt
8368 * is more important than cache hot data on the prev_cpu and from
8369 * a cpufreq perspective, it's better to have higher utilisation
8370 * on one CPU.
8371 */
8372 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
8373 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
8374
8375 if (sync) {
8376 struct rq *rq = cpu_rq(this_cpu);
8377
8378 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
8379 return this_cpu;
8380 }
8381
8382 if (available_idle_cpu(prev_cpu))
8383 return prev_cpu;
8384
8385 return nr_cpumask_bits;
8386 }
8387
8388 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)8389 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
8390 int this_cpu, int prev_cpu, int sync)
8391 {
8392 s64 this_eff_load, prev_eff_load;
8393 unsigned long task_load;
8394
8395 this_eff_load = cpu_load(cpu_rq(this_cpu));
8396
8397 if (sync) {
8398 unsigned long current_load = task_h_load(current);
8399
8400 if (current_load > this_eff_load)
8401 return this_cpu;
8402
8403 this_eff_load -= current_load;
8404 }
8405
8406 task_load = task_h_load(p);
8407
8408 this_eff_load += task_load;
8409 if (sched_feat(WA_BIAS))
8410 this_eff_load *= 100;
8411 this_eff_load *= capacity_of(prev_cpu);
8412
8413 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
8414 prev_eff_load -= task_load;
8415 if (sched_feat(WA_BIAS))
8416 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
8417 prev_eff_load *= capacity_of(this_cpu);
8418
8419 /*
8420 * If sync, adjust the weight of prev_eff_load such that if
8421 * prev_eff == this_eff that select_idle_sibling() will consider
8422 * stacking the wakee on top of the waker if no other CPU is
8423 * idle.
8424 */
8425 if (sync)
8426 prev_eff_load += 1;
8427
8428 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
8429 }
8430
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)8431 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
8432 int this_cpu, int prev_cpu, int sync)
8433 {
8434 int target = nr_cpumask_bits;
8435
8436 if (sched_feat(WA_IDLE))
8437 target = wake_affine_idle(this_cpu, prev_cpu, sync);
8438
8439 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
8440 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
8441
8442 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
8443 if (target != this_cpu)
8444 return prev_cpu;
8445
8446 schedstat_inc(sd->ttwu_move_affine);
8447 schedstat_inc(p->stats.nr_wakeups_affine);
8448 return target;
8449 }
8450
8451 static struct sched_group *
8452 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
8453
8454 /*
8455 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
8456 */
8457 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)8458 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
8459 {
8460 unsigned long load, min_load = ULONG_MAX;
8461 unsigned int min_exit_latency = UINT_MAX;
8462 u64 latest_idle_timestamp = 0;
8463 int least_loaded_cpu = this_cpu;
8464 int shallowest_idle_cpu = -1;
8465 int i;
8466
8467 /* Check if we have any choice: */
8468 if (group->group_weight == 1)
8469 return cpumask_first(sched_group_span(group));
8470
8471 /* Traverse only the allowed CPUs */
8472 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
8473 struct rq *rq = cpu_rq(i);
8474
8475 if (!sched_core_cookie_match(rq, p))
8476 continue;
8477
8478 if (choose_sched_idle_rq(rq, p))
8479 return i;
8480
8481 if (available_idle_cpu(i)) {
8482 struct cpuidle_state *idle = idle_get_state(rq);
8483 if (idle && idle->exit_latency < min_exit_latency) {
8484 /*
8485 * We give priority to a CPU whose idle state
8486 * has the smallest exit latency irrespective
8487 * of any idle timestamp.
8488 */
8489 min_exit_latency = idle->exit_latency;
8490 latest_idle_timestamp = rq->idle_stamp;
8491 shallowest_idle_cpu = i;
8492 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
8493 rq->idle_stamp > latest_idle_timestamp) {
8494 /*
8495 * If equal or no active idle state, then
8496 * the most recently idled CPU might have
8497 * a warmer cache.
8498 */
8499 latest_idle_timestamp = rq->idle_stamp;
8500 shallowest_idle_cpu = i;
8501 }
8502 } else if (shallowest_idle_cpu == -1) {
8503 load = cpu_load(cpu_rq(i));
8504 if (load < min_load) {
8505 min_load = load;
8506 least_loaded_cpu = i;
8507 }
8508 }
8509 }
8510
8511 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
8512 }
8513
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)8514 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
8515 int cpu, int prev_cpu, int sd_flag)
8516 {
8517 int new_cpu = cpu;
8518
8519 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
8520 return prev_cpu;
8521
8522 /*
8523 * We need task's util for cpu_util_without, sync it up to
8524 * prev_cpu's last_update_time.
8525 */
8526 if (!(sd_flag & SD_BALANCE_FORK))
8527 sync_entity_load_avg(&p->se);
8528
8529 while (sd) {
8530 struct sched_group *group;
8531 struct sched_domain *tmp;
8532 int weight;
8533
8534 if (!(sd->flags & sd_flag)) {
8535 sd = sd->child;
8536 continue;
8537 }
8538
8539 group = sched_balance_find_dst_group(sd, p, cpu);
8540 if (!group) {
8541 sd = sd->child;
8542 continue;
8543 }
8544
8545 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
8546 if (new_cpu == cpu) {
8547 /* Now try balancing at a lower domain level of 'cpu': */
8548 sd = sd->child;
8549 continue;
8550 }
8551
8552 /* Now try balancing at a lower domain level of 'new_cpu': */
8553 cpu = new_cpu;
8554 weight = sd->span_weight;
8555 sd = NULL;
8556 for_each_domain(cpu, tmp) {
8557 if (weight <= tmp->span_weight)
8558 break;
8559 if (tmp->flags & sd_flag)
8560 sd = tmp;
8561 }
8562 }
8563
8564 return new_cpu;
8565 }
8566
__select_idle_cpu(int cpu,struct task_struct * p)8567 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
8568 {
8569 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p))
8570 return cpu;
8571
8572 return -1;
8573 }
8574
8575 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
8576 EXPORT_SYMBOL_GPL(sched_smt_present);
8577
set_idle_cores(int cpu,int val)8578 static inline void set_idle_cores(int cpu, int val)
8579 {
8580 struct sched_domain_shared *sds;
8581
8582 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8583 if (sds)
8584 WRITE_ONCE(sds->has_idle_cores, val);
8585 }
8586
test_idle_cores(int cpu)8587 static inline bool test_idle_cores(int cpu)
8588 {
8589 struct sched_domain_shared *sds;
8590
8591 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
8592 if (sds)
8593 return READ_ONCE(sds->has_idle_cores);
8594
8595 return false;
8596 }
8597
8598 /*
8599 * Scans the local SMT mask to see if the entire core is idle, and records this
8600 * information in sd_balance_shared->has_idle_cores.
8601 *
8602 * Since SMT siblings share all cache levels, inspecting this limited remote
8603 * state should be fairly cheap.
8604 */
__update_idle_core(struct rq * rq)8605 void __update_idle_core(struct rq *rq)
8606 {
8607 int core = cpu_of(rq);
8608 int cpu;
8609
8610 rcu_read_lock();
8611 if (test_idle_cores(core))
8612 goto unlock;
8613
8614 for_each_cpu(cpu, cpu_smt_mask(core)) {
8615 if (cpu == core)
8616 continue;
8617
8618 if (!available_idle_cpu(cpu))
8619 goto unlock;
8620 }
8621
8622 set_idle_cores(core, 1);
8623 unlock:
8624 rcu_read_unlock();
8625 }
8626
8627 /*
8628 * Scan the entire LLC domain for idle cores; this dynamically switches off if
8629 * there are no idle cores left in the system; tracked through
8630 * sd_balance_shared->has_idle_cores and enabled through update_idle_core()
8631 * above.
8632 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)8633 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
8634 {
8635 bool idle = true;
8636 int cpu;
8637
8638 for_each_cpu(cpu, cpu_smt_mask(core)) {
8639 if (!available_idle_cpu(cpu)) {
8640 idle = false;
8641 if (*idle_cpu == -1) {
8642 if (choose_sched_idle_rq(cpu_rq(cpu), p) &&
8643 cpumask_test_cpu(cpu, cpus)) {
8644 *idle_cpu = cpu;
8645 break;
8646 }
8647 continue;
8648 }
8649 break;
8650 }
8651 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
8652 *idle_cpu = cpu;
8653 }
8654
8655 if (idle)
8656 return core;
8657
8658 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
8659 return -1;
8660 }
8661
8662 /*
8663 * Scan the local SMT mask for idle CPUs.
8664 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)8665 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
8666 {
8667 int cpu;
8668
8669 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
8670 if (cpu == target)
8671 continue;
8672 /*
8673 * Check if the CPU is in the LLC scheduling domain of @target.
8674 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
8675 */
8676 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8677 continue;
8678 if (choose_idle_cpu(cpu, p))
8679 return cpu;
8680 }
8681
8682 return -1;
8683 }
8684
8685 /*
8686 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
8687 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
8688 * average idle time for this rq (as found in rq->avg_idle).
8689 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)8690 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
8691 {
8692 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8693 int i, cpu, idle_cpu = -1, nr = INT_MAX;
8694
8695 if (sched_feat(SIS_UTIL) && sd->shared) {
8696 /*
8697 * Increment because !--nr is the condition to stop scan.
8698 *
8699 * Since "sd" is "sd_llc" for target CPU dereferenced in the
8700 * caller, it is safe to directly dereference "sd->shared".
8701 * Topology bits always ensure it assigned for "sd_llc" abd it
8702 * cannot disappear as long as we have a RCU protected
8703 * reference to one the associated "sd" here.
8704 */
8705 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
8706 /* overloaded LLC is unlikely to have idle cpu/core */
8707 if (nr == 1)
8708 return -1;
8709 }
8710
8711 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr))
8712 return -1;
8713
8714 if (static_branch_unlikely(&sched_cluster_active)) {
8715 struct sched_group *sg = sd->groups;
8716
8717 if (sg->flags & SD_CLUSTER) {
8718 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
8719 if (!cpumask_test_cpu(cpu, cpus))
8720 continue;
8721
8722 if (has_idle_core) {
8723 i = select_idle_core(p, cpu, cpus, &idle_cpu);
8724 if ((unsigned int)i < nr_cpumask_bits)
8725 return i;
8726 } else {
8727 if (--nr <= 0)
8728 return -1;
8729 idle_cpu = __select_idle_cpu(cpu, p);
8730 if ((unsigned int)idle_cpu < nr_cpumask_bits)
8731 return idle_cpu;
8732 }
8733 }
8734 cpumask_andnot(cpus, cpus, sched_group_span(sg));
8735 }
8736 }
8737
8738 for_each_cpu_wrap(cpu, cpus, target + 1) {
8739 if (has_idle_core) {
8740 i = select_idle_core(p, cpu, cpus, &idle_cpu);
8741 if ((unsigned int)i < nr_cpumask_bits)
8742 return i;
8743
8744 } else {
8745 if (--nr <= 0)
8746 return -1;
8747 idle_cpu = __select_idle_cpu(cpu, p);
8748 if ((unsigned int)idle_cpu < nr_cpumask_bits)
8749 break;
8750 }
8751 }
8752
8753 if (has_idle_core)
8754 set_idle_cores(target, false);
8755
8756 return idle_cpu;
8757 }
8758
8759 /*
8760 * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks,
8761 * where lower values indicate a better fit - see select_idle_capacity().
8762 *
8763 * A CPU that both fits the task and sits on a fully-idle SMT core is returned
8764 * immediately and is never assigned one of these ranks. On !SMT every CPU is
8765 * its own "core", so the early return covers all fits-and-idle cases and the
8766 * core-tier ranks below become unreachable.
8767 *
8768 * Rank Val Tier Meaning
8769 * ------------------------------ --- ------ ---------------------------
8770 * ASYM_IDLE_UCLAMP_MISFIT -4 core Idle core; capacity fits
8771 * util but uclamp_min misses.
8772 * ASYM_IDLE_COMPLETE_MISFIT -3 core Idle core; capacity does
8773 * not fit. Still beats every
8774 * thread-tier rank: a busy
8775 * sibling cuts effective
8776 * capacity more than a
8777 * misfit hurts a quiet core.
8778 * ASYM_IDLE_THREAD_FITS -2 thread Busy SMT sibling; capacity
8779 * fits util + uclamp.
8780 * ASYM_IDLE_THREAD_UCLAMP_MISFIT -1 thread Busy SMT sibling; capacity
8781 * fits but uclamp_min misses
8782 * (native util_fits_cpu()
8783 * return value).
8784 * ASYM_IDLE_THREAD_MISFIT 0 thread Busy SMT sibling; capacity
8785 * does not fit.
8786 *
8787 * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core,
8788 * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier:
8789 *
8790 * ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT (-4)
8791 * ASYM_IDLE_THREAD_MISFIT (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3)
8792 *
8793 * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core
8794 * candidate early-returns from select_idle_capacity().
8795 */
8796 enum asym_fits_state {
8797 ASYM_IDLE_UCLAMP_MISFIT = -4,
8798 ASYM_IDLE_COMPLETE_MISFIT,
8799 ASYM_IDLE_THREAD_FITS,
8800 ASYM_IDLE_THREAD_UCLAMP_MISFIT,
8801 ASYM_IDLE_THREAD_MISFIT,
8802
8803 /* util_fits_cpu() bias for idle core */
8804 ASYM_IDLE_CORE_BIAS = -3,
8805 };
8806
8807 /*
8808 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
8809 * the task fits. If no CPU is big enough, but there are idle ones, try to
8810 * maximize capacity.
8811 */
8812 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)8813 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
8814 {
8815 /*
8816 * On !SMT systems, has_idle_core is always false and preferred_core
8817 * is always true (CPU == core), so the SMT preference logic below
8818 * collapses to the plain capacity scan.
8819 */
8820 bool has_idle_core = sched_smt_active() && test_idle_cores(target);
8821 unsigned long task_util, util_min, util_max, best_cap = 0;
8822 int fits, best_fits = ASYM_IDLE_THREAD_MISFIT;
8823 int cpu, best_cpu = -1;
8824 struct cpumask *cpus;
8825 int nr = INT_MAX;
8826
8827 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8828 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
8829
8830 task_util = task_util_est(p);
8831 util_min = uclamp_eff_value(p, UCLAMP_MIN);
8832 util_max = uclamp_eff_value(p, UCLAMP_MAX);
8833
8834 if (sched_feat(SIS_UTIL) && sd->shared) {
8835 /*
8836 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits
8837 * the scan when not preferring an idle core.
8838 */
8839 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
8840 /* overloaded domain is unlikely to have idle cpu/core */
8841 if (nr == 1)
8842 return -1;
8843 }
8844
8845 for_each_cpu_wrap(cpu, cpus, target) {
8846 bool preferred_core = !has_idle_core || is_core_idle(cpu);
8847 unsigned long cpu_cap = capacity_of(cpu);
8848
8849 /*
8850 * Stop when the nr_idle_scan is exhausted (mirrors
8851 * select_idle_cpu() logic).
8852 */
8853 if (!has_idle_core && --nr <= 0)
8854 return best_cpu;
8855
8856 if (!choose_idle_cpu(cpu, p))
8857 continue;
8858
8859 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
8860
8861 /*
8862 * Perfect fit: capacity satisfies util + uclamp and the CPU
8863 * sits on a fully-idle SMT core, this is a !SMT system, or
8864 * there is no idle core to find.
8865 * Short-circuit the rank-based selection and return
8866 * immediately.
8867 */
8868 if (fits > 0 && preferred_core)
8869 return cpu;
8870 /*
8871 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
8872 * Look for the CPU with best capacity.
8873 */
8874 else if (fits < 0)
8875 cpu_cap = get_actual_cpu_capacity(cpu);
8876 /*
8877 * fits > 0 implies we are not on a preferred core, but the util
8878 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS
8879 * so the effective range becomes
8880 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where:
8881 * ASYM_IDLE_THREAD_MISFIT - does not fit
8882 * ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN
8883 * ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core
8884 */
8885 else if (fits > 0)
8886 fits = ASYM_IDLE_THREAD_FITS;
8887
8888 /*
8889 * If we are on a preferred core, translate the range of fits
8890 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to
8891 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT].
8892 * This ensures that an idle core is always given priority over
8893 * (partially) busy core.
8894 *
8895 * A fully fitting idle core would have returned early and hence
8896 * fits > 0 for preferred_core need not be dealt with.
8897 */
8898 if (preferred_core)
8899 fits += ASYM_IDLE_CORE_BIAS;
8900
8901 /*
8902 * First, select CPU which fits better (lower is more preferred).
8903 * Then, select the one with best capacity at same level.
8904 */
8905 if ((fits < best_fits) ||
8906 ((fits == best_fits) && (cpu_cap > best_cap))) {
8907 best_cap = cpu_cap;
8908 best_cpu = cpu;
8909 best_fits = fits;
8910 }
8911 }
8912
8913 /*
8914 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]
8915 * range means the chosen CPU is in a fully idle SMT core. Values above
8916 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best.
8917 *
8918 * The asym-capacity wakeup path returns from select_idle_sibling()
8919 * after this function and never runs select_idle_cpu(), so the usual
8920 * select_idle_cpu() tail that clears idle cores must live here when the
8921 * idle-core preference did not win.
8922 */
8923 if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT)
8924 set_idle_cores(target, false);
8925
8926 return best_cpu;
8927 }
8928
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)8929 static inline bool asym_fits_cpu(unsigned long util,
8930 unsigned long util_min,
8931 unsigned long util_max,
8932 int cpu)
8933 {
8934 if (sched_asym_cpucap_active()) {
8935 /*
8936 * Return true only if the cpu fully fits the task requirements
8937 * which include the utilization and the performance hints.
8938 *
8939 * When SMT is active, also require that the core has no busy
8940 * siblings.
8941 *
8942 * Note: gating on is_core_idle() also makes the early-bailout
8943 * candidates in select_idle_sibling() (target, prev,
8944 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the
8945 * NO_ASYM path does not do.
8946 */
8947 return (!sched_smt_active() || is_core_idle(cpu)) &&
8948 (util_fits_cpu(util, util_min, util_max, cpu) > 0);
8949 }
8950
8951 return true;
8952 }
8953
8954 /*
8955 * Try and locate an idle core/thread in the LLC cache domain.
8956 */
select_idle_sibling(struct task_struct * p,int prev,int target)8957 static int select_idle_sibling(struct task_struct *p, int prev, int target)
8958 {
8959 bool has_idle_core = false;
8960 struct sched_domain *sd;
8961 unsigned long task_util, util_min, util_max;
8962 int i, recent_used_cpu, prev_aff = -1;
8963
8964 /*
8965 * On asymmetric system, update task utilization because we will check
8966 * that the task fits with CPU's capacity.
8967 */
8968 if (sched_asym_cpucap_active()) {
8969 sync_entity_load_avg(&p->se);
8970 task_util = task_util_est(p);
8971 util_min = uclamp_eff_value(p, UCLAMP_MIN);
8972 util_max = uclamp_eff_value(p, UCLAMP_MAX);
8973 }
8974
8975 /*
8976 * per-cpu select_rq_mask usage
8977 */
8978 lockdep_assert_irqs_disabled();
8979
8980 if (choose_idle_cpu(target, p) &&
8981 asym_fits_cpu(task_util, util_min, util_max, target))
8982 return target;
8983
8984 /*
8985 * If the previous CPU is cache affine and idle, don't be stupid:
8986 */
8987 if (prev != target && cpus_share_cache(prev, target) &&
8988 choose_idle_cpu(prev, p) &&
8989 asym_fits_cpu(task_util, util_min, util_max, prev)) {
8990
8991 if (!static_branch_unlikely(&sched_cluster_active) ||
8992 cpus_share_resources(prev, target))
8993 return prev;
8994
8995 prev_aff = prev;
8996 }
8997
8998 /*
8999 * Allow a per-cpu kthread to stack with the wakee if the
9000 * kworker thread and the tasks previous CPUs are the same.
9001 * The assumption is that the wakee queued work for the
9002 * per-cpu kthread that is now complete and the wakeup is
9003 * essentially a sync wakeup. An obvious example of this
9004 * pattern is IO completions.
9005 */
9006 if (is_per_cpu_kthread(current) &&
9007 in_task() &&
9008 prev == smp_processor_id() &&
9009 this_rq()->nr_running <= 1 &&
9010 asym_fits_cpu(task_util, util_min, util_max, prev)) {
9011 return prev;
9012 }
9013
9014 /* Check a recently used CPU as a potential idle candidate: */
9015 recent_used_cpu = p->recent_used_cpu;
9016 p->recent_used_cpu = prev;
9017 if (recent_used_cpu != prev &&
9018 recent_used_cpu != target &&
9019 cpus_share_cache(recent_used_cpu, target) &&
9020 choose_idle_cpu(recent_used_cpu, p) &&
9021 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
9022 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
9023
9024 if (!static_branch_unlikely(&sched_cluster_active) ||
9025 cpus_share_resources(recent_used_cpu, target))
9026 return recent_used_cpu;
9027
9028 } else {
9029 recent_used_cpu = -1;
9030 }
9031
9032 /*
9033 * For asymmetric CPU capacity systems, our domain of interest is
9034 * sd_asym_cpucapacity rather than sd_llc.
9035 */
9036 if (sched_asym_cpucap_active()) {
9037 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target));
9038 /*
9039 * On an asymmetric CPU capacity system where an exclusive
9040 * cpuset defines a symmetric island (i.e. one unique
9041 * capacity_orig value through the cpuset), the key will be set
9042 * but the CPUs within that cpuset will not have a domain with
9043 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
9044 * capacity path.
9045 */
9046 if (sd) {
9047 i = select_idle_capacity(p, sd, target);
9048 return ((unsigned)i < nr_cpumask_bits) ? i : target;
9049 }
9050 }
9051
9052 sd = rcu_dereference_all(per_cpu(sd_llc, target));
9053 if (!sd)
9054 return target;
9055
9056 if (sched_smt_active()) {
9057 has_idle_core = test_idle_cores(target);
9058
9059 if (!has_idle_core && cpus_share_cache(prev, target)) {
9060 i = select_idle_smt(p, sd, prev);
9061 if ((unsigned int)i < nr_cpumask_bits)
9062 return i;
9063 }
9064 }
9065
9066 i = select_idle_cpu(p, sd, has_idle_core, target);
9067 if ((unsigned)i < nr_cpumask_bits)
9068 return i;
9069
9070 /*
9071 * For cluster machines which have lower sharing cache like L2 or
9072 * LLC Tag, we tend to find an idle CPU in the target's cluster
9073 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
9074 * use them if possible when no idle CPU found in select_idle_cpu().
9075 */
9076 if ((unsigned int)prev_aff < nr_cpumask_bits)
9077 return prev_aff;
9078 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
9079 return recent_used_cpu;
9080
9081 return target;
9082 }
9083
9084 /**
9085 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
9086 * @cpu: the CPU to get the utilization for
9087 * @p: task for which the CPU utilization should be predicted or NULL
9088 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
9089 * @boost: 1 to enable boosting, otherwise 0
9090 *
9091 * The unit of the return value must be the same as the one of CPU capacity
9092 * so that CPU utilization can be compared with CPU capacity.
9093 *
9094 * CPU utilization is the sum of running time of runnable tasks plus the
9095 * recent utilization of currently non-runnable tasks on that CPU.
9096 * It represents the amount of CPU capacity currently used by CFS tasks in
9097 * the range [0..max CPU capacity] with max CPU capacity being the CPU
9098 * capacity at f_max.
9099 *
9100 * The estimated CPU utilization is defined as the maximum between CPU
9101 * utilization and sum of the estimated utilization of the currently
9102 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
9103 * previously-executed tasks, which helps better deduce how busy a CPU will
9104 * be when a long-sleeping task wakes up. The contribution to CPU utilization
9105 * of such a task would be significantly decayed at this point of time.
9106 *
9107 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
9108 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
9109 * utilization. Boosting is implemented in cpu_util() so that internal
9110 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
9111 * latter via cpu_util_cfs_boost().
9112 *
9113 * CPU utilization can be higher than the current CPU capacity
9114 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
9115 * of rounding errors as well as task migrations or wakeups of new tasks.
9116 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
9117 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
9118 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
9119 * capacity. CPU utilization is allowed to overshoot current CPU capacity
9120 * though since this is useful for predicting the CPU capacity required
9121 * after task migrations (scheduler-driven DVFS).
9122 *
9123 * Return: (Boosted) (estimated) utilization for the specified CPU.
9124 */
9125 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)9126 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
9127 {
9128 bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu;
9129 bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu;
9130 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
9131 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
9132 unsigned long runnable;
9133
9134 /*
9135 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
9136 * contribution. If @p migrates from another CPU to @cpu add its
9137 * contribution. In all the other cases @cpu is not impacted by the
9138 * migration so its util_avg is already correct.
9139 */
9140 if (add_task)
9141 util += task_util(p);
9142 else if (sub_task)
9143 lsub_positive(&util, task_util(p));
9144
9145 if (boost) {
9146 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
9147 if (add_task)
9148 runnable += READ_ONCE(p->se.avg.runnable_avg);
9149 else if (sub_task)
9150 lsub_positive(&runnable,
9151 READ_ONCE(p->se.avg.runnable_avg));
9152 util = max(util, runnable);
9153 }
9154
9155 if (sched_feat(UTIL_EST)) {
9156 unsigned long util_est;
9157
9158 util_est = READ_ONCE(cfs_rq->avg.util_est);
9159
9160 /*
9161 * During wake-up @p isn't enqueued yet and doesn't contribute
9162 * to any cpu_rq(cpu)->cfs.avg.util_est.
9163 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
9164 * has been enqueued.
9165 *
9166 * During exec (@dst_cpu = -1) @p is enqueued and does
9167 * contribute to cpu_rq(cpu)->cfs.util_est.
9168 * Remove it to "simulate" cpu_util without @p's contribution.
9169 *
9170 * Despite the task_on_rq_queued(@p) check there is still a
9171 * small window for a possible race when an exec
9172 * select_task_rq_fair() races with LB's detach_task().
9173 *
9174 * detach_task()
9175 * deactivate_task()
9176 * p->on_rq = TASK_ON_RQ_MIGRATING;
9177 * -------------------------------- A
9178 * dequeue_task() \
9179 * dequeue_task_fair() + Race Time
9180 * util_est_dequeue() /
9181 * -------------------------------- B
9182 *
9183 * The additional check "current == p" is required to further
9184 * reduce the race window.
9185 */
9186 if (dst_cpu == cpu)
9187 util_est += _task_util_est(p);
9188 else if (p && unlikely(task_on_rq_queued(p) || current == p))
9189 lsub_positive(&util_est, _task_util_est(p));
9190
9191 util = max(util, util_est);
9192 }
9193
9194 return min(util, arch_scale_cpu_capacity(cpu));
9195 }
9196
cpu_util_cfs(int cpu)9197 unsigned long cpu_util_cfs(int cpu)
9198 {
9199 return cpu_util(cpu, NULL, -1, 0);
9200 }
9201
cpu_util_cfs_boost(int cpu)9202 unsigned long cpu_util_cfs_boost(int cpu)
9203 {
9204 return cpu_util(cpu, NULL, -1, 1);
9205 }
9206
9207 /*
9208 * cpu_util_without: compute cpu utilization without any contributions from *p
9209 * @cpu: the CPU which utilization is requested
9210 * @p: the task which utilization should be discounted
9211 *
9212 * The utilization of a CPU is defined by the utilization of tasks currently
9213 * enqueued on that CPU as well as tasks which are currently sleeping after an
9214 * execution on that CPU.
9215 *
9216 * This method returns the utilization of the specified CPU by discounting the
9217 * utilization of the specified task, whenever the task is currently
9218 * contributing to the CPU utilization.
9219 */
cpu_util_without(int cpu,struct task_struct * p)9220 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
9221 {
9222 /* Task has no contribution or is new */
9223 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9224 p = NULL;
9225
9226 return cpu_util(cpu, p, -1, 0);
9227 }
9228
9229 /*
9230 * This function computes an effective utilization for the given CPU, to be
9231 * used for frequency selection given the linear relation: f = u * f_max.
9232 *
9233 * The scheduler tracks the following metrics:
9234 *
9235 * cpu_util_{cfs,rt,dl,irq}()
9236 * cpu_bw_dl()
9237 *
9238 * Where the cfs,rt and dl util numbers are tracked with the same metric and
9239 * synchronized windows and are thus directly comparable.
9240 *
9241 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
9242 * which excludes things like IRQ and steal-time. These latter are then accrued
9243 * in the IRQ utilization.
9244 *
9245 * The DL bandwidth number OTOH is not a measured metric but a value computed
9246 * based on the task model parameters and gives the minimal utilization
9247 * required to meet deadlines.
9248 */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)9249 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
9250 unsigned long *min,
9251 unsigned long *max)
9252 {
9253 unsigned long util, irq, scale;
9254 struct rq *rq = cpu_rq(cpu);
9255
9256 scale = arch_scale_cpu_capacity(cpu);
9257
9258 /*
9259 * Early check to see if IRQ/steal time saturates the CPU, can be
9260 * because of inaccuracies in how we track these -- see
9261 * update_irq_load_avg().
9262 */
9263 irq = cpu_util_irq(rq);
9264 if (unlikely(irq >= scale)) {
9265 if (min)
9266 *min = scale;
9267 if (max)
9268 *max = scale;
9269 return scale;
9270 }
9271
9272 if (min) {
9273 /*
9274 * The minimum utilization returns the highest level between:
9275 * - the computed DL bandwidth needed with the IRQ pressure which
9276 * steals time to the deadline task.
9277 * - The minimum performance requirement for CFS and/or RT.
9278 */
9279 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
9280
9281 /*
9282 * When an RT task is runnable and uclamp is not used, we must
9283 * ensure that the task will run at maximum compute capacity.
9284 */
9285 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
9286 *min = max(*min, scale);
9287 }
9288
9289 /*
9290 * Because the time spend on RT/DL tasks is visible as 'lost' time to
9291 * CFS tasks and we use the same metric to track the effective
9292 * utilization (PELT windows are synchronized) we can directly add them
9293 * to obtain the CPU's actual utilization.
9294 */
9295 util = util_cfs + cpu_util_rt(rq);
9296 util += cpu_util_dl(rq);
9297
9298 /*
9299 * The maximum hint is a soft bandwidth requirement, which can be lower
9300 * than the actual utilization because of uclamp_max requirements.
9301 */
9302 if (max)
9303 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
9304
9305 if (util >= scale)
9306 return scale;
9307
9308 /*
9309 * There is still idle time; further improve the number by using the
9310 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
9311 * need to scale the task numbers:
9312 *
9313 * max - irq
9314 * U' = irq + --------- * U
9315 * max
9316 */
9317 util = scale_irq_capacity(util, irq, scale);
9318 util += irq;
9319
9320 return min(scale, util);
9321 }
9322
sched_cpu_util(int cpu)9323 unsigned long sched_cpu_util(int cpu)
9324 {
9325 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
9326 }
9327
9328 /*
9329 * energy_env - Utilization landscape for energy estimation.
9330 * @task_busy_time: Utilization contribution by the task for which we test the
9331 * placement. Given by eenv_task_busy_time().
9332 * @pd_busy_time: Utilization of the whole perf domain without the task
9333 * contribution. Given by eenv_pd_busy_time().
9334 * @cpu_cap: Maximum CPU capacity for the perf domain.
9335 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
9336 */
9337 struct energy_env {
9338 unsigned long task_busy_time;
9339 unsigned long pd_busy_time;
9340 unsigned long cpu_cap;
9341 unsigned long pd_cap;
9342 };
9343
9344 /*
9345 * Compute the task busy time for compute_energy(). This time cannot be
9346 * injected directly into effective_cpu_util() because of the IRQ scaling.
9347 * The latter only makes sense with the most recent CPUs where the task has
9348 * run.
9349 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)9350 static inline void eenv_task_busy_time(struct energy_env *eenv,
9351 struct task_struct *p, int prev_cpu)
9352 {
9353 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
9354 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
9355
9356 if (unlikely(irq >= max_cap))
9357 busy_time = max_cap;
9358 else
9359 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
9360
9361 eenv->task_busy_time = busy_time;
9362 }
9363
9364 /*
9365 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
9366 * utilization for each @pd_cpus, it however doesn't take into account
9367 * clamping since the ratio (utilization / cpu_capacity) is already enough to
9368 * scale the EM reported power consumption at the (eventually clamped)
9369 * cpu_capacity.
9370 *
9371 * The contribution of the task @p for which we want to estimate the
9372 * energy cost is removed (by cpu_util()) and must be calculated
9373 * separately (see eenv_task_busy_time). This ensures:
9374 *
9375 * - A stable PD utilization, no matter which CPU of that PD we want to place
9376 * the task on.
9377 *
9378 * - A fair comparison between CPUs as the task contribution (task_util())
9379 * will always be the same no matter which CPU utilization we rely on
9380 * (util_avg or util_est).
9381 *
9382 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
9383 * exceed @eenv->pd_cap.
9384 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)9385 static inline void eenv_pd_busy_time(struct energy_env *eenv,
9386 struct cpumask *pd_cpus,
9387 struct task_struct *p)
9388 {
9389 unsigned long busy_time = 0;
9390 int cpu;
9391
9392 for_each_cpu(cpu, pd_cpus) {
9393 unsigned long util = cpu_util(cpu, p, -1, 0);
9394
9395 busy_time += effective_cpu_util(cpu, util, NULL, NULL);
9396 }
9397
9398 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
9399 }
9400
9401 /*
9402 * Compute the maximum utilization for compute_energy() when the task @p
9403 * is placed on the cpu @dst_cpu.
9404 *
9405 * Returns the maximum utilization among @eenv->cpus. This utilization can't
9406 * exceed @eenv->cpu_cap.
9407 */
9408 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)9409 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
9410 struct task_struct *p, int dst_cpu)
9411 {
9412 unsigned long max_util = 0;
9413 int cpu;
9414
9415 for_each_cpu(cpu, pd_cpus) {
9416 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
9417 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
9418 unsigned long eff_util, min, max;
9419
9420 /*
9421 * Performance domain frequency: utilization clamping
9422 * must be considered since it affects the selection
9423 * of the performance domain frequency.
9424 * NOTE: in case RT tasks are running, by default the min
9425 * utilization can be max OPP.
9426 */
9427 eff_util = effective_cpu_util(cpu, util, &min, &max);
9428
9429 /* Task's uclamp can modify min and max value */
9430 if (tsk && uclamp_is_used()) {
9431 min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
9432
9433 /*
9434 * If there is no active max uclamp constraint,
9435 * directly use task's one, otherwise keep max.
9436 */
9437 if (uclamp_rq_is_idle(cpu_rq(cpu)))
9438 max = uclamp_eff_value(p, UCLAMP_MAX);
9439 else
9440 max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
9441 }
9442
9443 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
9444 max_util = max(max_util, eff_util);
9445 }
9446
9447 return min(max_util, eenv->cpu_cap);
9448 }
9449
9450 /*
9451 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
9452 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
9453 * contribution is ignored.
9454 */
9455 static inline unsigned long
compute_energy(struct energy_env * eenv,struct perf_domain * pd,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)9456 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
9457 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
9458 {
9459 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
9460 unsigned long busy_time = eenv->pd_busy_time;
9461 unsigned long energy;
9462
9463 if (dst_cpu >= 0)
9464 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
9465
9466 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
9467
9468 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
9469
9470 return energy;
9471 }
9472
9473 /*
9474 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
9475 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
9476 * spare capacity in each performance domain and uses it as a potential
9477 * candidate to execute the task. Then, it uses the Energy Model to figure
9478 * out which of the CPU candidates is the most energy-efficient.
9479 *
9480 * The rationale for this heuristic is as follows. In a performance domain,
9481 * all the most energy efficient CPU candidates (according to the Energy
9482 * Model) are those for which we'll request a low frequency. When there are
9483 * several CPUs for which the frequency request will be the same, we don't
9484 * have enough data to break the tie between them, because the Energy Model
9485 * only includes active power costs. With this model, if we assume that
9486 * frequency requests follow utilization (e.g. using schedutil), the CPU with
9487 * the maximum spare capacity in a performance domain is guaranteed to be among
9488 * the best candidates of the performance domain.
9489 *
9490 * In practice, it could be preferable from an energy standpoint to pack
9491 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
9492 * but that could also hurt our chances to go cluster idle, and we have no
9493 * ways to tell with the current Energy Model if this is actually a good
9494 * idea or not. So, find_energy_efficient_cpu() basically favors
9495 * cluster-packing, and spreading inside a cluster. That should at least be
9496 * a good thing for latency, and this is consistent with the idea that most
9497 * of the energy savings of EAS come from the asymmetry of the system, and
9498 * not so much from breaking the tie between identical CPUs. That's also the
9499 * reason why EAS is enabled in the topology code only for systems where
9500 * SD_ASYM_CPUCAPACITY is set.
9501 *
9502 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
9503 * they don't have any useful utilization data yet and it's not possible to
9504 * forecast their impact on energy consumption. Consequently, they will be
9505 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
9506 * to be energy-inefficient in some use-cases. The alternative would be to
9507 * bias new tasks towards specific types of CPUs first, or to try to infer
9508 * their util_avg from the parent task, but those heuristics could hurt
9509 * other use-cases too. So, until someone finds a better way to solve this,
9510 * let's keep things simple by re-using the existing slow path.
9511 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)9512 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
9513 {
9514 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
9515 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
9516 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
9517 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
9518 struct root_domain *rd = this_rq()->rd;
9519 int cpu, best_energy_cpu, target = -1;
9520 int prev_fits = -1, best_fits = -1;
9521 unsigned long best_actual_cap = 0;
9522 unsigned long prev_actual_cap = 0;
9523 struct sched_domain *sd;
9524 struct perf_domain *pd;
9525 struct energy_env eenv;
9526
9527 pd = rcu_dereference_all(rd->pd);
9528 if (!pd)
9529 return target;
9530
9531 /*
9532 * Energy-aware wake-up happens on the lowest sched_domain starting
9533 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
9534 */
9535 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity));
9536 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
9537 sd = sd->parent;
9538 if (!sd)
9539 return target;
9540
9541 target = prev_cpu;
9542
9543 sync_entity_load_avg(&p->se);
9544 if (!task_util_est(p) && p_util_min == 0)
9545 return target;
9546
9547 eenv_task_busy_time(&eenv, p, prev_cpu);
9548
9549 for (; pd; pd = pd->next) {
9550 unsigned long util_min = p_util_min, util_max = p_util_max;
9551 unsigned long cpu_cap, cpu_actual_cap, util;
9552 long prev_spare_cap = -1, max_spare_cap = -1;
9553 unsigned long rq_util_min, rq_util_max;
9554 unsigned long cur_delta, base_energy;
9555 int max_spare_cap_cpu = -1;
9556 int fits, max_fits = -1;
9557
9558 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask))
9559 continue;
9560
9561 /* Account external pressure for the energy estimation */
9562 cpu = cpumask_first(cpus);
9563 cpu_actual_cap = get_actual_cpu_capacity(cpu);
9564
9565 eenv.cpu_cap = cpu_actual_cap;
9566 eenv.pd_cap = 0;
9567
9568 for_each_cpu(cpu, cpus) {
9569 struct rq *rq = cpu_rq(cpu);
9570
9571 eenv.pd_cap += cpu_actual_cap;
9572
9573 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
9574 continue;
9575
9576 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
9577 continue;
9578
9579 util = cpu_util(cpu, p, cpu, 0);
9580 cpu_cap = capacity_of(cpu);
9581
9582 /*
9583 * Skip CPUs that cannot satisfy the capacity request.
9584 * IOW, placing the task there would make the CPU
9585 * overutilized. Take uclamp into account to see how
9586 * much capacity we can get out of the CPU; this is
9587 * aligned with sched_cpu_util().
9588 */
9589 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
9590 /*
9591 * Open code uclamp_rq_util_with() except for
9592 * the clamp() part. I.e.: apply max aggregation
9593 * only. util_fits_cpu() logic requires to
9594 * operate on non clamped util but must use the
9595 * max-aggregated uclamp_{min, max}.
9596 */
9597 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
9598 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
9599
9600 util_min = max(rq_util_min, p_util_min);
9601 util_max = max(rq_util_max, p_util_max);
9602 }
9603
9604 fits = util_fits_cpu(util, util_min, util_max, cpu);
9605 if (!fits)
9606 continue;
9607
9608 lsub_positive(&cpu_cap, util);
9609
9610 if (cpu == prev_cpu) {
9611 /* Always use prev_cpu as a candidate. */
9612 prev_spare_cap = cpu_cap;
9613 prev_fits = fits;
9614 } else if ((fits > max_fits) ||
9615 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
9616 /*
9617 * Find the CPU with the maximum spare capacity
9618 * among the remaining CPUs in the performance
9619 * domain.
9620 */
9621 max_spare_cap = cpu_cap;
9622 max_spare_cap_cpu = cpu;
9623 max_fits = fits;
9624 }
9625 }
9626
9627 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
9628 continue;
9629
9630 eenv_pd_busy_time(&eenv, cpus, p);
9631 /* Compute the 'base' energy of the pd, without @p */
9632 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
9633
9634 /* Evaluate the energy impact of using prev_cpu. */
9635 if (prev_spare_cap > -1) {
9636 prev_delta = compute_energy(&eenv, pd, cpus, p,
9637 prev_cpu);
9638 /* CPU utilization has changed */
9639 if (prev_delta < base_energy)
9640 return target;
9641 prev_delta -= base_energy;
9642 prev_actual_cap = cpu_actual_cap;
9643 best_delta = min(best_delta, prev_delta);
9644 }
9645
9646 /* Evaluate the energy impact of using max_spare_cap_cpu. */
9647 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
9648 /* Current best energy cpu fits better */
9649 if (max_fits < best_fits)
9650 continue;
9651
9652 /*
9653 * Both don't fit performance hint (i.e. uclamp_min)
9654 * but best energy cpu has better capacity.
9655 */
9656 if ((max_fits < 0) &&
9657 (cpu_actual_cap <= best_actual_cap))
9658 continue;
9659
9660 cur_delta = compute_energy(&eenv, pd, cpus, p,
9661 max_spare_cap_cpu);
9662 /* CPU utilization has changed */
9663 if (cur_delta < base_energy)
9664 return target;
9665 cur_delta -= base_energy;
9666
9667 /*
9668 * Both fit for the task but best energy cpu has lower
9669 * energy impact.
9670 */
9671 if ((max_fits > 0) && (best_fits > 0) &&
9672 (cur_delta >= best_delta))
9673 continue;
9674
9675 best_delta = cur_delta;
9676 best_energy_cpu = max_spare_cap_cpu;
9677 best_fits = max_fits;
9678 best_actual_cap = cpu_actual_cap;
9679 }
9680 }
9681
9682 if ((best_fits > prev_fits) ||
9683 ((best_fits > 0) && (best_delta < prev_delta)) ||
9684 ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
9685 target = best_energy_cpu;
9686
9687 return target;
9688 }
9689
9690 /*
9691 * select_task_rq_fair: Select target runqueue for the waking task in domains
9692 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
9693 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
9694 *
9695 * Balances load by selecting the idlest CPU in the idlest group, or under
9696 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
9697 *
9698 * Returns the target CPU number.
9699 */
9700 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)9701 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
9702 {
9703 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
9704 struct sched_domain *tmp, *sd = NULL;
9705 int cpu = smp_processor_id();
9706 int new_cpu = prev_cpu;
9707 int want_affine = 0;
9708 /* SD_flags and WF_flags share the first nibble */
9709 int sd_flag = wake_flags & 0xF;
9710
9711 /*
9712 * required for stable ->cpus_allowed
9713 */
9714 lockdep_assert_held(&p->pi_lock);
9715 if (wake_flags & WF_TTWU) {
9716 record_wakee(p);
9717
9718 if ((wake_flags & WF_CURRENT_CPU) &&
9719 cpumask_test_cpu(cpu, p->cpus_ptr))
9720 return cpu;
9721
9722 if (!is_rd_overutilized(this_rq()->rd)) {
9723 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
9724 if (new_cpu >= 0)
9725 return new_cpu;
9726 new_cpu = prev_cpu;
9727 }
9728
9729 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
9730 }
9731
9732 for_each_domain(cpu, tmp) {
9733 /*
9734 * If both 'cpu' and 'prev_cpu' are part of this domain,
9735 * cpu is a valid SD_WAKE_AFFINE target.
9736 */
9737 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
9738 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
9739 if (cpu != prev_cpu)
9740 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
9741
9742 sd = NULL; /* Prefer wake_affine over balance flags */
9743 break;
9744 }
9745
9746 /*
9747 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
9748 * usually do not have SD_BALANCE_WAKE set. That means wakeup
9749 * will usually go to the fast path.
9750 */
9751 if (tmp->flags & sd_flag)
9752 sd = tmp;
9753 else if (!want_affine)
9754 break;
9755 }
9756
9757 /* Slow path */
9758 if (unlikely(sd))
9759 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
9760
9761 /* Fast path */
9762 if (wake_flags & WF_TTWU)
9763 return select_idle_sibling(p, prev_cpu, new_cpu);
9764
9765 return new_cpu;
9766 }
9767
9768 /*
9769 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
9770 * cfs_rq_of(p) references at time of call are still valid and identify the
9771 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
9772 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)9773 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
9774 {
9775 struct sched_entity *se = &p->se;
9776
9777 if (!task_on_rq_migrating(p)) {
9778 remove_entity_load_avg(se);
9779
9780 /*
9781 * Here, the task's PELT values have been updated according to
9782 * the current rq's clock. But if that clock hasn't been
9783 * updated in a while, a substantial idle time will be missed,
9784 * leading to an inflation after wake-up on the new rq.
9785 *
9786 * Estimate the missing time from the cfs_rq last_update_time
9787 * and update sched_avg to improve the PELT continuity after
9788 * migration.
9789 */
9790 migrate_se_pelt_lag(se);
9791 }
9792
9793 /* Tell new CPU we are migrated */
9794 se->avg.last_update_time = 0;
9795
9796 update_scan_period(p, new_cpu);
9797 }
9798
task_dead_fair(struct task_struct * p)9799 static void task_dead_fair(struct task_struct *p)
9800 {
9801 struct sched_entity *se = &p->se;
9802 remove_entity_load_avg(se);
9803 }
9804
9805 /*
9806 * Set the max capacity the task is allowed to run at for misfit detection.
9807 */
set_task_max_allowed_capacity(struct task_struct * p)9808 static void set_task_max_allowed_capacity(struct task_struct *p)
9809 {
9810 struct asym_cap_data *entry;
9811
9812 if (!sched_asym_cpucap_active())
9813 return;
9814
9815 rcu_read_lock();
9816 list_for_each_entry_rcu(entry, &asym_cap_list, link) {
9817 cpumask_t *cpumask;
9818
9819 cpumask = cpu_capacity_span(entry);
9820 if (!cpumask_intersects(p->cpus_ptr, cpumask))
9821 continue;
9822
9823 p->max_allowed_capacity = entry->capacity;
9824 break;
9825 }
9826 rcu_read_unlock();
9827 }
9828
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)9829 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
9830 {
9831 set_cpus_allowed_common(p, ctx);
9832 set_task_max_allowed_capacity(p);
9833 }
9834
9835 enum preempt_wakeup_action {
9836 PREEMPT_WAKEUP_NONE, /* No preemption. */
9837 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */
9838 PREEMPT_WAKEUP_PICK, /* Let pick_eevdf() decide. */
9839 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */
9840 };
9841
set_preempt_buddy(struct cfs_rq * cfs_rq,struct sched_entity * pse)9842 static inline bool set_preempt_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
9843 {
9844 /*
9845 * Keep existing buddy if the deadline is sooner than pse.
9846 * The older buddy may be cache cold and completely unrelated
9847 * to the current wakeup but that is unpredictable where as
9848 * obeying the deadline is more in line with EEVDF objectives.
9849 */
9850 if (cfs_rq->next && entity_before(cfs_rq->next, pse))
9851 return false;
9852
9853 set_next_buddy(cfs_rq, pse);
9854 return true;
9855 }
9856
set_short_buddy(struct cfs_rq * cfs_rq,struct sched_entity * pse)9857 static inline bool set_short_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse)
9858 {
9859 if (cfs_rq->next && cfs_rq->next->slice < pse->slice)
9860 return false;
9861
9862 set_next_buddy(cfs_rq, pse);
9863 return true;
9864 }
9865
9866 /*
9867 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
9868 * strictly enforced because the hint is either misunderstood or
9869 * multiple tasks must be woken up.
9870 */
9871 static inline enum preempt_wakeup_action
preempt_sync(struct rq * rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)9872 preempt_sync(struct rq *rq, int wake_flags,
9873 struct sched_entity *pse, struct sched_entity *se)
9874 {
9875 u64 threshold, delta;
9876
9877 /*
9878 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
9879 * though it is likely harmless.
9880 */
9881 WARN_ON_ONCE(!(wake_flags & WF_TTWU));
9882
9883 threshold = sysctl_sched_migration_cost;
9884 delta = rq_clock_task(rq) - se->exec_start;
9885 if ((s64)delta < 0)
9886 delta = 0;
9887
9888 /*
9889 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
9890 * could run on other CPUs. Reduce the threshold before preemption is
9891 * allowed to an arbitrary lower value as it is more likely (but not
9892 * guaranteed) the waker requires the wakee to finish.
9893 */
9894 if (wake_flags & WF_RQ_SELECTED)
9895 threshold >>= 2;
9896
9897 /*
9898 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
9899 * wakeups to be issued.
9900 */
9901 if (entity_before(pse, se) && delta >= threshold)
9902 return PREEMPT_WAKEUP_RESCHED;
9903
9904 return PREEMPT_WAKEUP_NONE;
9905 }
9906
9907 /*
9908 * Preempt the current task with a newly woken task if needed:
9909 */
wakeup_preempt_fair(struct rq * rq,struct task_struct * p,int wake_flags)9910 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags)
9911 {
9912 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
9913 struct task_struct *donor = rq->donor;
9914 struct sched_entity *nse, *se = &donor->se, *pse = &p->se;
9915 struct cfs_rq *cfs_rq = &rq->cfs;
9916 int cse_is_idle, pse_is_idle;
9917
9918 /*
9919 * XXX Getting preempted by higher class, try and find idle CPU?
9920 */
9921 if (p->sched_class != &fair_sched_class ||
9922 donor->sched_class != &fair_sched_class)
9923 return;
9924
9925 if (unlikely(se == pse))
9926 return;
9927
9928 /*
9929 * This is possible from callers such as attach_tasks(), in which we
9930 * unconditionally wakeup_preempt() after an enqueue (which may have
9931 * lead to a throttle). This both saves work and prevents false
9932 * next-buddy nomination below.
9933 */
9934 if (task_is_throttled(p))
9935 return;
9936
9937 /*
9938 * We can come here with TIF_NEED_RESCHED already set from new task
9939 * wake up path.
9940 *
9941 * Note: this also catches the edge-case of curr being in a throttled
9942 * group (e.g. via set_curr_task), since update_curr() (in the
9943 * enqueue of curr) will have resulted in resched being set. This
9944 * prevents us from potentially nominating it as a false LAST_BUDDY
9945 * below.
9946 */
9947 if (!sched_feat(PREEMPT_SHORT) && test_tsk_need_resched(rq->curr))
9948 return;
9949
9950 if (!sched_feat(WAKEUP_PREEMPTION))
9951 return;
9952
9953 WARN_ON_ONCE(!pse);
9954
9955 cse_is_idle = se_is_idle(se);
9956 pse_is_idle = se_is_idle(pse);
9957
9958 nse = se;
9959 /*
9960 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
9961 * in the inverse case).
9962 */
9963 if (cse_is_idle && !pse_is_idle)
9964 goto preempt;
9965
9966 update_curr_fair(rq);
9967
9968 if (cse_is_idle != pse_is_idle)
9969 goto update;
9970
9971 /*
9972 * BATCH and IDLE tasks do not preempt others.
9973 */
9974 if (unlikely(!normal_policy(p->policy)))
9975 goto update;
9976
9977 /*
9978 * Do not preempt for tasks that are sched_delayed as it would violate
9979 * EEVDF to forcibly queue an ineligible task.
9980 */
9981 if (pse->sched_delayed)
9982 goto update;
9983
9984 /*
9985 * If @p has a shorter slice than current and @p is eligible, override
9986 * current's slice protection in order to allow preemption.
9987 */
9988 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
9989 preempt_action = PREEMPT_WAKEUP_SHORT;
9990 goto pick;
9991 }
9992
9993 /*
9994 * Ignore wakee preemption on WF_FORK as it is less likely that
9995 * there is shared data as exec often follow fork.
9996 */
9997 if (wake_flags & WF_FORK)
9998 goto update;
9999
10000 /* Prefer picking wakee soon if appropriate. */
10001 if (sched_feat(NEXT_BUDDY) && set_preempt_buddy(cfs_rq, pse)) {
10002 /*
10003 * Decide whether to obey WF_SYNC hint for a new buddy. Old
10004 * buddies are ignored as they may not be relevant to the
10005 * waker and less likely to be cache hot.
10006 */
10007 if (wake_flags & WF_SYNC)
10008 preempt_action = preempt_sync(rq, wake_flags, pse, se);
10009 }
10010
10011 switch (preempt_action) {
10012 case PREEMPT_WAKEUP_NONE:
10013 return;
10014 case PREEMPT_WAKEUP_RESCHED:
10015 goto preempt;
10016 case PREEMPT_WAKEUP_SHORT:
10017 fallthrough;
10018 case PREEMPT_WAKEUP_PICK:
10019 break;
10020 }
10021
10022 pick:
10023 if (cfs_rq->h_nr_queued) {
10024 nse = pick_next_entity(rq, preempt_action != PREEMPT_WAKEUP_SHORT);
10025 if (unlikely(!nse))
10026 goto pick;
10027
10028 /* If @p has become the most eligible task, force preemption */
10029 if (nse == pse)
10030 goto preempt;
10031 }
10032
10033 /*
10034 * If @p is eligible but not the next task to run then cancel protection
10035 * to prevent large scheduling latency
10036 */
10037 if (preempt_action == PREEMPT_WAKEUP_SHORT && entity_eligible(cfs_rq, pse))
10038 goto preempt;
10039 update:
10040 if (sched_feat(RUN_TO_PARITY))
10041 update_protect_slice(cfs_rq, se);
10042
10043 return;
10044
10045 preempt:
10046 cancel_protect_slice(se);
10047
10048 if (preempt_action == PREEMPT_WAKEUP_SHORT)
10049 set_short_buddy(cfs_rq, pse);
10050
10051 resched_curr_lazy(rq);
10052 }
10053
pick_task_fair(struct rq * rq,struct rq_flags * rf)10054 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
10055 __must_hold(__rq_lockp(rq))
10056 {
10057 struct cfs_rq *cfs_rq = &rq->cfs;
10058 struct sched_entity *se;
10059 struct task_struct *p;
10060 int new_tasks;
10061
10062 again:
10063 if (!cfs_rq->h_nr_queued)
10064 goto idle;
10065
10066 /* Might not have done put_prev_entity() */
10067 if (cfs_rq->curr && cfs_rq->curr->on_rq)
10068 update_curr_eevdf(cfs_rq);
10069
10070 se = pick_next_entity(rq, true);
10071 if (!se)
10072 goto again;
10073
10074 p = task_of(se);
10075 return p;
10076
10077 idle:
10078 if (sched_core_enabled(rq))
10079 return NULL;
10080
10081 new_tasks = sched_balance_newidle(rq, rf);
10082 if (new_tasks < 0)
10083 return RETRY_TASK;
10084 if (new_tasks > 0)
10085 goto again;
10086 return NULL;
10087 }
10088
10089 static struct task_struct *
fair_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)10090 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
10091 __must_hold(__rq_lockp(dl_se->rq))
10092 {
10093 return pick_task_fair(dl_se->rq, rf);
10094 }
10095
fair_server_init(struct rq * rq)10096 void fair_server_init(struct rq *rq)
10097 {
10098 struct sched_dl_entity *dl_se = &rq->fair_server;
10099
10100 init_dl_entity(dl_se);
10101
10102 dl_server_init(dl_se, rq, fair_server_pick_task);
10103 }
10104
10105 /*
10106 * Account for a descheduled task:
10107 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)10108 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
10109 {
10110 struct sched_entity *se = &prev->se;
10111 struct cfs_rq *cfs_rq = &rq->cfs;
10112 struct sched_entity *nse = NULL;
10113
10114 #ifdef CONFIG_FAIR_GROUP_SCHED
10115 if (next && next->sched_class == &fair_sched_class)
10116 nse = &next->se;
10117 #endif
10118
10119 while (se) {
10120 cfs_rq = cfs_rq_of(se);
10121 if (!nse || cfs_rq->h_curr)
10122 put_prev_entity(cfs_rq, se);
10123 #ifdef CONFIG_FAIR_GROUP_SCHED
10124 if (nse) {
10125 if (is_same_group(se, nse))
10126 break;
10127
10128 int d = nse->depth - se->depth;
10129 if (d >= 0) {
10130 /* nse has equal or greater depth, ascend */
10131 nse = parent_entity(nse);
10132 /* if nse is the deeper, do not ascend se */
10133 if (d > 0)
10134 continue;
10135 }
10136 }
10137 #endif
10138 se = parent_entity(se);
10139 }
10140
10141 /* Put 'current' back into the tree. */
10142 cfs_rq = &rq->cfs;
10143 se = &prev->se;
10144 WARN_ON_ONCE(cfs_rq->curr != se);
10145 cfs_rq->curr = NULL;
10146 if (se->on_rq)
10147 __enqueue_entity(cfs_rq, se);
10148 }
10149
10150 /*
10151 * sched_yield() is very simple
10152 */
yield_task_fair(struct rq * rq)10153 static void yield_task_fair(struct rq *rq)
10154 {
10155 struct task_struct *curr = rq->donor;
10156 struct sched_entity *se = &curr->se;
10157 struct cfs_rq *cfs_rq = &rq->cfs;
10158
10159 /*
10160 * Are we the only task in the tree?
10161 */
10162 if (unlikely(rq->nr_running == 1))
10163 return;
10164
10165 clear_buddies(cfs_rq, se);
10166
10167 update_rq_clock(rq);
10168 /*
10169 * Update run-time statistics of the 'current'.
10170 */
10171 update_curr_eevdf(cfs_rq);
10172 /*
10173 * Tell update_rq_clock() that we've just updated,
10174 * so we don't do microscopic update in schedule()
10175 * and double the fastpath cost.
10176 */
10177 rq_clock_skip_update(rq);
10178
10179 /*
10180 * Forfeit the remaining vruntime, only if the entity is eligible. This
10181 * condition is necessary because in core scheduling we prefer to run
10182 * ineligible tasks rather than force idling. If this happens we may
10183 * end up in a loop where the core scheduler picks the yielding task,
10184 * which yields immediately again; without the condition the vruntime
10185 * ends up quickly running away.
10186 */
10187 if (entity_eligible(cfs_rq, se)) {
10188 se->vruntime = se->deadline;
10189 update_deadline(cfs_rq, se);
10190 }
10191 }
10192
yield_to_task_fair(struct rq * rq,struct task_struct * p)10193 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
10194 {
10195 struct sched_entity *se = &p->se;
10196
10197 /* !se->on_rq also covers throttled task */
10198 if (!se->on_rq || se->sched_delayed)
10199 return false;
10200
10201 /* Tell the scheduler that we'd really like se to run next. */
10202 set_next_buddy(&task_rq(p)->cfs, se);
10203
10204 yield_task_fair(rq);
10205
10206 return true;
10207 }
10208
10209 /**************************************************
10210 * Fair scheduling class load-balancing methods.
10211 *
10212 * BASICS
10213 *
10214 * The purpose of load-balancing is to achieve the same basic fairness the
10215 * per-CPU scheduler provides, namely provide a proportional amount of compute
10216 * time to each task. This is expressed in the following equation:
10217 *
10218 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
10219 *
10220 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
10221 * W_i,0 is defined as:
10222 *
10223 * W_i,0 = \Sum_j w_i,j (2)
10224 *
10225 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
10226 * is derived from the nice value as per sched_prio_to_weight[].
10227 *
10228 * The weight average is an exponential decay average of the instantaneous
10229 * weight:
10230 *
10231 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
10232 *
10233 * C_i is the compute capacity of CPU i, typically it is the
10234 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
10235 * can also include other factors [XXX].
10236 *
10237 * To achieve this balance we define a measure of imbalance which follows
10238 * directly from (1):
10239 *
10240 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
10241 *
10242 * We them move tasks around to minimize the imbalance. In the continuous
10243 * function space it is obvious this converges, in the discrete case we get
10244 * a few fun cases generally called infeasible weight scenarios.
10245 *
10246 * [XXX expand on:
10247 * - infeasible weights;
10248 * - local vs global optima in the discrete case. ]
10249 *
10250 *
10251 * SCHED DOMAINS
10252 *
10253 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
10254 * for all i,j solution, we create a tree of CPUs that follows the hardware
10255 * topology where each level pairs two lower groups (or better). This results
10256 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
10257 * tree to only the first of the previous level and we decrease the frequency
10258 * of load-balance at each level inversely proportional to the number of CPUs in
10259 * the groups.
10260 *
10261 * This yields:
10262 *
10263 * log_2 n 1 n
10264 * \Sum { --- * --- * 2^i } = O(n) (5)
10265 * i = 0 2^i 2^i
10266 * `- size of each group
10267 * | | `- number of CPUs doing load-balance
10268 * | `- freq
10269 * `- sum over all levels
10270 *
10271 * Coupled with a limit on how many tasks we can migrate every balance pass,
10272 * this makes (5) the runtime complexity of the balancer.
10273 *
10274 * An important property here is that each CPU is still (indirectly) connected
10275 * to every other CPU in at most O(log n) steps:
10276 *
10277 * The adjacency matrix of the resulting graph is given by:
10278 *
10279 * log_2 n
10280 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
10281 * k = 0
10282 *
10283 * And you'll find that:
10284 *
10285 * A^(log_2 n)_i,j != 0 for all i,j (7)
10286 *
10287 * Showing there's indeed a path between every CPU in at most O(log n) steps.
10288 * The task movement gives a factor of O(m), giving a convergence complexity
10289 * of:
10290 *
10291 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
10292 *
10293 *
10294 * WORK CONSERVING
10295 *
10296 * In order to avoid CPUs going idle while there's still work to do, new idle
10297 * balancing is more aggressive and has the newly idle CPU iterate up the domain
10298 * tree itself instead of relying on other CPUs to bring it work.
10299 *
10300 * This adds some complexity to both (5) and (8) but it reduces the total idle
10301 * time.
10302 *
10303 * [XXX more?]
10304 *
10305 *
10306 * CGROUPS
10307 *
10308 * Cgroups make a horror show out of (2), instead of a simple sum we get:
10309 *
10310 * s_k,i
10311 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
10312 * S_k
10313 *
10314 * Where
10315 *
10316 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
10317 *
10318 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
10319 *
10320 * The big problem is S_k, its a global sum needed to compute a local (W_i)
10321 * property.
10322 *
10323 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
10324 * rewrite all of this once again.]
10325 */
10326
10327 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
10328
10329 enum fbq_type { regular, remote, all };
10330
10331 /*
10332 * 'group_type' describes the group of CPUs at the moment of load balancing.
10333 *
10334 * The enum is ordered by pulling priority, with the group with lowest priority
10335 * first so the group_type can simply be compared when selecting the busiest
10336 * group. See update_sd_pick_busiest().
10337 */
10338 enum group_type {
10339 /* The group has spare capacity that can be used to run more tasks. */
10340 group_has_spare = 0,
10341 /*
10342 * The group is fully used and the tasks don't compete for more CPU
10343 * cycles. Nevertheless, some tasks might wait before running.
10344 */
10345 group_fully_busy,
10346 /*
10347 * One task doesn't fit with CPU's capacity and must be migrated to a
10348 * more powerful CPU.
10349 */
10350 group_misfit_task,
10351 /*
10352 * Balance SMT group that's fully busy. Can benefit from migration
10353 * a task on SMT with busy sibling to another CPU on idle core.
10354 */
10355 group_smt_balance,
10356 /*
10357 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
10358 * and the task should be migrated to it instead of running on the
10359 * current CPU.
10360 */
10361 group_asym_packing,
10362 /*
10363 * The tasks' affinity constraints previously prevented the scheduler
10364 * from balancing the load across the system.
10365 */
10366 group_imbalanced,
10367 /*
10368 * There are tasks running on non-preferred LLC, possible to move
10369 * them to their preferred LLC without creating too much imbalance.
10370 * The priority of group_llc_balance is lower than that of
10371 * group_overloaded and higher than that of all other group types.
10372 * This is because group_llc_balance may exacerbate load imbalance.
10373 * If the LLC balancing attempt fails, the nr_balance_failed
10374 * mechanism will trigger other group types to rebalance the load.
10375 */
10376 group_llc_balance,
10377 /*
10378 * The CPU is overloaded and can't provide expected CPU cycles to all
10379 * tasks.
10380 */
10381 group_overloaded
10382 };
10383
10384 enum migration_type {
10385 migrate_load = 0,
10386 migrate_util,
10387 migrate_task,
10388 migrate_misfit,
10389 migrate_llc_task
10390 };
10391
10392 #define LBF_ALL_PINNED 0x01
10393 #define LBF_NEED_BREAK 0x02
10394 #define LBF_DST_PINNED 0x04
10395 #define LBF_SOME_PINNED 0x08
10396 #define LBF_ACTIVE_LB 0x10
10397 #define LBF_LLC_PINNED 0x20
10398
10399 struct lb_env {
10400 struct sched_domain *sd;
10401
10402 struct rq *src_rq;
10403 int src_cpu;
10404
10405 int dst_cpu;
10406 struct rq *dst_rq;
10407 bool dst_core_idle;
10408
10409 struct cpumask *dst_grpmask;
10410 int new_dst_cpu;
10411 enum cpu_idle_type idle;
10412 long imbalance;
10413 /* The set of CPUs under consideration for load-balancing */
10414 struct cpumask *cpus;
10415
10416 unsigned int flags;
10417
10418 unsigned int loop;
10419 unsigned int loop_break;
10420 unsigned int loop_max;
10421
10422 enum fbq_type fbq_type;
10423 enum migration_type migration_type;
10424 struct list_head tasks;
10425 };
10426
10427 /*
10428 * Is this task likely cache-hot:
10429 */
task_hot(struct task_struct * p,struct lb_env * env)10430 static int task_hot(struct task_struct *p, struct lb_env *env)
10431 {
10432 s64 delta;
10433
10434 lockdep_assert_rq_held(env->src_rq);
10435
10436 if (p->sched_class != &fair_sched_class)
10437 return 0;
10438
10439 if (unlikely(task_has_idle_policy(p)))
10440 return 0;
10441
10442 /* SMT siblings share cache */
10443 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
10444 return 0;
10445
10446 /*
10447 * Buddy candidates are cache hot:
10448 */
10449 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
10450 (&p->se == cfs_rq_of(&p->se)->next))
10451 return 1;
10452
10453 if (sysctl_sched_migration_cost == -1)
10454 return 1;
10455
10456 /*
10457 * Don't migrate task if the task's cookie does not match
10458 * with the destination CPU's core cookie.
10459 */
10460 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
10461 return 1;
10462
10463 if (sysctl_sched_migration_cost == 0)
10464 return 0;
10465
10466 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
10467
10468 return delta < (s64)sysctl_sched_migration_cost;
10469 }
10470
10471 #ifdef CONFIG_NUMA_BALANCING
10472 /*
10473 * Returns a positive value, if task migration degrades locality.
10474 * Returns 0, if task migration is not affected by locality.
10475 * Returns a negative value, if task migration improves locality i.e migration preferred.
10476 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)10477 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
10478 {
10479 struct numa_group *numa_group = rcu_dereference_all(p->numa_group);
10480 unsigned long src_weight, dst_weight;
10481 int src_nid, dst_nid, dist;
10482
10483 if (!static_branch_likely(&sched_numa_balancing))
10484 return 0;
10485
10486 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
10487 return 0;
10488
10489 src_nid = cpu_to_node(env->src_cpu);
10490 dst_nid = cpu_to_node(env->dst_cpu);
10491
10492 if (src_nid == dst_nid)
10493 return 0;
10494
10495 /* Migrating away from the preferred node is always bad. */
10496 if (src_nid == p->numa_preferred_nid) {
10497 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
10498 return 1;
10499 else
10500 return 0;
10501 }
10502
10503 /* Encourage migration to the preferred node. */
10504 if (dst_nid == p->numa_preferred_nid)
10505 return -1;
10506
10507 /* Leaving a core idle is often worse than degrading locality. */
10508 if (env->idle == CPU_IDLE)
10509 return 0;
10510
10511 dist = node_distance(src_nid, dst_nid);
10512 if (numa_group) {
10513 src_weight = group_weight(p, src_nid, dist);
10514 dst_weight = group_weight(p, dst_nid, dist);
10515 } else {
10516 src_weight = task_weight(p, src_nid, dist);
10517 dst_weight = task_weight(p, dst_nid, dist);
10518 }
10519
10520 return src_weight - dst_weight;
10521 }
10522
10523 #else /* !CONFIG_NUMA_BALANCING: */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)10524 static inline long migrate_degrades_locality(struct task_struct *p,
10525 struct lb_env *env)
10526 {
10527 return 0;
10528 }
10529 #endif /* !CONFIG_NUMA_BALANCING */
10530
10531 /*
10532 * Check whether the task is ineligible on the destination cpu
10533 *
10534 * When the PLACE_LAG scheduling feature is enabled and
10535 * dst_cfs_rq->nr_queued is greater than 1, if the task
10536 * is ineligible, it will also be ineligible when
10537 * it is migrated to the destination cpu.
10538 */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)10539 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
10540 {
10541 struct cfs_rq *dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
10542
10543 if (sched_feat(PLACE_LAG) && dst_cfs_rq->h_nr_queued &&
10544 !entity_eligible(&task_rq(p)->cfs, &p->se))
10545 return 1;
10546
10547 return 0;
10548 }
10549
10550 #ifdef CONFIG_SCHED_CACHE
10551 /*
10552 * The margin used when comparing LLC utilization with CPU capacity.
10553 * It determines the LLC load level where active LLC aggregation is
10554 * done.
10555 * Derived from fits_capacity().
10556 *
10557 * (default: ~50%, tunable via debugfs)
10558 */
fits_llc_capacity(unsigned long util,unsigned long max)10559 static bool fits_llc_capacity(unsigned long util, unsigned long max)
10560 {
10561 u32 aggr_pct = llc_overaggr_pct;
10562
10563 /*
10564 * For single core systems, raise the aggregation
10565 * threshold to accommodate more tasks.
10566 */
10567 if (cpu_smt_num_threads == 1)
10568 aggr_pct = (aggr_pct * 3 / 2);
10569
10570 return util * 100 < max * aggr_pct;
10571 }
10572
10573 /*
10574 * The margin used when comparing utilization.
10575 * is 'util1' noticeably greater than 'util2'
10576 * Derived from capacity_greater().
10577 * Bias is in perentage.
10578 */
10579 /* Allows dst util to be bigger than src util by up to bias percent */
10580 #define util_greater(util1, util2) \
10581 ((util1) * 100 > (util2) * (100 + llc_imb_pct))
10582
get_llc_stats(int cpu,unsigned long * util,unsigned long * cap)10583 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util,
10584 unsigned long *cap)
10585 {
10586 struct sched_domain_shared *sd_share;
10587
10588 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
10589 if (!sd_share)
10590 return false;
10591
10592 *util = READ_ONCE(sd_share->util_avg);
10593 *cap = READ_ONCE(sd_share->capacity);
10594
10595 return true;
10596 }
10597
10598 /*
10599 * Decision matrix according to the LLC utilization. To
10600 * decide whether we can do task aggregation across LLC.
10601 *
10602 * By default, 50% is the threshold for treating the LLC
10603 * as busy. The reason for choosing 50% is to avoid saturation
10604 * of SMT-2, and it is also a safe cutoff for other SMT-n
10605 * platforms. SMT-1 has higher threshold because it is
10606 * supposed to accommodate more tasks, see fits_llc_capacity().
10607 *
10608 * 20% is the utilization imbalance percentage to decide
10609 * if the preferred LLC is busier than the non-preferred LLC.
10610 * 20 is a little higher than the LLC domain's imbalance_pct
10611 * 17. The hysteresis is used to avoid task bouncing between the
10612 * preferred LLC and the non-preferred LLC, and it will
10613 * be turned into tunable debugfs.
10614 *
10615 * 1. moving towards the preferred LLC, dst is the preferred
10616 * LLC, src is not.
10617 *
10618 * src \ dst 30% 40% 50% 60%
10619 * 30% Y Y Y N
10620 * 40% Y Y Y Y
10621 * 50% Y Y G G
10622 * 60% Y Y G G
10623 *
10624 * 2. moving out of the preferred LLC, src is the preferred
10625 * LLC, dst is not:
10626 *
10627 * src \ dst 30% 40% 50% 60%
10628 * 30% N N N N
10629 * 40% N N N N
10630 * 50% N N G G
10631 * 60% Y N G G
10632 *
10633 * src : src_util
10634 * dst : dst_util
10635 * Y : Yes, migrate
10636 * N : No, do not migrate
10637 * G : let the Generic load balance to even the load.
10638 *
10639 * The intention is that if both LLCs are quite busy, cache aware
10640 * load balance should not be performed, and generic load balance
10641 * should take effect. However, if one is busy and the other is not,
10642 * the preferred LLC capacity(50%) and imbalance criteria(20%) should
10643 * be considered to determine whether LLC aggregation should be
10644 * performed to bias the load towards the preferred LLC.
10645 */
10646
10647 /* migration decision, 3 states are orthogonal. */
10648 enum llc_mig {
10649 mig_forbid = 0, /* N: Don't migrate task, respect LLC preference */
10650 mig_llc, /* Y: Do LLC preference based migration */
10651 mig_unrestricted /* G: Don't restrict generic load balance migration */
10652 };
10653
10654 /*
10655 * Check if task can be moved from the source LLC to the
10656 * destination LLC without breaking cache aware preferrence.
10657 * src_cpu and dst_cpu are arbitrary CPUs within the source
10658 * and destination LLCs, respectively.
10659 */
can_migrate_llc(int src_cpu,int dst_cpu,unsigned long tsk_util,bool to_pref)10660 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu,
10661 unsigned long tsk_util,
10662 bool to_pref)
10663 {
10664 unsigned long src_util, dst_util, src_cap, dst_cap;
10665
10666 if (!get_llc_stats(src_cpu, &src_util, &src_cap) ||
10667 !get_llc_stats(dst_cpu, &dst_util, &dst_cap))
10668 return mig_unrestricted;
10669
10670 src_util = src_util < tsk_util ? 0 : src_util - tsk_util;
10671 dst_util = dst_util + tsk_util;
10672
10673 if (!fits_llc_capacity(dst_util, dst_cap) &&
10674 !fits_llc_capacity(src_util, src_cap))
10675 return mig_unrestricted;
10676
10677 if (to_pref) {
10678 /*
10679 * Don't migrate if we will get preferred LLC too
10680 * heavily loaded and if the dest is much busier
10681 * than the src, in which case migration will
10682 * increase the imbalance too much.
10683 */
10684 if (!fits_llc_capacity(dst_util, dst_cap) &&
10685 util_greater(dst_util, src_util))
10686 return mig_forbid;
10687 } else {
10688 /*
10689 * Don't migrate if we will leave preferred LLC
10690 * too idle, or if this migration leads to the
10691 * non-preferred LLC falls within sysctl_aggr_imb percent
10692 * of preferred LLC, leading to migration again
10693 * back to preferred LLC.
10694 */
10695 if (fits_llc_capacity(src_util, src_cap) ||
10696 !util_greater(src_util, dst_util))
10697 return mig_forbid;
10698 }
10699 return mig_llc;
10700 }
10701
task_misfits_asym_cpu(struct lb_env * env,struct task_struct * p)10702 static inline bool task_misfits_asym_cpu(struct lb_env *env, struct task_struct *p)
10703 {
10704 /*
10705 * On asymmetric CPU capacity domains, do not let cache-aware
10706 * balancing pull the task onto a destination CPU that cannot
10707 * accommodate it. Doing so would turn the task into a misfit on
10708 * the destination, trading a cache-locality gain for a capacity
10709 * loss. If the task already does not fit its source CPU, the move
10710 * cannot make things worse, so let the LLC preference decide.
10711 */
10712 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && p &&
10713 !task_fits_cpu(p, env->dst_cpu) &&
10714 task_fits_cpu(p, env->src_cpu))
10715 return true;
10716
10717 return false;
10718 }
10719
10720 /*
10721 * Check if task p can migrate from source LLC to
10722 * destination LLC in terms of cache aware load balance.
10723 */
can_migrate_llc_task(struct lb_env * env,struct task_struct * p)10724 static enum llc_mig can_migrate_llc_task(struct lb_env *env,
10725 struct task_struct *p)
10726 {
10727 struct mm_struct *mm;
10728 bool to_pref;
10729 int cpu, src_cpu, dst_cpu;
10730
10731 if (task_misfits_asym_cpu(env, p))
10732 return mig_forbid;
10733
10734 src_cpu = env->src_cpu;
10735 dst_cpu = env->dst_cpu;
10736 mm = p->mm;
10737 if (!mm)
10738 return mig_unrestricted;
10739
10740 cpu = READ_ONCE(mm->sc_stat.cpu);
10741 if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu))
10742 return mig_unrestricted;
10743
10744 /* skip cache aware load balance for too many threads */
10745 if (invalid_llc_nr(mm, p, dst_cpu) ||
10746 exceed_llc_capacity(mm, dst_cpu)) {
10747 if (READ_ONCE(mm->sc_stat.cpu) != -1)
10748 WRITE_ONCE(mm->sc_stat.cpu, -1);
10749 return mig_unrestricted;
10750 }
10751
10752 if (cpus_share_cache(dst_cpu, cpu))
10753 to_pref = true;
10754 else if (cpus_share_cache(src_cpu, cpu))
10755 to_pref = false;
10756 else
10757 return mig_unrestricted;
10758
10759 return can_migrate_llc(src_cpu, dst_cpu,
10760 task_util(p), to_pref);
10761 }
10762
10763 /*
10764 * Check if active load balance breaks LLC locality in
10765 * terms of cache aware load balance. The load level and
10766 * imbalance do not warrant breaking LLC preference per
10767 * the can_migrate_llc() policy. Here, the benefit of
10768 * LLC locality outweighs the power efficiency gained from
10769 * migrating the only runnable task away.
10770 */
10771 static inline bool
alb_break_llc(struct lb_env * env)10772 alb_break_llc(struct lb_env *env)
10773 {
10774 if (!sched_cache_enabled())
10775 return false;
10776
10777 if (cpus_share_cache(env->src_cpu, env->dst_cpu))
10778 return false;
10779 /*
10780 * All tasks prefer to stay on their current CPU.
10781 * Do not pull a task from its preferred CPU if:
10782 * 1. It is the only task running and does not exceed
10783 * imbalance allowance; OR
10784 * 2. Migrating it away from its preferred LLC would violate
10785 * the cache-aware scheduling policy.
10786 */
10787 if (env->src_rq->nr_pref_llc_running &&
10788 env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) {
10789 unsigned long util = 0;
10790 struct task_struct *cur;
10791
10792 /*
10793 * Migrating misfit tasks from current CPU
10794 * to CPU with a better fit.
10795 * Prioritize that over LLC preference.
10796 */
10797 if (env->migration_type == migrate_misfit)
10798 return false;
10799
10800 if (env->src_rq->nr_running <= 1)
10801 return true;
10802
10803 cur = rcu_dereference_all(env->src_rq->curr);
10804 if (cur && cur->sched_class == &fair_sched_class)
10805 util = task_util(cur);
10806
10807 if (task_misfits_asym_cpu(env, cur) ||
10808 can_migrate_llc(env->src_cpu, env->dst_cpu,
10809 util, false) == mig_forbid)
10810 return true;
10811 }
10812
10813 return false;
10814 }
10815
10816 /*
10817 * Check if migrating task p from env->src_cpu to
10818 * env->dst_cpu breaks LLC localiy.
10819 */
migrate_degrades_llc(struct task_struct * p,struct lb_env * env)10820 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
10821 {
10822 if (!sched_cache_enabled())
10823 return false;
10824
10825 if (task_has_sched_core(p))
10826 return false;
10827 /*
10828 * Skip over tasks that would degrade LLC locality;
10829 * only when nr_balanced_failed is sufficiently high do we
10830 * ignore this constraint.
10831 *
10832 * Threshold of cache_nice_tries is set to 1 higher
10833 * than nr_balance_failed to avoid excessive task
10834 * migration at the same time.
10835 */
10836 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
10837 return false;
10838
10839 /*
10840 * We know the env->src_cpu has some tasks prefer to
10841 * run on env->dst_cpu, skip the tasks do not prefer
10842 * env->dst_cpu, and find the one that prefers.
10843 */
10844 if (env->migration_type == migrate_llc_task &&
10845 READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu))
10846 return true;
10847
10848 if (can_migrate_llc_task(env, p) != mig_forbid)
10849 return false;
10850
10851 return true;
10852 }
10853
10854 #else
get_llc_stats(int cpu,unsigned long * util,unsigned long * cap)10855 static inline bool get_llc_stats(int cpu, unsigned long *util,
10856 unsigned long *cap)
10857 {
10858 return false;
10859 }
10860
10861 static inline bool
alb_break_llc(struct lb_env * env)10862 alb_break_llc(struct lb_env *env)
10863 {
10864 return false;
10865 }
10866
10867 static inline bool
migrate_degrades_llc(struct task_struct * p,struct lb_env * env)10868 migrate_degrades_llc(struct task_struct *p, struct lb_env *env)
10869 {
10870 return false;
10871 }
10872 #endif
10873 /*
10874 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
10875 */
10876 static
can_migrate_task(struct task_struct * p,struct lb_env * env)10877 int can_migrate_task(struct task_struct *p, struct lb_env *env)
10878 {
10879 long degrades, hot;
10880
10881 lockdep_assert_rq_held(env->src_rq);
10882 if (p->sched_task_hot)
10883 p->sched_task_hot = 0;
10884
10885 /*
10886 * We do not migrate tasks that are:
10887 * 1) delayed dequeued unless we migrate load, or
10888 * 2) target cfs_rq is in throttled hierarchy, or
10889 * 3) cannot be migrated to this CPU due to cpus_ptr, or
10890 * 4) running (obviously), or
10891 * 5) are cache-hot on their current CPU, or
10892 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
10893 */
10894 if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
10895 return 0;
10896
10897 if (lb_throttled_hierarchy(p, env->dst_cpu))
10898 return 0;
10899
10900 /*
10901 * We want to prioritize the migration of eligible tasks.
10902 * For ineligible tasks we soft-limit them and only allow
10903 * them to migrate when nr_balance_failed is non-zero to
10904 * avoid load-balancing trying very hard to balance the load.
10905 */
10906 if (!env->sd->nr_balance_failed &&
10907 task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
10908 return 0;
10909
10910 /* Disregard percpu kthreads; they are where they need to be. */
10911 if (kthread_is_per_cpu(p))
10912 return 0;
10913
10914 if (task_is_blocked(p))
10915 return 0;
10916
10917 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
10918 int cpu;
10919
10920 schedstat_inc(p->stats.nr_failed_migrations_affine);
10921
10922 env->flags |= LBF_SOME_PINNED;
10923
10924 /*
10925 * Remember if this task can be migrated to any other CPU in
10926 * our sched_group. We may want to revisit it if we couldn't
10927 * meet load balance goals by pulling other tasks on src_cpu.
10928 *
10929 * Avoid computing new_dst_cpu
10930 * - for NEWLY_IDLE
10931 * - if we have already computed one in current iteration
10932 * - if it's an active balance
10933 */
10934 if (env->idle == CPU_NEWLY_IDLE ||
10935 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
10936 return 0;
10937
10938 /* Prevent to re-select dst_cpu via env's CPUs: */
10939 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
10940
10941 if (cpu < nr_cpu_ids) {
10942 env->flags |= LBF_DST_PINNED;
10943 env->new_dst_cpu = cpu;
10944 }
10945
10946 return 0;
10947 }
10948
10949 /* Record that we found at least one task that could run on dst_cpu */
10950 env->flags &= ~LBF_ALL_PINNED;
10951
10952 if (task_on_cpu(env->src_rq, p) ||
10953 task_current_donor(env->src_rq, p)) {
10954 schedstat_inc(p->stats.nr_failed_migrations_running);
10955 return 0;
10956 }
10957
10958 /*
10959 * Aggressive migration if:
10960 * 1) active balance
10961 * 2) destination numa is preferred
10962 * 3) task is cache cold, or
10963 * 4) too many balance attempts have failed.
10964 */
10965 if (env->flags & LBF_ACTIVE_LB)
10966 return 1;
10967
10968 degrades = migrate_degrades_locality(p, env);
10969 if (!degrades) {
10970 /*
10971 * If the NUMA locality is not broken,
10972 * further check if migration would hurt
10973 * LLC locality.
10974 */
10975 if (migrate_degrades_llc(p, env)) {
10976 /*
10977 * If regular load balancing fails to pull a task
10978 * due to LLC locality, this is expected behavior
10979 * and we set LBF_LLC_PINNED so we don't increase
10980 * nr_balance_failed unecessarily.
10981 */
10982 if (env->migration_type != migrate_llc_task)
10983 env->flags |= LBF_LLC_PINNED;
10984
10985 return 0;
10986 }
10987
10988 hot = task_hot(p, env);
10989 } else {
10990 hot = degrades > 0;
10991 }
10992
10993 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
10994 if (hot)
10995 p->sched_task_hot = 1;
10996 return 1;
10997 }
10998
10999 schedstat_inc(p->stats.nr_failed_migrations_hot);
11000 return 0;
11001 }
11002
11003 /*
11004 * detach_task() -- detach the task for the migration specified in env
11005 */
detach_task(struct task_struct * p,struct lb_env * env)11006 static void detach_task(struct task_struct *p, struct lb_env *env)
11007 {
11008 lockdep_assert_rq_held(env->src_rq);
11009
11010 if (p->sched_task_hot) {
11011 p->sched_task_hot = 0;
11012 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
11013 schedstat_inc(p->stats.nr_forced_migrations);
11014 }
11015
11016 WARN_ON(task_current(env->src_rq, p));
11017 WARN_ON(task_current_donor(env->src_rq, p));
11018
11019 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
11020 set_task_cpu(p, env->dst_cpu);
11021 }
11022
11023 /*
11024 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
11025 * part of active balancing operations within "domain".
11026 *
11027 * Returns a task if successful and NULL otherwise.
11028 */
detach_one_task(struct lb_env * env)11029 static struct task_struct *detach_one_task(struct lb_env *env)
11030 {
11031 struct task_struct *p;
11032
11033 lockdep_assert_rq_held(env->src_rq);
11034
11035 list_for_each_entry_reverse(p,
11036 &env->src_rq->cfs_tasks, se.group_node) {
11037 if (!can_migrate_task(p, env))
11038 continue;
11039
11040 detach_task(p, env);
11041
11042 /*
11043 * Right now, this is only the second place where
11044 * lb_gained[env->idle] is updated (other is detach_tasks)
11045 * so we can safely collect stats here rather than
11046 * inside detach_tasks().
11047 */
11048 schedstat_inc(env->sd->lb_gained[env->idle]);
11049 return p;
11050 }
11051 return NULL;
11052 }
11053
11054 /*
11055 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
11056 * busiest_rq, as part of a balancing operation within domain "sd".
11057 *
11058 * Returns number of detached tasks if successful and 0 otherwise.
11059 */
detach_tasks(struct lb_env * env)11060 static int detach_tasks(struct lb_env *env)
11061 {
11062 struct list_head *tasks = &env->src_rq->cfs_tasks;
11063 unsigned long util, load;
11064 struct task_struct *p;
11065 int detached = 0;
11066
11067 lockdep_assert_rq_held(env->src_rq);
11068
11069 /*
11070 * Source run queue has been emptied by another CPU, clear
11071 * LBF_ALL_PINNED flag as we will not test any task.
11072 */
11073 if (env->src_rq->nr_running <= 1) {
11074 env->flags &= ~LBF_ALL_PINNED;
11075 return 0;
11076 }
11077
11078 if (env->imbalance <= 0)
11079 return 0;
11080
11081 while (!list_empty(tasks)) {
11082 /*
11083 * We don't want to steal all, otherwise we may be treated likewise,
11084 * which could at worst lead to a livelock crash.
11085 */
11086 if (env->idle && env->src_rq->nr_running <= 1)
11087 break;
11088
11089 env->loop++;
11090 /* We've more or less seen every task there is, call it quits */
11091 if (env->loop > env->loop_max)
11092 break;
11093
11094 /* take a breather every nr_migrate tasks */
11095 if (env->loop > env->loop_break) {
11096 env->loop_break += SCHED_NR_MIGRATE_BREAK;
11097 env->flags |= LBF_NEED_BREAK;
11098 break;
11099 }
11100
11101 p = list_last_entry(tasks, struct task_struct, se.group_node);
11102
11103 if (!can_migrate_task(p, env))
11104 goto next;
11105
11106 switch (env->migration_type) {
11107 case migrate_load:
11108 /*
11109 * Depending of the number of CPUs and tasks and the
11110 * cgroup hierarchy, task_h_load() can return a null
11111 * value. Make sure that env->imbalance decreases
11112 * otherwise detach_tasks() will stop only after
11113 * detaching up to loop_max tasks.
11114 */
11115 load = max_t(unsigned long, task_h_load(p), 1);
11116
11117 if (sched_feat(LB_MIN) &&
11118 load < 16 && !env->sd->nr_balance_failed)
11119 goto next;
11120
11121 /*
11122 * Make sure that we don't migrate too much load.
11123 * Nevertheless, let relax the constraint if
11124 * scheduler fails to find a good waiting task to
11125 * migrate.
11126 */
11127 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
11128 goto next;
11129
11130 env->imbalance -= load;
11131 break;
11132
11133 case migrate_util:
11134 util = task_util_est(p);
11135
11136 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
11137 goto next;
11138
11139 env->imbalance -= util;
11140 break;
11141
11142 case migrate_task:
11143 env->imbalance--;
11144 break;
11145
11146 case migrate_misfit:
11147 /* This is not a misfit task */
11148 if (task_fits_cpu(p, env->src_cpu))
11149 goto next;
11150
11151 env->imbalance = 0;
11152 break;
11153
11154 case migrate_llc_task:
11155 env->imbalance--;
11156 break;
11157 }
11158
11159 detach_task(p, env);
11160 list_add(&p->se.group_node, &env->tasks);
11161
11162 detached++;
11163
11164 #ifdef CONFIG_PREEMPTION
11165 /*
11166 * NEWIDLE balancing is a source of latency, so preemptible
11167 * kernels will stop after the first task is detached to minimize
11168 * the critical section.
11169 */
11170 if (env->idle == CPU_NEWLY_IDLE)
11171 break;
11172 #endif
11173
11174 /*
11175 * We only want to steal up to the prescribed amount of
11176 * load/util/tasks.
11177 */
11178 if (env->imbalance <= 0)
11179 break;
11180
11181 continue;
11182 next:
11183 if (p->sched_task_hot)
11184 schedstat_inc(p->stats.nr_failed_migrations_hot);
11185
11186 list_move(&p->se.group_node, tasks);
11187 }
11188
11189 /*
11190 * Right now, this is one of only two places we collect this stat
11191 * so we can safely collect detach_one_task() stats here rather
11192 * than inside detach_one_task().
11193 */
11194 schedstat_add(env->sd->lb_gained[env->idle], detached);
11195
11196 return detached;
11197 }
11198
11199 /*
11200 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
11201 * new rq.
11202 */
attach_tasks(struct lb_env * env)11203 static void attach_tasks(struct lb_env *env)
11204 {
11205 struct list_head *tasks = &env->tasks;
11206 struct task_struct *p;
11207 struct rq_flags rf;
11208
11209 rq_lock(env->dst_rq, &rf);
11210 update_rq_clock(env->dst_rq);
11211
11212 while (!list_empty(tasks)) {
11213 p = list_first_entry(tasks, struct task_struct, se.group_node);
11214 list_del_init(&p->se.group_node);
11215
11216 attach_task(env->dst_rq, p);
11217 }
11218
11219 rq_unlock(env->dst_rq, &rf);
11220 }
11221
11222 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked_load(struct cfs_rq * cfs_rq)11223 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq)
11224 {
11225 if (cfs_rq->avg.load_avg)
11226 return true;
11227
11228 if (cfs_rq->avg.util_avg)
11229 return true;
11230
11231 return false;
11232 }
11233
others_have_blocked(struct rq * rq)11234 static inline bool others_have_blocked(struct rq *rq)
11235 {
11236 if (cpu_util_rt(rq))
11237 return true;
11238
11239 if (cpu_util_dl(rq))
11240 return true;
11241
11242 if (hw_load_avg(rq))
11243 return true;
11244
11245 if (cpu_util_irq(rq))
11246 return true;
11247
11248 return false;
11249 }
11250
update_blocked_load_tick(struct rq * rq)11251 static inline void update_blocked_load_tick(struct rq *rq)
11252 {
11253 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
11254 }
11255
update_has_blocked_load_status(struct rq * rq,bool has_blocked_load)11256 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load)
11257 {
11258 if (!has_blocked_load)
11259 rq->has_blocked_load = 0;
11260 }
11261 #else /* !CONFIG_NO_HZ_COMMON: */
cfs_rq_has_blocked_load(struct cfs_rq * cfs_rq)11262 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)11263 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)11264 static inline void update_blocked_load_tick(struct rq *rq) {}
update_has_blocked_load_status(struct rq * rq,bool has_blocked_load)11265 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {}
11266 #endif /* !CONFIG_NO_HZ_COMMON */
11267
__update_blocked_others(struct rq * rq,bool * done)11268 static bool __update_blocked_others(struct rq *rq, bool *done)
11269 {
11270 bool updated;
11271
11272 /*
11273 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
11274 * DL and IRQ signals have been updated before updating CFS.
11275 */
11276 updated = update_other_load_avgs(rq);
11277
11278 if (others_have_blocked(rq))
11279 *done = false;
11280
11281 return updated;
11282 }
11283
11284 #ifdef CONFIG_FAIR_GROUP_SCHED
11285
__update_blocked_fair(struct rq * rq,bool * done)11286 static bool __update_blocked_fair(struct rq *rq, bool *done)
11287 {
11288 struct cfs_rq *cfs_rq, *pos;
11289 bool decayed = false;
11290
11291 /*
11292 * Iterates the task_group tree in a bottom up fashion, see
11293 * list_add_leaf_cfs_rq() for details.
11294 */
11295 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
11296 struct sched_entity *se;
11297
11298 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
11299 update_tg_load_avg(cfs_rq);
11300
11301 if (cfs_rq->nr_queued == 0)
11302 update_idle_cfs_rq_clock_pelt(cfs_rq);
11303
11304 if (cfs_rq == &rq->cfs)
11305 decayed = true;
11306 }
11307
11308 /* Propagate pending load changes to the parent, if any: */
11309 se = cfs_rq_se(cfs_rq);
11310 if (se && !skip_blocked_update(se))
11311 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11312
11313 /*
11314 * There can be a lot of idle CPU cgroups. Don't let fully
11315 * decayed cfs_rqs linger on the list.
11316 */
11317 if (cfs_rq_is_decayed(cfs_rq))
11318 list_del_leaf_cfs_rq(cfs_rq);
11319
11320 /* Don't need periodic decay once load/util_avg are null */
11321 if (cfs_rq_has_blocked_load(cfs_rq))
11322 *done = false;
11323 }
11324
11325 return decayed;
11326 }
11327
11328 /*
11329 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
11330 * This needs to be done in a top-down fashion because the load of a child
11331 * group is a fraction of its parents load.
11332 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)11333 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
11334 {
11335 struct sched_entity *se = cfs_rq_se(cfs_rq);
11336 unsigned long now = jiffies;
11337 unsigned long load;
11338
11339 if (cfs_rq->last_h_load_update == now)
11340 return;
11341
11342 WRITE_ONCE(cfs_rq->h_load_next, NULL);
11343 for_each_sched_entity(se) {
11344 cfs_rq = cfs_rq_of(se);
11345 WRITE_ONCE(cfs_rq->h_load_next, se);
11346 if (cfs_rq->last_h_load_update == now)
11347 break;
11348 }
11349
11350 if (!se) {
11351 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
11352 cfs_rq->last_h_load_update = now;
11353 }
11354
11355 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
11356 load = cfs_rq->h_load;
11357 load = div64_ul(load * se->avg.load_avg,
11358 cfs_rq_load_avg(cfs_rq) + 1);
11359 cfs_rq = group_cfs_rq(se);
11360 cfs_rq->h_load = load;
11361 cfs_rq->last_h_load_update = now;
11362 }
11363 }
11364
task_h_load(struct task_struct * p)11365 static unsigned long task_h_load(struct task_struct *p)
11366 {
11367 struct cfs_rq *cfs_rq = task_cfs_rq(p);
11368
11369 update_cfs_rq_h_load(cfs_rq);
11370 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
11371 cfs_rq_load_avg(cfs_rq) + 1);
11372 }
11373 #else /* !CONFIG_FAIR_GROUP_SCHED: */
__update_blocked_fair(struct rq * rq,bool * done)11374 static bool __update_blocked_fair(struct rq *rq, bool *done)
11375 {
11376 struct cfs_rq *cfs_rq = &rq->cfs;
11377 bool decayed;
11378
11379 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
11380 if (cfs_rq_has_blocked_load(cfs_rq))
11381 *done = false;
11382
11383 return decayed;
11384 }
11385
task_h_load(struct task_struct * p)11386 static unsigned long task_h_load(struct task_struct *p)
11387 {
11388 return p->se.avg.load_avg;
11389 }
11390 #endif /* !CONFIG_FAIR_GROUP_SCHED */
11391
__sched_balance_update_blocked_averages(struct rq * rq)11392 static void __sched_balance_update_blocked_averages(struct rq *rq)
11393 {
11394 bool decayed = false, done = true;
11395
11396 update_blocked_load_tick(rq);
11397
11398 decayed |= __update_blocked_others(rq, &done);
11399 decayed |= __update_blocked_fair(rq, &done);
11400
11401 update_has_blocked_load_status(rq, !done);
11402 if (decayed)
11403 cpufreq_update_util(rq, 0);
11404 }
11405
sched_balance_update_blocked_averages(int cpu)11406 static void sched_balance_update_blocked_averages(int cpu)
11407 {
11408 struct rq *rq = cpu_rq(cpu);
11409
11410 guard(rq_lock_irqsave)(rq);
11411 update_rq_clock(rq);
11412 __sched_balance_update_blocked_averages(rq);
11413 }
11414
11415 /********** Helpers for sched_balance_find_src_group ************************/
11416
11417 /*
11418 * sg_lb_stats - stats of a sched_group required for load-balancing:
11419 */
11420 struct sg_lb_stats {
11421 unsigned long avg_load; /* Avg load over the CPUs of the group */
11422 unsigned long group_load; /* Total load over the CPUs of the group */
11423 unsigned long group_capacity; /* Capacity over the CPUs of the group */
11424 unsigned long group_util; /* Total utilization over the CPUs of the group */
11425 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
11426 unsigned int sum_nr_running; /* Nr of all tasks running in the group */
11427 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
11428 unsigned int idle_cpus; /* Nr of idle CPUs in the group */
11429 unsigned int group_weight;
11430 enum group_type group_type;
11431 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
11432 unsigned int group_smt_balance; /* Task on busy SMT be moved */
11433 unsigned int group_llc_balance; /* Tasks should be moved to preferred LLC */
11434 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
11435 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */
11436 #ifdef CONFIG_NUMA_BALANCING
11437 unsigned int nr_numa_running;
11438 unsigned int nr_preferred_running;
11439 #endif
11440 #ifdef CONFIG_SCHED_CACHE
11441 unsigned int nr_pref_dst_llc;
11442 #endif
11443 };
11444
11445 /*
11446 * sd_lb_stats - stats of a sched_domain required for load-balancing:
11447 */
11448 struct sd_lb_stats {
11449 struct sched_group *busiest; /* Busiest group in this sd */
11450 struct sched_group *local; /* Local group in this sd */
11451 unsigned long total_load; /* Total load of all groups in sd */
11452 unsigned long total_capacity; /* Total capacity of all groups in sd */
11453 unsigned long avg_load; /* Average load across all groups in sd */
11454 unsigned int prefer_sibling; /* Tasks should go to sibling first */
11455
11456 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
11457 struct sg_lb_stats local_stat; /* Statistics of the local group */
11458 };
11459
init_sd_lb_stats(struct sd_lb_stats * sds)11460 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
11461 {
11462 /*
11463 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
11464 * local_stat because update_sg_lb_stats() does a full clear/assignment.
11465 * We must however set busiest_stat::group_type and
11466 * busiest_stat::idle_cpus to the worst busiest group because
11467 * update_sd_pick_busiest() reads these before assignment.
11468 */
11469 *sds = (struct sd_lb_stats){
11470 .busiest = NULL,
11471 .local = NULL,
11472 .total_load = 0UL,
11473 .total_capacity = 0UL,
11474 .busiest_stat = {
11475 .idle_cpus = UINT_MAX,
11476 .group_type = group_has_spare,
11477 },
11478 };
11479 }
11480
scale_rt_capacity(int cpu)11481 static unsigned long scale_rt_capacity(int cpu)
11482 {
11483 unsigned long max = get_actual_cpu_capacity(cpu);
11484 struct rq *rq = cpu_rq(cpu);
11485 unsigned long used, free;
11486 unsigned long irq;
11487
11488 irq = cpu_util_irq(rq);
11489
11490 if (unlikely(irq >= max))
11491 return 1;
11492
11493 /*
11494 * avg_rt.util_avg and avg_dl.util_avg track binary signals
11495 * (running and not running) with weights 0 and 1024 respectively.
11496 */
11497 used = cpu_util_rt(rq);
11498 used += cpu_util_dl(rq);
11499
11500 if (unlikely(used >= max))
11501 return 1;
11502
11503 free = max - used;
11504
11505 return scale_irq_capacity(free, irq, max);
11506 }
11507
update_cpu_capacity(struct sched_domain * sd,int cpu)11508 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
11509 {
11510 unsigned long capacity = scale_rt_capacity(cpu);
11511 struct sched_group *sdg = sd->groups;
11512
11513 if (!capacity)
11514 capacity = 1;
11515
11516 cpu_rq(cpu)->cpu_capacity = capacity;
11517 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
11518
11519 sdg->sgc->capacity = capacity;
11520 sdg->sgc->min_capacity = capacity;
11521 sdg->sgc->max_capacity = capacity;
11522 }
11523
update_group_capacity(struct sched_domain * sd,int cpu)11524 void update_group_capacity(struct sched_domain *sd, int cpu)
11525 {
11526 struct sched_domain *child = sd->child;
11527 struct sched_group *group, *sdg = sd->groups;
11528 unsigned long capacity, min_capacity, max_capacity;
11529 unsigned long interval;
11530
11531 interval = msecs_to_jiffies(sd->balance_interval);
11532 interval = clamp(interval, 1UL, max_load_balance_interval);
11533 sdg->sgc->next_update = jiffies + interval;
11534
11535 if (!child) {
11536 update_cpu_capacity(sd, cpu);
11537 return;
11538 }
11539
11540 capacity = 0;
11541 min_capacity = ULONG_MAX;
11542 max_capacity = 0;
11543
11544 if (child->flags & SD_NUMA) {
11545 /*
11546 * SD_NUMA domains cannot assume that child groups
11547 * span the current group.
11548 */
11549
11550 for_each_cpu(cpu, sched_group_span(sdg)) {
11551 unsigned long cpu_cap = capacity_of(cpu);
11552
11553 capacity += cpu_cap;
11554 min_capacity = min(cpu_cap, min_capacity);
11555 max_capacity = max(cpu_cap, max_capacity);
11556 }
11557 } else {
11558 /*
11559 * !SD_NUMA domains can assume that child groups
11560 * span the current group.
11561 */
11562
11563 group = child->groups;
11564 do {
11565 struct sched_group_capacity *sgc = group->sgc;
11566
11567 capacity += sgc->capacity;
11568 min_capacity = min(sgc->min_capacity, min_capacity);
11569 max_capacity = max(sgc->max_capacity, max_capacity);
11570 group = group->next;
11571 } while (group != child->groups);
11572 }
11573
11574 sdg->sgc->capacity = capacity;
11575 sdg->sgc->min_capacity = min_capacity;
11576 sdg->sgc->max_capacity = max_capacity;
11577 }
11578
11579 /*
11580 * Check whether the capacity of the rq has been noticeably reduced by side
11581 * activity. The imbalance_pct is used for the threshold.
11582 * Return true is the capacity is reduced
11583 */
11584 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)11585 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
11586 {
11587 return ((rq->cpu_capacity * sd->imbalance_pct) <
11588 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
11589 }
11590
11591 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)11592 static inline bool check_misfit_status(struct rq *rq)
11593 {
11594 return rq->misfit_task_load;
11595 }
11596
11597 /*
11598 * Group imbalance indicates (and tries to solve) the problem where balancing
11599 * groups is inadequate due to ->cpus_ptr constraints.
11600 *
11601 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
11602 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
11603 * Something like:
11604 *
11605 * { 0 1 2 3 } { 4 5 6 7 }
11606 * * * * *
11607 *
11608 * If we were to balance group-wise we'd place two tasks in the first group and
11609 * two tasks in the second group. Clearly this is undesired as it will overload
11610 * cpu 3 and leave one of the CPUs in the second group unused.
11611 *
11612 * The current solution to this issue is detecting the skew in the first group
11613 * by noticing the lower domain failed to reach balance and had difficulty
11614 * moving tasks due to affinity constraints.
11615 *
11616 * When this is so detected; this group becomes a candidate for busiest; see
11617 * update_sd_pick_busiest(). And calculate_imbalance() and
11618 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
11619 * to create an effective group imbalance.
11620 *
11621 * This is a somewhat tricky proposition since the next run might not find the
11622 * group imbalance and decide the groups need to be balanced again. A most
11623 * subtle and fragile situation.
11624 */
11625
sg_imbalanced(struct sched_group * group)11626 static inline int sg_imbalanced(struct sched_group *group)
11627 {
11628 return group->sgc->imbalance;
11629 }
11630
11631 /*
11632 * group_has_capacity returns true if the group has spare capacity that could
11633 * be used by some tasks.
11634 * We consider that a group has spare capacity if the number of task is
11635 * smaller than the number of CPUs or if the utilization is lower than the
11636 * available capacity for CFS tasks.
11637 * For the latter, we use a threshold to stabilize the state, to take into
11638 * account the variance of the tasks' load and to return true if the available
11639 * capacity in meaningful for the load balancer.
11640 * As an example, an available capacity of 1% can appear but it doesn't make
11641 * any benefit for the load balance.
11642 */
11643 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)11644 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11645 {
11646 if (sgs->sum_nr_running < sgs->group_weight)
11647 return true;
11648
11649 if ((sgs->group_capacity * imbalance_pct) <
11650 (sgs->group_runnable * 100))
11651 return false;
11652
11653 if ((sgs->group_capacity * 100) >
11654 (sgs->group_util * imbalance_pct))
11655 return true;
11656
11657 return false;
11658 }
11659
11660 /*
11661 * group_is_overloaded returns true if the group has more tasks than it can
11662 * handle.
11663 * group_is_overloaded is not equals to !group_has_capacity because a group
11664 * with the exact right number of tasks, has no more spare capacity but is not
11665 * overloaded so both group_has_capacity and group_is_overloaded return
11666 * false.
11667 */
11668 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)11669 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
11670 {
11671 /*
11672 * With EAS and uclamp, 1 CPU in the group must be overutilized to
11673 * consider the group overloaded.
11674 */
11675 if (sched_energy_enabled() && !sgs->group_overutilized)
11676 return false;
11677
11678 if (sgs->sum_nr_running <= sgs->group_weight)
11679 return false;
11680
11681 if ((sgs->group_capacity * 100) <
11682 (sgs->group_util * imbalance_pct))
11683 return true;
11684
11685 if ((sgs->group_capacity * imbalance_pct) <
11686 (sgs->group_runnable * 100))
11687 return true;
11688
11689 return false;
11690 }
11691
11692 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)11693 group_type group_classify(unsigned int imbalance_pct,
11694 struct sched_group *group,
11695 struct sg_lb_stats *sgs)
11696 {
11697 if (group_is_overloaded(imbalance_pct, sgs))
11698 return group_overloaded;
11699
11700 if (sgs->group_llc_balance)
11701 return group_llc_balance;
11702
11703 if (sg_imbalanced(group))
11704 return group_imbalanced;
11705
11706 if (sgs->group_asym_packing)
11707 return group_asym_packing;
11708
11709 if (sgs->group_smt_balance)
11710 return group_smt_balance;
11711
11712 if (sgs->group_misfit_task_load)
11713 return group_misfit_task;
11714
11715 if (!group_has_capacity(imbalance_pct, sgs))
11716 return group_fully_busy;
11717
11718 return group_has_spare;
11719 }
11720
11721 /**
11722 * sched_use_asym_prio - Check whether asym_packing priority must be used
11723 * @sd: The scheduling domain of the load balancing
11724 * @cpu: A CPU
11725 *
11726 * Always use CPU priority when balancing load between SMT siblings. When
11727 * balancing load between cores, it is not sufficient that @cpu is idle. Only
11728 * use CPU priority if the whole core is idle.
11729 *
11730 * Returns: True if the priority of @cpu must be followed. False otherwise.
11731 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)11732 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
11733 {
11734 if (!(sd->flags & SD_ASYM_PACKING))
11735 return false;
11736
11737 if (!sched_smt_active())
11738 return true;
11739
11740 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
11741 }
11742
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)11743 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
11744 {
11745 /*
11746 * First check if @dst_cpu can do asym_packing load balance. Only do it
11747 * if it has higher priority than @src_cpu.
11748 */
11749 return sched_use_asym_prio(sd, dst_cpu) &&
11750 sched_asym_prefer(dst_cpu, src_cpu);
11751 }
11752
11753 /**
11754 * sched_group_asym - Check if the destination CPU can do asym_packing balance
11755 * @env: The load balancing environment
11756 * @sgs: Load-balancing statistics of the candidate busiest group
11757 * @group: The candidate busiest group
11758 *
11759 * @env::dst_cpu can do asym_packing if it has higher priority than the
11760 * preferred CPU of @group.
11761 *
11762 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
11763 * otherwise.
11764 */
11765 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11766 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
11767 {
11768 /*
11769 * CPU priorities do not make sense for SMT cores with more than one
11770 * busy sibling.
11771 */
11772 if ((group->flags & SD_SHARE_CPUCAPACITY) &&
11773 (sgs->group_weight - sgs->idle_cpus != 1))
11774 return false;
11775
11776 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
11777 }
11778
11779 /* One group has more than one SMT CPU while the other group does not */
smt_vs_nonsmt_groups(struct sched_group * sg1,struct sched_group * sg2)11780 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
11781 struct sched_group *sg2)
11782 {
11783 if (!sg1 || !sg2)
11784 return false;
11785
11786 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
11787 (sg2->flags & SD_SHARE_CPUCAPACITY);
11788 }
11789
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11790 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
11791 struct sched_group *group)
11792 {
11793 if (!env->idle)
11794 return false;
11795
11796 /*
11797 * For SMT source group, it is better to move a task
11798 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
11799 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
11800 * will not be on.
11801 */
11802 if (group->flags & SD_SHARE_CPUCAPACITY &&
11803 sgs->sum_h_nr_running > 1)
11804 return true;
11805
11806 return false;
11807 }
11808
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)11809 static inline long sibling_imbalance(struct lb_env *env,
11810 struct sd_lb_stats *sds,
11811 struct sg_lb_stats *busiest,
11812 struct sg_lb_stats *local)
11813 {
11814 int ncores_busiest, ncores_local;
11815 long imbalance;
11816
11817 if (!env->idle || !busiest->sum_nr_running)
11818 return 0;
11819
11820 ncores_busiest = sds->busiest->cores;
11821 ncores_local = sds->local->cores;
11822
11823 if (ncores_busiest == ncores_local) {
11824 imbalance = busiest->sum_nr_running;
11825 lsub_positive(&imbalance, local->sum_nr_running);
11826 return imbalance;
11827 }
11828
11829 /* Balance such that nr_running/ncores ratio are same on both groups */
11830 imbalance = ncores_local * busiest->sum_nr_running;
11831 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
11832 /* Normalize imbalance and do rounding on normalization */
11833 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
11834 imbalance /= ncores_local + ncores_busiest;
11835
11836 /* Take advantage of resource in an empty sched group */
11837 if (imbalance <= 1 && local->sum_nr_running == 0 &&
11838 busiest->sum_nr_running > 1)
11839 imbalance = 2;
11840
11841 return imbalance;
11842 }
11843
11844 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)11845 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
11846 {
11847 /*
11848 * When there is more than 1 task, the group_overloaded case already
11849 * takes care of cpu with reduced capacity
11850 */
11851 if (rq->cfs.h_nr_runnable != 1)
11852 return false;
11853
11854 return check_cpu_capacity(rq, sd);
11855 }
11856
11857 #ifdef CONFIG_SCHED_CACHE
11858 /*
11859 * Record the statistics for this scheduler group for later
11860 * use. These values guide load balancing on aggregating tasks
11861 * to a LLC.
11862 */
record_sg_llc_stats(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11863 static void record_sg_llc_stats(struct lb_env *env,
11864 struct sg_lb_stats *sgs,
11865 struct sched_group *group)
11866 {
11867 struct sched_domain_shared *sd_share;
11868 int cpu;
11869
11870 if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE)
11871 return;
11872
11873 /* Only care about sched domain spanning multiple LLCs */
11874 if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu)))
11875 return;
11876
11877 /*
11878 * At this point we know this group spans a LLC domain.
11879 * Record the statistic of this group in its corresponding
11880 * shared LLC domain.
11881 * Note: sd_share cannot be obtained via sd->child->shared,
11882 * because the latter refers to the domain that covers the
11883 * local group. Instead, sd_share should be located using
11884 * the first CPU of the LLC group.
11885 */
11886 cpu = cpumask_first(sched_group_span(group));
11887 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
11888 if (!sd_share)
11889 return;
11890
11891 if (READ_ONCE(sd_share->util_avg) != sgs->group_util)
11892 WRITE_ONCE(sd_share->util_avg, sgs->group_util);
11893
11894 if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity))
11895 WRITE_ONCE(sd_share->capacity, sgs->group_capacity);
11896 }
11897
11898 /*
11899 * Do LLC balance on sched group that contains LLC, and have tasks preferring
11900 * to run on LLC in idle dst_cpu.
11901 */
llc_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11902 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
11903 struct sched_group *group)
11904 {
11905 if (!sched_cache_enabled())
11906 return false;
11907
11908 if (env->sd->flags & SD_SHARE_LLC)
11909 return false;
11910
11911 /*
11912 * On asymmetric domains, group_misfit_task_load
11913 * should be prioritized to move tasks to CPU that fit them
11914 * over aggregating tasks to their preferred LLC.
11915 */
11916 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
11917 sgs->group_misfit_task_load)
11918 return false;
11919
11920 /*
11921 * Skip cache aware tagging if nr_balanced_failed is sufficiently high.
11922 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed
11923 * to avoid excessive task migration at the same time.
11924 */
11925 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1)
11926 return false;
11927
11928 if (sgs->nr_pref_dst_llc &&
11929 can_migrate_llc(cpumask_first(sched_group_span(group)),
11930 env->dst_cpu, 0, true) == mig_llc)
11931 return true;
11932
11933 return false;
11934 }
11935
update_llc_busiest(struct lb_env * env,struct sg_lb_stats * busiest,struct sg_lb_stats * sgs)11936 static bool update_llc_busiest(struct lb_env *env,
11937 struct sg_lb_stats *busiest,
11938 struct sg_lb_stats *sgs)
11939 {
11940 /*
11941 * There are more tasks that want to run on dst_cpu's LLC.
11942 */
11943 return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc;
11944 }
11945 #else
record_sg_llc_stats(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11946 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs,
11947 struct sched_group *group)
11948 {
11949 }
11950
llc_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)11951 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs,
11952 struct sched_group *group)
11953 {
11954 return false;
11955 }
11956
update_llc_busiest(struct lb_env * env,struct sg_lb_stats * busiest,struct sg_lb_stats * sgs)11957 static bool update_llc_busiest(struct lb_env *env,
11958 struct sg_lb_stats *busiest,
11959 struct sg_lb_stats *sgs)
11960 {
11961 return false;
11962 }
11963 #endif
11964
11965 /**
11966 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
11967 * @env: The load balancing environment.
11968 * @sds: Load-balancing data with statistics of the local group.
11969 * @group: sched_group whose statistics are to be updated.
11970 * @sgs: variable to hold the statistics for this group.
11971 * @sg_overloaded: sched_group is overloaded
11972 */
update_sg_lb_stats(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * group,struct sg_lb_stats * sgs,bool * sg_overloaded)11973 static inline void update_sg_lb_stats(struct lb_env *env,
11974 struct sd_lb_stats *sds,
11975 struct sched_group *group,
11976 struct sg_lb_stats *sgs,
11977 bool *sg_overloaded)
11978 {
11979 int i, nr_running, local_group, sd_flags = env->sd->flags;
11980 bool balancing_at_rd = !env->sd->parent;
11981
11982 memset(sgs, 0, sizeof(*sgs));
11983
11984 local_group = group == sds->local;
11985
11986 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11987 struct rq *rq = cpu_rq(i);
11988 unsigned long load = cpu_load(rq);
11989
11990 sgs->group_load += load;
11991 sgs->group_util += cpu_util_cfs(i);
11992 sgs->group_runnable += cpu_runnable(rq);
11993 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
11994
11995 nr_running = rq->nr_running;
11996 sgs->sum_nr_running += nr_running;
11997
11998 if (cpu_overutilized(i))
11999 sgs->group_overutilized = 1;
12000
12001 #ifdef CONFIG_SCHED_CACHE
12002 if (sched_cache_enabled()) {
12003 struct sched_domain *sd_tmp;
12004 int dst_llc;
12005
12006 dst_llc = llc_id(env->dst_cpu);
12007 if (llc_id(i) != dst_llc) {
12008 sd_tmp = rcu_dereference_all(rq->sd);
12009 if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max)
12010 sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc];
12011 }
12012 }
12013 #endif
12014
12015 /*
12016 * No need to call idle_cpu() if nr_running is not 0
12017 */
12018 if (!nr_running && idle_cpu(i)) {
12019 sgs->idle_cpus++;
12020 /* Idle cpu can't have misfit task */
12021 continue;
12022 }
12023
12024 /* Overload indicator is only updated at root domain */
12025 if (balancing_at_rd && nr_running > 1)
12026 *sg_overloaded = 1;
12027
12028 #ifdef CONFIG_NUMA_BALANCING
12029 /* Only fbq_classify_group() uses this to classify NUMA groups */
12030 if (sd_flags & SD_NUMA) {
12031 sgs->nr_numa_running += rq->nr_numa_running;
12032 sgs->nr_preferred_running += rq->nr_preferred_running;
12033 }
12034 #endif
12035 if (local_group)
12036 continue;
12037
12038 if (sd_flags & SD_ASYM_CPUCAPACITY) {
12039 if (rq->misfit_task_load) {
12040 /*
12041 * Always mark the root domain overloaded so big
12042 * CPUs can pick up misfit tasks via newly idle
12043 * balance.
12044 */
12045 if (balancing_at_rd)
12046 *sg_overloaded = 1;
12047
12048 /*
12049 * Only account misfit load if @dst_cpu can
12050 * help; otherwise, the group may be classified
12051 * as misfit_task and update_sd_pick_busiest()
12052 * will skip it.
12053 */
12054 if (capacity_greater(capacity_of(env->dst_cpu),
12055 group->sgc->max_capacity) &&
12056 (sgs->group_misfit_task_load < rq->misfit_task_load))
12057 sgs->group_misfit_task_load = rq->misfit_task_load;
12058 }
12059 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
12060 /* Check for a task running on a CPU with reduced capacity */
12061 if (sgs->group_misfit_task_load < load)
12062 sgs->group_misfit_task_load = load;
12063 }
12064 }
12065
12066 sgs->group_capacity = group->sgc->capacity;
12067
12068 sgs->group_weight = group->group_weight;
12069
12070 if (!local_group) {
12071 /* Check if dst CPU is idle and preferred to this group */
12072 if (env->idle && sgs->sum_h_nr_running &&
12073 sched_group_asym(env, sgs, group))
12074 sgs->group_asym_packing = 1;
12075
12076 /* Check for loaded SMT group to be balanced to dst CPU */
12077 if (smt_balance(env, sgs, group))
12078 sgs->group_smt_balance = 1;
12079
12080 /* Check for tasks in this group can be moved to their preferred LLC */
12081 if (llc_balance(env, sgs, group))
12082 sgs->group_llc_balance = 1;
12083 }
12084
12085 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
12086
12087 record_sg_llc_stats(env, sgs, group);
12088 /* Computing avg_load makes sense only when group is overloaded */
12089 if (sgs->group_type == group_overloaded)
12090 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12091 sgs->group_capacity;
12092 }
12093
12094 /**
12095 * update_sd_pick_busiest - return 1 on busiest group
12096 * @env: The load balancing environment.
12097 * @sds: sched_domain statistics
12098 * @sg: sched_group candidate to be checked for being the busiest
12099 * @sgs: sched_group statistics
12100 *
12101 * Determine if @sg is a busier group than the previously selected
12102 * busiest group.
12103 *
12104 * Return: %true if @sg is a busier group than the previously selected
12105 * busiest group. %false otherwise.
12106 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)12107 static bool update_sd_pick_busiest(struct lb_env *env,
12108 struct sd_lb_stats *sds,
12109 struct sched_group *sg,
12110 struct sg_lb_stats *sgs)
12111 {
12112 struct sg_lb_stats *busiest = &sds->busiest_stat;
12113
12114 /* Make sure that there is at least one task to pull */
12115 if (!sgs->sum_h_nr_running)
12116 return false;
12117
12118 /*
12119 * Don't try to pull misfit tasks we can't help.
12120 * We can use max_capacity here as reduction in capacity on some
12121 * CPUs in the group should either be possible to resolve
12122 * internally or be covered by avg_load imbalance (eventually).
12123 *
12124 * When SMT is active, only pull a misfit to dst_cpu if it is on a
12125 * fully idle core; otherwise the effective capacity of the core is
12126 * reduced and we may not actually provide more capacity than the
12127 * source.
12128 */
12129 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12130 (sgs->group_type == group_misfit_task) &&
12131 (!env->dst_core_idle ||
12132 !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
12133 sds->local_stat.group_type != group_has_spare))
12134 return false;
12135
12136 /*
12137 * Candidate sg has no more than one task per CPU and has higher
12138 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
12139 * throughput. Maximize throughput, power/energy consequences are not
12140 * considered.
12141 */
12142 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
12143 (sgs->group_type <= group_fully_busy) &&
12144 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
12145 return false;
12146
12147 if (sgs->group_type > busiest->group_type)
12148 return true;
12149
12150 if (sgs->group_type < busiest->group_type)
12151 return false;
12152
12153 /*
12154 * The candidate and the current busiest group are the same type of
12155 * group. Let check which one is the busiest according to the type.
12156 */
12157
12158 switch (sgs->group_type) {
12159 case group_overloaded:
12160 /* Select the overloaded group with highest avg_load. */
12161 return sgs->avg_load > busiest->avg_load;
12162
12163 case group_llc_balance:
12164 /* Select the group with most tasks preferring dst LLC */
12165 return update_llc_busiest(env, busiest, sgs);
12166
12167 case group_imbalanced:
12168 /*
12169 * Select the 1st imbalanced group as we don't have any way to
12170 * choose one more than another.
12171 */
12172 return false;
12173
12174 case group_asym_packing:
12175 /* Prefer to move from lowest priority CPU's work */
12176 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
12177 READ_ONCE(sg->asym_prefer_cpu));
12178
12179 case group_misfit_task:
12180 /*
12181 * If we have more than one misfit sg go with the biggest
12182 * misfit.
12183 */
12184 return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
12185
12186 case group_smt_balance:
12187 /*
12188 * Check if we have spare CPUs on either SMT group to
12189 * choose has spare or fully busy handling.
12190 */
12191 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
12192 goto has_spare;
12193
12194 fallthrough;
12195
12196 case group_fully_busy:
12197 /*
12198 * Select the fully busy group with highest avg_load. In
12199 * theory, there is no need to pull task from such kind of
12200 * group because tasks have all compute capacity that they need
12201 * but we can still improve the overall throughput by reducing
12202 * contention when accessing shared HW resources.
12203 *
12204 * XXX for now avg_load is not computed and always 0 so we
12205 * select the 1st one, except if @sg is composed of SMT
12206 * siblings.
12207 */
12208
12209 if (sgs->avg_load < busiest->avg_load)
12210 return false;
12211
12212 if (sgs->avg_load == busiest->avg_load) {
12213 /*
12214 * SMT sched groups need more help than non-SMT groups.
12215 * If @sg happens to also be SMT, either choice is good.
12216 */
12217 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
12218 return false;
12219 }
12220
12221 break;
12222
12223 case group_has_spare:
12224 /*
12225 * Do not pick sg with SMT CPUs over sg with pure CPUs,
12226 * as we do not want to pull task off SMT core with one task
12227 * and make the core idle.
12228 */
12229 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
12230 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
12231 return false;
12232 else
12233 return true;
12234 }
12235 has_spare:
12236
12237 /*
12238 * Select not overloaded group with lowest number of idle CPUs
12239 * and highest number of running tasks. We could also compare
12240 * the spare capacity which is more stable but it can end up
12241 * that the group has less spare capacity but finally more idle
12242 * CPUs which means less opportunity to pull tasks.
12243 */
12244 if (sgs->idle_cpus > busiest->idle_cpus)
12245 return false;
12246 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
12247 (sgs->sum_nr_running <= busiest->sum_nr_running))
12248 return false;
12249
12250 break;
12251 }
12252
12253 return true;
12254 }
12255
12256 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)12257 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12258 {
12259 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
12260 return regular;
12261 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
12262 return remote;
12263 return all;
12264 }
12265
fbq_classify_rq(struct rq * rq)12266 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12267 {
12268 if (rq->nr_running > rq->nr_numa_running)
12269 return regular;
12270 if (rq->nr_running > rq->nr_preferred_running)
12271 return remote;
12272 return all;
12273 }
12274 #else /* !CONFIG_NUMA_BALANCING: */
fbq_classify_group(struct sg_lb_stats * sgs)12275 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
12276 {
12277 return all;
12278 }
12279
fbq_classify_rq(struct rq * rq)12280 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
12281 {
12282 return regular;
12283 }
12284 #endif /* !CONFIG_NUMA_BALANCING */
12285
12286
12287 struct sg_lb_stats;
12288
12289 /*
12290 * task_running_on_cpu - return 1 if @p is running on @cpu.
12291 */
12292
task_running_on_cpu(int cpu,struct task_struct * p)12293 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
12294 {
12295 /* Task has no contribution or is new */
12296 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
12297 return 0;
12298
12299 if (task_on_rq_queued(p))
12300 return 1;
12301
12302 return 0;
12303 }
12304
12305 /**
12306 * idle_cpu_without - would a given CPU be idle without p ?
12307 * @cpu: the processor on which idleness is tested.
12308 * @p: task which should be ignored.
12309 *
12310 * Return: 1 if the CPU would be idle. 0 otherwise.
12311 */
idle_cpu_without(int cpu,struct task_struct * p)12312 static int idle_cpu_without(int cpu, struct task_struct *p)
12313 {
12314 struct rq *rq = cpu_rq(cpu);
12315
12316 if (rq->curr != rq->idle && rq->curr != p)
12317 return 0;
12318
12319 /*
12320 * rq->nr_running can't be used but an updated version without the
12321 * impact of p on cpu must be used instead. The updated nr_running
12322 * be computed and tested before calling idle_cpu_without().
12323 */
12324
12325 if (rq->ttwu_pending)
12326 return 0;
12327
12328 return 1;
12329 }
12330
12331 /*
12332 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
12333 * @sd: The sched_domain level to look for idlest group.
12334 * @group: sched_group whose statistics are to be updated.
12335 * @sgs: variable to hold the statistics for this group.
12336 * @p: The task for which we look for the idlest group/CPU.
12337 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)12338 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
12339 struct sched_group *group,
12340 struct sg_lb_stats *sgs,
12341 struct task_struct *p)
12342 {
12343 int i, nr_running;
12344
12345 memset(sgs, 0, sizeof(*sgs));
12346
12347 /* Assume that task can't fit any CPU of the group */
12348 if (sd->flags & SD_ASYM_CPUCAPACITY)
12349 sgs->group_misfit_task_load = 1;
12350
12351 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
12352 struct rq *rq = cpu_rq(i);
12353 unsigned int local;
12354
12355 sgs->group_load += cpu_load_without(rq, p);
12356 sgs->group_util += cpu_util_without(i, p);
12357 sgs->group_runnable += cpu_runnable_without(rq, p);
12358 local = task_running_on_cpu(i, p);
12359 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
12360
12361 nr_running = rq->nr_running - local;
12362 sgs->sum_nr_running += nr_running;
12363
12364 /*
12365 * No need to call idle_cpu_without() if nr_running is not 0
12366 */
12367 if (!nr_running && idle_cpu_without(i, p))
12368 sgs->idle_cpus++;
12369
12370 /* Check if task fits in the CPU */
12371 if (sd->flags & SD_ASYM_CPUCAPACITY &&
12372 sgs->group_misfit_task_load &&
12373 task_fits_cpu(p, i))
12374 sgs->group_misfit_task_load = 0;
12375
12376 }
12377
12378 sgs->group_capacity = group->sgc->capacity;
12379
12380 sgs->group_weight = group->group_weight;
12381
12382 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
12383
12384 /*
12385 * Computing avg_load makes sense only when group is fully busy or
12386 * overloaded
12387 */
12388 if (sgs->group_type == group_fully_busy ||
12389 sgs->group_type == group_overloaded)
12390 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
12391 sgs->group_capacity;
12392 }
12393
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)12394 static bool update_pick_idlest(struct sched_group *idlest,
12395 struct sg_lb_stats *idlest_sgs,
12396 struct sched_group *group,
12397 struct sg_lb_stats *sgs)
12398 {
12399 if (sgs->group_type < idlest_sgs->group_type)
12400 return true;
12401
12402 if (sgs->group_type > idlest_sgs->group_type)
12403 return false;
12404
12405 /*
12406 * The candidate and the current idlest group are the same type of
12407 * group. Let check which one is the idlest according to the type.
12408 */
12409
12410 switch (sgs->group_type) {
12411 case group_overloaded:
12412 case group_fully_busy:
12413 /* Select the group with lowest avg_load. */
12414 if (idlest_sgs->avg_load <= sgs->avg_load)
12415 return false;
12416 break;
12417
12418 case group_llc_balance:
12419 case group_imbalanced:
12420 case group_asym_packing:
12421 case group_smt_balance:
12422 /* Those types are not used in the slow wakeup path */
12423 return false;
12424
12425 case group_misfit_task:
12426 /* Select group with the highest max capacity */
12427 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
12428 return false;
12429 break;
12430
12431 case group_has_spare:
12432 /* Select group with most idle CPUs */
12433 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
12434 return false;
12435
12436 /* Select group with lowest group_util */
12437 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
12438 idlest_sgs->group_util <= sgs->group_util)
12439 return false;
12440
12441 break;
12442 }
12443
12444 return true;
12445 }
12446
12447 /*
12448 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
12449 * domain.
12450 *
12451 * Assumes p is allowed on at least one CPU in sd.
12452 */
12453 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)12454 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
12455 {
12456 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
12457 struct sg_lb_stats local_sgs, tmp_sgs;
12458 struct sg_lb_stats *sgs;
12459 unsigned long imbalance;
12460 struct sg_lb_stats idlest_sgs = {
12461 .avg_load = UINT_MAX,
12462 .group_type = group_overloaded,
12463 };
12464
12465 do {
12466 int local_group;
12467
12468 /* Skip over this group if it has no CPUs allowed */
12469 if (!cpumask_intersects(sched_group_span(group),
12470 p->cpus_ptr))
12471 continue;
12472
12473 /* Skip over this group if no cookie matched */
12474 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
12475 continue;
12476
12477 local_group = cpumask_test_cpu(this_cpu,
12478 sched_group_span(group));
12479
12480 if (local_group) {
12481 sgs = &local_sgs;
12482 local = group;
12483 } else {
12484 sgs = &tmp_sgs;
12485 }
12486
12487 update_sg_wakeup_stats(sd, group, sgs, p);
12488
12489 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
12490 idlest = group;
12491 idlest_sgs = *sgs;
12492 }
12493
12494 } while (group = group->next, group != sd->groups);
12495
12496
12497 /* There is no idlest group to push tasks to */
12498 if (!idlest)
12499 return NULL;
12500
12501 /* The local group has been skipped because of CPU affinity */
12502 if (!local)
12503 return idlest;
12504
12505 /*
12506 * If the local group is idler than the selected idlest group
12507 * don't try and push the task.
12508 */
12509 if (local_sgs.group_type < idlest_sgs.group_type)
12510 return NULL;
12511
12512 /*
12513 * If the local group is busier than the selected idlest group
12514 * try and push the task.
12515 */
12516 if (local_sgs.group_type > idlest_sgs.group_type)
12517 return idlest;
12518
12519 switch (local_sgs.group_type) {
12520 case group_overloaded:
12521 case group_fully_busy:
12522
12523 /* Calculate allowed imbalance based on load */
12524 imbalance = scale_load_down(NICE_0_LOAD) *
12525 (sd->imbalance_pct-100) / 100;
12526
12527 /*
12528 * When comparing groups across NUMA domains, it's possible for
12529 * the local domain to be very lightly loaded relative to the
12530 * remote domains but "imbalance" skews the comparison making
12531 * remote CPUs look much more favourable. When considering
12532 * cross-domain, add imbalance to the load on the remote node
12533 * and consider staying local.
12534 */
12535
12536 if ((sd->flags & SD_NUMA) &&
12537 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
12538 return NULL;
12539
12540 /*
12541 * If the local group is less loaded than the selected
12542 * idlest group don't try and push any tasks.
12543 */
12544 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
12545 return NULL;
12546
12547 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
12548 return NULL;
12549 break;
12550
12551 case group_llc_balance:
12552 case group_imbalanced:
12553 case group_asym_packing:
12554 case group_smt_balance:
12555 /* Those type are not used in the slow wakeup path */
12556 return NULL;
12557
12558 case group_misfit_task:
12559 /* Select group with the highest max capacity */
12560 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
12561 return NULL;
12562 break;
12563
12564 case group_has_spare:
12565 #ifdef CONFIG_NUMA
12566 if (sd->flags & SD_NUMA) {
12567 int imb_numa_nr = sd->imb_numa_nr;
12568 #ifdef CONFIG_NUMA_BALANCING
12569 int idlest_cpu;
12570 /*
12571 * If there is spare capacity at NUMA, try to select
12572 * the preferred node
12573 */
12574 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
12575 return NULL;
12576
12577 idlest_cpu = cpumask_first(sched_group_span(idlest));
12578 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
12579 return idlest;
12580 #endif /* CONFIG_NUMA_BALANCING */
12581 /*
12582 * Otherwise, keep the task close to the wakeup source
12583 * and improve locality if the number of running tasks
12584 * would remain below threshold where an imbalance is
12585 * allowed while accounting for the possibility the
12586 * task is pinned to a subset of CPUs. If there is a
12587 * real need of migration, periodic load balance will
12588 * take care of it.
12589 */
12590 if (p->nr_cpus_allowed != NR_CPUS) {
12591 unsigned int w = cpumask_weight_and(p->cpus_ptr,
12592 sched_group_span(local));
12593 imb_numa_nr = min(w, sd->imb_numa_nr);
12594 }
12595
12596 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
12597 if (!adjust_numa_imbalance(imbalance,
12598 local_sgs.sum_nr_running + 1,
12599 imb_numa_nr)) {
12600 return NULL;
12601 }
12602 }
12603 #endif /* CONFIG_NUMA */
12604
12605 /*
12606 * Select group with highest number of idle CPUs. We could also
12607 * compare the utilization which is more stable but it can end
12608 * up that the group has less spare capacity but finally more
12609 * idle CPUs which means more opportunity to run task.
12610 */
12611 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
12612 return NULL;
12613 break;
12614 }
12615
12616 return idlest;
12617 }
12618
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)12619 static void update_idle_cpu_scan(struct lb_env *env,
12620 unsigned long sum_util)
12621 {
12622 struct sched_domain_shared *sd_share;
12623 struct sched_domain *sd = env->sd;
12624 int llc_weight, pct;
12625 u64 x, y, tmp;
12626 /*
12627 * Update the number of CPUs to scan in LLC domain, which could
12628 * be used as a hint in select_idle_cpu(). The update of sd_share
12629 * could be expensive because it is within a shared cache line.
12630 * So the write of this hint only occurs during periodic load
12631 * balancing, rather than CPU_NEWLY_IDLE, because the latter
12632 * can fire way more frequently than the former.
12633 */
12634 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
12635 return;
12636
12637 sd_share = sd->shared;
12638 if (!sd_share)
12639 return;
12640
12641 /*
12642 * The number of CPUs to search drops as sum_util increases, when
12643 * sum_util hits 85% or above, the scan stops.
12644 * The reason to choose 85% as the threshold is because this is the
12645 * imbalance_pct(117) when a LLC sched group is overloaded.
12646 *
12647 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
12648 * and y'= y / SCHED_CAPACITY_SCALE
12649 *
12650 * x is the ratio of sum_util compared to the CPU capacity:
12651 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
12652 * y' is the ratio of CPUs to be scanned in the LLC domain,
12653 * and the number of CPUs to scan is calculated by:
12654 *
12655 * nr_scan = llc_weight * y' [2]
12656 *
12657 * When x hits the threshold of overloaded, AKA, when
12658 * x = 100 / pct, y drops to 0. According to [1],
12659 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
12660 *
12661 * Scale x by SCHED_CAPACITY_SCALE:
12662 * x' = sum_util / llc_weight; [3]
12663 *
12664 * and finally [1] becomes:
12665 * y = SCHED_CAPACITY_SCALE -
12666 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
12667 *
12668 */
12669 /* equation [3] */
12670 x = sum_util;
12671 llc_weight = sd->span_weight;
12672 do_div(x, llc_weight);
12673
12674 /* equation [4] */
12675 pct = sd->imbalance_pct;
12676 tmp = x * x * pct * pct;
12677 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
12678 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
12679 y = SCHED_CAPACITY_SCALE - tmp;
12680
12681 /* equation [2] */
12682 y *= llc_weight;
12683 do_div(y, SCHED_CAPACITY_SCALE);
12684 if ((int)y != sd_share->nr_idle_scan)
12685 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
12686 }
12687
12688 /**
12689 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
12690 * @env: The load balancing environment.
12691 * @sds: variable to hold the statistics for this sched_domain.
12692 */
12693
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)12694 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
12695 {
12696 struct sched_group *sg = env->sd->groups;
12697 struct sg_lb_stats *local = &sds->local_stat;
12698 struct sg_lb_stats tmp_sgs;
12699 unsigned long sum_util = 0;
12700 bool sg_overloaded = 0, sg_overutilized = 0;
12701
12702 env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu);
12703
12704 do {
12705 struct sg_lb_stats *sgs = &tmp_sgs;
12706 int local_group;
12707
12708 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
12709 if (local_group) {
12710 sds->local = sg;
12711 sgs = local;
12712
12713 if (env->idle != CPU_NEWLY_IDLE ||
12714 time_after_eq(jiffies, sg->sgc->next_update))
12715 update_group_capacity(env->sd, env->dst_cpu);
12716 }
12717
12718 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded);
12719
12720 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
12721 sds->busiest = sg;
12722 sds->busiest_stat = *sgs;
12723 }
12724
12725 sg_overutilized |= sgs->group_overutilized;
12726
12727 /* Now, start updating sd_lb_stats */
12728 sds->total_load += sgs->group_load;
12729 sds->total_capacity += sgs->group_capacity;
12730
12731 sum_util += sgs->group_util;
12732 sg = sg->next;
12733 } while (sg != env->sd->groups);
12734
12735 /*
12736 * Indicate that the child domain of the busiest group prefers tasks
12737 * go to a child's sibling domains first. NB the flags of a sched group
12738 * are those of the child domain.
12739 */
12740 if (sds->busiest)
12741 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
12742
12743
12744 if (env->sd->flags & SD_NUMA)
12745 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
12746
12747 if (!env->sd->parent) {
12748 /* update overload indicator if we are at root domain */
12749 set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
12750
12751 /* Update over-utilization (tipping point, U >= 0) indicator */
12752 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
12753 } else if (sg_overutilized) {
12754 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
12755 }
12756
12757 update_idle_cpu_scan(env, sum_util);
12758 }
12759
12760 /**
12761 * calculate_imbalance - Calculate the amount of imbalance present within the
12762 * groups of a given sched_domain during load balance.
12763 * @env: load balance environment
12764 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
12765 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)12766 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
12767 {
12768 struct sg_lb_stats *local, *busiest;
12769
12770 local = &sds->local_stat;
12771 busiest = &sds->busiest_stat;
12772
12773 if (busiest->group_type == group_misfit_task) {
12774 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
12775 /* Set imbalance to allow misfit tasks to be balanced. */
12776 env->migration_type = migrate_misfit;
12777 env->imbalance = 1;
12778 } else {
12779 /*
12780 * Set load imbalance to allow moving task from cpu
12781 * with reduced capacity.
12782 */
12783 env->migration_type = migrate_load;
12784 env->imbalance = busiest->group_misfit_task_load;
12785 }
12786 return;
12787 }
12788
12789 if (busiest->group_type == group_asym_packing) {
12790 /*
12791 * In case of asym capacity, we will try to migrate all load to
12792 * the preferred CPU.
12793 */
12794 env->migration_type = migrate_task;
12795 env->imbalance = busiest->sum_h_nr_running;
12796 return;
12797 }
12798
12799 if (busiest->group_type == group_smt_balance) {
12800 /* Reduce number of tasks sharing CPU capacity */
12801 env->migration_type = migrate_task;
12802 env->imbalance = 1;
12803 return;
12804 }
12805
12806 #ifdef CONFIG_SCHED_CACHE
12807 if (busiest->group_type == group_llc_balance) {
12808 /* Move a task that prefer local LLC */
12809 env->migration_type = migrate_llc_task;
12810 env->imbalance = 1;
12811 return;
12812 }
12813 #endif
12814
12815 if (busiest->group_type == group_imbalanced) {
12816 /*
12817 * In the group_imb case we cannot rely on group-wide averages
12818 * to ensure CPU-load equilibrium, try to move any task to fix
12819 * the imbalance. The next load balance will take care of
12820 * balancing back the system.
12821 */
12822 env->migration_type = migrate_task;
12823 env->imbalance = 1;
12824 return;
12825 }
12826
12827 /*
12828 * Try to use spare capacity of local group without overloading it or
12829 * emptying busiest.
12830 */
12831 if (local->group_type == group_has_spare) {
12832 if ((busiest->group_type > group_fully_busy) &&
12833 !(env->sd->flags & SD_SHARE_LLC)) {
12834 /*
12835 * If busiest is overloaded, try to fill spare
12836 * capacity. This might end up creating spare capacity
12837 * in busiest or busiest still being overloaded but
12838 * there is no simple way to directly compute the
12839 * amount of load to migrate in order to balance the
12840 * system.
12841 */
12842 env->migration_type = migrate_util;
12843 env->imbalance = max(local->group_capacity, local->group_util) -
12844 local->group_util;
12845
12846 /*
12847 * In some cases, the group's utilization is max or even
12848 * higher than capacity because of migrations but the
12849 * local CPU is (newly) idle. There is at least one
12850 * waiting task in this overloaded busiest group. Let's
12851 * try to pull it.
12852 */
12853 if (env->idle && env->imbalance == 0) {
12854 env->migration_type = migrate_task;
12855 env->imbalance = 1;
12856 }
12857
12858 return;
12859 }
12860
12861 if (busiest->group_weight == 1 || sds->prefer_sibling) {
12862 /*
12863 * When prefer sibling, evenly spread running tasks on
12864 * groups.
12865 */
12866 env->migration_type = migrate_task;
12867 env->imbalance = sibling_imbalance(env, sds, busiest, local);
12868 } else {
12869
12870 /*
12871 * If there is no overload, we just want to even the number of
12872 * idle CPUs.
12873 */
12874 env->migration_type = migrate_task;
12875 env->imbalance = max_t(long, 0,
12876 (local->idle_cpus - busiest->idle_cpus));
12877 }
12878
12879 #ifdef CONFIG_NUMA
12880 /* Consider allowing a small imbalance between NUMA groups */
12881 if (env->sd->flags & SD_NUMA) {
12882 env->imbalance = adjust_numa_imbalance(env->imbalance,
12883 local->sum_nr_running + 1,
12884 env->sd->imb_numa_nr);
12885 }
12886 #endif
12887
12888 /* Number of tasks to move to restore balance */
12889 env->imbalance >>= 1;
12890
12891 return;
12892 }
12893
12894 /*
12895 * Local is fully busy but has to take more load to relieve the
12896 * busiest group
12897 */
12898 if (local->group_type < group_overloaded) {
12899 /*
12900 * Local will become overloaded so the avg_load metrics are
12901 * finally needed.
12902 */
12903
12904 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
12905 local->group_capacity;
12906
12907 /*
12908 * If the local group is more loaded than the selected
12909 * busiest group don't try to pull any tasks.
12910 */
12911 if (local->avg_load >= busiest->avg_load) {
12912 env->imbalance = 0;
12913 return;
12914 }
12915
12916 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
12917 sds->total_capacity;
12918
12919 /*
12920 * If the local group is more loaded than the average system
12921 * load, don't try to pull any tasks.
12922 */
12923 if (local->avg_load >= sds->avg_load) {
12924 env->imbalance = 0;
12925 return;
12926 }
12927
12928 }
12929
12930 /*
12931 * Both group are or will become overloaded and we're trying to get all
12932 * the CPUs to the average_load, so we don't want to push ourselves
12933 * above the average load, nor do we wish to reduce the max loaded CPU
12934 * below the average load. At the same time, we also don't want to
12935 * reduce the group load below the group capacity. Thus we look for
12936 * the minimum possible imbalance.
12937 */
12938 env->migration_type = migrate_load;
12939 env->imbalance = min(
12940 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
12941 (sds->avg_load - local->avg_load) * local->group_capacity
12942 ) / SCHED_CAPACITY_SCALE;
12943 }
12944
12945 /******* sched_balance_find_src_group() helpers end here *********************/
12946
12947 /*
12948 * Decision matrix according to the local and busiest group type:
12949 *
12950 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
12951 * has_spare nr_idle balanced N/A N/A balanced balanced
12952 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
12953 * misfit_task force N/A N/A N/A N/A N/A
12954 * asym_packing force force N/A N/A force force
12955 * imbalanced force force N/A N/A force force
12956 * overloaded force force N/A N/A force avg_load
12957 *
12958 * N/A : Not Applicable because already filtered while updating
12959 * statistics.
12960 * balanced : The system is balanced for these 2 groups.
12961 * force : Calculate the imbalance as load migration is probably needed.
12962 * avg_load : Only if imbalance is significant enough.
12963 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
12964 * different in groups.
12965 */
12966
12967 /**
12968 * sched_balance_find_src_group - Returns the busiest group within the sched_domain
12969 * if there is an imbalance.
12970 * @env: The load balancing environment.
12971 *
12972 * Also calculates the amount of runnable load which should be moved
12973 * to restore balance.
12974 *
12975 * Return: - The busiest group if imbalance exists.
12976 */
sched_balance_find_src_group(struct lb_env * env)12977 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
12978 {
12979 struct sg_lb_stats *local, *busiest;
12980 struct sd_lb_stats sds;
12981
12982 init_sd_lb_stats(&sds);
12983
12984 /*
12985 * Compute the various statistics relevant for load balancing at
12986 * this level.
12987 */
12988 update_sd_lb_stats(env, &sds);
12989
12990 /* There is no busy sibling group to pull tasks from */
12991 if (!sds.busiest)
12992 goto out_balanced;
12993
12994 busiest = &sds.busiest_stat;
12995
12996 /* Misfit tasks should be dealt with regardless of the avg load */
12997 if (busiest->group_type == group_misfit_task)
12998 goto force_balance;
12999
13000 if (!is_rd_overutilized(env->dst_rq->rd) &&
13001 rcu_dereference_all(env->dst_rq->rd->pd))
13002 goto out_balanced;
13003
13004 /* ASYM feature bypasses nice load balance check */
13005 if (busiest->group_type == group_asym_packing)
13006 goto force_balance;
13007
13008 /*
13009 * If the busiest group is imbalanced the below checks don't
13010 * work because they assume all things are equal, which typically
13011 * isn't true due to cpus_ptr constraints and the like.
13012 */
13013 if (busiest->group_type == group_imbalanced)
13014 goto force_balance;
13015
13016 local = &sds.local_stat;
13017 /*
13018 * If the local group is busier than the selected busiest group
13019 * don't try and pull any tasks.
13020 */
13021 if (local->group_type > busiest->group_type)
13022 goto out_balanced;
13023
13024 /*
13025 * When groups are overloaded, use the avg_load to ensure fairness
13026 * between tasks.
13027 */
13028 if (local->group_type == group_overloaded) {
13029 /*
13030 * If the local group is more loaded than the selected
13031 * busiest group don't try to pull any tasks.
13032 */
13033 if (local->avg_load >= busiest->avg_load)
13034 goto out_balanced;
13035
13036 /* XXX broken for overlapping NUMA groups */
13037 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
13038 sds.total_capacity;
13039
13040 /*
13041 * Don't pull any tasks if this group is already above the
13042 * domain average load.
13043 */
13044 if (local->avg_load >= sds.avg_load)
13045 goto out_balanced;
13046
13047 /*
13048 * If the busiest group is more loaded, use imbalance_pct to be
13049 * conservative.
13050 */
13051 if (100 * busiest->avg_load <=
13052 env->sd->imbalance_pct * local->avg_load)
13053 goto out_balanced;
13054 }
13055
13056 /*
13057 * Try to move all excess tasks to a sibling domain of the busiest
13058 * group's child domain.
13059 */
13060 if (sds.prefer_sibling && local->group_type == group_has_spare &&
13061 (busiest->group_type == group_llc_balance ||
13062 sibling_imbalance(env, &sds, busiest, local) > 1))
13063 goto force_balance;
13064
13065 if (busiest->group_type != group_overloaded) {
13066 if (!env->idle) {
13067 /*
13068 * If the busiest group is not overloaded (and as a
13069 * result the local one too) but this CPU is already
13070 * busy, let another idle CPU try to pull task.
13071 */
13072 goto out_balanced;
13073 }
13074
13075 if (busiest->group_type == group_smt_balance &&
13076 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
13077 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
13078 goto force_balance;
13079 }
13080
13081 if (busiest->group_weight > 1 &&
13082 local->idle_cpus <= (busiest->idle_cpus + 1)) {
13083 /*
13084 * If the busiest group is not overloaded
13085 * and there is no imbalance between this and busiest
13086 * group wrt idle CPUs, it is balanced. The imbalance
13087 * becomes significant if the diff is greater than 1
13088 * otherwise we might end up to just move the imbalance
13089 * on another group. Of course this applies only if
13090 * there is more than 1 CPU per group.
13091 */
13092 goto out_balanced;
13093 }
13094
13095 if (busiest->sum_h_nr_running == 1) {
13096 /*
13097 * busiest doesn't have any tasks waiting to run
13098 */
13099 goto out_balanced;
13100 }
13101 }
13102
13103 force_balance:
13104 /* Looks like there is an imbalance. Compute it */
13105 calculate_imbalance(env, &sds);
13106 return env->imbalance ? sds.busiest : NULL;
13107
13108 out_balanced:
13109 env->imbalance = 0;
13110 return NULL;
13111 }
13112
13113 /*
13114 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
13115 */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)13116 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
13117 struct sched_group *group)
13118 {
13119 struct rq *busiest = NULL, *rq;
13120 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
13121 unsigned int __maybe_unused busiest_pref_llc = 0;
13122 struct sched_domain __maybe_unused *sd_tmp;
13123 unsigned int busiest_nr = 0;
13124 int __maybe_unused dst_llc;
13125 int i;
13126
13127 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
13128 unsigned long capacity, load, util;
13129 unsigned int nr_running;
13130 enum fbq_type rt;
13131
13132 rq = cpu_rq(i);
13133 rt = fbq_classify_rq(rq);
13134
13135 /*
13136 * We classify groups/runqueues into three groups:
13137 * - regular: there are !numa tasks
13138 * - remote: there are numa tasks that run on the 'wrong' node
13139 * - all: there is no distinction
13140 *
13141 * In order to avoid migrating ideally placed numa tasks,
13142 * ignore those when there's better options.
13143 *
13144 * If we ignore the actual busiest queue to migrate another
13145 * task, the next balance pass can still reduce the busiest
13146 * queue by moving tasks around inside the node.
13147 *
13148 * If we cannot move enough load due to this classification
13149 * the next pass will adjust the group classification and
13150 * allow migration of more tasks.
13151 *
13152 * Both cases only affect the total convergence complexity.
13153 */
13154 if (rt > env->fbq_type)
13155 continue;
13156
13157 nr_running = rq->cfs.h_nr_runnable;
13158 if (!nr_running)
13159 continue;
13160
13161 capacity = capacity_of(i);
13162
13163 /*
13164 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
13165 * eventually lead to active_balancing high->low capacity.
13166 * Higher per-CPU capacity is considered better than balancing
13167 * average load.
13168 */
13169 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
13170 nr_running == 1) {
13171 bool cluster_equal_cap = static_branch_unlikely(&sched_cluster_active) &&
13172 (get_actual_cpu_capacity(env->dst_cpu) ==
13173 get_actual_cpu_capacity(i));
13174 bool smt_degraded_cap = sched_smt_active() && !is_core_idle(i);
13175
13176 /*
13177 * Busy SMT siblings reduce the capacity of CPU @i. Do
13178 * not skip it in this case.
13179 *
13180 * CONFIG_SCHED_CLUSTER requires balancing load across
13181 * clusters of identical capacity, accounting for
13182 * hardware and cpufreq pressure.
13183 */
13184 if (!smt_degraded_cap && !cluster_equal_cap &&
13185 !capacity_greater(capacity_of(env->dst_cpu), capacity))
13186 continue;
13187 }
13188
13189 /*
13190 * Make sure we only pull tasks from a CPU of lower priority
13191 * when balancing between SMT siblings.
13192 *
13193 * If balancing between cores, let lower priority CPUs help
13194 * SMT cores with more than one busy sibling.
13195 */
13196 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
13197 continue;
13198
13199 switch (env->migration_type) {
13200 case migrate_load:
13201 /*
13202 * When comparing with load imbalance, use cpu_load()
13203 * which is not scaled with the CPU capacity.
13204 */
13205 load = cpu_load(rq);
13206
13207 if (nr_running == 1 && load > env->imbalance &&
13208 !check_cpu_capacity(rq, env->sd))
13209 break;
13210
13211 /*
13212 * For the load comparisons with the other CPUs,
13213 * consider the cpu_load() scaled with the CPU
13214 * capacity, so that the load can be moved away
13215 * from the CPU that is potentially running at a
13216 * lower capacity.
13217 *
13218 * Thus we're looking for max(load_i / capacity_i),
13219 * crosswise multiplication to rid ourselves of the
13220 * division works out to:
13221 * load_i * capacity_j > load_j * capacity_i;
13222 * where j is our previous maximum.
13223 */
13224 if (load * busiest_capacity > busiest_load * capacity) {
13225 busiest_load = load;
13226 busiest_capacity = capacity;
13227 busiest = rq;
13228 }
13229 break;
13230
13231 case migrate_util:
13232 util = cpu_util_cfs_boost(i);
13233
13234 /*
13235 * Don't try to pull utilization from a CPU with one
13236 * running task. Whatever its utilization, we will fail
13237 * detach the task.
13238 */
13239 if (nr_running <= 1)
13240 continue;
13241
13242 if (busiest_util < util) {
13243 busiest_util = util;
13244 busiest = rq;
13245 }
13246 break;
13247
13248 case migrate_task:
13249 if (busiest_nr < nr_running) {
13250 busiest_nr = nr_running;
13251 busiest = rq;
13252 }
13253 break;
13254
13255 case migrate_misfit:
13256 /*
13257 * For ASYM_CPUCAPACITY domains with misfit tasks we
13258 * simply seek the "biggest" misfit task.
13259 */
13260 if (rq->misfit_task_load > busiest_load) {
13261 busiest_load = rq->misfit_task_load;
13262 busiest = rq;
13263 }
13264
13265 break;
13266
13267 case migrate_llc_task:
13268 #ifdef CONFIG_SCHED_CACHE
13269 sd_tmp = rcu_dereference_all(rq->sd);
13270 dst_llc = llc_id(env->dst_cpu);
13271
13272 if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) {
13273 unsigned int this_pref_llc =
13274 sd_tmp->llc_counts[dst_llc];
13275
13276 if (busiest_pref_llc < this_pref_llc) {
13277 busiest_pref_llc = this_pref_llc;
13278 busiest = rq;
13279 }
13280 }
13281 #endif
13282 break;
13283
13284 }
13285 }
13286
13287 return busiest;
13288 }
13289
13290 /*
13291 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
13292 * so long as it is large enough.
13293 */
13294 #define MAX_PINNED_INTERVAL 512
13295
13296 static inline bool
asym_active_balance(struct lb_env * env)13297 asym_active_balance(struct lb_env *env)
13298 {
13299 /*
13300 * ASYM_PACKING needs to force migrate tasks from busy but lower
13301 * priority CPUs in order to pack all tasks in the highest priority
13302 * CPUs. When done between cores, do it only if the whole core if the
13303 * whole core is idle.
13304 *
13305 * If @env::src_cpu is an SMT core with busy siblings, let
13306 * the lower priority @env::dst_cpu help it. Do not follow
13307 * CPU priority.
13308 */
13309 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
13310 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
13311 !sched_use_asym_prio(env->sd, env->src_cpu));
13312 }
13313
13314 static inline bool
imbalanced_active_balance(struct lb_env * env)13315 imbalanced_active_balance(struct lb_env *env)
13316 {
13317 struct sched_domain *sd = env->sd;
13318
13319 /*
13320 * The imbalanced case includes the case of pinned tasks preventing a fair
13321 * distribution of the load on the system but also the even distribution of the
13322 * threads on a system with spare capacity
13323 */
13324 if ((env->migration_type == migrate_task) &&
13325 (sd->nr_balance_failed > sd->cache_nice_tries+2))
13326 return 1;
13327
13328 return 0;
13329 }
13330
need_active_balance(struct lb_env * env)13331 static int need_active_balance(struct lb_env *env)
13332 {
13333 struct sched_domain *sd = env->sd;
13334
13335 if (alb_break_llc(env))
13336 return 0;
13337
13338 if (asym_active_balance(env))
13339 return 1;
13340
13341 if (imbalanced_active_balance(env))
13342 return 1;
13343
13344 /*
13345 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
13346 * It's worth migrating the task if the src_cpu's capacity is reduced
13347 * because of other sched_class or IRQs if more capacity stays
13348 * available on dst_cpu.
13349 */
13350 if (env->idle &&
13351 (env->src_rq->cfs.h_nr_runnable == 1)) {
13352 if ((check_cpu_capacity(env->src_rq, sd)) &&
13353 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
13354 return 1;
13355 }
13356
13357 if (env->migration_type == migrate_misfit ||
13358 env->migration_type == migrate_llc_task)
13359 return 1;
13360
13361 return 0;
13362 }
13363
13364 static int active_load_balance_cpu_stop(void *data);
13365
should_we_balance(struct lb_env * env)13366 static int should_we_balance(struct lb_env *env)
13367 {
13368 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
13369 struct sched_group *sg = env->sd->groups;
13370 int cpu, idle_smt = -1;
13371
13372 /*
13373 * Ensure the balancing environment is consistent; can happen
13374 * when the softirq triggers 'during' hotplug.
13375 */
13376 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
13377 return 0;
13378
13379 /*
13380 * In the newly idle case, we will allow all the CPUs
13381 * to do the newly idle load balance.
13382 *
13383 * However, we bail out if we already have tasks or a wakeup pending,
13384 * to optimize wakeup latency.
13385 */
13386 if (env->idle == CPU_NEWLY_IDLE) {
13387 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
13388 return 0;
13389 return 1;
13390 }
13391
13392 cpumask_copy(swb_cpus, group_balance_mask(sg));
13393 /* Try to find first idle CPU */
13394 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
13395 if (!idle_cpu(cpu))
13396 continue;
13397
13398 /*
13399 * Don't balance to idle SMT in busy core right away when
13400 * balancing cores, but remember the first idle SMT CPU for
13401 * later consideration. Find CPU on an idle core first.
13402 */
13403 if (sched_smt_active() &&
13404 !(env->sd->flags & SD_SHARE_CPUCAPACITY) &&
13405 !is_core_idle(cpu)) {
13406 if (idle_smt == -1)
13407 idle_smt = cpu;
13408 /*
13409 * If the core is not idle, and first SMT sibling which is
13410 * idle has been found, then its not needed to check other
13411 * SMT siblings for idleness:
13412 */
13413 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
13414 continue;
13415 }
13416
13417 /*
13418 * Are we the first idle core in a non-SMT domain or higher,
13419 * or the first idle CPU in a SMT domain?
13420 */
13421 return cpu == env->dst_cpu;
13422 }
13423
13424 /* Are we the first idle CPU with busy siblings? */
13425 if (idle_smt != -1)
13426 return idle_smt == env->dst_cpu;
13427
13428 /* Are we the first CPU of this group ? */
13429 return group_balance_cpu(sg) == env->dst_cpu;
13430 }
13431
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)13432 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
13433 enum cpu_idle_type idle)
13434 {
13435 if (!schedstat_enabled())
13436 return;
13437
13438 switch (env->migration_type) {
13439 case migrate_load:
13440 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
13441 break;
13442 case migrate_util:
13443 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
13444 break;
13445 case migrate_task:
13446 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
13447 break;
13448 case migrate_misfit:
13449 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
13450 break;
13451 case migrate_llc_task:
13452 break;
13453 }
13454 }
13455
13456 /*
13457 * This flag serializes load-balancing passes over large domains
13458 * (above the NODE topology level) - only one load-balancing instance
13459 * may run at a time, to reduce overhead on very large systems with
13460 * lots of CPUs and large NUMA distances.
13461 *
13462 * - Note that load-balancing passes triggered while another one
13463 * is executing are skipped and not re-tried.
13464 *
13465 * - Also note that this does not serialize rebalance_domains()
13466 * execution, as non-SD_SERIALIZE domains will still be
13467 * load-balanced in parallel.
13468 */
13469 static atomic_t sched_balance_running = ATOMIC_INIT(0);
13470
13471 /*
13472 * Check this_cpu to ensure it is balanced within domain. Attempt to move
13473 * tasks if there is an imbalance.
13474 */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)13475 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
13476 struct sched_domain *sd, enum cpu_idle_type idle,
13477 int *continue_balancing)
13478 {
13479 int ld_moved, cur_ld_moved, active_balance = 0;
13480 struct sched_domain *sd_parent = sd->parent;
13481 struct sched_group *group;
13482 struct rq *busiest;
13483 struct rq_flags rf;
13484 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
13485 struct lb_env env = {
13486 .sd = sd,
13487 .dst_cpu = this_cpu,
13488 .dst_rq = this_rq,
13489 .dst_grpmask = group_balance_mask(sd->groups),
13490 .idle = idle,
13491 .loop_break = SCHED_NR_MIGRATE_BREAK,
13492 .cpus = cpus,
13493 .fbq_type = all,
13494 .tasks = LIST_HEAD_INIT(env.tasks),
13495 };
13496 bool need_unlock = false;
13497
13498 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
13499
13500 schedstat_inc(sd->lb_count[idle]);
13501
13502 redo:
13503 if (!should_we_balance(&env)) {
13504 *continue_balancing = 0;
13505 goto out_balanced;
13506 }
13507
13508 if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
13509 int zero = 0;
13510 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
13511 goto out_balanced;
13512
13513 need_unlock = true;
13514 }
13515
13516 group = sched_balance_find_src_group(&env);
13517 if (!group) {
13518 schedstat_inc(sd->lb_nobusyg[idle]);
13519 goto out_balanced;
13520 }
13521
13522 busiest = sched_balance_find_src_rq(&env, group);
13523 if (!busiest) {
13524 schedstat_inc(sd->lb_nobusyq[idle]);
13525 goto out_balanced;
13526 }
13527
13528 WARN_ON_ONCE(busiest == env.dst_rq);
13529
13530 update_lb_imbalance_stat(&env, sd, idle);
13531
13532 env.src_cpu = busiest->cpu;
13533 env.src_rq = busiest;
13534
13535 ld_moved = 0;
13536 /* Clear this flag as soon as we find a pullable task */
13537 env.flags |= LBF_ALL_PINNED;
13538 if (busiest->nr_running > 1) {
13539 /*
13540 * Attempt to move tasks. If sched_balance_find_src_group has found
13541 * an imbalance but busiest->nr_running <= 1, the group is
13542 * still unbalanced. ld_moved simply stays zero, so it is
13543 * correctly treated as an imbalance.
13544 */
13545 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
13546
13547 more_balance:
13548 rq_lock_irqsave(busiest, &rf);
13549 update_rq_clock(busiest);
13550
13551 /*
13552 * cur_ld_moved - load moved in current iteration
13553 * ld_moved - cumulative load moved across iterations
13554 */
13555 cur_ld_moved = detach_tasks(&env);
13556
13557 /*
13558 * We've detached some tasks from busiest_rq. Every
13559 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
13560 * unlock busiest->lock, and we are able to be sure
13561 * that nobody can manipulate the tasks in parallel.
13562 * See task_rq_lock() family for the details.
13563 */
13564
13565 rq_unlock(busiest, &rf);
13566
13567 if (cur_ld_moved) {
13568 attach_tasks(&env);
13569 ld_moved += cur_ld_moved;
13570 }
13571
13572 local_irq_restore(rf.flags);
13573
13574 if (env.flags & LBF_NEED_BREAK) {
13575 env.flags &= ~LBF_NEED_BREAK;
13576 goto more_balance;
13577 }
13578
13579 /*
13580 * Revisit (affine) tasks on src_cpu that couldn't be moved to
13581 * us and move them to an alternate dst_cpu in our sched_group
13582 * where they can run. The upper limit on how many times we
13583 * iterate on same src_cpu is dependent on number of CPUs in our
13584 * sched_group.
13585 *
13586 * This changes load balance semantics a bit on who can move
13587 * load to a given_cpu. In addition to the given_cpu itself
13588 * (or a ilb_cpu acting on its behalf where given_cpu is
13589 * nohz-idle), we now have balance_cpu in a position to move
13590 * load to given_cpu. In rare situations, this may cause
13591 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
13592 * _independently_ and at _same_ time to move some load to
13593 * given_cpu) causing excess load to be moved to given_cpu.
13594 * This however should not happen so much in practice and
13595 * moreover subsequent load balance cycles should correct the
13596 * excess load moved.
13597 */
13598 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
13599
13600 /* Prevent to re-select dst_cpu via env's CPUs */
13601 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
13602
13603 env.dst_rq = cpu_rq(env.new_dst_cpu);
13604 env.dst_cpu = env.new_dst_cpu;
13605 env.flags &= ~LBF_DST_PINNED;
13606 env.loop = 0;
13607 env.loop_break = SCHED_NR_MIGRATE_BREAK;
13608
13609 /*
13610 * Go back to "more_balance" rather than "redo" since we
13611 * need to continue with same src_cpu.
13612 */
13613 goto more_balance;
13614 }
13615
13616 /*
13617 * We failed to reach balance because of affinity.
13618 */
13619 if (sd_parent) {
13620 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
13621
13622 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
13623 *group_imbalance = 1;
13624 }
13625
13626 /* All tasks on this runqueue were pinned by CPU affinity */
13627 if (unlikely(env.flags & LBF_ALL_PINNED)) {
13628 __cpumask_clear_cpu(cpu_of(busiest), cpus);
13629 /*
13630 * Attempting to continue load balancing at the current
13631 * sched_domain level only makes sense if there are
13632 * active CPUs remaining as possible busiest CPUs to
13633 * pull load from which are not contained within the
13634 * destination group that is receiving any migrated
13635 * load.
13636 */
13637 if (!cpumask_subset(cpus, env.dst_grpmask)) {
13638 env.loop = 0;
13639 env.loop_break = SCHED_NR_MIGRATE_BREAK;
13640 goto redo;
13641 }
13642 goto out_all_pinned;
13643 }
13644 }
13645
13646 if (ld_moved) {
13647 sd->nr_balance_failed = 0;
13648 goto out_unbalanced;
13649 }
13650
13651 schedstat_inc(sd->lb_failed[idle]);
13652 /*
13653 * Increment the failure counter only on periodic balance.
13654 * We do not want newidle balance, which can be very
13655 * frequent, pollute the failure counter causing
13656 * excessive cache_hot migrations and active balances.
13657 *
13658 * Similarly for migration_misfit which is not related to
13659 * load/util migration, don't pollute nr_balance_failed.
13660 *
13661 * The same for cache aware scheduling's allowance for
13662 * load imbalance. If regular load balance does not
13663 * migrate task due to LLC locality, it is a expected
13664 * behavior and don't pollute nr_balance_failed.
13665 * See can_migrate_task().
13666 */
13667 if (idle != CPU_NEWLY_IDLE &&
13668 env.migration_type != migrate_misfit &&
13669 !(env.flags & LBF_LLC_PINNED))
13670 sd->nr_balance_failed++;
13671
13672 if (!need_active_balance(&env))
13673 goto out_unbalanced;
13674
13675 scoped_guard (raw_spin_rq_lock_irqsave, busiest) {
13676 /*
13677 * Don't kick the active_load_balance_cpu_stop,
13678 * if the curr task on busiest CPU can't be
13679 * moved to this_cpu:
13680 */
13681 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr))
13682 goto out_one_pinned;
13683
13684 /* Record that we found at least one task that could run on this_cpu */
13685 env.flags &= ~LBF_ALL_PINNED;
13686
13687 /*
13688 * ->active_balance synchronizes accesses to
13689 * ->active_balance_work. Once set, it's cleared
13690 * only after active load balance is finished.
13691 */
13692 if (busiest->active_balance)
13693 goto out_unbalanced;
13694
13695 /*
13696 * @busiest dropped its rq_lock in the middle of
13697 * scheduling out its ->curr task (->on_rq := 0), no
13698 * need to forcefully punt it away with active balance.
13699 */
13700 if (!busiest->curr->on_rq)
13701 goto out_unbalanced;
13702
13703 busiest->active_balance = 1;
13704 busiest->push_cpu = this_cpu;
13705 active_balance = 1;
13706 preempt_disable();
13707 }
13708 if (active_balance) {
13709 stop_one_cpu_nowait(cpu_of(busiest),
13710 active_load_balance_cpu_stop, busiest,
13711 &busiest->active_balance_work);
13712 }
13713 preempt_enable();
13714
13715 out_unbalanced:
13716 /* We were unbalanced, so reset the balancing interval */
13717 sd->balance_interval = sd->min_interval;
13718 goto out;
13719
13720 out_balanced:
13721 /*
13722 * We reach balance although we may have faced some affinity
13723 * constraints. Clear the imbalance flag only if other tasks got
13724 * a chance to move and fix the imbalance.
13725 */
13726 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
13727 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
13728
13729 if (*group_imbalance)
13730 *group_imbalance = 0;
13731 }
13732
13733 out_all_pinned:
13734 /*
13735 * We reach balance because all tasks are pinned at this level so
13736 * we can't migrate them. Let the imbalance flag set so parent level
13737 * can try to migrate them.
13738 */
13739 schedstat_inc(sd->lb_balanced[idle]);
13740
13741 sd->nr_balance_failed = 0;
13742
13743 out_one_pinned:
13744 ld_moved = 0;
13745
13746 /*
13747 * sched_balance_newidle() disregards balance intervals, so we could
13748 * repeatedly reach this code, which would lead to balance_interval
13749 * skyrocketing in a short amount of time. Skip the balance_interval
13750 * increase logic to avoid that.
13751 *
13752 * Similarly misfit migration which is not necessarily an indication of
13753 * the system being busy and requires lb to backoff to let it settle
13754 * down.
13755 */
13756 if (env.idle == CPU_NEWLY_IDLE ||
13757 env.migration_type == migrate_misfit)
13758 goto out;
13759
13760 /* tune up the balancing interval */
13761 if ((env.flags & LBF_ALL_PINNED &&
13762 sd->balance_interval < MAX_PINNED_INTERVAL) ||
13763 sd->balance_interval < sd->max_interval)
13764 sd->balance_interval *= 2;
13765 out:
13766 if (need_unlock)
13767 atomic_set_release(&sched_balance_running, 0);
13768
13769 return ld_moved;
13770 }
13771
13772 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)13773 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
13774 {
13775 unsigned long interval = sd->balance_interval;
13776
13777 if (cpu_busy)
13778 interval *= sd->busy_factor;
13779
13780 /* scale ms to jiffies */
13781 interval = msecs_to_jiffies(interval);
13782
13783 /*
13784 * Reduce likelihood of busy balancing at higher domains racing with
13785 * balancing at lower domains by preventing their balancing periods
13786 * from being multiples of each other.
13787 */
13788 if (cpu_busy)
13789 interval -= 1;
13790
13791 interval = clamp(interval, 1UL, max_load_balance_interval);
13792
13793 return interval;
13794 }
13795
13796 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)13797 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
13798 {
13799 unsigned long interval, next;
13800
13801 /* used by idle balance, so cpu_busy = 0 */
13802 interval = get_sd_balance_interval(sd, 0);
13803 next = sd->last_balance + interval;
13804
13805 if (time_after(*next_balance, next))
13806 *next_balance = next;
13807 }
13808
13809 /*
13810 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
13811 * running tasks off the busiest CPU onto idle CPUs. It requires at
13812 * least 1 task to be running on each physical CPU where possible, and
13813 * avoids physical / logical imbalances.
13814 */
active_load_balance_cpu_stop(void * data)13815 static int active_load_balance_cpu_stop(void *data)
13816 {
13817 struct rq *busiest_rq = data;
13818 int busiest_cpu = cpu_of(busiest_rq);
13819 int target_cpu = busiest_rq->push_cpu;
13820 struct rq *target_rq = cpu_rq(target_cpu);
13821 struct sched_domain *sd;
13822 struct task_struct *p = NULL;
13823 struct rq_flags rf;
13824
13825 rq_lock_irq(busiest_rq, &rf);
13826 /*
13827 * Between queueing the stop-work and running it is a hole in which
13828 * CPUs can become inactive. We should not move tasks from or to
13829 * inactive CPUs.
13830 */
13831 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
13832 goto out_unlock;
13833
13834 /* Make sure the requested CPU hasn't gone down in the meantime: */
13835 if (unlikely(busiest_cpu != smp_processor_id() ||
13836 !busiest_rq->active_balance))
13837 goto out_unlock;
13838
13839 /* Is there any task to move? */
13840 if (busiest_rq->nr_running <= 1)
13841 goto out_unlock;
13842
13843 /*
13844 * This condition is "impossible", if it occurs
13845 * we need to fix it. Originally reported by
13846 * Bjorn Helgaas on a 128-CPU setup.
13847 */
13848 WARN_ON_ONCE(busiest_rq == target_rq);
13849
13850 /* Search for an sd spanning us and the target CPU. */
13851 rcu_read_lock();
13852 for_each_domain(target_cpu, sd) {
13853 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
13854 break;
13855 }
13856
13857 if (likely(sd)) {
13858 struct lb_env env = {
13859 .sd = sd,
13860 .dst_cpu = target_cpu,
13861 .dst_rq = target_rq,
13862 .src_cpu = busiest_rq->cpu,
13863 .src_rq = busiest_rq,
13864 .idle = CPU_IDLE,
13865 .flags = LBF_ACTIVE_LB,
13866 };
13867
13868 schedstat_inc(sd->alb_count);
13869 update_rq_clock(busiest_rq);
13870
13871 p = detach_one_task(&env);
13872 if (p) {
13873 schedstat_inc(sd->alb_pushed);
13874 /* Active balancing done, reset the failure counter. */
13875 sd->nr_balance_failed = 0;
13876 } else {
13877 schedstat_inc(sd->alb_failed);
13878 }
13879 }
13880 rcu_read_unlock();
13881 out_unlock:
13882 busiest_rq->active_balance = 0;
13883 rq_unlock(busiest_rq, &rf);
13884
13885 if (p)
13886 attach_one_task(target_rq, p);
13887
13888 local_irq_enable();
13889
13890 return 0;
13891 }
13892
13893 /*
13894 * Scale the max sched_balance_rq interval with the number of CPUs in the system.
13895 * This trades load-balance latency on larger machines for less cross talk.
13896 */
update_max_interval(void)13897 void update_max_interval(void)
13898 {
13899 max_load_balance_interval = HZ*num_online_cpus()/10;
13900 }
13901
update_newidle_stats(struct sched_domain * sd,unsigned int success)13902 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
13903 {
13904 sd->newidle_call++;
13905 sd->newidle_success += success;
13906
13907 if (sd->newidle_call >= 1024) {
13908 u64 now = sched_clock();
13909 s64 delta = now - sd->newidle_stamp;
13910 sd->newidle_stamp = now;
13911 int ratio = 0;
13912
13913 if (delta < 0)
13914 delta = 0;
13915
13916 if (sched_feat(NI_RATE)) {
13917 /*
13918 * ratio delta freq
13919 *
13920 * 1024 - 4 s - 128 Hz
13921 * 512 - 2 s - 256 Hz
13922 * 256 - 1 s - 512 Hz
13923 * 128 - .5 s - 1024 Hz
13924 * 64 - .25 s - 2048 Hz
13925 */
13926 ratio = delta >> 22;
13927 }
13928
13929 ratio += sd->newidle_success;
13930
13931 sd->newidle_ratio = min(1024, ratio);
13932 sd->newidle_call /= 2;
13933 sd->newidle_success /= 2;
13934 }
13935 }
13936
13937 static inline bool
update_newidle_cost(struct sched_domain * sd,u64 cost,unsigned int success)13938 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
13939 {
13940 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
13941 unsigned long now = jiffies;
13942
13943 if (cost)
13944 update_newidle_stats(sd, success);
13945
13946 if (cost > sd->max_newidle_lb_cost) {
13947 /*
13948 * Track max cost of a domain to make sure to not delay the
13949 * next wakeup on the CPU.
13950 */
13951 sd->max_newidle_lb_cost = cost;
13952 sd->last_decay_max_lb_cost = now;
13953
13954 } else if (time_after(now, next_decay)) {
13955 /*
13956 * Decay the newidle max times by ~1% per second to ensure that
13957 * it is not outdated and the current max cost is actually
13958 * shorter.
13959 */
13960 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
13961 sd->last_decay_max_lb_cost = now;
13962 return true;
13963 }
13964
13965 return false;
13966 }
13967
13968 /*
13969 * It checks each scheduling domain to see if it is due to be balanced,
13970 * and initiates a balancing operation if so.
13971 *
13972 * Balancing parameters are set up in init_sched_domains.
13973 */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)13974 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
13975 {
13976 int continue_balancing = 1;
13977 int cpu = rq->cpu;
13978 int busy = idle != CPU_IDLE && !sched_idle_rq(rq);
13979 unsigned long interval;
13980 struct sched_domain *sd;
13981 /* Earliest time when we have to do rebalance again */
13982 unsigned long next_balance = jiffies + 60*HZ;
13983 int update_next_balance = 0;
13984 int need_decay = 0;
13985 u64 max_cost = 0;
13986
13987 rcu_read_lock();
13988 for_each_domain(cpu, sd) {
13989 /*
13990 * Decay the newidle max times here because this is a regular
13991 * visit to all the domains.
13992 */
13993 need_decay = update_newidle_cost(sd, 0, 0);
13994 max_cost += sd->max_newidle_lb_cost;
13995
13996 /*
13997 * Stop the load balance at this level. There is another
13998 * CPU in our sched group which is doing load balancing more
13999 * actively.
14000 */
14001 if (!continue_balancing) {
14002 if (need_decay)
14003 continue;
14004 break;
14005 }
14006
14007 interval = get_sd_balance_interval(sd, busy);
14008 if (time_after_eq(jiffies, sd->last_balance + interval)) {
14009 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
14010 /*
14011 * The LBF_DST_PINNED logic could have changed
14012 * env->dst_cpu, so we can't know our idle
14013 * state even if we migrated tasks. Update it.
14014 */
14015 idle = idle_cpu(cpu);
14016 busy = !idle && !sched_idle_rq(rq);
14017 }
14018 sd->last_balance = jiffies;
14019 interval = get_sd_balance_interval(sd, busy);
14020 }
14021 if (time_after(next_balance, sd->last_balance + interval)) {
14022 next_balance = sd->last_balance + interval;
14023 update_next_balance = 1;
14024 }
14025 }
14026 if (need_decay) {
14027 /*
14028 * Ensure the rq-wide value also decays but keep it at a
14029 * reasonable floor to avoid funnies with rq->avg_idle.
14030 */
14031 rq->max_idle_balance_cost =
14032 max((u64)sysctl_sched_migration_cost, max_cost);
14033 }
14034 rcu_read_unlock();
14035
14036 /*
14037 * next_balance will be updated only when there is a need.
14038 * When the cpu is attached to null domain for ex, it will not be
14039 * updated.
14040 */
14041 if (likely(update_next_balance))
14042 rq->next_balance = next_balance;
14043
14044 }
14045
on_null_domain(struct rq * rq)14046 static inline int on_null_domain(struct rq *rq)
14047 {
14048 return unlikely(!rcu_dereference_sched(rq->sd));
14049 }
14050
14051 #ifdef CONFIG_NO_HZ_COMMON
14052 /*
14053 * NOHZ idle load balancing (ILB) details:
14054 *
14055 * - When one of the busy CPUs notices that there may be an idle rebalancing
14056 * needed, they will kick the idle load balancer, which then does idle
14057 * load balancing for all the idle CPUs.
14058 */
find_new_ilb(void)14059 static inline int find_new_ilb(void)
14060 {
14061 struct cpumask *ilb_cpus;
14062 int ilb_cpu, fallback = -1;
14063
14064 lockdep_assert_irqs_disabled();
14065
14066 /*
14067 * Reuse the per-CPU select_rq_mask, which is protected from concurrent
14068 * use on this CPU by having interrupts disabled.
14069 */
14070 ilb_cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
14071 cpumask_and(ilb_cpus, nohz.idle_cpus_mask,
14072 housekeeping_cpumask(HK_TYPE_KERNEL_NOISE));
14073
14074 for_each_cpu(ilb_cpu, ilb_cpus) {
14075 if (!idle_cpu(ilb_cpu)) {
14076 /*
14077 * Once an idle fallback exists, a busy CPU proves that
14078 * this core cannot be fully idle. Skip its siblings.
14079 */
14080 if (sched_smt_active() && fallback >= 0)
14081 cpumask_andnot(ilb_cpus, ilb_cpus, cpu_smt_mask(ilb_cpu));
14082 continue;
14083 }
14084
14085 /*
14086 * Running the idle load balancer on an idle sibling of a busy
14087 * SMT core can reduce the capacity available to its sibling. Prefer
14088 * a CPU whose entire core is idle, but retain the first idle CPU as
14089 * a fallback so idle balancing can still make progress when no fully
14090 * idle core exists.
14091 */
14092 if (sched_smt_active() && !is_core_idle(ilb_cpu)) {
14093 if (fallback < 0)
14094 fallback = ilb_cpu;
14095
14096 /*
14097 * The core is not idle, so there is no need to check
14098 * any of its other SMT siblings.
14099 */
14100 cpumask_andnot(ilb_cpus, ilb_cpus,
14101 cpu_smt_mask(ilb_cpu));
14102 continue;
14103 }
14104
14105 return ilb_cpu;
14106 }
14107
14108 return fallback;
14109 }
14110
14111 /*
14112 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
14113 * SMP function call (IPI).
14114 *
14115 * Prefer a CPU on a fully idle core in the HK_TYPE_KERNEL_NOISE housekeeping
14116 * set. Fall back to the first idle CPU when no fully idle core exists.
14117 */
kick_ilb(unsigned int flags)14118 static void kick_ilb(unsigned int flags)
14119 {
14120 int ilb_cpu;
14121
14122 /*
14123 * Increase nohz.next_balance only when if full ilb is triggered but
14124 * not if we only update stats.
14125 */
14126 if (flags & NOHZ_BALANCE_KICK)
14127 nohz.next_balance = jiffies+1;
14128
14129 ilb_cpu = find_new_ilb();
14130 if (ilb_cpu < 0)
14131 return;
14132
14133 /*
14134 * Don't bother if no new NOHZ balance work items for ilb_cpu,
14135 * i.e. all bits in flags are already set in ilb_cpu.
14136 */
14137 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
14138 return;
14139
14140 /*
14141 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
14142 * the first flag owns it; cleared by nohz_csd_func().
14143 */
14144 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
14145 if (flags & NOHZ_KICK_MASK)
14146 return;
14147
14148 /*
14149 * This way we generate an IPI on the target CPU which
14150 * is idle, and the softirq performing NOHZ idle load balancing
14151 * will be run before returning from the IPI.
14152 */
14153 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
14154 }
14155
14156 /*
14157 * Current decision point for kicking the idle load balancer in the presence
14158 * of idle CPUs in the system.
14159 */
nohz_balancer_kick(struct rq * rq)14160 static void nohz_balancer_kick(struct rq *rq)
14161 {
14162 unsigned long now = jiffies;
14163 struct sched_domain_shared *sds;
14164 struct sched_domain *sd;
14165 int nr_busy, i, cpu = rq->cpu;
14166 unsigned int flags = 0;
14167
14168 if (unlikely(rq->idle_balance))
14169 return;
14170
14171 /*
14172 * We may be recently in ticked or tickless idle mode. At the first
14173 * busy tick after returning from idle, we will update the busy stats.
14174 */
14175 nohz_balance_exit_idle(rq);
14176
14177 if (READ_ONCE(nohz.has_blocked_load) &&
14178 time_after(now, READ_ONCE(nohz.next_blocked)))
14179 flags = NOHZ_STATS_KICK;
14180
14181 /*
14182 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0
14183 * Skip the read if time is not due.
14184 *
14185 * If none are in tickless mode, there maybe a narrow window
14186 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called.
14187 * But idle load balancing is not done as find_new_ilb fails.
14188 * That's very rare. So read nohz.nr_cpus only if time is due.
14189 */
14190 if (time_before(now, nohz.next_balance))
14191 goto out;
14192
14193 /*
14194 * None are in tickless mode and hence no need for NOHZ idle load
14195 * balancing
14196 */
14197 if (unlikely(cpumask_empty(nohz.idle_cpus_mask)))
14198 return;
14199
14200 if (rq->nr_running >= 2) {
14201 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14202 goto out;
14203 }
14204
14205 sd = rcu_dereference_all(rq->sd);
14206 if (sd) {
14207 /*
14208 * If there's a runnable CFS task and the current CPU has reduced
14209 * capacity, kick the ILB to see if there's a better CPU to run on:
14210 */
14211 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
14212 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14213 goto out;
14214 }
14215 }
14216
14217 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu));
14218 if (sd) {
14219 /*
14220 * When ASYM_PACKING; see if there's a more preferred CPU
14221 * currently idle; in which case, kick the ILB to move tasks
14222 * around.
14223 *
14224 * When balancing between cores, all the SMT siblings of the
14225 * preferred CPU must be idle.
14226 */
14227 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
14228 if (sched_asym(sd, i, cpu)) {
14229 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14230 goto out;
14231 }
14232 }
14233 }
14234
14235 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu));
14236 if (sd) {
14237 /*
14238 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
14239 * to run the misfit task on.
14240 */
14241 if (check_misfit_status(rq))
14242 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14243
14244 /*
14245 * For asymmetric systems, we do not want to nicely balance
14246 * cache use, instead we want to embrace asymmetry and only
14247 * ensure tasks have enough CPU capacity.
14248 *
14249 * Skip the LLC logic because it's not relevant in that case.
14250 */
14251 goto out;
14252 }
14253
14254 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu));
14255 if (sds) {
14256 /*
14257 * If there is an imbalance between LLC domains (IOW we could
14258 * increase the overall cache utilization), we need a less-loaded LLC
14259 * domain to pull some load from. Likewise, we may need to spread
14260 * load within the current LLC domain (e.g. packed SMT cores but
14261 * other CPUs are idle). We can't really know from here how busy
14262 * the others are - so just get a NOHZ balance going if it looks
14263 * like this LLC domain has tasks we could move.
14264 */
14265 nr_busy = atomic_read(&sds->nr_busy_cpus);
14266 if (nr_busy > 1)
14267 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
14268 }
14269 out:
14270 if (READ_ONCE(nohz.needs_update))
14271 flags |= NOHZ_NEXT_KICK;
14272
14273 if (flags)
14274 kick_ilb(flags);
14275 }
14276
set_cpu_sd_state_busy(int cpu)14277 static void set_cpu_sd_state_busy(int cpu)
14278 {
14279 struct sched_domain *sd;
14280 sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14281
14282 /*
14283 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this
14284 * domain has no shared object there is nothing to clear or account.
14285 */
14286 if (!sd || !sd->shared || !sd->nohz_idle)
14287 return;
14288 sd->nohz_idle = 0;
14289
14290 atomic_inc(&sd->shared->nr_busy_cpus);
14291 }
14292
nohz_balance_exit_idle(struct rq * rq)14293 void nohz_balance_exit_idle(struct rq *rq)
14294 {
14295 WARN_ON_ONCE(rq != this_rq());
14296
14297 if (likely(!rq->nohz_tick_stopped))
14298 return;
14299
14300 rq->nohz_tick_stopped = 0;
14301 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
14302
14303 set_cpu_sd_state_busy(rq->cpu);
14304 }
14305
set_cpu_sd_state_idle(int cpu)14306 static void set_cpu_sd_state_idle(int cpu)
14307 {
14308 struct sched_domain *sd;
14309 sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
14310
14311 /* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */
14312 if (!sd || !sd->shared || sd->nohz_idle)
14313 return;
14314 sd->nohz_idle = 1;
14315
14316 atomic_dec(&sd->shared->nr_busy_cpus);
14317 }
14318
14319 /*
14320 * This routine will record that the CPU is going idle with tick stopped.
14321 * This info will be used in performing idle load balancing in the future.
14322 */
nohz_balance_enter_idle(int cpu)14323 void nohz_balance_enter_idle(int cpu)
14324 {
14325 struct rq *rq = cpu_rq(cpu);
14326
14327 WARN_ON_ONCE(cpu != smp_processor_id());
14328
14329 /* If this CPU is going down, then nothing needs to be done: */
14330 if (!cpu_active(cpu))
14331 return;
14332
14333 /*
14334 * Can be set safely without rq->lock held
14335 * If a clear happens, it will have evaluated last additions because
14336 * rq->lock is held during the check and the clear
14337 */
14338 rq->has_blocked_load = 1;
14339
14340 /*
14341 * The tick is still stopped but load could have been added in the
14342 * meantime. We set the nohz.has_blocked_load flag to trig a check of the
14343 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
14344 * of nohz.has_blocked_load can only happen after checking the new load
14345 */
14346 if (rq->nohz_tick_stopped)
14347 goto out;
14348
14349 /* If we're a completely isolated CPU, we don't play: */
14350 if (on_null_domain(rq))
14351 return;
14352
14353 rq->nohz_tick_stopped = 1;
14354
14355 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
14356
14357 /*
14358 * Ensures that if nohz_idle_balance() fails to observe our
14359 * @idle_cpus_mask store, it must observe the @has_blocked_load
14360 * and @needs_update stores.
14361 */
14362 smp_mb__after_atomic();
14363
14364 set_cpu_sd_state_idle(cpu);
14365
14366 WRITE_ONCE(nohz.needs_update, 1);
14367 out:
14368 /*
14369 * Each time a cpu enter idle, we assume that it has blocked load and
14370 * enable the periodic update of the load of idle CPUs
14371 */
14372 WRITE_ONCE(nohz.has_blocked_load, 1);
14373 }
14374
update_nohz_stats(struct rq * rq)14375 static bool update_nohz_stats(struct rq *rq)
14376 {
14377 unsigned int cpu = rq->cpu;
14378
14379 if (!rq->has_blocked_load)
14380 return false;
14381
14382 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
14383 return false;
14384
14385 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
14386 return true;
14387
14388 sched_balance_update_blocked_averages(cpu);
14389
14390 return rq->has_blocked_load;
14391 }
14392
14393 /*
14394 * Internal function that runs load balance for all idle CPUs. The load balance
14395 * can be a simple update of blocked load or a complete load balance with
14396 * tasks movement depending of flags.
14397 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)14398 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
14399 {
14400 /* Earliest time when we have to do rebalance again */
14401 unsigned long now = jiffies;
14402 unsigned long next_balance = now + 60*HZ;
14403 bool has_blocked_load = false;
14404 int update_next_balance = 0;
14405 int this_cpu = this_rq->cpu;
14406 int balance_cpu;
14407 struct rq *rq;
14408
14409 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
14410
14411 /*
14412 * We assume there will be no idle load after this update and clear
14413 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will
14414 * set the has_blocked_load flag and trigger another update of idle load.
14415 * Because a cpu that becomes idle, is added to idle_cpus_mask before
14416 * setting the flag, we are sure to not clear the state and not
14417 * check the load of an idle cpu.
14418 *
14419 * Same applies to idle_cpus_mask vs needs_update.
14420 */
14421 if (flags & NOHZ_STATS_KICK)
14422 WRITE_ONCE(nohz.has_blocked_load, 0);
14423 if (flags & NOHZ_NEXT_KICK)
14424 WRITE_ONCE(nohz.needs_update, 0);
14425
14426 /*
14427 * Ensures that if we miss the CPU, we must see the has_blocked_load
14428 * store from nohz_balance_enter_idle().
14429 */
14430 smp_mb();
14431
14432 /*
14433 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
14434 * chance for other idle cpu to pull load.
14435 */
14436 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
14437 if (!idle_cpu(balance_cpu))
14438 continue;
14439
14440 /*
14441 * If this CPU gets work to do, stop the load balancing
14442 * work being done for other CPUs. Next load
14443 * balancing owner will pick it up.
14444 */
14445 if (!idle_cpu(this_cpu) && need_resched()) {
14446 if (flags & NOHZ_STATS_KICK)
14447 has_blocked_load = true;
14448 if (flags & NOHZ_NEXT_KICK)
14449 WRITE_ONCE(nohz.needs_update, 1);
14450 goto abort;
14451 }
14452
14453 rq = cpu_rq(balance_cpu);
14454
14455 if (flags & NOHZ_STATS_KICK)
14456 has_blocked_load |= update_nohz_stats(rq);
14457
14458 /*
14459 * If time for next balance is due,
14460 * do the balance.
14461 */
14462 if (time_after_eq(jiffies, rq->next_balance)) {
14463 struct rq_flags rf;
14464
14465 rq_lock_irqsave(rq, &rf);
14466 update_rq_clock(rq);
14467 rq_unlock_irqrestore(rq, &rf);
14468
14469 if (flags & NOHZ_BALANCE_KICK)
14470 sched_balance_domains(rq, CPU_IDLE);
14471 }
14472
14473 if (time_after(next_balance, rq->next_balance)) {
14474 next_balance = rq->next_balance;
14475 update_next_balance = 1;
14476 }
14477 }
14478
14479 /*
14480 * next_balance will be updated only when there is a need.
14481 * When the CPU is attached to null domain for ex, it will not be
14482 * updated.
14483 */
14484 if (likely(update_next_balance))
14485 nohz.next_balance = next_balance;
14486
14487 if (flags & NOHZ_STATS_KICK)
14488 WRITE_ONCE(nohz.next_blocked,
14489 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
14490
14491 abort:
14492 /* There is still blocked load, enable periodic update */
14493 if (has_blocked_load)
14494 WRITE_ONCE(nohz.has_blocked_load, 1);
14495 }
14496
14497 /*
14498 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
14499 * rebalancing for all the CPUs for whom scheduler ticks are stopped.
14500 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)14501 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14502 {
14503 unsigned int flags = this_rq->nohz_idle_balance;
14504
14505 if (!flags)
14506 return false;
14507
14508 this_rq->nohz_idle_balance = 0;
14509
14510 if (idle != CPU_IDLE)
14511 return false;
14512
14513 _nohz_idle_balance(this_rq, flags);
14514
14515 return true;
14516 }
14517
14518 /*
14519 * Check if we need to directly run the ILB for updating blocked load before
14520 * entering idle state. Here we run ILB directly without issuing IPIs.
14521 *
14522 * Note that when this function is called, the tick may not yet be stopped on
14523 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
14524 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
14525 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
14526 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
14527 * called from this function on (this) CPU that's not yet in the mask. That's
14528 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
14529 * updating the blocked load of already idle CPUs without waking up one of
14530 * those idle CPUs and outside the preempt disable / IRQ off phase of the local
14531 * cpu about to enter idle, because it can take a long time.
14532 */
nohz_run_idle_balance(int cpu)14533 void nohz_run_idle_balance(int cpu)
14534 {
14535 unsigned int flags;
14536
14537 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
14538
14539 /*
14540 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
14541 * (i.e. NOHZ_STATS_KICK set) and will do the same.
14542 */
14543 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
14544 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
14545 }
14546
nohz_newidle_balance(struct rq * this_rq)14547 static void nohz_newidle_balance(struct rq *this_rq)
14548 {
14549 int this_cpu = this_rq->cpu;
14550
14551 /* Will wake up very soon. No time for doing anything else*/
14552 if (this_rq->avg_idle < sysctl_sched_migration_cost)
14553 return;
14554
14555 /* Don't need to update blocked load of idle CPUs*/
14556 if (!READ_ONCE(nohz.has_blocked_load) ||
14557 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
14558 return;
14559
14560 /*
14561 * Set the need to trigger ILB in order to update blocked load
14562 * before entering idle state.
14563 */
14564 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
14565 }
14566
14567 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balancer_kick(struct rq * rq)14568 static inline void nohz_balancer_kick(struct rq *rq) { }
14569
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)14570 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
14571 {
14572 return false;
14573 }
14574
nohz_newidle_balance(struct rq * this_rq)14575 static inline void nohz_newidle_balance(struct rq *this_rq) { }
14576 #endif /* !CONFIG_NO_HZ_COMMON */
14577
14578 /*
14579 * sched_balance_newidle is called by schedule() if this_cpu is about to become
14580 * idle. Attempts to pull tasks from other CPUs.
14581 *
14582 * Returns:
14583 * < 0 - we released the lock and there are !fair tasks present
14584 * 0 - failed, no new tasks
14585 * > 0 - success, new (fair) tasks present
14586 */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)14587 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
14588 __must_hold(__rq_lockp(this_rq))
14589 {
14590 unsigned long next_balance = jiffies + HZ;
14591 int this_cpu = this_rq->cpu;
14592 int continue_balancing = 1;
14593 u64 t0, t1, curr_cost = 0;
14594 struct sched_domain *sd;
14595 int pulled_task = 0;
14596
14597 update_misfit_status(NULL, this_rq);
14598
14599 /*
14600 * There is a task waiting to run. No need to search for one.
14601 * Return 0; the task will be enqueued when switching to idle.
14602 */
14603 if (this_rq->ttwu_pending)
14604 return 0;
14605
14606 /*
14607 * We must set idle_stamp _before_ calling sched_balance_rq()
14608 * for CPU_NEWLY_IDLE, such that we measure the this duration
14609 * as idle time.
14610 */
14611 this_rq->idle_stamp = rq_clock(this_rq);
14612
14613 /*
14614 * Do not pull tasks towards !active CPUs...
14615 */
14616 if (!cpu_active(this_cpu))
14617 return 0;
14618
14619 /*
14620 * This is OK, because current is on_cpu, which avoids it being picked
14621 * for load-balance and preemption/IRQs are still disabled avoiding
14622 * further scheduler activity on it and we're being very careful to
14623 * re-start the picking loop.
14624 */
14625 rq_unpin_lock(this_rq, rf);
14626
14627 sd = rcu_dereference_sched_domain(this_rq->sd);
14628 if (!sd)
14629 goto out;
14630
14631 if (!get_rd_overloaded(this_rq->rd) ||
14632 this_rq->avg_idle < sd->max_newidle_lb_cost) {
14633
14634 update_next_balance(sd, &next_balance);
14635 goto out;
14636 }
14637
14638 /*
14639 * Include sched_balance_update_blocked_averages() in the cost
14640 * calculation because it can be quite costly -- this ensures we skip
14641 * it when avg_idle gets to be very low.
14642 */
14643 t0 = sched_clock_cpu(this_cpu);
14644 __sched_balance_update_blocked_averages(this_rq);
14645
14646 rq_modified_begin(this_rq, &fair_sched_class);
14647 raw_spin_rq_unlock(this_rq);
14648
14649 for_each_domain(this_cpu, sd) {
14650 u64 domain_cost;
14651
14652 update_next_balance(sd, &next_balance);
14653
14654 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
14655 break;
14656
14657 if (sd->flags & SD_BALANCE_NEWIDLE) {
14658 unsigned int weight = 1;
14659
14660 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) {
14661 /*
14662 * Throw a 1k sided dice; and only run
14663 * newidle_balance according to the success
14664 * rate.
14665 */
14666 u32 d1k = sched_rng() % 1024;
14667 weight = 1 + sd->newidle_ratio;
14668 if (d1k > weight) {
14669 update_newidle_stats(sd, 0);
14670 continue;
14671 }
14672 weight = (1024 + weight/2) / weight;
14673 }
14674
14675 pulled_task = sched_balance_rq(this_cpu, this_rq,
14676 sd, CPU_NEWLY_IDLE,
14677 &continue_balancing);
14678
14679 t1 = sched_clock_cpu(this_cpu);
14680 domain_cost = t1 - t0;
14681 curr_cost += domain_cost;
14682 t0 = t1;
14683
14684 /*
14685 * Track max cost of a domain to make sure to not delay the
14686 * next wakeup on the CPU.
14687 */
14688 update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
14689 }
14690
14691 /*
14692 * Stop searching for tasks to pull if there are
14693 * now runnable tasks on this rq.
14694 */
14695 if (pulled_task || !continue_balancing)
14696 break;
14697 }
14698
14699 raw_spin_rq_lock(this_rq);
14700
14701 if (curr_cost > this_rq->max_idle_balance_cost)
14702 this_rq->max_idle_balance_cost = curr_cost;
14703
14704 /*
14705 * While browsing the domains, we released the rq lock, a task could
14706 * have been enqueued in the meantime. Since we're not going idle,
14707 * pretend we pulled a task.
14708 */
14709 if (this_rq->cfs.h_nr_queued && !pulled_task)
14710 pulled_task = 1;
14711
14712 /* If a higher prio class was modified, restart the pick */
14713 if (rq_modified_above(this_rq, &fair_sched_class))
14714 pulled_task = -1;
14715
14716 out:
14717 /* Move the next balance forward */
14718 if (time_after(this_rq->next_balance, next_balance))
14719 this_rq->next_balance = next_balance;
14720
14721 if (pulled_task)
14722 this_rq->idle_stamp = 0;
14723 else
14724 nohz_newidle_balance(this_rq);
14725
14726 rq_repin_lock(this_rq, rf);
14727
14728 return pulled_task;
14729 }
14730
14731 /*
14732 * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
14733 *
14734 * - directly from the local sched_tick() for periodic load balancing
14735 *
14736 * - indirectly from a remote sched_tick() for NOHZ idle balancing
14737 * through the SMP cross-call nohz_csd_func()
14738 */
sched_balance_softirq(void)14739 static __latent_entropy void sched_balance_softirq(void)
14740 {
14741 struct rq *this_rq = this_rq();
14742 enum cpu_idle_type idle = this_rq->idle_balance;
14743 /*
14744 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
14745 * balancing on behalf of the other idle CPUs whose ticks are
14746 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
14747 * give the idle CPUs a chance to load balance. Else we may
14748 * load balance only within the local sched_domain hierarchy
14749 * and abort nohz_idle_balance altogether if we pull some load.
14750 */
14751 if (nohz_idle_balance(this_rq, idle))
14752 return;
14753
14754 /* normal load balance */
14755 sched_balance_update_blocked_averages(this_rq->cpu);
14756 sched_balance_domains(this_rq, idle);
14757 }
14758
14759 /*
14760 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
14761 */
sched_balance_trigger(struct rq * rq)14762 void sched_balance_trigger(struct rq *rq)
14763 {
14764 /*
14765 * Don't need to rebalance while attached to NULL domain or
14766 * runqueue CPU is not active
14767 */
14768 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
14769 return;
14770
14771 if (time_after_eq(jiffies, rq->next_balance))
14772 raise_softirq(SCHED_SOFTIRQ);
14773
14774 nohz_balancer_kick(rq);
14775 }
14776
rq_online_fair(struct rq * rq)14777 static void rq_online_fair(struct rq *rq)
14778 {
14779 update_sysctl();
14780
14781 update_runtime_enabled(rq);
14782 }
14783
rq_offline_fair(struct rq * rq)14784 static void rq_offline_fair(struct rq *rq)
14785 {
14786 update_sysctl();
14787
14788 /* Ensure any throttled groups are reachable by pick_next_task */
14789 unthrottle_offline_cfs_rqs(rq);
14790
14791 /* Ensure that we remove rq contribution to group share: */
14792 clear_tg_offline_cfs_rqs(rq);
14793 }
14794
14795 #ifdef CONFIG_SCHED_CORE
14796 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)14797 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
14798 {
14799 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
14800 u64 slice = se->slice;
14801
14802 return (rtime * min_nr_tasks > slice);
14803 }
14804
14805 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)14806 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
14807 {
14808 if (!sched_core_enabled(rq))
14809 return;
14810
14811 /*
14812 * If runqueue has only one task which used up its slice and
14813 * if the sibling is forced idle, then trigger schedule to
14814 * give forced idle task a chance.
14815 *
14816 * __entity_slice_used() considers only this active rq and it gets the
14817 * whole slice. But during force idle, we have siblings acting
14818 * like a single runqueue and hence we need to consider runnable
14819 * tasks on this CPU and the forced idle CPU. Ideally, we should
14820 * go through the forced idle rq, but that would be a perf hit.
14821 * We can assume that the forced idle CPU has at least
14822 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
14823 * if we need to give up the CPU.
14824 */
14825 if (rq->core->core_forceidle_count && rq->cfs.h_nr_queued == 1 &&
14826 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
14827 resched_curr(rq);
14828 }
14829
14830 /*
14831 * Consider any infeasible weight scenario. Take for instance two tasks,
14832 * each bound to their respective sibling, one with weight 1 and one with
14833 * weight 2. Then the lower weight task will run ahead of the higher weight
14834 * task without bound.
14835 *
14836 * This utterly destroys the concept of a shared time base.
14837 *
14838 * Remember; all this is about a proportionally fair scheduling, where each
14839 * tasks receives:
14840 *
14841 * w_i
14842 * dt_i = ---------- dt (1)
14843 * \Sum_j w_j
14844 *
14845 * which we do by tracking a virtual time, s_i:
14846 *
14847 * 1
14848 * s_i = --- d[t]_i (2)
14849 * w_i
14850 *
14851 * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
14852 * The immediate corollary is that the ideal schedule S, where (2) to use
14853 * an infinitesimal delta, is:
14854 *
14855 * 1
14856 * S = ---------- dt (3)
14857 * \Sum_i w_i
14858 *
14859 * From which we can define the lag, or deviation from the ideal, as:
14860 *
14861 * lag(i) = S - s_i (4)
14862 *
14863 * And since the one and only purpose is to approximate S, we get that:
14864 *
14865 * \Sum_i w_i lag(i) := 0 (5)
14866 *
14867 * If this were not so, we no longer converge to S, and we can no longer
14868 * claim our scheduler has any of the properties we derive from S. This is
14869 * exactly what you did above, you broke it!
14870 *
14871 *
14872 * Let's continue for a while though; to see if there is anything useful to
14873 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
14874 *
14875 * \Sum_i w_i s_i
14876 * S = -------------- (6)
14877 * \Sum_i w_i
14878 *
14879 * Which gives us a way to compute S, given our s_i. Now, if you've read
14880 * our code, you know that we do not in fact do this, the reason for this
14881 * is two-fold. Firstly, computing S in that way requires a 64bit division
14882 * for every time we'd use it (see 12), and secondly, this only describes
14883 * the steady-state, it doesn't handle dynamics.
14884 *
14885 * Anyway, in (6): s_i -> x + (s_i - x), to get:
14886 *
14887 * \Sum_i w_i (s_i - x)
14888 * S - x = -------------------- (7)
14889 * \Sum_i w_i
14890 *
14891 * Which shows that S and s_i transform alike (which makes perfect sense
14892 * given that S is basically the (weighted) average of s_i).
14893 *
14894 * So the thing to remember is that the above is strictly UP. It is
14895 * possible to generalize to multiple runqueues -- however it gets really
14896 * yuck when you have to add affinity support, as illustrated by our very
14897 * first counter-example.
14898 *
14899 * Luckily I think we can avoid needing a full multi-queue variant for
14900 * core-scheduling (or load-balancing). The crucial observation is that we
14901 * only actually need this comparison in the presence of forced-idle; only
14902 * then do we need to tell if the stalled rq has higher priority over the
14903 * other.
14904 *
14905 * [XXX assumes SMT2; better consider the more general case, I suspect
14906 * it'll work out because our comparison is always between 2 rqs and the
14907 * answer is only interesting if one of them is forced-idle]
14908 *
14909 * And (under assumption of SMT2) when there is forced-idle, there is only
14910 * a single queue, so everything works like normal.
14911 *
14912 * Let, for our runqueue 'k':
14913 *
14914 * T_k = \Sum_i w_i s_i
14915 * W_k = \Sum_i w_i ; for all i of k (8)
14916 *
14917 * Then we can write (6) like:
14918 *
14919 * T_k
14920 * S_k = --- (9)
14921 * W_k
14922 *
14923 * From which immediately follows that:
14924 *
14925 * T_k + T_l
14926 * S_k+l = --------- (10)
14927 * W_k + W_l
14928 *
14929 * On which we can define a combined lag:
14930 *
14931 * lag_k+l(i) := S_k+l - s_i (11)
14932 *
14933 * And that gives us the tools to compare tasks across a combined runqueue.
14934 *
14935 *
14936 * Combined this gives the following:
14937 *
14938 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
14939 * using (7); this only requires storing single 'time'-stamps.
14940 *
14941 * b) when comparing tasks between 2 runqueues of which one is forced-idle,
14942 * compare the combined lag, per (11).
14943 *
14944 * Now, of course cgroups (I so hate them) make this more interesting in
14945 * that a) seems to suggest we need to iterate all cgroup on a CPU at such
14946 * boundaries, but I think we can avoid that. The force-idle is for the
14947 * whole CPU, all it's rqs. So we can mark it in the root and lazily
14948 * propagate downward on demand.
14949 */
14950
14951 /*
14952 * So this sync is basically a relative reset of S to 0.
14953 *
14954 * So with 2 queues, when one goes idle, we drop them both to 0 and one
14955 * then increases due to not being idle, and the idle one builds up lag to
14956 * get re-elected. So far so simple, right?
14957 *
14958 * When there's 3, we can have the situation where 2 run and one is idle,
14959 * we sync to 0 and let the idle one build up lag to get re-election. Now
14960 * suppose another one also drops idle. At this point dropping all to 0
14961 * again would destroy the built-up lag from the queue that was already
14962 * idle, not good.
14963 *
14964 * So instead of syncing everything, we can:
14965 *
14966 * less := !((s64)(s_a - s_b) <= 0)
14967 *
14968 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
14969 * == v_a - (v_b - S_a + S_b)
14970 *
14971 * IOW, we can recast the (lag) comparison to a one-sided difference.
14972 * So if then, instead of syncing the whole queue, sync the idle queue
14973 * against the active queue with S_a + S_b at the point where we sync.
14974 *
14975 * (XXX consider the implication of living in a cyclic group: N / 2^n N)
14976 *
14977 * This gives us means of syncing single queues against the active queue,
14978 * and for already idle queues to preserve their build-up lag.
14979 *
14980 * Of course, then we get the situation where there's 2 active and one
14981 * going idle, who do we pick to sync against? Theory would have us sync
14982 * against the combined S, but as we've already demonstrated, there is no
14983 * such thing in infeasible weight scenarios.
14984 *
14985 * One thing I've considered; and this is where that core_active rudiment
14986 * came from, is having active queues sync up between themselves after
14987 * every tick. This limits the observed divergence due to the work
14988 * conservancy.
14989 *
14990 * On top of that, we can improve upon things by employing (10) here.
14991 */
14992
14993 /*
14994 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
14995 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)14996 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
14997 bool forceidle)
14998 {
14999 for_each_sched_entity(se) {
15000 struct cfs_rq *cfs_rq = cfs_rq_of(se);
15001
15002 if (forceidle) {
15003 if (cfs_rq->forceidle_seq == fi_seq)
15004 break;
15005 cfs_rq->forceidle_seq = fi_seq;
15006 }
15007
15008 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
15009 }
15010 }
15011
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)15012 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
15013 {
15014 struct sched_entity *se = &p->se;
15015
15016 if (p->sched_class != &fair_sched_class)
15017 return;
15018
15019 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
15020 }
15021
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)15022 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
15023 bool in_fi)
15024 {
15025 struct rq *rq = task_rq(a);
15026 const struct sched_entity *sea = &a->se;
15027 const struct sched_entity *seb = &b->se;
15028 struct cfs_rq *cfs_rqa;
15029 struct cfs_rq *cfs_rqb;
15030 s64 delta;
15031
15032 WARN_ON_ONCE(task_rq(b)->core != rq->core);
15033
15034 cfs_rqa = &task_rq(a)->cfs;
15035 cfs_rqb = &task_rq(b)->cfs;
15036
15037 /*
15038 * Find delta after normalizing se's vruntime with its cfs_rq's
15039 * zero_vruntime_fi, which would have been updated in prior calls
15040 * to se_fi_update().
15041 */
15042 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) +
15043 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi);
15044
15045 return delta > 0;
15046 }
15047
task_is_throttled_fair(struct task_struct * p,int cpu)15048 static int task_is_throttled_fair(struct task_struct *p, int cpu)
15049 {
15050 struct cfs_rq *cfs_rq;
15051
15052 #ifdef CONFIG_FAIR_GROUP_SCHED
15053 cfs_rq = tg_cfs_rq(task_group(p), cpu);
15054 #else
15055 cfs_rq = &cpu_rq(cpu)->cfs;
15056 #endif
15057 return throttled_hierarchy(cfs_rq);
15058 }
15059 #else /* !CONFIG_SCHED_CORE: */
task_tick_core(struct rq * rq,struct task_struct * curr)15060 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
15061 #endif /* !CONFIG_SCHED_CORE */
15062
15063 /*
15064 * scheduler tick hitting a task of our scheduling class.
15065 *
15066 * NOTE: This function can be called remotely by the tick offload that
15067 * goes along full dynticks. Therefore no local assumption can be made
15068 * and everything must be accessed through the @rq and @curr passed in
15069 * parameters.
15070 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)15071 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
15072 {
15073 struct sched_entity *se = &curr->se;
15074
15075 if (se->on_rq) {
15076 unsigned long weight = NICE_0_LOAD;
15077 struct cfs_rq *cfs_rq;
15078
15079 for_each_sched_entity(se) {
15080 cfs_rq = cfs_rq_of(se);
15081 entity_tick(cfs_rq, se, queued);
15082
15083 weight = __calc_prop_weight(cfs_rq, se, weight);
15084 }
15085
15086 se = &curr->se;
15087 reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15088 }
15089
15090 if (queued)
15091 return;
15092
15093 if (static_branch_unlikely(&sched_numa_balancing))
15094 task_tick_numa(rq, curr);
15095
15096 task_tick_cache(rq, curr);
15097
15098 update_misfit_status(curr, rq);
15099 check_update_overutilized_status(task_rq(curr));
15100
15101 task_tick_core(rq, curr);
15102 }
15103
15104 /*
15105 * called on fork with the child task as argument from the parent's context
15106 * - child not yet on the tasklist
15107 * - preemption disabled
15108 */
task_fork_fair(struct task_struct * p)15109 static void task_fork_fair(struct task_struct *p)
15110 {
15111 set_task_max_allowed_capacity(p);
15112 }
15113
15114 /*
15115 * Priority of the task has changed. Check to see if we preempt
15116 * the current task.
15117 */
15118 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,u64 oldprio)15119 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
15120 {
15121 if (!task_on_rq_queued(p))
15122 return;
15123
15124 if (p->prio == oldprio)
15125 return;
15126
15127 if (rq->cfs.h_nr_queued == 1)
15128 return;
15129
15130 /*
15131 * Reschedule if we are currently running on this runqueue and
15132 * our priority decreased, or if we are not currently running on
15133 * this runqueue and our priority is higher than the current's
15134 */
15135 if (task_current_donor(rq, p)) {
15136 if (p->prio > oldprio)
15137 resched_curr(rq);
15138 } else {
15139 wakeup_preempt(rq, p, 0);
15140 }
15141 }
15142
15143 #ifdef CONFIG_FAIR_GROUP_SCHED
15144 /*
15145 * Propagate the changes of the sched_entity across the tg tree to make it
15146 * visible to the root
15147 */
propagate_entity_cfs_rq(struct sched_entity * se)15148 static void propagate_entity_cfs_rq(struct sched_entity *se)
15149 {
15150 struct cfs_rq *cfs_rq = cfs_rq_of(se);
15151
15152 /*
15153 * If a task gets attached to this cfs_rq and before being queued,
15154 * it gets migrated to another CPU due to reasons like affinity
15155 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
15156 * that removed load decayed or it can cause faireness problem.
15157 */
15158 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15159 list_add_leaf_cfs_rq(cfs_rq);
15160
15161 /* Start to propagate at parent */
15162 se = se->parent;
15163
15164 for_each_sched_entity(se) {
15165 cfs_rq = cfs_rq_of(se);
15166
15167 update_load_avg(cfs_rq, se, UPDATE_TG);
15168
15169 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
15170 list_add_leaf_cfs_rq(cfs_rq);
15171 }
15172
15173 assert_list_leaf_cfs_rq(rq_of(cfs_rq));
15174 }
15175 #else /* !CONFIG_FAIR_GROUP_SCHED: */
propagate_entity_cfs_rq(struct sched_entity * se)15176 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
15177 #endif /* !CONFIG_FAIR_GROUP_SCHED */
15178
detach_entity_cfs_rq(struct sched_entity * se)15179 static void detach_entity_cfs_rq(struct sched_entity *se)
15180 {
15181 struct cfs_rq *cfs_rq = cfs_rq_of(se);
15182
15183 /*
15184 * In case the task sched_avg hasn't been attached:
15185 * - A forked task which hasn't been woken up by wake_up_new_task().
15186 * - A task which has been woken up by try_to_wake_up() but is
15187 * waiting for actually being woken up by sched_ttwu_pending().
15188 */
15189 if (!se->avg.last_update_time)
15190 return;
15191
15192 /* Catch up with the cfs_rq and remove our load when we leave */
15193 update_load_avg(cfs_rq, se, 0);
15194 detach_entity_load_avg(cfs_rq, se);
15195 update_tg_load_avg(cfs_rq);
15196 propagate_entity_cfs_rq(se);
15197 }
15198
attach_entity_cfs_rq(struct sched_entity * se)15199 static void attach_entity_cfs_rq(struct sched_entity *se)
15200 {
15201 struct cfs_rq *cfs_rq = cfs_rq_of(se);
15202
15203 /* Synchronize entity with its cfs_rq */
15204 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
15205 attach_entity_load_avg(cfs_rq, se);
15206 update_tg_load_avg(cfs_rq);
15207 propagate_entity_cfs_rq(se);
15208 }
15209
detach_task_cfs_rq(struct task_struct * p)15210 static void detach_task_cfs_rq(struct task_struct *p)
15211 {
15212 struct sched_entity *se = &p->se;
15213
15214 detach_entity_cfs_rq(se);
15215 }
15216
attach_task_cfs_rq(struct task_struct * p)15217 static void attach_task_cfs_rq(struct task_struct *p)
15218 {
15219 struct sched_entity *se = &p->se;
15220
15221 attach_entity_cfs_rq(se);
15222 }
15223
switching_from_fair(struct rq * rq,struct task_struct * p)15224 static void switching_from_fair(struct rq *rq, struct task_struct *p)
15225 {
15226 if (p->se.sched_delayed)
15227 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
15228 }
15229
switched_from_fair(struct rq * rq,struct task_struct * p)15230 static void switched_from_fair(struct rq *rq, struct task_struct *p)
15231 {
15232 detach_task_cfs_rq(p);
15233 }
15234
switched_to_fair(struct rq * rq,struct task_struct * p)15235 static void switched_to_fair(struct rq *rq, struct task_struct *p)
15236 {
15237 WARN_ON_ONCE(p->se.sched_delayed);
15238
15239 attach_task_cfs_rq(p);
15240
15241 set_task_max_allowed_capacity(p);
15242
15243 if (task_on_rq_queued(p)) {
15244 /*
15245 * We were most likely switched from sched_rt, so
15246 * kick off the schedule if running, otherwise just see
15247 * if we can still preempt the current task.
15248 */
15249 if (task_current_donor(rq, p))
15250 resched_curr(rq);
15251 else
15252 wakeup_preempt(rq, p, 0);
15253 }
15254 }
15255
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)15256 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
15257 {
15258 struct sched_entity *se = &p->se;
15259 bool throttled = false;
15260 struct cfs_rq *cfs_rq = &rq->cfs;
15261 unsigned long weight = NICE_0_LOAD;
15262 bool on_rq = se->on_rq;
15263
15264 clear_buddies(cfs_rq, se);
15265
15266 if (on_rq)
15267 __dequeue_entity(cfs_rq, se);
15268
15269 for_each_sched_entity(se) {
15270 cfs_rq = cfs_rq_of(se);
15271
15272 if (!IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) ||
15273 !first || !cfs_rq->h_curr)
15274 set_next_entity(cfs_rq, se);
15275
15276 /* ensure bandwidth has been allocated on our new cfs_rq */
15277 throttled |= account_cfs_rq_runtime(cfs_rq, 0);
15278
15279 if (on_rq)
15280 weight = __calc_prop_weight(cfs_rq, se, weight);
15281 }
15282
15283 if (throttled)
15284 task_throttle_setup_work(p);
15285
15286 se = &p->se;
15287 cfs_rq->curr = se;
15288
15289 if (on_rq) {
15290 reweight_eevdf(cfs_rq, se, weight, se->on_rq);
15291 if (first)
15292 set_protect_slice(cfs_rq, se);
15293 }
15294
15295 if (task_on_rq_queued(p)) {
15296 /*
15297 * Move the next running task to the front of the list, so our
15298 * cfs_tasks list becomes MRU one.
15299 */
15300 list_move(&se->group_node, &rq->cfs_tasks);
15301 }
15302 if (!first)
15303 return;
15304
15305 WARN_ON_ONCE(se->sched_delayed);
15306
15307 if (hrtick_enabled_fair(rq))
15308 hrtick_start_fair(rq, p);
15309
15310 update_misfit_status(p, rq);
15311 sched_fair_update_stop_tick(rq, p);
15312 }
15313
init_cfs_rq(struct cfs_rq * cfs_rq)15314 void init_cfs_rq(struct cfs_rq *cfs_rq)
15315 {
15316 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
15317 cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
15318 raw_spin_lock_init(&cfs_rq->removed.lock);
15319 }
15320
15321 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)15322 static void task_change_group_fair(struct task_struct *p)
15323 {
15324 /*
15325 * We couldn't detach or attach a forked task which
15326 * hasn't been woken up by wake_up_new_task().
15327 */
15328 if (READ_ONCE(p->__state) == TASK_NEW)
15329 return;
15330
15331 detach_task_cfs_rq(p);
15332
15333 /* Tell se's cfs_rq has been changed -- migrated */
15334 p->se.avg.last_update_time = 0;
15335 set_task_rq(p, task_cpu(p));
15336 attach_task_cfs_rq(p);
15337 }
15338
free_fair_sched_group(struct task_group * tg)15339 void free_fair_sched_group(struct task_group *tg)
15340 {
15341 free_percpu(tg->cfs_rq);
15342 }
15343
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)15344 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
15345 {
15346 struct cfs_tg_state __percpu *state;
15347 struct sched_entity *se;
15348 struct cfs_rq *cfs_rq;
15349 int i;
15350
15351 state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL);
15352 if (!state)
15353 goto err;
15354
15355 tg->cfs_rq = &state->cfs_rq;
15356 tg->shares = NICE_0_LOAD;
15357
15358 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
15359
15360 for_each_possible_cpu(i) {
15361 cfs_rq = tg_cfs_rq(tg, i);
15362 if (!cfs_rq)
15363 goto err;
15364
15365 se = tg_se(tg, i);
15366 init_cfs_rq(cfs_rq);
15367 init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i));
15368 init_entity_runnable_average(se);
15369 }
15370
15371 return 1;
15372
15373 err:
15374 return 0;
15375 }
15376
online_fair_sched_group(struct task_group * tg)15377 void online_fair_sched_group(struct task_group *tg)
15378 {
15379 struct sched_entity *se;
15380 struct rq_flags rf;
15381 struct rq *rq;
15382 int i;
15383
15384 for_each_possible_cpu(i) {
15385 rq = cpu_rq(i);
15386 se = tg_se(tg, i);
15387 rq_lock_irq(rq, &rf);
15388 update_rq_clock(rq);
15389 attach_entity_cfs_rq(se);
15390 sync_throttle(tg, i);
15391 rq_unlock_irq(rq, &rf);
15392 }
15393 }
15394
unregister_fair_sched_group(struct task_group * tg)15395 void unregister_fair_sched_group(struct task_group *tg)
15396 {
15397 int cpu;
15398
15399 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
15400
15401 for_each_possible_cpu(cpu) {
15402 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);
15403 struct sched_entity *se = tg_se(tg, cpu);
15404 struct rq *rq = cpu_rq(cpu);
15405
15406 if (se)
15407 remove_entity_load_avg(se);
15408
15409 /*
15410 * Only empty task groups can be destroyed; so we can speculatively
15411 * check on_list without danger of it being re-added.
15412 */
15413 if (cfs_rq->on_list) {
15414 guard(rq_lock_irqsave)(rq);
15415 list_del_leaf_cfs_rq(cfs_rq);
15416 }
15417 }
15418 }
15419
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)15420 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
15421 struct sched_entity *se, int cpu,
15422 struct sched_entity *parent)
15423 {
15424 struct rq *rq = cpu_rq(cpu);
15425
15426 cfs_rq->tg = tg;
15427 cfs_rq->rq = rq;
15428 init_cfs_rq_runtime(cfs_rq);
15429
15430 /* se could be NULL for root_task_group */
15431 if (!se)
15432 return;
15433
15434 if (!parent) {
15435 se->cfs_rq = &rq->cfs;
15436 se->depth = 0;
15437 } else {
15438 se->cfs_rq = parent->my_q;
15439 se->depth = parent->depth + 1;
15440 }
15441
15442 se->my_q = cfs_rq;
15443 /* guarantee group entities always have weight */
15444 update_load_set(&se->load, NICE_0_LOAD);
15445 se->parent = parent;
15446 }
15447
15448 static DEFINE_MUTEX(shares_mutex);
15449
__sched_group_set_shares(struct task_group * tg,unsigned long shares)15450 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
15451 {
15452 int i;
15453
15454 lockdep_assert_held(&shares_mutex);
15455
15456 /*
15457 * We can't change the weight of the root cgroup.
15458 */
15459 if (is_root_task_group(tg))
15460 return -EINVAL;
15461
15462 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
15463
15464 if (tg->shares == shares)
15465 return 0;
15466
15467 tg->shares = shares;
15468 for_each_possible_cpu(i) {
15469 struct rq *rq = cpu_rq(i);
15470 struct sched_entity *se = tg_se(tg, i);
15471 struct rq_flags rf;
15472
15473 /* Propagate contribution to hierarchy */
15474 rq_lock_irqsave(rq, &rf);
15475 update_rq_clock(rq);
15476 for_each_sched_entity(se) {
15477 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
15478 update_cfs_group(se);
15479 }
15480 rq_unlock_irqrestore(rq, &rf);
15481 }
15482
15483 return 0;
15484 }
15485
sched_group_set_shares(struct task_group * tg,unsigned long shares)15486 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
15487 {
15488 int ret;
15489
15490 mutex_lock(&shares_mutex);
15491 if (tg_is_idle(tg))
15492 ret = -EINVAL;
15493 else
15494 ret = __sched_group_set_shares(tg, shares);
15495 mutex_unlock(&shares_mutex);
15496
15497 return ret;
15498 }
15499
sched_group_set_idle(struct task_group * tg,long idle)15500 int sched_group_set_idle(struct task_group *tg, long idle)
15501 {
15502 int i;
15503
15504 if (tg == &root_task_group)
15505 return -EINVAL;
15506
15507 if (idle < 0 || idle > 1)
15508 return -EINVAL;
15509
15510 mutex_lock(&shares_mutex);
15511
15512 if (tg->idle == idle) {
15513 mutex_unlock(&shares_mutex);
15514 return 0;
15515 }
15516
15517 tg->idle = idle;
15518
15519 for_each_possible_cpu(i) {
15520 struct rq *rq = cpu_rq(i);
15521 struct sched_entity *se = tg_se(tg, i);
15522 struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i);
15523 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
15524 long idle_task_delta;
15525 struct rq_flags rf;
15526
15527 rq_lock_irqsave(rq, &rf);
15528
15529 grp_cfs_rq->idle = idle;
15530 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
15531 goto next_cpu;
15532
15533 idle_task_delta = grp_cfs_rq->h_nr_queued -
15534 grp_cfs_rq->h_nr_idle;
15535 if (!cfs_rq_is_idle(grp_cfs_rq))
15536 idle_task_delta *= -1;
15537
15538 for_each_sched_entity(se) {
15539 struct cfs_rq *cfs_rq = cfs_rq_of(se);
15540
15541 if (!se->on_rq)
15542 break;
15543
15544 cfs_rq->h_nr_idle += idle_task_delta;
15545
15546 /* Already accounted at parent level and above. */
15547 if (cfs_rq_is_idle(cfs_rq))
15548 break;
15549 }
15550
15551 next_cpu:
15552 rq_unlock_irqrestore(rq, &rf);
15553 }
15554
15555 /* Idle groups have minimum weight. */
15556 if (tg_is_idle(tg))
15557 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
15558 else
15559 __sched_group_set_shares(tg, NICE_0_LOAD);
15560
15561 mutex_unlock(&shares_mutex);
15562 return 0;
15563 }
15564
15565 #endif /* CONFIG_FAIR_GROUP_SCHED */
15566
15567
get_rr_interval_fair(struct rq * rq,struct task_struct * task)15568 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
15569 {
15570 struct sched_entity *se = &task->se;
15571 unsigned int rr_interval = 0;
15572
15573 /*
15574 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
15575 * idle runqueue:
15576 */
15577 if (rq->cfs.load.weight)
15578 rr_interval = NS_TO_JIFFIES(se->slice);
15579
15580 return rr_interval;
15581 }
15582
15583 /*
15584 * All the scheduling class methods:
15585 */
15586 DEFINE_SCHED_CLASS(fair) = {
15587 .enqueue_task = enqueue_task_fair,
15588 .dequeue_task = dequeue_task_fair,
15589 .yield_task = yield_task_fair,
15590 .yield_to_task = yield_to_task_fair,
15591
15592 .wakeup_preempt = wakeup_preempt_fair,
15593
15594 .pick_task = pick_task_fair,
15595 .put_prev_task = put_prev_task_fair,
15596 .set_next_task = set_next_task_fair,
15597
15598 .select_task_rq = select_task_rq_fair,
15599 .migrate_task_rq = migrate_task_rq_fair,
15600
15601 .rq_online = rq_online_fair,
15602 .rq_offline = rq_offline_fair,
15603
15604 .task_dead = task_dead_fair,
15605 .set_cpus_allowed = set_cpus_allowed_fair,
15606
15607 .task_tick = task_tick_fair,
15608 .task_fork = task_fork_fair,
15609
15610 .reweight_task = reweight_task_fair,
15611 .prio_changed = prio_changed_fair,
15612 .switching_from = switching_from_fair,
15613 .switched_from = switched_from_fair,
15614 .switched_to = switched_to_fair,
15615
15616 .get_rr_interval = get_rr_interval_fair,
15617
15618 .update_curr = update_curr_fair,
15619
15620 #ifdef CONFIG_FAIR_GROUP_SCHED
15621 .task_change_group = task_change_group_fair,
15622 #endif
15623
15624 #ifdef CONFIG_SCHED_CORE
15625 .task_is_throttled = task_is_throttled_fair,
15626 #endif
15627
15628 #ifdef CONFIG_UCLAMP_TASK
15629 .uclamp_enabled = 1,
15630 #endif
15631 };
15632
print_cfs_stats(struct seq_file * m,int cpu)15633 void print_cfs_stats(struct seq_file *m, int cpu)
15634 {
15635 struct cfs_rq *cfs_rq, *pos;
15636
15637 rcu_read_lock();
15638 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
15639 print_cfs_rq(m, cpu, cfs_rq);
15640 rcu_read_unlock();
15641 }
15642
15643 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)15644 void show_numa_stats(struct task_struct *p, struct seq_file *m)
15645 {
15646 int node;
15647 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
15648 struct numa_group *ng;
15649
15650 rcu_read_lock();
15651 ng = rcu_dereference_all(p->numa_group);
15652 for_each_online_node(node) {
15653 if (p->numa_faults) {
15654 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
15655 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
15656 }
15657 if (ng) {
15658 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
15659 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
15660 }
15661 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
15662 }
15663 rcu_read_unlock();
15664 }
15665 #endif /* CONFIG_NUMA_BALANCING */
15666
init_sched_fair_class(void)15667 __init void init_sched_fair_class(void)
15668 {
15669 int i;
15670
15671 for_each_possible_cpu(i) {
15672 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
15673 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
15674 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
15675 GFP_KERNEL, cpu_to_node(i));
15676
15677 #ifdef CONFIG_CFS_BANDWIDTH
15678 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
15679 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
15680 #endif
15681 }
15682
15683 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
15684
15685 #ifdef CONFIG_NO_HZ_COMMON
15686 nohz.next_balance = jiffies;
15687 nohz.next_blocked = jiffies;
15688 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
15689 #endif
15690 }
15691