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/spinlock_api.h>
30 #include <linux/cpumask_api.h>
31 #include <linux/lockdep_api.h>
32 #include <linux/softirq.h>
33 #include <linux/refcount_api.h>
34 #include <linux/topology.h>
35 #include <linux/sched/clock.h>
36 #include <linux/sched/cond_resched.h>
37 #include <linux/sched/cputime.h>
38 #include <linux/sched/isolation.h>
39 #include <linux/sched/nohz.h>
40 #include <linux/sched/prio.h>
41
42 #include <linux/cpuidle.h>
43 #include <linux/interrupt.h>
44 #include <linux/memory-tiers.h>
45 #include <linux/mempolicy.h>
46 #include <linux/mutex_api.h>
47 #include <linux/profile.h>
48 #include <linux/psi.h>
49 #include <linux/ratelimit.h>
50 #include <linux/task_work.h>
51 #include <linux/rbtree_augmented.h>
52
53 #include <asm/switch_to.h>
54
55 #include <uapi/linux/sched/types.h>
56
57 #include "sched.h"
58 #include "stats.h"
59 #include "autogroup.h"
60
61 /*
62 * The initial- and re-scaling of tunables is configurable
63 *
64 * Options are:
65 *
66 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
67 * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus)
68 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
69 *
70 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
71 */
72 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
73
74 /*
75 * Minimal preemption granularity for CPU-bound tasks:
76 *
77 * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
78 */
79 unsigned int sysctl_sched_base_slice = 700000ULL;
80 static unsigned int normalized_sysctl_sched_base_slice = 700000ULL;
81
82 __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL;
83
setup_sched_thermal_decay_shift(char * str)84 static int __init setup_sched_thermal_decay_shift(char *str)
85 {
86 pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
87 return 1;
88 }
89 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
90
91 /*
92 * For asym packing, by default the lower numbered CPU has higher priority.
93 */
arch_asym_cpu_priority(int cpu)94 int __weak arch_asym_cpu_priority(int cpu)
95 {
96 return -cpu;
97 }
98
99 /*
100 * The margin used when comparing utilization with CPU capacity.
101 *
102 * (default: ~20%)
103 */
104 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
105
106 /*
107 * The margin used when comparing CPU capacities.
108 * is 'cap1' noticeably greater than 'cap2'
109 *
110 * (default: ~5%)
111 */
112 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
113
114 #ifdef CONFIG_CFS_BANDWIDTH
115 /*
116 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
117 * each time a cfs_rq requests quota.
118 *
119 * Note: in the case that the slice exceeds the runtime remaining (either due
120 * to consumption or the quota being specified to be smaller than the slice)
121 * we will always only issue the remaining available time.
122 *
123 * (default: 5 msec, units: microseconds)
124 */
125 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
126 #endif
127
128 #ifdef CONFIG_NUMA_BALANCING
129 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
130 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
131 #endif
132
133 #ifdef CONFIG_SYSCTL
134 static const struct ctl_table sched_fair_sysctls[] = {
135 #ifdef CONFIG_CFS_BANDWIDTH
136 {
137 .procname = "sched_cfs_bandwidth_slice_us",
138 .data = &sysctl_sched_cfs_bandwidth_slice,
139 .maxlen = sizeof(unsigned int),
140 .mode = 0644,
141 .proc_handler = proc_dointvec_minmax,
142 .extra1 = SYSCTL_ONE,
143 },
144 #endif
145 #ifdef CONFIG_NUMA_BALANCING
146 {
147 .procname = "numa_balancing_promote_rate_limit_MBps",
148 .data = &sysctl_numa_balancing_promote_rate_limit,
149 .maxlen = sizeof(unsigned int),
150 .mode = 0644,
151 .proc_handler = proc_dointvec_minmax,
152 .extra1 = SYSCTL_ZERO,
153 },
154 #endif /* CONFIG_NUMA_BALANCING */
155 };
156
sched_fair_sysctl_init(void)157 static int __init sched_fair_sysctl_init(void)
158 {
159 register_sysctl_init("kernel", sched_fair_sysctls);
160 return 0;
161 }
162 late_initcall(sched_fair_sysctl_init);
163 #endif /* CONFIG_SYSCTL */
164
update_load_add(struct load_weight * lw,unsigned long inc)165 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
166 {
167 lw->weight += inc;
168 lw->inv_weight = 0;
169 }
170
update_load_sub(struct load_weight * lw,unsigned long dec)171 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
172 {
173 lw->weight -= dec;
174 lw->inv_weight = 0;
175 }
176
update_load_set(struct load_weight * lw,unsigned long w)177 static inline void update_load_set(struct load_weight *lw, unsigned long w)
178 {
179 lw->weight = w;
180 lw->inv_weight = 0;
181 }
182
183 /*
184 * Increase the granularity value when there are more CPUs,
185 * because with more CPUs the 'effective latency' as visible
186 * to users decreases. But the relationship is not linear,
187 * so pick a second-best guess by going with the log2 of the
188 * number of CPUs.
189 *
190 * This idea comes from the SD scheduler of Con Kolivas:
191 */
get_update_sysctl_factor(void)192 static unsigned int get_update_sysctl_factor(void)
193 {
194 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
195 unsigned int factor;
196
197 switch (sysctl_sched_tunable_scaling) {
198 case SCHED_TUNABLESCALING_NONE:
199 factor = 1;
200 break;
201 case SCHED_TUNABLESCALING_LINEAR:
202 factor = cpus;
203 break;
204 case SCHED_TUNABLESCALING_LOG:
205 default:
206 factor = 1 + ilog2(cpus);
207 break;
208 }
209
210 return factor;
211 }
212
update_sysctl(void)213 static void update_sysctl(void)
214 {
215 unsigned int factor = get_update_sysctl_factor();
216
217 #define SET_SYSCTL(name) \
218 (sysctl_##name = (factor) * normalized_sysctl_##name)
219 SET_SYSCTL(sched_base_slice);
220 #undef SET_SYSCTL
221 }
222
sched_init_granularity(void)223 void __init sched_init_granularity(void)
224 {
225 update_sysctl();
226 }
227
228 #ifndef CONFIG_64BIT
229 #define WMULT_CONST (~0U)
230 #define WMULT_SHIFT 32
231
__update_inv_weight(struct load_weight * lw)232 static void __update_inv_weight(struct load_weight *lw)
233 {
234 unsigned long w;
235
236 if (likely(lw->inv_weight))
237 return;
238
239 w = scale_load_down(lw->weight);
240
241 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
242 lw->inv_weight = 1;
243 else if (unlikely(!w))
244 lw->inv_weight = WMULT_CONST;
245 else
246 lw->inv_weight = WMULT_CONST / w;
247 }
248
249 /*
250 * delta_exec * weight / lw.weight
251 * OR
252 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
253 *
254 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
255 * we're guaranteed shift stays positive because inv_weight is guaranteed to
256 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
257 *
258 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
259 * weight/lw.weight <= 1, and therefore our shift will also be positive.
260 */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)261 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
262 {
263 u64 fact = scale_load_down(weight);
264 u32 fact_hi = (u32)(fact >> 32);
265 int shift = WMULT_SHIFT;
266 int fs;
267
268 __update_inv_weight(lw);
269
270 if (unlikely(fact_hi)) {
271 fs = fls(fact_hi);
272 shift -= fs;
273 fact >>= fs;
274 }
275
276 fact = mul_u32_u32(fact, lw->inv_weight);
277
278 fact_hi = (u32)(fact >> 32);
279 if (fact_hi) {
280 fs = fls(fact_hi);
281 shift -= fs;
282 fact >>= fs;
283 }
284
285 return mul_u64_u32_shr(delta_exec, fact, shift);
286 }
287 #else
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)288 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
289 {
290 return (delta_exec * weight) / lw->weight;
291 }
292 #endif
293
294 /*
295 * delta /= w
296 */
calc_delta_fair(u64 delta,struct sched_entity * se)297 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
298 {
299 if (unlikely(se->load.weight != NICE_0_LOAD))
300 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
301
302 return delta;
303 }
304
305 const struct sched_class fair_sched_class;
306
307 /**************************************************************
308 * CFS operations on generic schedulable entities:
309 */
310
311 #ifdef CONFIG_FAIR_GROUP_SCHED
312
313 /* Walk up scheduling entities hierarchy */
314 #define for_each_sched_entity(se) \
315 for (; se; se = se->parent)
316
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)317 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
318 {
319 struct rq *rq = rq_of(cfs_rq);
320 int cpu = cpu_of(rq);
321
322 if (cfs_rq->on_list)
323 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
324
325 cfs_rq->on_list = 1;
326
327 /*
328 * Ensure we either appear before our parent (if already
329 * enqueued) or force our parent to appear after us when it is
330 * enqueued. The fact that we always enqueue bottom-up
331 * reduces this to two cases and a special case for the root
332 * cfs_rq. Furthermore, it also means that we will always reset
333 * tmp_alone_branch either when the branch is connected
334 * to a tree or when we reach the top of the tree
335 */
336 if (cfs_rq->tg->parent &&
337 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
338 /*
339 * If parent is already on the list, we add the child
340 * just before. Thanks to circular linked property of
341 * the list, this means to put the child at the tail
342 * of the list that starts by parent.
343 */
344 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
345 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
346 /*
347 * The branch is now connected to its tree so we can
348 * reset tmp_alone_branch to the beginning of the
349 * list.
350 */
351 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
352 return true;
353 }
354
355 if (!cfs_rq->tg->parent) {
356 /*
357 * cfs rq without parent should be put
358 * at the tail of the list.
359 */
360 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
361 &rq->leaf_cfs_rq_list);
362 /*
363 * We have reach the top of a tree so we can reset
364 * tmp_alone_branch to the beginning of the list.
365 */
366 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
367 return true;
368 }
369
370 /*
371 * The parent has not already been added so we want to
372 * make sure that it will be put after us.
373 * tmp_alone_branch points to the begin of the branch
374 * where we will add parent.
375 */
376 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
377 /*
378 * update tmp_alone_branch to points to the new begin
379 * of the branch
380 */
381 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
382 return false;
383 }
384
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)385 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
386 {
387 if (cfs_rq->on_list) {
388 struct rq *rq = rq_of(cfs_rq);
389
390 /*
391 * With cfs_rq being unthrottled/throttled during an enqueue,
392 * it can happen the tmp_alone_branch points to the leaf that
393 * we finally want to delete. In this case, tmp_alone_branch moves
394 * to the prev element but it will point to rq->leaf_cfs_rq_list
395 * at the end of the enqueue.
396 */
397 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
398 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
399
400 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
401 cfs_rq->on_list = 0;
402 }
403 }
404
assert_list_leaf_cfs_rq(struct rq * rq)405 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
406 {
407 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
408 }
409
410 /* Iterate through all leaf cfs_rq's on a runqueue */
411 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
412 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
413 leaf_cfs_rq_list)
414
415 /* Do the two (enqueued) entities belong to the same group ? */
416 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)417 is_same_group(struct sched_entity *se, struct sched_entity *pse)
418 {
419 if (se->cfs_rq == pse->cfs_rq)
420 return se->cfs_rq;
421
422 return NULL;
423 }
424
parent_entity(const struct sched_entity * se)425 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
426 {
427 return se->parent;
428 }
429
430 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)431 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
432 {
433 int se_depth, pse_depth;
434
435 /*
436 * preemption test can be made between sibling entities who are in the
437 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
438 * both tasks until we find their ancestors who are siblings of common
439 * parent.
440 */
441
442 /* First walk up until both entities are at same depth */
443 se_depth = (*se)->depth;
444 pse_depth = (*pse)->depth;
445
446 while (se_depth > pse_depth) {
447 se_depth--;
448 *se = parent_entity(*se);
449 }
450
451 while (pse_depth > se_depth) {
452 pse_depth--;
453 *pse = parent_entity(*pse);
454 }
455
456 while (!is_same_group(*se, *pse)) {
457 *se = parent_entity(*se);
458 *pse = parent_entity(*pse);
459 }
460 }
461
tg_is_idle(struct task_group * tg)462 static int tg_is_idle(struct task_group *tg)
463 {
464 return tg->idle > 0;
465 }
466
cfs_rq_is_idle(struct cfs_rq * cfs_rq)467 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
468 {
469 return cfs_rq->idle > 0;
470 }
471
se_is_idle(struct sched_entity * se)472 static int se_is_idle(struct sched_entity *se)
473 {
474 if (entity_is_task(se))
475 return task_has_idle_policy(task_of(se));
476 return cfs_rq_is_idle(group_cfs_rq(se));
477 }
478
479 #else /* !CONFIG_FAIR_GROUP_SCHED: */
480
481 #define for_each_sched_entity(se) \
482 for (; se; se = NULL)
483
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)484 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
485 {
486 return true;
487 }
488
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)489 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
490 {
491 }
492
assert_list_leaf_cfs_rq(struct rq * rq)493 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
494 {
495 }
496
497 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
498 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
499
parent_entity(struct sched_entity * se)500 static inline struct sched_entity *parent_entity(struct sched_entity *se)
501 {
502 return NULL;
503 }
504
505 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)506 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
507 {
508 }
509
tg_is_idle(struct task_group * tg)510 static inline int tg_is_idle(struct task_group *tg)
511 {
512 return 0;
513 }
514
cfs_rq_is_idle(struct cfs_rq * cfs_rq)515 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
516 {
517 return 0;
518 }
519
se_is_idle(struct sched_entity * se)520 static int se_is_idle(struct sched_entity *se)
521 {
522 return task_has_idle_policy(task_of(se));
523 }
524
525 #endif /* !CONFIG_FAIR_GROUP_SCHED */
526
527 static __always_inline
528 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
529
530 /**************************************************************
531 * Scheduling class tree data structure manipulation methods:
532 */
533
534 extern void __BUILD_BUG_vruntime_cmp(void);
535
536 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */
537
538 #define vruntime_cmp(A, CMP_STR, B) ({ \
539 int __res = 0; \
540 \
541 if (!__builtin_strcmp(CMP_STR, "<")) { \
542 __res = ((s64)((A)-(B)) < 0); \
543 } else if (!__builtin_strcmp(CMP_STR, "<=")) { \
544 __res = ((s64)((A)-(B)) <= 0); \
545 } else if (!__builtin_strcmp(CMP_STR, ">")) { \
546 __res = ((s64)((A)-(B)) > 0); \
547 } else if (!__builtin_strcmp(CMP_STR, ">=")) { \
548 __res = ((s64)((A)-(B)) >= 0); \
549 } else { \
550 /* Unknown operator throws linker error: */ \
551 __BUILD_BUG_vruntime_cmp(); \
552 } \
553 \
554 __res; \
555 })
556
557 extern void __BUILD_BUG_vruntime_op(void);
558
559 #define vruntime_op(A, OP_STR, B) ({ \
560 s64 __res = 0; \
561 \
562 if (!__builtin_strcmp(OP_STR, "-")) { \
563 __res = (s64)((A)-(B)); \
564 } else { \
565 /* Unknown operator throws linker error: */ \
566 __BUILD_BUG_vruntime_op(); \
567 } \
568 \
569 __res; \
570 })
571
572
max_vruntime(u64 max_vruntime,u64 vruntime)573 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
574 {
575 if (vruntime_cmp(vruntime, ">", max_vruntime))
576 max_vruntime = vruntime;
577
578 return max_vruntime;
579 }
580
min_vruntime(u64 min_vruntime,u64 vruntime)581 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
582 {
583 if (vruntime_cmp(vruntime, "<", min_vruntime))
584 min_vruntime = vruntime;
585
586 return min_vruntime;
587 }
588
entity_before(const struct sched_entity * a,const struct sched_entity * b)589 static inline bool entity_before(const struct sched_entity *a,
590 const struct sched_entity *b)
591 {
592 /*
593 * Tiebreak on vruntime seems unnecessary since it can
594 * hardly happen.
595 */
596 return vruntime_cmp(a->deadline, "<", b->deadline);
597 }
598
599 /*
600 * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale
601 * and this value should be no more than two lag bounds. Which puts it in the
602 * general order of:
603 *
604 * (slice + TICK_NSEC) << NICE_0_LOAD_SHIFT
605 *
606 * which is around 44 bits in size (on 64bit); that is 20 for
607 * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for
608 * however many msec the actual slice+tick ends up begin.
609 *
610 * (disregarding the actual divide-by-weight part makes for the worst case
611 * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually
612 * being the zero-lag point).
613 */
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)614 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
615 {
616 return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime);
617 }
618
619 #define __node_2_se(node) \
620 rb_entry((node), struct sched_entity, run_node)
621
622 /*
623 * Compute virtual time from the per-task service numbers:
624 *
625 * Fair schedulers conserve lag:
626 *
627 * \Sum lag_i = 0
628 *
629 * Where lag_i is given by:
630 *
631 * lag_i = S - s_i = w_i * (V - v_i)
632 *
633 * Where S is the ideal service time and V is it's virtual time counterpart.
634 * Therefore:
635 *
636 * \Sum lag_i = 0
637 * \Sum w_i * (V - v_i) = 0
638 * \Sum (w_i * V - w_i * v_i) = 0
639 *
640 * From which we can solve an expression for V in v_i (which we have in
641 * se->vruntime):
642 *
643 * \Sum v_i * w_i \Sum v_i * w_i
644 * V = -------------- = --------------
645 * \Sum w_i W
646 *
647 * Specifically, this is the weighted average of all entity virtual runtimes.
648 *
649 * [[ NOTE: this is only equal to the ideal scheduler under the condition
650 * that join/leave operations happen at lag_i = 0, otherwise the
651 * virtual time has non-contiguous motion equivalent to:
652 *
653 * V +-= lag_i / W
654 *
655 * Also see the comment in place_entity() that deals with this. ]]
656 *
657 * However, since v_i is u64, and the multiplication could easily overflow
658 * transform it into a relative form that uses smaller quantities:
659 *
660 * Substitute: v_i == (v_i - v0) + v0
661 *
662 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
663 * V = ---------------------------- = --------------------- + v0
664 * W W
665 *
666 * Which we track using:
667 *
668 * v0 := cfs_rq->zero_vruntime
669 * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime
670 * \Sum w_i := cfs_rq->sum_weight
671 *
672 * Since zero_vruntime closely tracks the per-task service, these
673 * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag
674 * induced in the system due to quantisation.
675 */
avg_vruntime_weight(struct cfs_rq * cfs_rq,unsigned long w)676 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w)
677 {
678 #ifdef CONFIG_64BIT
679 if (cfs_rq->sum_shift)
680 w = max(2UL, w >> cfs_rq->sum_shift);
681 #endif
682 return w;
683 }
684
685 static inline void
__sum_w_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)686 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
687 {
688 unsigned long weight = avg_vruntime_weight(cfs_rq, se->load.weight);
689 s64 w_vruntime, key = entity_key(cfs_rq, se);
690
691 w_vruntime = key * weight;
692 WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62));
693
694 cfs_rq->sum_w_vruntime += w_vruntime;
695 cfs_rq->sum_weight += weight;
696 }
697
698 static void
sum_w_vruntime_add_paranoid(struct cfs_rq * cfs_rq,struct sched_entity * se)699 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se)
700 {
701 unsigned long weight;
702 s64 key, tmp;
703
704 again:
705 weight = avg_vruntime_weight(cfs_rq, se->load.weight);
706 key = entity_key(cfs_rq, se);
707
708 if (check_mul_overflow(key, weight, &key))
709 goto overflow;
710
711 if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp))
712 goto overflow;
713
714 cfs_rq->sum_w_vruntime = tmp;
715 cfs_rq->sum_weight += weight;
716 return;
717
718 overflow:
719 /*
720 * There's gotta be a limit -- if we're still failing at this point
721 * there's really nothing much to be done about things.
722 */
723 BUG_ON(cfs_rq->sum_shift >= 10);
724 cfs_rq->sum_shift++;
725
726 /*
727 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1
728 */
729 cfs_rq->sum_w_vruntime = 0;
730 cfs_rq->sum_weight = 0;
731
732 for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost;
733 node; node = rb_next(node))
734 __sum_w_vruntime_add(cfs_rq, __node_2_se(node));
735
736 goto again;
737 }
738
739 static void
sum_w_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)740 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
741 {
742 if (sched_feat(PARANOID_AVG))
743 return sum_w_vruntime_add_paranoid(cfs_rq, se);
744
745 __sum_w_vruntime_add(cfs_rq, se);
746 }
747
748 static void
sum_w_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)749 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
750 {
751 unsigned long weight = avg_vruntime_weight(cfs_rq, se->load.weight);
752 s64 key = entity_key(cfs_rq, se);
753
754 cfs_rq->sum_w_vruntime -= key * weight;
755 cfs_rq->sum_weight -= weight;
756 }
757
758 static inline
update_zero_vruntime(struct cfs_rq * cfs_rq,s64 delta)759 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta)
760 {
761 /*
762 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight
763 */
764 cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta;
765 cfs_rq->zero_vruntime += delta;
766 }
767
768 /*
769 * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true
770 * For this to be so, the result of this function must have a left bias.
771 *
772 * Called in:
773 * - place_entity() -- before enqueue
774 * - update_entity_lag() -- before dequeue
775 * - update_deadline() -- slice expiration
776 *
777 * This means it is one entry 'behind' but that puts it close enough to where
778 * the bound on entity_key() is at most two lag bounds.
779 */
avg_vruntime(struct cfs_rq * cfs_rq)780 u64 avg_vruntime(struct cfs_rq *cfs_rq)
781 {
782 struct sched_entity *curr = cfs_rq->curr;
783 long weight = cfs_rq->sum_weight;
784 s64 delta = 0;
785
786 if (curr && !curr->on_rq)
787 curr = NULL;
788
789 if (weight) {
790 s64 runtime = cfs_rq->sum_w_vruntime;
791
792 if (curr) {
793 unsigned long w = avg_vruntime_weight(cfs_rq, curr->load.weight);
794
795 runtime += entity_key(cfs_rq, curr) * w;
796 weight += w;
797 }
798
799 /* sign flips effective floor / ceiling */
800 if (runtime < 0)
801 runtime -= (weight - 1);
802
803 delta = div64_long(runtime, weight);
804 } else if (curr) {
805 /*
806 * When there is but one element, it is the average.
807 */
808 delta = curr->vruntime - cfs_rq->zero_vruntime;
809 }
810
811 update_zero_vruntime(cfs_rq, delta);
812
813 return cfs_rq->zero_vruntime;
814 }
815
816 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq);
817
818 /*
819 * lag_i = S - s_i = w_i * (V - v_i)
820 *
821 * However, since V is approximated by the weighted average of all entities it
822 * is possible -- by addition/removal/reweight to the tree -- to move V around
823 * and end up with a larger lag than we started with.
824 *
825 * Limit this to either double the slice length with a minimum of TICK_NSEC
826 * since that is the timing granularity.
827 *
828 * EEVDF gives the following limit for a steady state system:
829 *
830 * -r_max < lag < max(r_max, q)
831 */
entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se,u64 avruntime)832 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime)
833 {
834 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC;
835 s64 vlag, limit;
836
837 vlag = avruntime - se->vruntime;
838 limit = calc_delta_fair(max_slice, se);
839
840 return clamp(vlag, -limit, limit);
841 }
842
843 /*
844 * Delayed dequeue aims to reduce the negative lag of a dequeued task. While
845 * updating the lag of an entity, check that negative lag didn't increase
846 * during the delayed dequeue period which would be unfair.
847 * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO
848 * is set.
849 *
850 * Return true if the lag has been adjusted.
851 */
852 static __always_inline
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)853 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
854 {
855 s64 vlag = entity_lag(cfs_rq, se, avg_vruntime(cfs_rq));
856 bool ret;
857
858 WARN_ON_ONCE(!se->on_rq);
859
860 if (se->sched_delayed) {
861 /* previous vlag < 0 otherwise se would not be delayed */
862 vlag = max(vlag, se->vlag);
863 if (sched_feat(DELAY_ZERO))
864 vlag = min(vlag, 0);
865 }
866 ret = (vlag == se->vlag);
867 se->vlag = vlag;
868
869 return ret;
870 }
871
872 /*
873 * Entity is eligible once it received less service than it ought to have,
874 * eg. lag >= 0.
875 *
876 * lag_i = S - s_i = w_i*(V - v_i)
877 *
878 * lag_i >= 0 -> V >= v_i
879 *
880 * \Sum (v_i - v)*w_i
881 * V = ------------------ + v
882 * \Sum w_i
883 *
884 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
885 *
886 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
887 * to the loss in precision caused by the division.
888 */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)889 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
890 {
891 struct sched_entity *curr = cfs_rq->curr;
892 s64 avg = cfs_rq->sum_w_vruntime;
893 long load = cfs_rq->sum_weight;
894
895 if (curr && curr->on_rq) {
896 unsigned long weight = avg_vruntime_weight(cfs_rq, curr->load.weight);
897
898 avg += entity_key(cfs_rq, curr) * weight;
899 load += weight;
900 }
901
902 return avg >= vruntime_op(vruntime, "-", cfs_rq->zero_vruntime) * load;
903 }
904
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)905 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
906 {
907 return vruntime_eligible(cfs_rq, se->vruntime);
908 }
909
cfs_rq_min_slice(struct cfs_rq * cfs_rq)910 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
911 {
912 struct sched_entity *root = __pick_root_entity(cfs_rq);
913 struct sched_entity *curr = cfs_rq->curr;
914 u64 min_slice = ~0ULL;
915
916 if (curr && curr->on_rq)
917 min_slice = curr->slice;
918
919 if (root)
920 min_slice = min(min_slice, root->min_slice);
921
922 return min_slice;
923 }
924
cfs_rq_max_slice(struct cfs_rq * cfs_rq)925 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq)
926 {
927 struct sched_entity *root = __pick_root_entity(cfs_rq);
928 struct sched_entity *curr = cfs_rq->curr;
929 u64 max_slice = 0ULL;
930
931 if (curr && curr->on_rq)
932 max_slice = curr->slice;
933
934 if (root)
935 max_slice = max(max_slice, root->max_slice);
936
937 return max_slice;
938 }
939
__entity_less(struct rb_node * a,const struct rb_node * b)940 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
941 {
942 return entity_before(__node_2_se(a), __node_2_se(b));
943 }
944
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)945 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
946 {
947 if (node) {
948 struct sched_entity *rse = __node_2_se(node);
949
950 if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime))
951 se->min_vruntime = rse->min_vruntime;
952 }
953 }
954
__min_slice_update(struct sched_entity * se,struct rb_node * node)955 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
956 {
957 if (node) {
958 struct sched_entity *rse = __node_2_se(node);
959 if (rse->min_slice < se->min_slice)
960 se->min_slice = rse->min_slice;
961 }
962 }
963
__max_slice_update(struct sched_entity * se,struct rb_node * node)964 static inline void __max_slice_update(struct sched_entity *se, struct rb_node *node)
965 {
966 if (node) {
967 struct sched_entity *rse = __node_2_se(node);
968 if (rse->max_slice > se->max_slice)
969 se->max_slice = rse->max_slice;
970 }
971 }
972
973 /*
974 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
975 */
min_vruntime_update(struct sched_entity * se,bool exit)976 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
977 {
978 u64 old_min_vruntime = se->min_vruntime;
979 u64 old_min_slice = se->min_slice;
980 u64 old_max_slice = se->max_slice;
981 struct rb_node *node = &se->run_node;
982
983 se->min_vruntime = se->vruntime;
984 __min_vruntime_update(se, node->rb_right);
985 __min_vruntime_update(se, node->rb_left);
986
987 se->min_slice = se->slice;
988 __min_slice_update(se, node->rb_right);
989 __min_slice_update(se, node->rb_left);
990
991 se->max_slice = se->slice;
992 __max_slice_update(se, node->rb_right);
993 __max_slice_update(se, node->rb_left);
994
995 return se->min_vruntime == old_min_vruntime &&
996 se->min_slice == old_min_slice &&
997 se->max_slice == old_max_slice;
998 }
999
1000 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
1001 run_node, min_vruntime, min_vruntime_update);
1002
1003 /*
1004 * Enqueue an entity into the rb-tree:
1005 */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)1006 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1007 {
1008 sum_w_vruntime_add(cfs_rq, se);
1009 se->min_vruntime = se->vruntime;
1010 se->min_slice = se->slice;
1011 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1012 __entity_less, &min_vruntime_cb);
1013 }
1014
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)1015 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1016 {
1017 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
1018 &min_vruntime_cb);
1019 sum_w_vruntime_sub(cfs_rq, se);
1020 }
1021
__pick_root_entity(struct cfs_rq * cfs_rq)1022 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
1023 {
1024 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
1025
1026 if (!root)
1027 return NULL;
1028
1029 return __node_2_se(root);
1030 }
1031
__pick_first_entity(struct cfs_rq * cfs_rq)1032 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
1033 {
1034 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
1035
1036 if (!left)
1037 return NULL;
1038
1039 return __node_2_se(left);
1040 }
1041
1042 /*
1043 * Set the vruntime up to which an entity can run before looking
1044 * for another entity to pick.
1045 * In case of run to parity, we use the shortest slice of the enqueued
1046 * entities to set the protected period.
1047 * When run to parity is disabled, we give a minimum quantum to the running
1048 * entity to ensure progress.
1049 */
set_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)1050 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1051 {
1052 u64 slice = normalized_sysctl_sched_base_slice;
1053 u64 vprot = se->deadline;
1054
1055 if (sched_feat(RUN_TO_PARITY))
1056 slice = cfs_rq_min_slice(cfs_rq);
1057
1058 slice = min(slice, se->slice);
1059 if (slice != se->slice)
1060 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
1061
1062 se->vprot = vprot;
1063 }
1064
update_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)1065 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
1066 {
1067 u64 slice = cfs_rq_min_slice(cfs_rq);
1068
1069 se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se));
1070 }
1071
protect_slice(struct sched_entity * se)1072 static inline bool protect_slice(struct sched_entity *se)
1073 {
1074 return vruntime_cmp(se->vruntime, "<", se->vprot);
1075 }
1076
cancel_protect_slice(struct sched_entity * se)1077 static inline void cancel_protect_slice(struct sched_entity *se)
1078 {
1079 if (protect_slice(se))
1080 se->vprot = se->vruntime;
1081 }
1082
1083 /*
1084 * Earliest Eligible Virtual Deadline First
1085 *
1086 * In order to provide latency guarantees for different request sizes
1087 * EEVDF selects the best runnable task from two criteria:
1088 *
1089 * 1) the task must be eligible (must be owed service)
1090 *
1091 * 2) from those tasks that meet 1), we select the one
1092 * with the earliest virtual deadline.
1093 *
1094 * We can do this in O(log n) time due to an augmented RB-tree. The
1095 * tree keeps the entries sorted on deadline, but also functions as a
1096 * heap based on the vruntime by keeping:
1097 *
1098 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
1099 *
1100 * Which allows tree pruning through eligibility.
1101 */
__pick_eevdf(struct cfs_rq * cfs_rq,bool protect)1102 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
1103 {
1104 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
1105 struct sched_entity *se = __pick_first_entity(cfs_rq);
1106 struct sched_entity *curr = cfs_rq->curr;
1107 struct sched_entity *best = NULL;
1108
1109 /*
1110 * We can safely skip eligibility check if there is only one entity
1111 * in this cfs_rq, saving some cycles.
1112 */
1113 if (cfs_rq->nr_queued == 1)
1114 return curr && curr->on_rq ? curr : se;
1115
1116 /*
1117 * Picking the ->next buddy will affect latency but not fairness.
1118 */
1119 if (sched_feat(PICK_BUDDY) && protect &&
1120 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
1121 /* ->next will never be delayed */
1122 WARN_ON_ONCE(cfs_rq->next->sched_delayed);
1123 return cfs_rq->next;
1124 }
1125
1126 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
1127 curr = NULL;
1128
1129 if (curr && protect && protect_slice(curr))
1130 return curr;
1131
1132 /* Pick the leftmost entity if it's eligible */
1133 if (se && entity_eligible(cfs_rq, se)) {
1134 best = se;
1135 goto found;
1136 }
1137
1138 /* Heap search for the EEVD entity */
1139 while (node) {
1140 struct rb_node *left = node->rb_left;
1141
1142 /*
1143 * Eligible entities in left subtree are always better
1144 * choices, since they have earlier deadlines.
1145 */
1146 if (left && vruntime_eligible(cfs_rq,
1147 __node_2_se(left)->min_vruntime)) {
1148 node = left;
1149 continue;
1150 }
1151
1152 se = __node_2_se(node);
1153
1154 /*
1155 * The left subtree either is empty or has no eligible
1156 * entity, so check the current node since it is the one
1157 * with earliest deadline that might be eligible.
1158 */
1159 if (entity_eligible(cfs_rq, se)) {
1160 best = se;
1161 break;
1162 }
1163
1164 node = node->rb_right;
1165 }
1166 found:
1167 if (!best || (curr && entity_before(curr, best)))
1168 best = curr;
1169
1170 return best;
1171 }
1172
pick_eevdf(struct cfs_rq * cfs_rq)1173 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
1174 {
1175 return __pick_eevdf(cfs_rq, true);
1176 }
1177
__pick_last_entity(struct cfs_rq * cfs_rq)1178 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1179 {
1180 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1181
1182 if (!last)
1183 return NULL;
1184
1185 return __node_2_se(last);
1186 }
1187
1188 /**************************************************************
1189 * Scheduling class statistics methods:
1190 */
sched_update_scaling(void)1191 int sched_update_scaling(void)
1192 {
1193 unsigned int factor = get_update_sysctl_factor();
1194
1195 #define WRT_SYSCTL(name) \
1196 (normalized_sysctl_##name = sysctl_##name / (factor))
1197 WRT_SYSCTL(sched_base_slice);
1198 #undef WRT_SYSCTL
1199
1200 return 0;
1201 }
1202
1203 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1204
1205 /*
1206 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1207 * this is probably good enough.
1208 */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1209 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1210 {
1211 if (vruntime_cmp(se->vruntime, "<", se->deadline))
1212 return false;
1213
1214 /*
1215 * For EEVDF the virtual time slope is determined by w_i (iow.
1216 * nice) while the request time r_i is determined by
1217 * sysctl_sched_base_slice.
1218 */
1219 if (!se->custom_slice)
1220 se->slice = sysctl_sched_base_slice;
1221
1222 /*
1223 * EEVDF: vd_i = ve_i + r_i / w_i
1224 */
1225 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1226 avg_vruntime(cfs_rq);
1227
1228 /*
1229 * The task has consumed its request, reschedule.
1230 */
1231 return true;
1232 }
1233
1234 #include "pelt.h"
1235
1236 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1237 static unsigned long task_h_load(struct task_struct *p);
1238 static unsigned long capacity_of(int cpu);
1239
1240 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1241 void init_entity_runnable_average(struct sched_entity *se)
1242 {
1243 struct sched_avg *sa = &se->avg;
1244
1245 memset(sa, 0, sizeof(*sa));
1246
1247 /*
1248 * Tasks are initialized with full load to be seen as heavy tasks until
1249 * they get a chance to stabilize to their real load level.
1250 * Group entities are initialized with zero load to reflect the fact that
1251 * nothing has been attached to the task group yet.
1252 */
1253 if (entity_is_task(se))
1254 sa->load_avg = scale_load_down(se->load.weight);
1255
1256 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1257 }
1258
1259 /*
1260 * With new tasks being created, their initial util_avgs are extrapolated
1261 * based on the cfs_rq's current util_avg:
1262 *
1263 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1264 * * se_weight(se)
1265 *
1266 * However, in many cases, the above util_avg does not give a desired
1267 * value. Moreover, the sum of the util_avgs may be divergent, such
1268 * as when the series is a harmonic series.
1269 *
1270 * To solve this problem, we also cap the util_avg of successive tasks to
1271 * only 1/2 of the left utilization budget:
1272 *
1273 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1274 *
1275 * where n denotes the nth task and cpu_scale the CPU capacity.
1276 *
1277 * For example, for a CPU with 1024 of capacity, a simplest series from
1278 * the beginning would be like:
1279 *
1280 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1281 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1282 *
1283 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1284 * if util_avg > util_avg_cap.
1285 */
post_init_entity_util_avg(struct task_struct * p)1286 void post_init_entity_util_avg(struct task_struct *p)
1287 {
1288 struct sched_entity *se = &p->se;
1289 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1290 struct sched_avg *sa = &se->avg;
1291 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1292 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1293
1294 if (p->sched_class != &fair_sched_class) {
1295 /*
1296 * For !fair tasks do:
1297 *
1298 update_cfs_rq_load_avg(now, cfs_rq);
1299 attach_entity_load_avg(cfs_rq, se);
1300 switched_from_fair(rq, p);
1301 *
1302 * such that the next switched_to_fair() has the
1303 * expected state.
1304 */
1305 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1306 return;
1307 }
1308
1309 if (cap > 0) {
1310 if (cfs_rq->avg.util_avg != 0) {
1311 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se);
1312 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1313
1314 if (sa->util_avg > cap)
1315 sa->util_avg = cap;
1316 } else {
1317 sa->util_avg = cap;
1318 }
1319 }
1320
1321 sa->runnable_avg = sa->util_avg;
1322 }
1323
update_se(struct rq * rq,struct sched_entity * se)1324 static s64 update_se(struct rq *rq, struct sched_entity *se)
1325 {
1326 u64 now = rq_clock_task(rq);
1327 s64 delta_exec;
1328
1329 delta_exec = now - se->exec_start;
1330 if (unlikely(delta_exec <= 0))
1331 return delta_exec;
1332
1333 se->exec_start = now;
1334 if (entity_is_task(se)) {
1335 struct task_struct *donor = task_of(se);
1336 struct task_struct *running = rq->curr;
1337 /*
1338 * If se is a task, we account the time against the running
1339 * task, as w/ proxy-exec they may not be the same.
1340 */
1341 running->se.exec_start = now;
1342 running->se.sum_exec_runtime += delta_exec;
1343
1344 trace_sched_stat_runtime(running, delta_exec);
1345 account_group_exec_runtime(running, delta_exec);
1346
1347 /* cgroup time is always accounted against the donor */
1348 cgroup_account_cputime(donor, delta_exec);
1349 } else {
1350 /* If not task, account the time against donor se */
1351 se->sum_exec_runtime += delta_exec;
1352 }
1353
1354 if (schedstat_enabled()) {
1355 struct sched_statistics *stats;
1356
1357 stats = __schedstats_from_se(se);
1358 __schedstat_set(stats->exec_max,
1359 max(delta_exec, stats->exec_max));
1360 }
1361
1362 return delta_exec;
1363 }
1364
1365 static void set_next_buddy(struct sched_entity *se);
1366
1367 /*
1368 * Used by other classes to account runtime.
1369 */
update_curr_common(struct rq * rq)1370 s64 update_curr_common(struct rq *rq)
1371 {
1372 return update_se(rq, &rq->donor->se);
1373 }
1374
1375 /*
1376 * Update the current task's runtime statistics.
1377 */
update_curr(struct cfs_rq * cfs_rq)1378 static void update_curr(struct cfs_rq *cfs_rq)
1379 {
1380 /*
1381 * Note: cfs_rq->curr corresponds to the task picked to
1382 * run (ie: rq->donor.se) which due to proxy-exec may
1383 * not necessarily be the actual task running
1384 * (rq->curr.se). This is easy to confuse!
1385 */
1386 struct sched_entity *curr = cfs_rq->curr;
1387 struct rq *rq = rq_of(cfs_rq);
1388 s64 delta_exec;
1389 bool resched;
1390
1391 if (unlikely(!curr))
1392 return;
1393
1394 delta_exec = update_se(rq, curr);
1395 if (unlikely(delta_exec <= 0))
1396 return;
1397
1398 curr->vruntime += calc_delta_fair(delta_exec, curr);
1399 resched = update_deadline(cfs_rq, curr);
1400
1401 if (entity_is_task(curr)) {
1402 /*
1403 * If the fair_server is active, we need to account for the
1404 * fair_server time whether or not the task is running on
1405 * behalf of fair_server or not:
1406 * - If the task is running on behalf of fair_server, we need
1407 * to limit its time based on the assigned runtime.
1408 * - Fair task that runs outside of fair_server should account
1409 * against fair_server such that it can account for this time
1410 * and possibly avoid running this period.
1411 */
1412 dl_server_update(&rq->fair_server, delta_exec);
1413 }
1414
1415 account_cfs_rq_runtime(cfs_rq, delta_exec);
1416
1417 if (cfs_rq->nr_queued == 1)
1418 return;
1419
1420 if (resched || !protect_slice(curr)) {
1421 resched_curr_lazy(rq);
1422 clear_buddies(cfs_rq, curr);
1423 }
1424 }
1425
update_curr_fair(struct rq * rq)1426 static void update_curr_fair(struct rq *rq)
1427 {
1428 update_curr(cfs_rq_of(&rq->donor->se));
1429 }
1430
1431 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1432 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1433 {
1434 struct sched_statistics *stats;
1435 struct task_struct *p = NULL;
1436
1437 if (!schedstat_enabled())
1438 return;
1439
1440 stats = __schedstats_from_se(se);
1441
1442 if (entity_is_task(se))
1443 p = task_of(se);
1444
1445 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1446 }
1447
1448 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1449 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1450 {
1451 struct sched_statistics *stats;
1452 struct task_struct *p = NULL;
1453
1454 if (!schedstat_enabled())
1455 return;
1456
1457 stats = __schedstats_from_se(se);
1458
1459 /*
1460 * When the sched_schedstat changes from 0 to 1, some sched se
1461 * maybe already in the runqueue, the se->statistics.wait_start
1462 * will be 0.So it will let the delta wrong. We need to avoid this
1463 * scenario.
1464 */
1465 if (unlikely(!schedstat_val(stats->wait_start)))
1466 return;
1467
1468 if (entity_is_task(se))
1469 p = task_of(se);
1470
1471 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1472 }
1473
1474 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1475 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1476 {
1477 struct sched_statistics *stats;
1478 struct task_struct *tsk = NULL;
1479
1480 if (!schedstat_enabled())
1481 return;
1482
1483 stats = __schedstats_from_se(se);
1484
1485 if (entity_is_task(se))
1486 tsk = task_of(se);
1487
1488 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1489 }
1490
1491 /*
1492 * Task is being enqueued - update stats:
1493 */
1494 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1495 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1496 {
1497 if (!schedstat_enabled())
1498 return;
1499
1500 /*
1501 * Are we enqueueing a waiting task? (for current tasks
1502 * a dequeue/enqueue event is a NOP)
1503 */
1504 if (se != cfs_rq->curr)
1505 update_stats_wait_start_fair(cfs_rq, se);
1506
1507 if (flags & ENQUEUE_WAKEUP)
1508 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1509 }
1510
1511 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1512 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1513 {
1514
1515 if (!schedstat_enabled())
1516 return;
1517
1518 /*
1519 * Mark the end of the wait period if dequeueing a
1520 * waiting task:
1521 */
1522 if (se != cfs_rq->curr)
1523 update_stats_wait_end_fair(cfs_rq, se);
1524
1525 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1526 struct task_struct *tsk = task_of(se);
1527 unsigned int state;
1528
1529 /* XXX racy against TTWU */
1530 state = READ_ONCE(tsk->__state);
1531 if (state & TASK_INTERRUPTIBLE)
1532 __schedstat_set(tsk->stats.sleep_start,
1533 rq_clock(rq_of(cfs_rq)));
1534 if (state & TASK_UNINTERRUPTIBLE)
1535 __schedstat_set(tsk->stats.block_start,
1536 rq_clock(rq_of(cfs_rq)));
1537 }
1538 }
1539
1540 /*
1541 * We are picking a new current task - update its stats:
1542 */
1543 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1544 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1545 {
1546 /*
1547 * We are starting a new run period:
1548 */
1549 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1550 }
1551
1552 /**************************************************
1553 * Scheduling class queueing methods:
1554 */
1555
is_core_idle(int cpu)1556 static inline bool is_core_idle(int cpu)
1557 {
1558 #ifdef CONFIG_SCHED_SMT
1559 int sibling;
1560
1561 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1562 if (cpu == sibling)
1563 continue;
1564
1565 if (!idle_cpu(sibling))
1566 return false;
1567 }
1568 #endif
1569
1570 return true;
1571 }
1572
1573 #ifdef CONFIG_NUMA
1574 #define NUMA_IMBALANCE_MIN 2
1575
1576 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1577 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1578 {
1579 /*
1580 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1581 * threshold. Above this threshold, individual tasks may be contending
1582 * for both memory bandwidth and any shared HT resources. This is an
1583 * approximation as the number of running tasks may not be related to
1584 * the number of busy CPUs due to sched_setaffinity.
1585 */
1586 if (dst_running > imb_numa_nr)
1587 return imbalance;
1588
1589 /*
1590 * Allow a small imbalance based on a simple pair of communicating
1591 * tasks that remain local when the destination is lightly loaded.
1592 */
1593 if (imbalance <= NUMA_IMBALANCE_MIN)
1594 return 0;
1595
1596 return imbalance;
1597 }
1598 #endif /* CONFIG_NUMA */
1599
1600 #ifdef CONFIG_NUMA_BALANCING
1601 /*
1602 * Approximate time to scan a full NUMA task in ms. The task scan period is
1603 * calculated based on the tasks virtual memory size and
1604 * numa_balancing_scan_size.
1605 */
1606 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1607 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1608
1609 /* Portion of address space to scan in MB */
1610 unsigned int sysctl_numa_balancing_scan_size = 256;
1611
1612 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1613 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1614
1615 /* The page with hint page fault latency < threshold in ms is considered hot */
1616 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1617
1618 struct numa_group {
1619 refcount_t refcount;
1620
1621 spinlock_t lock; /* nr_tasks, tasks */
1622 int nr_tasks;
1623 pid_t gid;
1624 int active_nodes;
1625
1626 struct rcu_head rcu;
1627 unsigned long total_faults;
1628 unsigned long max_faults_cpu;
1629 /*
1630 * faults[] array is split into two regions: faults_mem and faults_cpu.
1631 *
1632 * Faults_cpu is used to decide whether memory should move
1633 * towards the CPU. As a consequence, these stats are weighted
1634 * more by CPU use than by memory faults.
1635 */
1636 unsigned long faults[];
1637 };
1638
1639 /*
1640 * For functions that can be called in multiple contexts that permit reading
1641 * ->numa_group (see struct task_struct for locking rules).
1642 */
deref_task_numa_group(struct task_struct * p)1643 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1644 {
1645 return rcu_dereference_check(p->numa_group, p == current ||
1646 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1647 }
1648
deref_curr_numa_group(struct task_struct * p)1649 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1650 {
1651 return rcu_dereference_protected(p->numa_group, p == current);
1652 }
1653
1654 static inline unsigned long group_faults_priv(struct numa_group *ng);
1655 static inline unsigned long group_faults_shared(struct numa_group *ng);
1656
task_nr_scan_windows(struct task_struct * p)1657 static unsigned int task_nr_scan_windows(struct task_struct *p)
1658 {
1659 unsigned long rss = 0;
1660 unsigned long nr_scan_pages;
1661
1662 /*
1663 * Calculations based on RSS as non-present and empty pages are skipped
1664 * by the PTE scanner and NUMA hinting faults should be trapped based
1665 * on resident pages
1666 */
1667 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
1668 rss = get_mm_rss(p->mm);
1669 if (!rss)
1670 rss = nr_scan_pages;
1671
1672 rss = round_up(rss, nr_scan_pages);
1673 return rss / nr_scan_pages;
1674 }
1675
1676 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1677 #define MAX_SCAN_WINDOW 2560
1678
task_scan_min(struct task_struct * p)1679 static unsigned int task_scan_min(struct task_struct *p)
1680 {
1681 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1682 unsigned int scan, floor;
1683 unsigned int windows = 1;
1684
1685 if (scan_size < MAX_SCAN_WINDOW)
1686 windows = MAX_SCAN_WINDOW / scan_size;
1687 floor = 1000 / windows;
1688
1689 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1690 return max_t(unsigned int, floor, scan);
1691 }
1692
task_scan_start(struct task_struct * p)1693 static unsigned int task_scan_start(struct task_struct *p)
1694 {
1695 unsigned long smin = task_scan_min(p);
1696 unsigned long period = smin;
1697 struct numa_group *ng;
1698
1699 /* Scale the maximum scan period with the amount of shared memory. */
1700 rcu_read_lock();
1701 ng = rcu_dereference_all(p->numa_group);
1702 if (ng) {
1703 unsigned long shared = group_faults_shared(ng);
1704 unsigned long private = group_faults_priv(ng);
1705
1706 period *= refcount_read(&ng->refcount);
1707 period *= shared + 1;
1708 period /= private + shared + 1;
1709 }
1710 rcu_read_unlock();
1711
1712 return max(smin, period);
1713 }
1714
task_scan_max(struct task_struct * p)1715 static unsigned int task_scan_max(struct task_struct *p)
1716 {
1717 unsigned long smin = task_scan_min(p);
1718 unsigned long smax;
1719 struct numa_group *ng;
1720
1721 /* Watch for min being lower than max due to floor calculations */
1722 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1723
1724 /* Scale the maximum scan period with the amount of shared memory. */
1725 ng = deref_curr_numa_group(p);
1726 if (ng) {
1727 unsigned long shared = group_faults_shared(ng);
1728 unsigned long private = group_faults_priv(ng);
1729 unsigned long period = smax;
1730
1731 period *= refcount_read(&ng->refcount);
1732 period *= shared + 1;
1733 period /= private + shared + 1;
1734
1735 smax = max(smax, period);
1736 }
1737
1738 return max(smin, smax);
1739 }
1740
account_numa_enqueue(struct rq * rq,struct task_struct * p)1741 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1742 {
1743 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1744 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1745 }
1746
account_numa_dequeue(struct rq * rq,struct task_struct * p)1747 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1748 {
1749 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1750 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1751 }
1752
1753 /* Shared or private faults. */
1754 #define NR_NUMA_HINT_FAULT_TYPES 2
1755
1756 /* Memory and CPU locality */
1757 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1758
1759 /* Averaged statistics, and temporary buffers. */
1760 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1761
task_numa_group_id(struct task_struct * p)1762 pid_t task_numa_group_id(struct task_struct *p)
1763 {
1764 struct numa_group *ng;
1765 pid_t gid = 0;
1766
1767 rcu_read_lock();
1768 ng = rcu_dereference_all(p->numa_group);
1769 if (ng)
1770 gid = ng->gid;
1771 rcu_read_unlock();
1772
1773 return gid;
1774 }
1775
1776 /*
1777 * The averaged statistics, shared & private, memory & CPU,
1778 * occupy the first half of the array. The second half of the
1779 * array is for current counters, which are averaged into the
1780 * first set by task_numa_placement.
1781 */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1782 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1783 {
1784 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1785 }
1786
task_faults(struct task_struct * p,int nid)1787 static inline unsigned long task_faults(struct task_struct *p, int nid)
1788 {
1789 if (!p->numa_faults)
1790 return 0;
1791
1792 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1793 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1794 }
1795
group_faults(struct task_struct * p,int nid)1796 static inline unsigned long group_faults(struct task_struct *p, int nid)
1797 {
1798 struct numa_group *ng = deref_task_numa_group(p);
1799
1800 if (!ng)
1801 return 0;
1802
1803 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1804 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1805 }
1806
group_faults_cpu(struct numa_group * group,int nid)1807 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1808 {
1809 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1810 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1811 }
1812
group_faults_priv(struct numa_group * ng)1813 static inline unsigned long group_faults_priv(struct numa_group *ng)
1814 {
1815 unsigned long faults = 0;
1816 int node;
1817
1818 for_each_online_node(node) {
1819 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1820 }
1821
1822 return faults;
1823 }
1824
group_faults_shared(struct numa_group * ng)1825 static inline unsigned long group_faults_shared(struct numa_group *ng)
1826 {
1827 unsigned long faults = 0;
1828 int node;
1829
1830 for_each_online_node(node) {
1831 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1832 }
1833
1834 return faults;
1835 }
1836
1837 /*
1838 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1839 * considered part of a numa group's pseudo-interleaving set. Migrations
1840 * between these nodes are slowed down, to allow things to settle down.
1841 */
1842 #define ACTIVE_NODE_FRACTION 3
1843
numa_is_active_node(int nid,struct numa_group * ng)1844 static bool numa_is_active_node(int nid, struct numa_group *ng)
1845 {
1846 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1847 }
1848
1849 /* 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)1850 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1851 int lim_dist, bool task)
1852 {
1853 unsigned long score = 0;
1854 int node, max_dist;
1855
1856 /*
1857 * All nodes are directly connected, and the same distance
1858 * from each other. No need for fancy placement algorithms.
1859 */
1860 if (sched_numa_topology_type == NUMA_DIRECT)
1861 return 0;
1862
1863 /* sched_max_numa_distance may be changed in parallel. */
1864 max_dist = READ_ONCE(sched_max_numa_distance);
1865 /*
1866 * This code is called for each node, introducing N^2 complexity,
1867 * which should be OK given the number of nodes rarely exceeds 8.
1868 */
1869 for_each_online_node(node) {
1870 unsigned long faults;
1871 int dist = node_distance(nid, node);
1872
1873 /*
1874 * The furthest away nodes in the system are not interesting
1875 * for placement; nid was already counted.
1876 */
1877 if (dist >= max_dist || node == nid)
1878 continue;
1879
1880 /*
1881 * On systems with a backplane NUMA topology, compare groups
1882 * of nodes, and move tasks towards the group with the most
1883 * memory accesses. When comparing two nodes at distance
1884 * "hoplimit", only nodes closer by than "hoplimit" are part
1885 * of each group. Skip other nodes.
1886 */
1887 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1888 continue;
1889
1890 /* Add up the faults from nearby nodes. */
1891 if (task)
1892 faults = task_faults(p, node);
1893 else
1894 faults = group_faults(p, node);
1895
1896 /*
1897 * On systems with a glueless mesh NUMA topology, there are
1898 * no fixed "groups of nodes". Instead, nodes that are not
1899 * directly connected bounce traffic through intermediate
1900 * nodes; a numa_group can occupy any set of nodes.
1901 * The further away a node is, the less the faults count.
1902 * This seems to result in good task placement.
1903 */
1904 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1905 faults *= (max_dist - dist);
1906 faults /= (max_dist - LOCAL_DISTANCE);
1907 }
1908
1909 score += faults;
1910 }
1911
1912 return score;
1913 }
1914
1915 /*
1916 * These return the fraction of accesses done by a particular task, or
1917 * task group, on a particular numa node. The group weight is given a
1918 * larger multiplier, in order to group tasks together that are almost
1919 * evenly spread out between numa nodes.
1920 */
task_weight(struct task_struct * p,int nid,int dist)1921 static inline unsigned long task_weight(struct task_struct *p, int nid,
1922 int dist)
1923 {
1924 unsigned long faults, total_faults;
1925
1926 if (!p->numa_faults)
1927 return 0;
1928
1929 total_faults = p->total_numa_faults;
1930
1931 if (!total_faults)
1932 return 0;
1933
1934 faults = task_faults(p, nid);
1935 faults += score_nearby_nodes(p, nid, dist, true);
1936
1937 return 1000 * faults / total_faults;
1938 }
1939
group_weight(struct task_struct * p,int nid,int dist)1940 static inline unsigned long group_weight(struct task_struct *p, int nid,
1941 int dist)
1942 {
1943 struct numa_group *ng = deref_task_numa_group(p);
1944 unsigned long faults, total_faults;
1945
1946 if (!ng)
1947 return 0;
1948
1949 total_faults = ng->total_faults;
1950
1951 if (!total_faults)
1952 return 0;
1953
1954 faults = group_faults(p, nid);
1955 faults += score_nearby_nodes(p, nid, dist, false);
1956
1957 return 1000 * faults / total_faults;
1958 }
1959
1960 /*
1961 * If memory tiering mode is enabled, cpupid of slow memory page is
1962 * used to record scan time instead of CPU and PID. When tiering mode
1963 * is disabled at run time, the scan time (in cpupid) will be
1964 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1965 * access out of array bound.
1966 */
cpupid_valid(int cpupid)1967 static inline bool cpupid_valid(int cpupid)
1968 {
1969 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1970 }
1971
1972 /*
1973 * For memory tiering mode, if there are enough free pages (more than
1974 * enough watermark defined here) in fast memory node, to take full
1975 * advantage of fast memory capacity, all recently accessed slow
1976 * memory pages will be migrated to fast memory node without
1977 * considering hot threshold.
1978 */
pgdat_free_space_enough(struct pglist_data * pgdat)1979 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1980 {
1981 int z;
1982 unsigned long enough_wmark;
1983
1984 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1985 pgdat->node_present_pages >> 4);
1986 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1987 struct zone *zone = pgdat->node_zones + z;
1988
1989 if (!populated_zone(zone))
1990 continue;
1991
1992 if (zone_watermark_ok(zone, 0,
1993 promo_wmark_pages(zone) + enough_wmark,
1994 ZONE_MOVABLE, 0))
1995 return true;
1996 }
1997 return false;
1998 }
1999
2000 /*
2001 * For memory tiering mode, when page tables are scanned, the scan
2002 * time will be recorded in struct page in addition to make page
2003 * PROT_NONE for slow memory page. So when the page is accessed, in
2004 * hint page fault handler, the hint page fault latency is calculated
2005 * via,
2006 *
2007 * hint page fault latency = hint page fault time - scan time
2008 *
2009 * The smaller the hint page fault latency, the higher the possibility
2010 * for the page to be hot.
2011 */
numa_hint_fault_latency(struct folio * folio)2012 static int numa_hint_fault_latency(struct folio *folio)
2013 {
2014 int last_time, time;
2015
2016 time = jiffies_to_msecs(jiffies);
2017 last_time = folio_xchg_access_time(folio, time);
2018
2019 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
2020 }
2021
2022 /*
2023 * For memory tiering mode, too high promotion/demotion throughput may
2024 * hurt application latency. So we provide a mechanism to rate limit
2025 * the number of pages that are tried to be promoted.
2026 */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)2027 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
2028 unsigned long rate_limit, int nr)
2029 {
2030 unsigned long nr_cand;
2031 unsigned int now, start;
2032
2033 now = jiffies_to_msecs(jiffies);
2034 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
2035 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2036 start = pgdat->nbp_rl_start;
2037 if (now - start > MSEC_PER_SEC &&
2038 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
2039 pgdat->nbp_rl_nr_cand = nr_cand;
2040 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
2041 return true;
2042 return false;
2043 }
2044
2045 #define NUMA_MIGRATION_ADJUST_STEPS 16
2046
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)2047 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
2048 unsigned long rate_limit,
2049 unsigned int ref_th)
2050 {
2051 unsigned int now, start, th_period, unit_th, th;
2052 unsigned long nr_cand, ref_cand, diff_cand;
2053
2054 now = jiffies_to_msecs(jiffies);
2055 th_period = sysctl_numa_balancing_scan_period_max;
2056 start = pgdat->nbp_th_start;
2057 if (now - start > th_period &&
2058 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
2059 ref_cand = rate_limit *
2060 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
2061 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
2062 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
2063 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
2064 th = pgdat->nbp_threshold ? : ref_th;
2065 if (diff_cand > ref_cand * 11 / 10)
2066 th = max(th - unit_th, unit_th);
2067 else if (diff_cand < ref_cand * 9 / 10)
2068 th = min(th + unit_th, ref_th * 2);
2069 pgdat->nbp_th_nr_cand = nr_cand;
2070 pgdat->nbp_threshold = th;
2071 }
2072 }
2073
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)2074 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
2075 int src_nid, int dst_cpu)
2076 {
2077 struct numa_group *ng = deref_curr_numa_group(p);
2078 int dst_nid = cpu_to_node(dst_cpu);
2079 int last_cpupid, this_cpupid;
2080
2081 /*
2082 * Cannot migrate to memoryless nodes.
2083 */
2084 if (!node_state(dst_nid, N_MEMORY))
2085 return false;
2086
2087 /*
2088 * The pages in slow memory node should be migrated according
2089 * to hot/cold instead of private/shared.
2090 */
2091 if (folio_use_access_time(folio)) {
2092 struct pglist_data *pgdat;
2093 unsigned long rate_limit;
2094 unsigned int latency, th, def_th;
2095 long nr = folio_nr_pages(folio);
2096
2097 pgdat = NODE_DATA(dst_nid);
2098 if (pgdat_free_space_enough(pgdat)) {
2099 /* workload changed, reset hot threshold */
2100 pgdat->nbp_threshold = 0;
2101 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
2102 return true;
2103 }
2104
2105 def_th = sysctl_numa_balancing_hot_threshold;
2106 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
2107 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
2108
2109 th = pgdat->nbp_threshold ? : def_th;
2110 latency = numa_hint_fault_latency(folio);
2111 if (latency >= th)
2112 return false;
2113
2114 return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
2115 }
2116
2117 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
2118 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
2119
2120 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
2121 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
2122 return false;
2123
2124 /*
2125 * Allow first faults or private faults to migrate immediately early in
2126 * the lifetime of a task. The magic number 4 is based on waiting for
2127 * two full passes of the "multi-stage node selection" test that is
2128 * executed below.
2129 */
2130 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
2131 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
2132 return true;
2133
2134 /*
2135 * Multi-stage node selection is used in conjunction with a periodic
2136 * migration fault to build a temporal task<->page relation. By using
2137 * a two-stage filter we remove short/unlikely relations.
2138 *
2139 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
2140 * a task's usage of a particular page (n_p) per total usage of this
2141 * page (n_t) (in a given time-span) to a probability.
2142 *
2143 * Our periodic faults will sample this probability and getting the
2144 * same result twice in a row, given these samples are fully
2145 * independent, is then given by P(n)^2, provided our sample period
2146 * is sufficiently short compared to the usage pattern.
2147 *
2148 * This quadric squishes small probabilities, making it less likely we
2149 * act on an unlikely task<->page relation.
2150 */
2151 if (!cpupid_pid_unset(last_cpupid) &&
2152 cpupid_to_nid(last_cpupid) != dst_nid)
2153 return false;
2154
2155 /* Always allow migrate on private faults */
2156 if (cpupid_match_pid(p, last_cpupid))
2157 return true;
2158
2159 /* A shared fault, but p->numa_group has not been set up yet. */
2160 if (!ng)
2161 return true;
2162
2163 /*
2164 * Destination node is much more heavily used than the source
2165 * node? Allow migration.
2166 */
2167 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2168 ACTIVE_NODE_FRACTION)
2169 return true;
2170
2171 /*
2172 * Distribute memory according to CPU & memory use on each node,
2173 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2174 *
2175 * faults_cpu(dst) 3 faults_cpu(src)
2176 * --------------- * - > ---------------
2177 * faults_mem(dst) 4 faults_mem(src)
2178 */
2179 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2180 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2181 }
2182
2183 /*
2184 * 'numa_type' describes the node at the moment of load balancing.
2185 */
2186 enum numa_type {
2187 /* The node has spare capacity that can be used to run more tasks. */
2188 node_has_spare = 0,
2189 /*
2190 * The node is fully used and the tasks don't compete for more CPU
2191 * cycles. Nevertheless, some tasks might wait before running.
2192 */
2193 node_fully_busy,
2194 /*
2195 * The node is overloaded and can't provide expected CPU cycles to all
2196 * tasks.
2197 */
2198 node_overloaded
2199 };
2200
2201 /* Cached statistics for all CPUs within a node */
2202 struct numa_stats {
2203 unsigned long load;
2204 unsigned long runnable;
2205 unsigned long util;
2206 /* Total compute capacity of CPUs on a node */
2207 unsigned long compute_capacity;
2208 unsigned int nr_running;
2209 unsigned int weight;
2210 enum numa_type node_type;
2211 int idle_cpu;
2212 };
2213
2214 struct task_numa_env {
2215 struct task_struct *p;
2216
2217 int src_cpu, src_nid;
2218 int dst_cpu, dst_nid;
2219 int imb_numa_nr;
2220
2221 struct numa_stats src_stats, dst_stats;
2222
2223 int imbalance_pct;
2224 int dist;
2225
2226 struct task_struct *best_task;
2227 long best_imp;
2228 int best_cpu;
2229 };
2230
2231 static unsigned long cpu_load(struct rq *rq);
2232 static unsigned long cpu_runnable(struct rq *rq);
2233
2234 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2235 numa_type numa_classify(unsigned int imbalance_pct,
2236 struct numa_stats *ns)
2237 {
2238 if ((ns->nr_running > ns->weight) &&
2239 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2240 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2241 return node_overloaded;
2242
2243 if ((ns->nr_running < ns->weight) ||
2244 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2245 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2246 return node_has_spare;
2247
2248 return node_fully_busy;
2249 }
2250
2251 #ifdef CONFIG_SCHED_SMT
2252 /* Forward declarations of select_idle_sibling helpers */
2253 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2254 static inline int numa_idle_core(int idle_core, int cpu)
2255 {
2256 if (!static_branch_likely(&sched_smt_present) ||
2257 idle_core >= 0 || !test_idle_cores(cpu))
2258 return idle_core;
2259
2260 /*
2261 * Prefer cores instead of packing HT siblings
2262 * and triggering future load balancing.
2263 */
2264 if (is_core_idle(cpu))
2265 idle_core = cpu;
2266
2267 return idle_core;
2268 }
2269 #else /* !CONFIG_SCHED_SMT: */
numa_idle_core(int idle_core,int cpu)2270 static inline int numa_idle_core(int idle_core, int cpu)
2271 {
2272 return idle_core;
2273 }
2274 #endif /* !CONFIG_SCHED_SMT */
2275
2276 /*
2277 * Gather all necessary information to make NUMA balancing placement
2278 * decisions that are compatible with standard load balancer. This
2279 * borrows code and logic from update_sg_lb_stats but sharing a
2280 * common implementation is impractical.
2281 */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2282 static void update_numa_stats(struct task_numa_env *env,
2283 struct numa_stats *ns, int nid,
2284 bool find_idle)
2285 {
2286 int cpu, idle_core = -1;
2287
2288 memset(ns, 0, sizeof(*ns));
2289 ns->idle_cpu = -1;
2290
2291 rcu_read_lock();
2292 for_each_cpu(cpu, cpumask_of_node(nid)) {
2293 struct rq *rq = cpu_rq(cpu);
2294
2295 ns->load += cpu_load(rq);
2296 ns->runnable += cpu_runnable(rq);
2297 ns->util += cpu_util_cfs(cpu);
2298 ns->nr_running += rq->cfs.h_nr_runnable;
2299 ns->compute_capacity += capacity_of(cpu);
2300
2301 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2302 if (READ_ONCE(rq->numa_migrate_on) ||
2303 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2304 continue;
2305
2306 if (ns->idle_cpu == -1)
2307 ns->idle_cpu = cpu;
2308
2309 idle_core = numa_idle_core(idle_core, cpu);
2310 }
2311 }
2312 rcu_read_unlock();
2313
2314 ns->weight = cpumask_weight(cpumask_of_node(nid));
2315
2316 ns->node_type = numa_classify(env->imbalance_pct, ns);
2317
2318 if (idle_core >= 0)
2319 ns->idle_cpu = idle_core;
2320 }
2321
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2322 static void task_numa_assign(struct task_numa_env *env,
2323 struct task_struct *p, long imp)
2324 {
2325 struct rq *rq = cpu_rq(env->dst_cpu);
2326
2327 /* Check if run-queue part of active NUMA balance. */
2328 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2329 int cpu;
2330 int start = env->dst_cpu;
2331
2332 /* Find alternative idle CPU. */
2333 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2334 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2335 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2336 continue;
2337 }
2338
2339 env->dst_cpu = cpu;
2340 rq = cpu_rq(env->dst_cpu);
2341 if (!xchg(&rq->numa_migrate_on, 1))
2342 goto assign;
2343 }
2344
2345 /* Failed to find an alternative idle CPU */
2346 return;
2347 }
2348
2349 assign:
2350 /*
2351 * Clear previous best_cpu/rq numa-migrate flag, since task now
2352 * found a better CPU to move/swap.
2353 */
2354 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2355 rq = cpu_rq(env->best_cpu);
2356 WRITE_ONCE(rq->numa_migrate_on, 0);
2357 }
2358
2359 if (env->best_task)
2360 put_task_struct(env->best_task);
2361 if (p)
2362 get_task_struct(p);
2363
2364 env->best_task = p;
2365 env->best_imp = imp;
2366 env->best_cpu = env->dst_cpu;
2367 }
2368
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2369 static bool load_too_imbalanced(long src_load, long dst_load,
2370 struct task_numa_env *env)
2371 {
2372 long imb, old_imb;
2373 long orig_src_load, orig_dst_load;
2374 long src_capacity, dst_capacity;
2375
2376 /*
2377 * The load is corrected for the CPU capacity available on each node.
2378 *
2379 * src_load dst_load
2380 * ------------ vs ---------
2381 * src_capacity dst_capacity
2382 */
2383 src_capacity = env->src_stats.compute_capacity;
2384 dst_capacity = env->dst_stats.compute_capacity;
2385
2386 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2387
2388 orig_src_load = env->src_stats.load;
2389 orig_dst_load = env->dst_stats.load;
2390
2391 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2392
2393 /* Would this change make things worse? */
2394 return (imb > old_imb);
2395 }
2396
2397 /*
2398 * Maximum NUMA importance can be 1998 (2*999);
2399 * SMALLIMP @ 30 would be close to 1998/64.
2400 * Used to deter task migration.
2401 */
2402 #define SMALLIMP 30
2403
2404 /*
2405 * This checks if the overall compute and NUMA accesses of the system would
2406 * be improved if the source tasks was migrated to the target dst_cpu taking
2407 * into account that it might be best if task running on the dst_cpu should
2408 * be exchanged with the source task
2409 */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2410 static bool task_numa_compare(struct task_numa_env *env,
2411 long taskimp, long groupimp, bool maymove)
2412 {
2413 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2414 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2415 long imp = p_ng ? groupimp : taskimp;
2416 struct task_struct *cur;
2417 long src_load, dst_load;
2418 int dist = env->dist;
2419 long moveimp = imp;
2420 long load;
2421 bool stopsearch = false;
2422
2423 if (READ_ONCE(dst_rq->numa_migrate_on))
2424 return false;
2425
2426 rcu_read_lock();
2427 cur = rcu_dereference_all(dst_rq->curr);
2428 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
2429 !cur->mm))
2430 cur = NULL;
2431
2432 /*
2433 * Because we have preemption enabled we can get migrated around and
2434 * end try selecting ourselves (current == env->p) as a swap candidate.
2435 */
2436 if (cur == env->p) {
2437 stopsearch = true;
2438 goto unlock;
2439 }
2440
2441 if (!cur) {
2442 if (maymove && moveimp >= env->best_imp)
2443 goto assign;
2444 else
2445 goto unlock;
2446 }
2447
2448 /* Skip this swap candidate if cannot move to the source cpu. */
2449 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2450 goto unlock;
2451
2452 /*
2453 * Skip this swap candidate if it is not moving to its preferred
2454 * node and the best task is.
2455 */
2456 if (env->best_task &&
2457 env->best_task->numa_preferred_nid == env->src_nid &&
2458 cur->numa_preferred_nid != env->src_nid) {
2459 goto unlock;
2460 }
2461
2462 /*
2463 * "imp" is the fault differential for the source task between the
2464 * source and destination node. Calculate the total differential for
2465 * the source task and potential destination task. The more negative
2466 * the value is, the more remote accesses that would be expected to
2467 * be incurred if the tasks were swapped.
2468 *
2469 * If dst and source tasks are in the same NUMA group, or not
2470 * in any group then look only at task weights.
2471 */
2472 cur_ng = rcu_dereference_all(cur->numa_group);
2473 if (cur_ng == p_ng) {
2474 /*
2475 * Do not swap within a group or between tasks that have
2476 * no group if there is spare capacity. Swapping does
2477 * not address the load imbalance and helps one task at
2478 * the cost of punishing another.
2479 */
2480 if (env->dst_stats.node_type == node_has_spare)
2481 goto unlock;
2482
2483 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2484 task_weight(cur, env->dst_nid, dist);
2485 /*
2486 * Add some hysteresis to prevent swapping the
2487 * tasks within a group over tiny differences.
2488 */
2489 if (cur_ng)
2490 imp -= imp / 16;
2491 } else {
2492 /*
2493 * Compare the group weights. If a task is all by itself
2494 * (not part of a group), use the task weight instead.
2495 */
2496 if (cur_ng && p_ng)
2497 imp += group_weight(cur, env->src_nid, dist) -
2498 group_weight(cur, env->dst_nid, dist);
2499 else
2500 imp += task_weight(cur, env->src_nid, dist) -
2501 task_weight(cur, env->dst_nid, dist);
2502 }
2503
2504 /* Discourage picking a task already on its preferred node */
2505 if (cur->numa_preferred_nid == env->dst_nid)
2506 imp -= imp / 16;
2507
2508 /*
2509 * Encourage picking a task that moves to its preferred node.
2510 * This potentially makes imp larger than it's maximum of
2511 * 1998 (see SMALLIMP and task_weight for why) but in this
2512 * case, it does not matter.
2513 */
2514 if (cur->numa_preferred_nid == env->src_nid)
2515 imp += imp / 8;
2516
2517 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2518 imp = moveimp;
2519 cur = NULL;
2520 goto assign;
2521 }
2522
2523 /*
2524 * Prefer swapping with a task moving to its preferred node over a
2525 * task that is not.
2526 */
2527 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2528 env->best_task->numa_preferred_nid != env->src_nid) {
2529 goto assign;
2530 }
2531
2532 /*
2533 * If the NUMA importance is less than SMALLIMP,
2534 * task migration might only result in ping pong
2535 * of tasks and also hurt performance due to cache
2536 * misses.
2537 */
2538 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2539 goto unlock;
2540
2541 /*
2542 * In the overloaded case, try and keep the load balanced.
2543 */
2544 load = task_h_load(env->p) - task_h_load(cur);
2545 if (!load)
2546 goto assign;
2547
2548 dst_load = env->dst_stats.load + load;
2549 src_load = env->src_stats.load - load;
2550
2551 if (load_too_imbalanced(src_load, dst_load, env))
2552 goto unlock;
2553
2554 assign:
2555 /* Evaluate an idle CPU for a task numa move. */
2556 if (!cur) {
2557 int cpu = env->dst_stats.idle_cpu;
2558
2559 /* Nothing cached so current CPU went idle since the search. */
2560 if (cpu < 0)
2561 cpu = env->dst_cpu;
2562
2563 /*
2564 * If the CPU is no longer truly idle and the previous best CPU
2565 * is, keep using it.
2566 */
2567 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2568 idle_cpu(env->best_cpu)) {
2569 cpu = env->best_cpu;
2570 }
2571
2572 env->dst_cpu = cpu;
2573 }
2574
2575 task_numa_assign(env, cur, imp);
2576
2577 /*
2578 * If a move to idle is allowed because there is capacity or load
2579 * balance improves then stop the search. While a better swap
2580 * candidate may exist, a search is not free.
2581 */
2582 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2583 stopsearch = true;
2584
2585 /*
2586 * If a swap candidate must be identified and the current best task
2587 * moves its preferred node then stop the search.
2588 */
2589 if (!maymove && env->best_task &&
2590 env->best_task->numa_preferred_nid == env->src_nid) {
2591 stopsearch = true;
2592 }
2593 unlock:
2594 rcu_read_unlock();
2595
2596 return stopsearch;
2597 }
2598
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2599 static void task_numa_find_cpu(struct task_numa_env *env,
2600 long taskimp, long groupimp)
2601 {
2602 bool maymove = false;
2603 int cpu;
2604
2605 /*
2606 * If dst node has spare capacity, then check if there is an
2607 * imbalance that would be overruled by the load balancer.
2608 */
2609 if (env->dst_stats.node_type == node_has_spare) {
2610 unsigned int imbalance;
2611 int src_running, dst_running;
2612
2613 /*
2614 * Would movement cause an imbalance? Note that if src has
2615 * more running tasks that the imbalance is ignored as the
2616 * move improves the imbalance from the perspective of the
2617 * CPU load balancer.
2618 * */
2619 src_running = env->src_stats.nr_running - 1;
2620 dst_running = env->dst_stats.nr_running + 1;
2621 imbalance = max(0, dst_running - src_running);
2622 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2623 env->imb_numa_nr);
2624
2625 /* Use idle CPU if there is no imbalance */
2626 if (!imbalance) {
2627 maymove = true;
2628 if (env->dst_stats.idle_cpu >= 0) {
2629 env->dst_cpu = env->dst_stats.idle_cpu;
2630 task_numa_assign(env, NULL, 0);
2631 return;
2632 }
2633 }
2634 } else {
2635 long src_load, dst_load, load;
2636 /*
2637 * If the improvement from just moving env->p direction is better
2638 * than swapping tasks around, check if a move is possible.
2639 */
2640 load = task_h_load(env->p);
2641 dst_load = env->dst_stats.load + load;
2642 src_load = env->src_stats.load - load;
2643 maymove = !load_too_imbalanced(src_load, dst_load, env);
2644 }
2645
2646 /* Skip CPUs if the source task cannot migrate */
2647 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) {
2648 env->dst_cpu = cpu;
2649 if (task_numa_compare(env, taskimp, groupimp, maymove))
2650 break;
2651 }
2652 }
2653
task_numa_migrate(struct task_struct * p)2654 static int task_numa_migrate(struct task_struct *p)
2655 {
2656 struct task_numa_env env = {
2657 .p = p,
2658
2659 .src_cpu = task_cpu(p),
2660 .src_nid = task_node(p),
2661
2662 .imbalance_pct = 112,
2663
2664 .best_task = NULL,
2665 .best_imp = 0,
2666 .best_cpu = -1,
2667 };
2668 unsigned long taskweight, groupweight;
2669 struct sched_domain *sd;
2670 long taskimp, groupimp;
2671 struct numa_group *ng;
2672 struct rq *best_rq;
2673 int nid, ret, dist;
2674
2675 /*
2676 * Pick the lowest SD_NUMA domain, as that would have the smallest
2677 * imbalance and would be the first to start moving tasks about.
2678 *
2679 * And we want to avoid any moving of tasks about, as that would create
2680 * random movement of tasks -- counter the numa conditions we're trying
2681 * to satisfy here.
2682 */
2683 rcu_read_lock();
2684 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu));
2685 if (sd) {
2686 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2687 env.imb_numa_nr = sd->imb_numa_nr;
2688 }
2689 rcu_read_unlock();
2690
2691 /*
2692 * Cpusets can break the scheduler domain tree into smaller
2693 * balance domains, some of which do not cross NUMA boundaries.
2694 * Tasks that are "trapped" in such domains cannot be migrated
2695 * elsewhere, so there is no point in (re)trying.
2696 */
2697 if (unlikely(!sd)) {
2698 sched_setnuma(p, task_node(p));
2699 return -EINVAL;
2700 }
2701
2702 env.dst_nid = p->numa_preferred_nid;
2703 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2704 taskweight = task_weight(p, env.src_nid, dist);
2705 groupweight = group_weight(p, env.src_nid, dist);
2706 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2707 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2708 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2709 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2710
2711 /* Try to find a spot on the preferred nid. */
2712 task_numa_find_cpu(&env, taskimp, groupimp);
2713
2714 /*
2715 * Look at other nodes in these cases:
2716 * - there is no space available on the preferred_nid
2717 * - the task is part of a numa_group that is interleaved across
2718 * multiple NUMA nodes; in order to better consolidate the group,
2719 * we need to check other locations.
2720 */
2721 ng = deref_curr_numa_group(p);
2722 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2723 for_each_node_state(nid, N_CPU) {
2724 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2725 continue;
2726
2727 dist = node_distance(env.src_nid, env.dst_nid);
2728 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2729 dist != env.dist) {
2730 taskweight = task_weight(p, env.src_nid, dist);
2731 groupweight = group_weight(p, env.src_nid, dist);
2732 }
2733
2734 /* Only consider nodes where both task and groups benefit */
2735 taskimp = task_weight(p, nid, dist) - taskweight;
2736 groupimp = group_weight(p, nid, dist) - groupweight;
2737 if (taskimp < 0 && groupimp < 0)
2738 continue;
2739
2740 env.dist = dist;
2741 env.dst_nid = nid;
2742 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2743 task_numa_find_cpu(&env, taskimp, groupimp);
2744 }
2745 }
2746
2747 /*
2748 * If the task is part of a workload that spans multiple NUMA nodes,
2749 * and is migrating into one of the workload's active nodes, remember
2750 * this node as the task's preferred numa node, so the workload can
2751 * settle down.
2752 * A task that migrated to a second choice node will be better off
2753 * trying for a better one later. Do not set the preferred node here.
2754 */
2755 if (ng) {
2756 if (env.best_cpu == -1)
2757 nid = env.src_nid;
2758 else
2759 nid = cpu_to_node(env.best_cpu);
2760
2761 if (nid != p->numa_preferred_nid)
2762 sched_setnuma(p, nid);
2763 }
2764
2765 /* No better CPU than the current one was found. */
2766 if (env.best_cpu == -1) {
2767 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2768 return -EAGAIN;
2769 }
2770
2771 best_rq = cpu_rq(env.best_cpu);
2772 if (env.best_task == NULL) {
2773 ret = migrate_task_to(p, env.best_cpu);
2774 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2775 if (ret != 0)
2776 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2777 return ret;
2778 }
2779
2780 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2781 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2782
2783 if (ret != 0)
2784 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2785 put_task_struct(env.best_task);
2786 return ret;
2787 }
2788
2789 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2790 static void numa_migrate_preferred(struct task_struct *p)
2791 {
2792 unsigned long interval = HZ;
2793
2794 /* This task has no NUMA fault statistics yet */
2795 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2796 return;
2797
2798 /* Periodically retry migrating the task to the preferred node */
2799 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2800 p->numa_migrate_retry = jiffies + interval;
2801
2802 /* Success if task is already running on preferred CPU */
2803 if (task_node(p) == p->numa_preferred_nid)
2804 return;
2805
2806 /* Otherwise, try migrate to a CPU on the preferred node */
2807 task_numa_migrate(p);
2808 }
2809
2810 /*
2811 * Find out how many nodes the workload is actively running on. Do this by
2812 * tracking the nodes from which NUMA hinting faults are triggered. This can
2813 * be different from the set of nodes where the workload's memory is currently
2814 * located.
2815 */
numa_group_count_active_nodes(struct numa_group * numa_group)2816 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2817 {
2818 unsigned long faults, max_faults = 0;
2819 int nid, active_nodes = 0;
2820
2821 for_each_node_state(nid, N_CPU) {
2822 faults = group_faults_cpu(numa_group, nid);
2823 if (faults > max_faults)
2824 max_faults = faults;
2825 }
2826
2827 for_each_node_state(nid, N_CPU) {
2828 faults = group_faults_cpu(numa_group, nid);
2829 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2830 active_nodes++;
2831 }
2832
2833 numa_group->max_faults_cpu = max_faults;
2834 numa_group->active_nodes = active_nodes;
2835 }
2836
2837 /*
2838 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2839 * increments. The more local the fault statistics are, the higher the scan
2840 * period will be for the next scan window. If local/(local+remote) ratio is
2841 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2842 * the scan period will decrease. Aim for 70% local accesses.
2843 */
2844 #define NUMA_PERIOD_SLOTS 10
2845 #define NUMA_PERIOD_THRESHOLD 7
2846
2847 /*
2848 * Increase the scan period (slow down scanning) if the majority of
2849 * our memory is already on our local node, or if the majority of
2850 * the page accesses are shared with other processes.
2851 * Otherwise, decrease the scan period.
2852 */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2853 static void update_task_scan_period(struct task_struct *p,
2854 unsigned long shared, unsigned long private)
2855 {
2856 unsigned int period_slot;
2857 int lr_ratio, ps_ratio;
2858 int diff;
2859
2860 unsigned long remote = p->numa_faults_locality[0];
2861 unsigned long local = p->numa_faults_locality[1];
2862
2863 /*
2864 * If there were no record hinting faults then either the task is
2865 * completely idle or all activity is in areas that are not of interest
2866 * to automatic numa balancing. Related to that, if there were failed
2867 * migration then it implies we are migrating too quickly or the local
2868 * node is overloaded. In either case, scan slower
2869 */
2870 if (local + shared == 0 || p->numa_faults_locality[2]) {
2871 p->numa_scan_period = min(p->numa_scan_period_max,
2872 p->numa_scan_period << 1);
2873
2874 p->mm->numa_next_scan = jiffies +
2875 msecs_to_jiffies(p->numa_scan_period);
2876
2877 return;
2878 }
2879
2880 /*
2881 * Prepare to scale scan period relative to the current period.
2882 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2883 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2884 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2885 */
2886 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2887 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2888 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2889
2890 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2891 /*
2892 * Most memory accesses are local. There is no need to
2893 * do fast NUMA scanning, since memory is already local.
2894 */
2895 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2896 if (!slot)
2897 slot = 1;
2898 diff = slot * period_slot;
2899 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2900 /*
2901 * Most memory accesses are shared with other tasks.
2902 * There is no point in continuing fast NUMA scanning,
2903 * since other tasks may just move the memory elsewhere.
2904 */
2905 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2906 if (!slot)
2907 slot = 1;
2908 diff = slot * period_slot;
2909 } else {
2910 /*
2911 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2912 * yet they are not on the local NUMA node. Speed up
2913 * NUMA scanning to get the memory moved over.
2914 */
2915 int ratio = max(lr_ratio, ps_ratio);
2916 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2917 }
2918
2919 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2920 task_scan_min(p), task_scan_max(p));
2921 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2922 }
2923
2924 /*
2925 * Get the fraction of time the task has been running since the last
2926 * NUMA placement cycle. The scheduler keeps similar statistics, but
2927 * decays those on a 32ms period, which is orders of magnitude off
2928 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2929 * stats only if the task is so new there are no NUMA statistics yet.
2930 */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2931 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2932 {
2933 u64 runtime, delta, now;
2934 /* Use the start of this time slice to avoid calculations. */
2935 now = p->se.exec_start;
2936 runtime = p->se.sum_exec_runtime;
2937
2938 if (p->last_task_numa_placement) {
2939 delta = runtime - p->last_sum_exec_runtime;
2940 *period = now - p->last_task_numa_placement;
2941
2942 /* Avoid time going backwards, prevent potential divide error: */
2943 if (unlikely((s64)*period < 0))
2944 *period = 0;
2945 } else {
2946 delta = p->se.avg.load_sum;
2947 *period = LOAD_AVG_MAX;
2948 }
2949
2950 p->last_sum_exec_runtime = runtime;
2951 p->last_task_numa_placement = now;
2952
2953 return delta;
2954 }
2955
2956 /*
2957 * Determine the preferred nid for a task in a numa_group. This needs to
2958 * be done in a way that produces consistent results with group_weight,
2959 * otherwise workloads might not converge.
2960 */
preferred_group_nid(struct task_struct * p,int nid)2961 static int preferred_group_nid(struct task_struct *p, int nid)
2962 {
2963 nodemask_t nodes;
2964 int dist;
2965
2966 /* Direct connections between all NUMA nodes. */
2967 if (sched_numa_topology_type == NUMA_DIRECT)
2968 return nid;
2969
2970 /*
2971 * On a system with glueless mesh NUMA topology, group_weight
2972 * scores nodes according to the number of NUMA hinting faults on
2973 * both the node itself, and on nearby nodes.
2974 */
2975 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2976 unsigned long score, max_score = 0;
2977 int node, max_node = nid;
2978
2979 dist = sched_max_numa_distance;
2980
2981 for_each_node_state(node, N_CPU) {
2982 score = group_weight(p, node, dist);
2983 if (score > max_score) {
2984 max_score = score;
2985 max_node = node;
2986 }
2987 }
2988 return max_node;
2989 }
2990
2991 /*
2992 * Finding the preferred nid in a system with NUMA backplane
2993 * interconnect topology is more involved. The goal is to locate
2994 * tasks from numa_groups near each other in the system, and
2995 * untangle workloads from different sides of the system. This requires
2996 * searching down the hierarchy of node groups, recursively searching
2997 * inside the highest scoring group of nodes. The nodemask tricks
2998 * keep the complexity of the search down.
2999 */
3000 nodes = node_states[N_CPU];
3001 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
3002 unsigned long max_faults = 0;
3003 nodemask_t max_group = NODE_MASK_NONE;
3004 int a, b;
3005
3006 /* Are there nodes at this distance from each other? */
3007 if (!find_numa_distance(dist))
3008 continue;
3009
3010 for_each_node_mask(a, nodes) {
3011 unsigned long faults = 0;
3012 nodemask_t this_group;
3013 nodes_clear(this_group);
3014
3015 /* Sum group's NUMA faults; includes a==b case. */
3016 for_each_node_mask(b, nodes) {
3017 if (node_distance(a, b) < dist) {
3018 faults += group_faults(p, b);
3019 node_set(b, this_group);
3020 node_clear(b, nodes);
3021 }
3022 }
3023
3024 /* Remember the top group. */
3025 if (faults > max_faults) {
3026 max_faults = faults;
3027 max_group = this_group;
3028 /*
3029 * subtle: at the smallest distance there is
3030 * just one node left in each "group", the
3031 * winner is the preferred nid.
3032 */
3033 nid = a;
3034 }
3035 }
3036 /* Next round, evaluate the nodes within max_group. */
3037 if (!max_faults)
3038 break;
3039 nodes = max_group;
3040 }
3041 return nid;
3042 }
3043
task_numa_placement(struct task_struct * p)3044 static void task_numa_placement(struct task_struct *p)
3045 __context_unsafe(/* conditional locking */)
3046 {
3047 int seq, nid, max_nid = NUMA_NO_NODE;
3048 unsigned long max_faults = 0;
3049 unsigned long fault_types[2] = { 0, 0 };
3050 unsigned long total_faults;
3051 u64 runtime, period;
3052 spinlock_t *group_lock = NULL;
3053 struct numa_group *ng;
3054
3055 /*
3056 * The p->mm->numa_scan_seq field gets updated without
3057 * exclusive access. Use READ_ONCE() here to ensure
3058 * that the field is read in a single access:
3059 */
3060 seq = READ_ONCE(p->mm->numa_scan_seq);
3061 if (p->numa_scan_seq == seq)
3062 return;
3063 p->numa_scan_seq = seq;
3064 p->numa_scan_period_max = task_scan_max(p);
3065
3066 total_faults = p->numa_faults_locality[0] +
3067 p->numa_faults_locality[1];
3068 runtime = numa_get_avg_runtime(p, &period);
3069
3070 /* If the task is part of a group prevent parallel updates to group stats */
3071 ng = deref_curr_numa_group(p);
3072 if (ng) {
3073 group_lock = &ng->lock;
3074 spin_lock_irq(group_lock);
3075 }
3076
3077 /* Find the node with the highest number of faults */
3078 for_each_online_node(nid) {
3079 /* Keep track of the offsets in numa_faults array */
3080 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
3081 unsigned long faults = 0, group_faults = 0;
3082 int priv;
3083
3084 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
3085 long diff, f_diff, f_weight;
3086
3087 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
3088 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
3089 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
3090 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
3091
3092 /* Decay existing window, copy faults since last scan */
3093 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
3094 fault_types[priv] += p->numa_faults[membuf_idx];
3095 p->numa_faults[membuf_idx] = 0;
3096
3097 /*
3098 * Normalize the faults_from, so all tasks in a group
3099 * count according to CPU use, instead of by the raw
3100 * number of faults. Tasks with little runtime have
3101 * little over-all impact on throughput, and thus their
3102 * faults are less important.
3103 */
3104 f_weight = div64_u64(runtime << 16, period + 1);
3105 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
3106 (total_faults + 1);
3107 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
3108 p->numa_faults[cpubuf_idx] = 0;
3109
3110 p->numa_faults[mem_idx] += diff;
3111 p->numa_faults[cpu_idx] += f_diff;
3112 faults += p->numa_faults[mem_idx];
3113 p->total_numa_faults += diff;
3114 if (ng) {
3115 /*
3116 * safe because we can only change our own group
3117 *
3118 * mem_idx represents the offset for a given
3119 * nid and priv in a specific region because it
3120 * is at the beginning of the numa_faults array.
3121 */
3122 ng->faults[mem_idx] += diff;
3123 ng->faults[cpu_idx] += f_diff;
3124 ng->total_faults += diff;
3125 group_faults += ng->faults[mem_idx];
3126 }
3127 }
3128
3129 if (!ng) {
3130 if (faults > max_faults) {
3131 max_faults = faults;
3132 max_nid = nid;
3133 }
3134 } else if (group_faults > max_faults) {
3135 max_faults = group_faults;
3136 max_nid = nid;
3137 }
3138 }
3139
3140 /* Cannot migrate task to CPU-less node */
3141 max_nid = numa_nearest_node(max_nid, N_CPU);
3142
3143 if (ng) {
3144 numa_group_count_active_nodes(ng);
3145 spin_unlock_irq(group_lock);
3146 max_nid = preferred_group_nid(p, max_nid);
3147 }
3148
3149 if (max_faults) {
3150 /* Set the new preferred node */
3151 if (max_nid != p->numa_preferred_nid)
3152 sched_setnuma(p, max_nid);
3153 }
3154
3155 update_task_scan_period(p, fault_types[0], fault_types[1]);
3156 }
3157
get_numa_group(struct numa_group * grp)3158 static inline int get_numa_group(struct numa_group *grp)
3159 {
3160 return refcount_inc_not_zero(&grp->refcount);
3161 }
3162
put_numa_group(struct numa_group * grp)3163 static inline void put_numa_group(struct numa_group *grp)
3164 {
3165 if (refcount_dec_and_test(&grp->refcount))
3166 kfree_rcu(grp, rcu);
3167 }
3168
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)3169 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3170 int *priv)
3171 {
3172 struct numa_group *grp, *my_grp;
3173 struct task_struct *tsk;
3174 bool join = false;
3175 int cpu = cpupid_to_cpu(cpupid);
3176 int i;
3177
3178 if (unlikely(!deref_curr_numa_group(p))) {
3179 unsigned int size = sizeof(struct numa_group) +
3180 NR_NUMA_HINT_FAULT_STATS *
3181 nr_node_ids * sizeof(unsigned long);
3182
3183 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3184 if (!grp)
3185 return;
3186
3187 refcount_set(&grp->refcount, 1);
3188 grp->active_nodes = 1;
3189 grp->max_faults_cpu = 0;
3190 spin_lock_init(&grp->lock);
3191 grp->gid = p->pid;
3192
3193 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3194 grp->faults[i] = p->numa_faults[i];
3195
3196 grp->total_faults = p->total_numa_faults;
3197
3198 grp->nr_tasks++;
3199 rcu_assign_pointer(p->numa_group, grp);
3200 }
3201
3202 rcu_read_lock();
3203 tsk = READ_ONCE(cpu_rq(cpu)->curr);
3204
3205 if (!cpupid_match_pid(tsk, cpupid))
3206 goto no_join;
3207
3208 grp = rcu_dereference_all(tsk->numa_group);
3209 if (!grp)
3210 goto no_join;
3211
3212 my_grp = deref_curr_numa_group(p);
3213 if (grp == my_grp)
3214 goto no_join;
3215
3216 /*
3217 * Only join the other group if its bigger; if we're the bigger group,
3218 * the other task will join us.
3219 */
3220 if (my_grp->nr_tasks > grp->nr_tasks)
3221 goto no_join;
3222
3223 /*
3224 * Tie-break on the grp address.
3225 */
3226 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3227 goto no_join;
3228
3229 /* Always join threads in the same process. */
3230 if (tsk->mm == current->mm)
3231 join = true;
3232
3233 /* Simple filter to avoid false positives due to PID collisions */
3234 if (flags & TNF_SHARED)
3235 join = true;
3236
3237 /* Update priv based on whether false sharing was detected */
3238 *priv = !join;
3239
3240 if (join && !get_numa_group(grp))
3241 goto no_join;
3242
3243 rcu_read_unlock();
3244
3245 if (!join)
3246 return;
3247
3248 WARN_ON_ONCE(irqs_disabled());
3249 double_lock_irq(&my_grp->lock, &grp->lock);
3250
3251 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3252 my_grp->faults[i] -= p->numa_faults[i];
3253 grp->faults[i] += p->numa_faults[i];
3254 }
3255 my_grp->total_faults -= p->total_numa_faults;
3256 grp->total_faults += p->total_numa_faults;
3257
3258 my_grp->nr_tasks--;
3259 grp->nr_tasks++;
3260
3261 spin_unlock(&my_grp->lock);
3262 spin_unlock_irq(&grp->lock);
3263
3264 rcu_assign_pointer(p->numa_group, grp);
3265
3266 put_numa_group(my_grp);
3267 return;
3268
3269 no_join:
3270 rcu_read_unlock();
3271 return;
3272 }
3273
3274 /*
3275 * Get rid of NUMA statistics associated with a task (either current or dead).
3276 * If @final is set, the task is dead and has reached refcount zero, so we can
3277 * safely free all relevant data structures. Otherwise, there might be
3278 * concurrent reads from places like load balancing and procfs, and we should
3279 * reset the data back to default state without freeing ->numa_faults.
3280 */
task_numa_free(struct task_struct * p,bool final)3281 void task_numa_free(struct task_struct *p, bool final)
3282 {
3283 /* safe: p either is current or is being freed by current */
3284 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3285 unsigned long *numa_faults = p->numa_faults;
3286 unsigned long flags;
3287 int i;
3288
3289 if (!numa_faults)
3290 return;
3291
3292 if (grp) {
3293 spin_lock_irqsave(&grp->lock, flags);
3294 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3295 grp->faults[i] -= p->numa_faults[i];
3296 grp->total_faults -= p->total_numa_faults;
3297
3298 grp->nr_tasks--;
3299 spin_unlock_irqrestore(&grp->lock, flags);
3300 RCU_INIT_POINTER(p->numa_group, NULL);
3301 put_numa_group(grp);
3302 }
3303
3304 if (final) {
3305 p->numa_faults = NULL;
3306 kfree(numa_faults);
3307 } else {
3308 p->total_numa_faults = 0;
3309 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3310 numa_faults[i] = 0;
3311 }
3312 }
3313
3314 /*
3315 * Got a PROT_NONE fault for a page on @node.
3316 */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3317 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3318 {
3319 struct task_struct *p = current;
3320 bool migrated = flags & TNF_MIGRATED;
3321 int cpu_node = task_node(current);
3322 int local = !!(flags & TNF_FAULT_LOCAL);
3323 struct numa_group *ng;
3324 int priv;
3325
3326 if (!static_branch_likely(&sched_numa_balancing))
3327 return;
3328
3329 /* for example, ksmd faulting in a user's mm */
3330 if (!p->mm)
3331 return;
3332
3333 /*
3334 * NUMA faults statistics are unnecessary for the slow memory
3335 * node for memory tiering mode.
3336 */
3337 if (!node_is_toptier(mem_node) &&
3338 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3339 !cpupid_valid(last_cpupid)))
3340 return;
3341
3342 /* Allocate buffer to track faults on a per-node basis */
3343 if (unlikely(!p->numa_faults)) {
3344 int size = sizeof(*p->numa_faults) *
3345 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3346
3347 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3348 if (!p->numa_faults)
3349 return;
3350
3351 p->total_numa_faults = 0;
3352 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3353 }
3354
3355 /*
3356 * First accesses are treated as private, otherwise consider accesses
3357 * to be private if the accessing pid has not changed
3358 */
3359 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3360 priv = 1;
3361 } else {
3362 priv = cpupid_match_pid(p, last_cpupid);
3363 if (!priv && !(flags & TNF_NO_GROUP))
3364 task_numa_group(p, last_cpupid, flags, &priv);
3365 }
3366
3367 /*
3368 * If a workload spans multiple NUMA nodes, a shared fault that
3369 * occurs wholly within the set of nodes that the workload is
3370 * actively using should be counted as local. This allows the
3371 * scan rate to slow down when a workload has settled down.
3372 */
3373 ng = deref_curr_numa_group(p);
3374 if (!priv && !local && ng && ng->active_nodes > 1 &&
3375 numa_is_active_node(cpu_node, ng) &&
3376 numa_is_active_node(mem_node, ng))
3377 local = 1;
3378
3379 /*
3380 * Retry to migrate task to preferred node periodically, in case it
3381 * previously failed, or the scheduler moved us.
3382 */
3383 if (time_after(jiffies, p->numa_migrate_retry)) {
3384 task_numa_placement(p);
3385 numa_migrate_preferred(p);
3386 }
3387
3388 if (migrated)
3389 p->numa_pages_migrated += pages;
3390 if (flags & TNF_MIGRATE_FAIL)
3391 p->numa_faults_locality[2] += pages;
3392
3393 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3394 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3395 p->numa_faults_locality[local] += pages;
3396 }
3397
reset_ptenuma_scan(struct task_struct * p)3398 static void reset_ptenuma_scan(struct task_struct *p)
3399 {
3400 /*
3401 * We only did a read acquisition of the mmap sem, so
3402 * p->mm->numa_scan_seq is written to without exclusive access
3403 * and the update is not guaranteed to be atomic. That's not
3404 * much of an issue though, since this is just used for
3405 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3406 * expensive, to avoid any form of compiler optimizations:
3407 */
3408 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3409 p->mm->numa_scan_offset = 0;
3410 }
3411
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3412 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3413 {
3414 unsigned long pids;
3415 /*
3416 * Allow unconditional access first two times, so that all the (pages)
3417 * of VMAs get prot_none fault introduced irrespective of accesses.
3418 * This is also done to avoid any side effect of task scanning
3419 * amplifying the unfairness of disjoint set of VMAs' access.
3420 */
3421 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3422 return true;
3423
3424 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3425 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3426 return true;
3427
3428 /*
3429 * Complete a scan that has already started regardless of PID access, or
3430 * some VMAs may never be scanned in multi-threaded applications:
3431 */
3432 if (mm->numa_scan_offset > vma->vm_start) {
3433 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3434 return true;
3435 }
3436
3437 /*
3438 * This vma has not been accessed for a while, and if the number
3439 * the threads in the same process is low, which means no other
3440 * threads can help scan this vma, force a vma scan.
3441 */
3442 if (READ_ONCE(mm->numa_scan_seq) >
3443 (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3444 return true;
3445
3446 return false;
3447 }
3448
3449 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3450
3451 /*
3452 * The expensive part of numa migration is done from task_work context.
3453 * Triggered from task_tick_numa().
3454 */
task_numa_work(struct callback_head * work)3455 static void task_numa_work(struct callback_head *work)
3456 {
3457 unsigned long migrate, next_scan, now = jiffies;
3458 struct task_struct *p = current;
3459 struct mm_struct *mm = p->mm;
3460 u64 runtime = p->se.sum_exec_runtime;
3461 struct vm_area_struct *vma;
3462 unsigned long start, end;
3463 unsigned long nr_pte_updates = 0;
3464 long pages, virtpages;
3465 struct vma_iterator vmi;
3466 bool vma_pids_skipped;
3467 bool vma_pids_forced = false;
3468
3469 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
3470
3471 work->next = work;
3472 /*
3473 * Who cares about NUMA placement when they're dying.
3474 *
3475 * NOTE: make sure not to dereference p->mm before this check,
3476 * exit_task_work() happens _after_ exit_mm() so we could be called
3477 * without p->mm even though we still had it when we enqueued this
3478 * work.
3479 */
3480 if (p->flags & PF_EXITING)
3481 return;
3482
3483 /*
3484 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
3485 * no page can be migrated.
3486 */
3487 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
3488 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
3489 return;
3490 }
3491
3492 if (!mm->numa_next_scan) {
3493 mm->numa_next_scan = now +
3494 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3495 }
3496
3497 /*
3498 * Enforce maximal scan/migration frequency..
3499 */
3500 migrate = mm->numa_next_scan;
3501 if (time_before(now, migrate))
3502 return;
3503
3504 if (p->numa_scan_period == 0) {
3505 p->numa_scan_period_max = task_scan_max(p);
3506 p->numa_scan_period = task_scan_start(p);
3507 }
3508
3509 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3510 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3511 return;
3512
3513 /*
3514 * Delay this task enough that another task of this mm will likely win
3515 * the next time around.
3516 */
3517 p->node_stamp += 2 * TICK_NSEC;
3518
3519 pages = sysctl_numa_balancing_scan_size;
3520 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3521 virtpages = pages * 8; /* Scan up to this much virtual space */
3522 if (!pages)
3523 return;
3524
3525
3526 if (!mmap_read_trylock(mm))
3527 return;
3528
3529 /*
3530 * VMAs are skipped if the current PID has not trapped a fault within
3531 * the VMA recently. Allow scanning to be forced if there is no
3532 * suitable VMA remaining.
3533 */
3534 vma_pids_skipped = false;
3535
3536 retry_pids:
3537 start = mm->numa_scan_offset;
3538 vma_iter_init(&vmi, mm, start);
3539 vma = vma_next(&vmi);
3540 if (!vma) {
3541 reset_ptenuma_scan(p);
3542 start = 0;
3543 vma_iter_set(&vmi, start);
3544 vma = vma_next(&vmi);
3545 }
3546
3547 for (; vma; vma = vma_next(&vmi)) {
3548 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3549 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3550 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3551 continue;
3552 }
3553
3554 /*
3555 * Shared library pages mapped by multiple processes are not
3556 * migrated as it is expected they are cache replicated. Avoid
3557 * hinting faults in read-only file-backed mappings or the vDSO
3558 * as migrating the pages will be of marginal benefit.
3559 */
3560 if (!vma->vm_mm ||
3561 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3562 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3563 continue;
3564 }
3565
3566 /*
3567 * Skip inaccessible VMAs to avoid any confusion between
3568 * PROT_NONE and NUMA hinting PTEs
3569 */
3570 if (!vma_is_accessible(vma)) {
3571 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3572 continue;
3573 }
3574
3575 /* Initialise new per-VMA NUMAB state. */
3576 if (!vma->numab_state) {
3577 struct vma_numab_state *ptr;
3578
3579 ptr = kzalloc_obj(*ptr);
3580 if (!ptr)
3581 continue;
3582
3583 if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3584 kfree(ptr);
3585 continue;
3586 }
3587
3588 vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3589
3590 vma->numab_state->next_scan = now +
3591 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3592
3593 /* Reset happens after 4 times scan delay of scan start */
3594 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
3595 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3596
3597 /*
3598 * Ensure prev_scan_seq does not match numa_scan_seq,
3599 * to prevent VMAs being skipped prematurely on the
3600 * first scan:
3601 */
3602 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3603 }
3604
3605 /*
3606 * Scanning the VMAs of short lived tasks add more overhead. So
3607 * delay the scan for new VMAs.
3608 */
3609 if (mm->numa_scan_seq && time_before(jiffies,
3610 vma->numab_state->next_scan)) {
3611 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3612 continue;
3613 }
3614
3615 /* RESET access PIDs regularly for old VMAs. */
3616 if (mm->numa_scan_seq &&
3617 time_after(jiffies, vma->numab_state->pids_active_reset)) {
3618 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3619 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3620 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3621 vma->numab_state->pids_active[1] = 0;
3622 }
3623
3624 /* Do not rescan VMAs twice within the same sequence. */
3625 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3626 mm->numa_scan_offset = vma->vm_end;
3627 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3628 continue;
3629 }
3630
3631 /*
3632 * Do not scan the VMA if task has not accessed it, unless no other
3633 * VMA candidate exists.
3634 */
3635 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3636 vma_pids_skipped = true;
3637 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3638 continue;
3639 }
3640
3641 do {
3642 start = max(start, vma->vm_start);
3643 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3644 end = min(end, vma->vm_end);
3645 nr_pte_updates = change_prot_numa(vma, start, end);
3646
3647 /*
3648 * Try to scan sysctl_numa_balancing_size worth of
3649 * hpages that have at least one present PTE that
3650 * is not already PTE-numa. If the VMA contains
3651 * areas that are unused or already full of prot_numa
3652 * PTEs, scan up to virtpages, to skip through those
3653 * areas faster.
3654 */
3655 if (nr_pte_updates)
3656 pages -= (end - start) >> PAGE_SHIFT;
3657 virtpages -= (end - start) >> PAGE_SHIFT;
3658
3659 start = end;
3660 if (pages <= 0 || virtpages <= 0)
3661 goto out;
3662
3663 cond_resched();
3664 } while (end != vma->vm_end);
3665
3666 /* VMA scan is complete, do not scan until next sequence. */
3667 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3668
3669 /*
3670 * Only force scan within one VMA at a time, to limit the
3671 * cost of scanning a potentially uninteresting VMA.
3672 */
3673 if (vma_pids_forced)
3674 break;
3675 }
3676
3677 /*
3678 * If no VMAs are remaining and VMAs were skipped due to the PID
3679 * not accessing the VMA previously, then force a scan to ensure
3680 * forward progress:
3681 */
3682 if (!vma && !vma_pids_forced && vma_pids_skipped) {
3683 vma_pids_forced = true;
3684 goto retry_pids;
3685 }
3686
3687 out:
3688 /*
3689 * It is possible to reach the end of the VMA list but the last few
3690 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3691 * would find the !migratable VMA on the next scan but not reset the
3692 * scanner to the start so check it now.
3693 */
3694 if (vma)
3695 mm->numa_scan_offset = start;
3696 else
3697 reset_ptenuma_scan(p);
3698 mmap_read_unlock(mm);
3699
3700 /*
3701 * Make sure tasks use at least 32x as much time to run other code
3702 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3703 * Usually update_task_scan_period slows down scanning enough; on an
3704 * overloaded system we need to limit overhead on a per task basis.
3705 */
3706 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3707 u64 diff = p->se.sum_exec_runtime - runtime;
3708 p->node_stamp += 32 * diff;
3709 }
3710 }
3711
init_numa_balancing(u64 clone_flags,struct task_struct * p)3712 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
3713 {
3714 int mm_users = 0;
3715 struct mm_struct *mm = p->mm;
3716
3717 if (mm) {
3718 mm_users = atomic_read(&mm->mm_users);
3719 if (mm_users == 1) {
3720 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3721 mm->numa_scan_seq = 0;
3722 }
3723 }
3724 p->node_stamp = 0;
3725 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3726 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3727 p->numa_migrate_retry = 0;
3728 /* Protect against double add, see task_tick_numa and task_numa_work */
3729 p->numa_work.next = &p->numa_work;
3730 p->numa_faults = NULL;
3731 p->numa_pages_migrated = 0;
3732 p->total_numa_faults = 0;
3733 RCU_INIT_POINTER(p->numa_group, NULL);
3734 p->last_task_numa_placement = 0;
3735 p->last_sum_exec_runtime = 0;
3736
3737 init_task_work(&p->numa_work, task_numa_work);
3738
3739 /* New address space, reset the preferred nid */
3740 if (!(clone_flags & CLONE_VM)) {
3741 p->numa_preferred_nid = NUMA_NO_NODE;
3742 return;
3743 }
3744
3745 /*
3746 * New thread, keep existing numa_preferred_nid which should be copied
3747 * already by arch_dup_task_struct but stagger when scans start.
3748 */
3749 if (mm) {
3750 unsigned int delay;
3751
3752 delay = min_t(unsigned int, task_scan_max(current),
3753 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3754 delay += 2 * TICK_NSEC;
3755 p->node_stamp = delay;
3756 }
3757 }
3758
3759 /*
3760 * Drive the periodic memory faults..
3761 */
task_tick_numa(struct rq * rq,struct task_struct * curr)3762 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3763 {
3764 struct callback_head *work = &curr->numa_work;
3765 u64 period, now;
3766
3767 /*
3768 * We don't care about NUMA placement if we don't have memory.
3769 */
3770 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3771 return;
3772
3773 /*
3774 * Using runtime rather than walltime has the dual advantage that
3775 * we (mostly) drive the selection from busy threads and that the
3776 * task needs to have done some actual work before we bother with
3777 * NUMA placement.
3778 */
3779 now = curr->se.sum_exec_runtime;
3780 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3781
3782 if (now > curr->node_stamp + period) {
3783 if (!curr->node_stamp)
3784 curr->numa_scan_period = task_scan_start(curr);
3785 curr->node_stamp += period;
3786
3787 if (!time_before(jiffies, curr->mm->numa_next_scan))
3788 task_work_add(curr, work, TWA_RESUME);
3789 }
3790 }
3791
update_scan_period(struct task_struct * p,int new_cpu)3792 static void update_scan_period(struct task_struct *p, int new_cpu)
3793 {
3794 int src_nid = cpu_to_node(task_cpu(p));
3795 int dst_nid = cpu_to_node(new_cpu);
3796
3797 if (!static_branch_likely(&sched_numa_balancing))
3798 return;
3799
3800 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3801 return;
3802
3803 if (src_nid == dst_nid)
3804 return;
3805
3806 /*
3807 * Allow resets if faults have been trapped before one scan
3808 * has completed. This is most likely due to a new task that
3809 * is pulled cross-node due to wakeups or load balancing.
3810 */
3811 if (p->numa_scan_seq) {
3812 /*
3813 * Avoid scan adjustments if moving to the preferred
3814 * node or if the task was not previously running on
3815 * the preferred node.
3816 */
3817 if (dst_nid == p->numa_preferred_nid ||
3818 (p->numa_preferred_nid != NUMA_NO_NODE &&
3819 src_nid != p->numa_preferred_nid))
3820 return;
3821 }
3822
3823 p->numa_scan_period = task_scan_start(p);
3824 }
3825
3826 #else /* !CONFIG_NUMA_BALANCING: */
3827
task_tick_numa(struct rq * rq,struct task_struct * curr)3828 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3829 {
3830 }
3831
account_numa_enqueue(struct rq * rq,struct task_struct * p)3832 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3833 {
3834 }
3835
account_numa_dequeue(struct rq * rq,struct task_struct * p)3836 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3837 {
3838 }
3839
update_scan_period(struct task_struct * p,int new_cpu)3840 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3841 {
3842 }
3843
3844 #endif /* !CONFIG_NUMA_BALANCING */
3845
3846 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3847 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3848 {
3849 update_load_add(&cfs_rq->load, se->load.weight);
3850 if (entity_is_task(se)) {
3851 struct rq *rq = rq_of(cfs_rq);
3852
3853 account_numa_enqueue(rq, task_of(se));
3854 list_add(&se->group_node, &rq->cfs_tasks);
3855 }
3856 cfs_rq->nr_queued++;
3857 }
3858
3859 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3860 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3861 {
3862 update_load_sub(&cfs_rq->load, se->load.weight);
3863 if (entity_is_task(se)) {
3864 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3865 list_del_init(&se->group_node);
3866 }
3867 cfs_rq->nr_queued--;
3868 }
3869
3870 /*
3871 * Signed add and clamp on underflow.
3872 *
3873 * Explicitly do a load-store to ensure the intermediate value never hits
3874 * memory. This allows lockless observations without ever seeing the negative
3875 * values.
3876 */
3877 #define add_positive(_ptr, _val) do { \
3878 typeof(_ptr) ptr = (_ptr); \
3879 __signed_scalar_typeof(*ptr) val = (_val); \
3880 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3881 \
3882 res = var + val; \
3883 \
3884 if (val < 0 && res > var) \
3885 res = 0; \
3886 \
3887 WRITE_ONCE(*ptr, res); \
3888 } while (0)
3889
3890 /*
3891 * Remove and clamp on negative, from a local variable.
3892 *
3893 * A variant of sub_positive(), which does not use explicit load-store
3894 * and is thus optimized for local variable updates.
3895 */
3896 #define lsub_positive(_ptr, _val) do { \
3897 typeof(_ptr) ptr = (_ptr); \
3898 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3899 } while (0)
3900
3901
3902 /*
3903 * Because of rounding, se->util_sum might ends up being +1 more than
3904 * cfs->util_sum. Although this is not a problem by itself, detaching
3905 * a lot of tasks with the rounding problem between 2 updates of
3906 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
3907 * cfs_util_avg is not.
3908 *
3909 * Check that util_sum is still above its lower bound for the new
3910 * util_avg. Given that period_contrib might have moved since the last
3911 * sync, we are only sure that util_sum must be above or equal to
3912 * util_avg * minimum possible divider
3913 */
3914 #define __update_sa(sa, name, delta_avg, delta_sum) do { \
3915 add_positive(&(sa)->name##_avg, delta_avg); \
3916 add_positive(&(sa)->name##_sum, delta_sum); \
3917 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \
3918 (sa)->name##_sum, \
3919 (sa)->name##_avg * PELT_MIN_DIVIDER); \
3920 } while (0)
3921
3922 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3923 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3924 {
3925 __update_sa(&cfs_rq->avg, load, se->avg.load_avg,
3926 se_weight(se) * se->avg.load_sum);
3927 }
3928
3929 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3930 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3931 {
3932 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg,
3933 se_weight(se) * -se->avg.load_sum);
3934 }
3935
3936 static void
rescale_entity(struct sched_entity * se,unsigned long weight,bool rel_vprot)3937 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot)
3938 {
3939 unsigned long old_weight = se->load.weight;
3940
3941 /*
3942 * VRUNTIME
3943 * --------
3944 *
3945 * COROLLARY #1: The virtual runtime of the entity needs to be
3946 * adjusted if re-weight at !0-lag point.
3947 *
3948 * Proof: For contradiction assume this is not true, so we can
3949 * re-weight without changing vruntime at !0-lag point.
3950 *
3951 * Weight VRuntime Avg-VRuntime
3952 * before w v V
3953 * after w' v' V'
3954 *
3955 * Since lag needs to be preserved through re-weight:
3956 *
3957 * lag = (V - v)*w = (V'- v')*w', where v = v'
3958 * ==> V' = (V - v)*w/w' + v (1)
3959 *
3960 * Let W be the total weight of the entities before reweight,
3961 * since V' is the new weighted average of entities:
3962 *
3963 * V' = (WV + w'v - wv) / (W + w' - w) (2)
3964 *
3965 * by using (1) & (2) we obtain:
3966 *
3967 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
3968 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
3969 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
3970 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
3971 *
3972 * Since we are doing at !0-lag point which means V != v, we
3973 * can simplify (3):
3974 *
3975 * ==> W / (W + w' - w) = w / w'
3976 * ==> Ww' = Ww + ww' - ww
3977 * ==> W * (w' - w) = w * (w' - w)
3978 * ==> W = w (re-weight indicates w' != w)
3979 *
3980 * So the cfs_rq contains only one entity, hence vruntime of
3981 * the entity @v should always equal to the cfs_rq's weighted
3982 * average vruntime @V, which means we will always re-weight
3983 * at 0-lag point, thus breach assumption. Proof completed.
3984 *
3985 *
3986 * COROLLARY #2: Re-weight does NOT affect weighted average
3987 * vruntime of all the entities.
3988 *
3989 * Proof: According to corollary #1, Eq. (1) should be:
3990 *
3991 * (V - v)*w = (V' - v')*w'
3992 * ==> v' = V' - (V - v)*w/w' (4)
3993 *
3994 * According to the weighted average formula, we have:
3995 *
3996 * V' = (WV - wv + w'v') / (W - w + w')
3997 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
3998 * = (WV - wv + w'V' - Vw + wv) / (W - w + w')
3999 * = (WV + w'V' - Vw) / (W - w + w')
4000 *
4001 * ==> V'*(W - w + w') = WV + w'V' - Vw
4002 * ==> V' * (W - w) = (W - w) * V (5)
4003 *
4004 * If the entity is the only one in the cfs_rq, then reweight
4005 * always occurs at 0-lag point, so V won't change. Or else
4006 * there are other entities, hence W != w, then Eq. (5) turns
4007 * into V' = V. So V won't change in either case, proof done.
4008 *
4009 *
4010 * So according to corollary #1 & #2, the effect of re-weight
4011 * on vruntime should be:
4012 *
4013 * v' = V' - (V - v) * w / w' (4)
4014 * = V - (V - v) * w / w'
4015 * = V - vl * w / w'
4016 * = V - vl'
4017 */
4018 se->vlag = div64_long(se->vlag * old_weight, weight);
4019
4020 /*
4021 * DEADLINE
4022 * --------
4023 *
4024 * When the weight changes, the virtual time slope changes and
4025 * we should adjust the relative virtual deadline accordingly.
4026 *
4027 * d' = v' + (d - v)*w/w'
4028 * = V' - (V - v)*w/w' + (d - v)*w/w'
4029 * = V - (V - v)*w/w' + (d - v)*w/w'
4030 * = V + (d - V)*w/w'
4031 */
4032 if (se->rel_deadline)
4033 se->deadline = div64_long(se->deadline * old_weight, weight);
4034
4035 if (rel_vprot)
4036 se->vprot = div64_long(se->vprot * old_weight, weight);
4037 }
4038
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)4039 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
4040 unsigned long weight)
4041 {
4042 bool curr = cfs_rq->curr == se;
4043 bool rel_vprot = false;
4044 u64 avruntime = 0;
4045
4046 if (se->on_rq) {
4047 /* commit outstanding execution time */
4048 update_curr(cfs_rq);
4049 avruntime = avg_vruntime(cfs_rq);
4050 se->vlag = entity_lag(cfs_rq, se, avruntime);
4051 se->deadline -= avruntime;
4052 se->rel_deadline = 1;
4053 if (curr && protect_slice(se)) {
4054 se->vprot -= avruntime;
4055 rel_vprot = true;
4056 }
4057
4058 cfs_rq->nr_queued--;
4059 if (!curr)
4060 __dequeue_entity(cfs_rq, se);
4061 update_load_sub(&cfs_rq->load, se->load.weight);
4062 }
4063 dequeue_load_avg(cfs_rq, se);
4064
4065 rescale_entity(se, weight, rel_vprot);
4066
4067 update_load_set(&se->load, weight);
4068
4069 do {
4070 u32 divider = get_pelt_divider(&se->avg);
4071 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
4072 } while (0);
4073
4074 enqueue_load_avg(cfs_rq, se);
4075 if (se->on_rq) {
4076 if (rel_vprot)
4077 se->vprot += avruntime;
4078 se->deadline += avruntime;
4079 se->rel_deadline = 0;
4080 se->vruntime = avruntime - se->vlag;
4081
4082 update_load_add(&cfs_rq->load, se->load.weight);
4083 if (!curr)
4084 __enqueue_entity(cfs_rq, se);
4085 cfs_rq->nr_queued++;
4086 }
4087 }
4088
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)4089 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
4090 const struct load_weight *lw)
4091 {
4092 struct sched_entity *se = &p->se;
4093 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4094 struct load_weight *load = &se->load;
4095
4096 reweight_entity(cfs_rq, se, lw->weight);
4097 load->inv_weight = lw->inv_weight;
4098 }
4099
4100 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
4101
4102 #ifdef CONFIG_FAIR_GROUP_SCHED
4103 /*
4104 * All this does is approximate the hierarchical proportion which includes that
4105 * global sum we all love to hate.
4106 *
4107 * That is, the weight of a group entity, is the proportional share of the
4108 * group weight based on the group runqueue weights. That is:
4109 *
4110 * tg->weight * grq->load.weight
4111 * ge->load.weight = ----------------------------- (1)
4112 * \Sum grq->load.weight
4113 *
4114 * Now, because computing that sum is prohibitively expensive to compute (been
4115 * there, done that) we approximate it with this average stuff. The average
4116 * moves slower and therefore the approximation is cheaper and more stable.
4117 *
4118 * So instead of the above, we substitute:
4119 *
4120 * grq->load.weight -> grq->avg.load_avg (2)
4121 *
4122 * which yields the following:
4123 *
4124 * tg->weight * grq->avg.load_avg
4125 * ge->load.weight = ------------------------------ (3)
4126 * tg->load_avg
4127 *
4128 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
4129 *
4130 * That is shares_avg, and it is right (given the approximation (2)).
4131 *
4132 * The problem with it is that because the average is slow -- it was designed
4133 * to be exactly that of course -- this leads to transients in boundary
4134 * conditions. In specific, the case where the group was idle and we start the
4135 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
4136 * yielding bad latency etc..
4137 *
4138 * Now, in that special case (1) reduces to:
4139 *
4140 * tg->weight * grq->load.weight
4141 * ge->load.weight = ----------------------------- = tg->weight (4)
4142 * grp->load.weight
4143 *
4144 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
4145 *
4146 * So what we do is modify our approximation (3) to approach (4) in the (near)
4147 * UP case, like:
4148 *
4149 * ge->load.weight =
4150 *
4151 * tg->weight * grq->load.weight
4152 * --------------------------------------------------- (5)
4153 * tg->load_avg - grq->avg.load_avg + grq->load.weight
4154 *
4155 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
4156 * we need to use grq->avg.load_avg as its lower bound, which then gives:
4157 *
4158 *
4159 * tg->weight * grq->load.weight
4160 * ge->load.weight = ----------------------------- (6)
4161 * tg_load_avg'
4162 *
4163 * Where:
4164 *
4165 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
4166 * max(grq->load.weight, grq->avg.load_avg)
4167 *
4168 * And that is shares_weight and is icky. In the (near) UP case it approaches
4169 * (4) while in the normal case it approaches (3). It consistently
4170 * overestimates the ge->load.weight and therefore:
4171 *
4172 * \Sum ge->load.weight >= tg->weight
4173 *
4174 * hence icky!
4175 */
calc_group_shares(struct cfs_rq * cfs_rq)4176 static long calc_group_shares(struct cfs_rq *cfs_rq)
4177 {
4178 long tg_weight, tg_shares, load, shares;
4179 struct task_group *tg = cfs_rq->tg;
4180
4181 tg_shares = READ_ONCE(tg->shares);
4182
4183 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
4184
4185 tg_weight = atomic_long_read(&tg->load_avg);
4186
4187 /* Ensure tg_weight >= load */
4188 tg_weight -= cfs_rq->tg_load_avg_contrib;
4189 tg_weight += load;
4190
4191 shares = (tg_shares * load);
4192 if (tg_weight)
4193 shares /= tg_weight;
4194
4195 /*
4196 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
4197 * of a group with small tg->shares value. It is a floor value which is
4198 * assigned as a minimum load.weight to the sched_entity representing
4199 * the group on a CPU.
4200 *
4201 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
4202 * on an 8-core system with 8 tasks each runnable on one CPU shares has
4203 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
4204 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
4205 * instead of 0.
4206 */
4207 return clamp_t(long, shares, MIN_SHARES, tg_shares);
4208 }
4209
4210 /*
4211 * Recomputes the group entity based on the current state of its group
4212 * runqueue.
4213 */
update_cfs_group(struct sched_entity * se)4214 static void update_cfs_group(struct sched_entity *se)
4215 {
4216 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4217 long shares;
4218
4219 /*
4220 * When a group becomes empty, preserve its weight. This matters for
4221 * DELAY_DEQUEUE.
4222 */
4223 if (!gcfs_rq || !gcfs_rq->load.weight)
4224 return;
4225
4226 shares = calc_group_shares(gcfs_rq);
4227 if (unlikely(se->load.weight != shares))
4228 reweight_entity(cfs_rq_of(se), se, shares);
4229 }
4230
4231 #else /* !CONFIG_FAIR_GROUP_SCHED: */
update_cfs_group(struct sched_entity * se)4232 static inline void update_cfs_group(struct sched_entity *se)
4233 {
4234 }
4235 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4236
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)4237 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
4238 {
4239 struct rq *rq = rq_of(cfs_rq);
4240
4241 if (&rq->cfs == cfs_rq) {
4242 /*
4243 * There are a few boundary cases this might miss but it should
4244 * get called often enough that that should (hopefully) not be
4245 * a real problem.
4246 *
4247 * It will not get called when we go idle, because the idle
4248 * thread is a different class (!fair), nor will the utilization
4249 * number include things like RT tasks.
4250 *
4251 * As is, the util number is not freq-invariant (we'd have to
4252 * implement arch_scale_freq_capacity() for that).
4253 *
4254 * See cpu_util_cfs().
4255 */
4256 cpufreq_update_util(rq, flags);
4257 }
4258 }
4259
load_avg_is_decayed(struct sched_avg * sa)4260 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4261 {
4262 if (sa->load_sum)
4263 return false;
4264
4265 if (sa->util_sum)
4266 return false;
4267
4268 if (sa->runnable_sum)
4269 return false;
4270
4271 /*
4272 * _avg must be null when _sum are null because _avg = _sum / divider
4273 * Make sure that rounding and/or propagation of PELT values never
4274 * break this.
4275 */
4276 WARN_ON_ONCE(sa->load_avg ||
4277 sa->util_avg ||
4278 sa->runnable_avg);
4279
4280 return true;
4281 }
4282
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)4283 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4284 {
4285 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4286 cfs_rq->last_update_time_copy);
4287 }
4288 #ifdef CONFIG_FAIR_GROUP_SCHED
4289 /*
4290 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4291 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4292 * bottom-up, we only have to test whether the cfs_rq before us on the list
4293 * is our child.
4294 * If cfs_rq is not on the list, test whether a child needs its to be added to
4295 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
4296 */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4297 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4298 {
4299 struct cfs_rq *prev_cfs_rq;
4300 struct list_head *prev;
4301 struct rq *rq = rq_of(cfs_rq);
4302
4303 if (cfs_rq->on_list) {
4304 prev = cfs_rq->leaf_cfs_rq_list.prev;
4305 } else {
4306 prev = rq->tmp_alone_branch;
4307 }
4308
4309 if (prev == &rq->leaf_cfs_rq_list)
4310 return false;
4311
4312 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4313
4314 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4315 }
4316
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4317 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4318 {
4319 if (cfs_rq->load.weight)
4320 return false;
4321
4322 if (!load_avg_is_decayed(&cfs_rq->avg))
4323 return false;
4324
4325 if (child_cfs_rq_on_list(cfs_rq))
4326 return false;
4327
4328 if (cfs_rq->tg_load_avg_contrib)
4329 return false;
4330
4331 return true;
4332 }
4333
4334 /**
4335 * update_tg_load_avg - update the tg's load avg
4336 * @cfs_rq: the cfs_rq whose avg changed
4337 *
4338 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4339 * However, because tg->load_avg is a global value there are performance
4340 * considerations.
4341 *
4342 * In order to avoid having to look at the other cfs_rq's, we use a
4343 * differential update where we store the last value we propagated. This in
4344 * turn allows skipping updates if the differential is 'small'.
4345 *
4346 * Updating tg's load_avg is necessary before update_cfs_share().
4347 */
update_tg_load_avg(struct cfs_rq * cfs_rq)4348 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4349 {
4350 long delta;
4351 u64 now;
4352
4353 /*
4354 * No need to update load_avg for root_task_group as it is not used.
4355 */
4356 if (cfs_rq->tg == &root_task_group)
4357 return;
4358
4359 /* rq has been offline and doesn't contribute to the share anymore: */
4360 if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4361 return;
4362
4363 /*
4364 * For migration heavy workloads, access to tg->load_avg can be
4365 * unbound. Limit the update rate to at most once per ms.
4366 */
4367 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4368 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4369 return;
4370
4371 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4372 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4373 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4374 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4375 cfs_rq->last_update_tg_load_avg = now;
4376 }
4377 }
4378
clear_tg_load_avg(struct cfs_rq * cfs_rq)4379 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4380 {
4381 long delta;
4382 u64 now;
4383
4384 /*
4385 * No need to update load_avg for root_task_group, as it is not used.
4386 */
4387 if (cfs_rq->tg == &root_task_group)
4388 return;
4389
4390 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4391 delta = 0 - cfs_rq->tg_load_avg_contrib;
4392 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4393 cfs_rq->tg_load_avg_contrib = 0;
4394 cfs_rq->last_update_tg_load_avg = now;
4395 }
4396
4397 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4398 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4399 {
4400 struct task_group *tg;
4401
4402 lockdep_assert_rq_held(rq);
4403
4404 /*
4405 * The rq clock has already been updated in
4406 * set_rq_offline(), so we should skip updating
4407 * the rq clock again in unthrottle_cfs_rq().
4408 */
4409 rq_clock_start_loop_update(rq);
4410
4411 rcu_read_lock();
4412 list_for_each_entry_rcu(tg, &task_groups, list) {
4413 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4414
4415 clear_tg_load_avg(cfs_rq);
4416 }
4417 rcu_read_unlock();
4418
4419 rq_clock_stop_loop_update(rq);
4420 }
4421
4422 /*
4423 * Called within set_task_rq() right before setting a task's CPU. The
4424 * caller only guarantees p->pi_lock is held; no other assumptions,
4425 * including the state of rq->lock, should be made.
4426 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4427 void set_task_rq_fair(struct sched_entity *se,
4428 struct cfs_rq *prev, struct cfs_rq *next)
4429 {
4430 u64 p_last_update_time;
4431 u64 n_last_update_time;
4432
4433 if (!sched_feat(ATTACH_AGE_LOAD))
4434 return;
4435
4436 /*
4437 * We are supposed to update the task to "current" time, then its up to
4438 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4439 * getting what current time is, so simply throw away the out-of-date
4440 * time. This will result in the wakee task is less decayed, but giving
4441 * the wakee more load sounds not bad.
4442 */
4443 if (!(se->avg.last_update_time && prev))
4444 return;
4445
4446 p_last_update_time = cfs_rq_last_update_time(prev);
4447 n_last_update_time = cfs_rq_last_update_time(next);
4448
4449 __update_load_avg_blocked_se(p_last_update_time, se);
4450 se->avg.last_update_time = n_last_update_time;
4451 }
4452
4453 /*
4454 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4455 * propagate its contribution. The key to this propagation is the invariant
4456 * that for each group:
4457 *
4458 * ge->avg == grq->avg (1)
4459 *
4460 * _IFF_ we look at the pure running and runnable sums. Because they
4461 * represent the very same entity, just at different points in the hierarchy.
4462 *
4463 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4464 * and simply copies the running/runnable sum over (but still wrong, because
4465 * the group entity and group rq do not have their PELT windows aligned).
4466 *
4467 * However, update_tg_cfs_load() is more complex. So we have:
4468 *
4469 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4470 *
4471 * And since, like util, the runnable part should be directly transferable,
4472 * the following would _appear_ to be the straight forward approach:
4473 *
4474 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4475 *
4476 * And per (1) we have:
4477 *
4478 * ge->avg.runnable_avg == grq->avg.runnable_avg
4479 *
4480 * Which gives:
4481 *
4482 * ge->load.weight * grq->avg.load_avg
4483 * ge->avg.load_avg = ----------------------------------- (4)
4484 * grq->load.weight
4485 *
4486 * Except that is wrong!
4487 *
4488 * Because while for entities historical weight is not important and we
4489 * really only care about our future and therefore can consider a pure
4490 * runnable sum, runqueues can NOT do this.
4491 *
4492 * We specifically want runqueues to have a load_avg that includes
4493 * historical weights. Those represent the blocked load, the load we expect
4494 * to (shortly) return to us. This only works by keeping the weights as
4495 * integral part of the sum. We therefore cannot decompose as per (3).
4496 *
4497 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4498 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4499 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4500 * runnable section of these tasks overlap (or not). If they were to perfectly
4501 * align the rq as a whole would be runnable 2/3 of the time. If however we
4502 * always have at least 1 runnable task, the rq as a whole is always runnable.
4503 *
4504 * So we'll have to approximate.. :/
4505 *
4506 * Given the constraint:
4507 *
4508 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4509 *
4510 * We can construct a rule that adds runnable to a rq by assuming minimal
4511 * overlap.
4512 *
4513 * On removal, we'll assume each task is equally runnable; which yields:
4514 *
4515 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4516 *
4517 * XXX: only do this for the part of runnable > running ?
4518 *
4519 */
4520 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4521 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4522 {
4523 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4524 u32 new_sum, divider;
4525
4526 /* Nothing to update */
4527 if (!delta_avg)
4528 return;
4529
4530 /*
4531 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4532 * See ___update_load_avg() for details.
4533 */
4534 divider = get_pelt_divider(&cfs_rq->avg);
4535
4536 /* Set new sched_entity's utilization */
4537 se->avg.util_avg = gcfs_rq->avg.util_avg;
4538 new_sum = se->avg.util_avg * divider;
4539 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4540 se->avg.util_sum = new_sum;
4541
4542 /* Update parent cfs_rq utilization */
4543 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum);
4544 }
4545
4546 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4547 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4548 {
4549 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4550 u32 new_sum, divider;
4551
4552 /* Nothing to update */
4553 if (!delta_avg)
4554 return;
4555
4556 /*
4557 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4558 * See ___update_load_avg() for details.
4559 */
4560 divider = get_pelt_divider(&cfs_rq->avg);
4561
4562 /* Set new sched_entity's runnable */
4563 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4564 new_sum = se->avg.runnable_avg * divider;
4565 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4566 se->avg.runnable_sum = new_sum;
4567
4568 /* Update parent cfs_rq runnable */
4569 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum);
4570 }
4571
4572 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4573 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4574 {
4575 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4576 unsigned long load_avg;
4577 u64 load_sum = 0;
4578 s64 delta_sum;
4579 u32 divider;
4580
4581 if (!runnable_sum)
4582 return;
4583
4584 gcfs_rq->prop_runnable_sum = 0;
4585
4586 /*
4587 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4588 * See ___update_load_avg() for details.
4589 */
4590 divider = get_pelt_divider(&cfs_rq->avg);
4591
4592 if (runnable_sum >= 0) {
4593 /*
4594 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4595 * the CPU is saturated running == runnable.
4596 */
4597 runnable_sum += se->avg.load_sum;
4598 runnable_sum = min_t(long, runnable_sum, divider);
4599 } else {
4600 /*
4601 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4602 * assuming all tasks are equally runnable.
4603 */
4604 if (scale_load_down(gcfs_rq->load.weight)) {
4605 load_sum = div_u64(gcfs_rq->avg.load_sum,
4606 scale_load_down(gcfs_rq->load.weight));
4607 }
4608
4609 /* But make sure to not inflate se's runnable */
4610 runnable_sum = min(se->avg.load_sum, load_sum);
4611 }
4612
4613 /*
4614 * runnable_sum can't be lower than running_sum
4615 * Rescale running sum to be in the same range as runnable sum
4616 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4617 * runnable_sum is in [0 : LOAD_AVG_MAX]
4618 */
4619 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4620 runnable_sum = max(runnable_sum, running_sum);
4621
4622 load_sum = se_weight(se) * runnable_sum;
4623 load_avg = div_u64(load_sum, divider);
4624
4625 delta_avg = load_avg - se->avg.load_avg;
4626 if (!delta_avg)
4627 return;
4628
4629 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4630
4631 se->avg.load_sum = runnable_sum;
4632 se->avg.load_avg = load_avg;
4633 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum);
4634 }
4635
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4636 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4637 {
4638 cfs_rq->propagate = 1;
4639 cfs_rq->prop_runnable_sum += runnable_sum;
4640 }
4641
4642 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4643 static inline int propagate_entity_load_avg(struct sched_entity *se)
4644 {
4645 struct cfs_rq *cfs_rq, *gcfs_rq;
4646
4647 if (entity_is_task(se))
4648 return 0;
4649
4650 gcfs_rq = group_cfs_rq(se);
4651 if (!gcfs_rq->propagate)
4652 return 0;
4653
4654 gcfs_rq->propagate = 0;
4655
4656 cfs_rq = cfs_rq_of(se);
4657
4658 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4659
4660 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4661 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4662 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4663
4664 trace_pelt_cfs_tp(cfs_rq);
4665 trace_pelt_se_tp(se);
4666
4667 return 1;
4668 }
4669
4670 /*
4671 * Check if we need to update the load and the utilization of a blocked
4672 * group_entity:
4673 */
skip_blocked_update(struct sched_entity * se)4674 static inline bool skip_blocked_update(struct sched_entity *se)
4675 {
4676 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4677
4678 /*
4679 * If sched_entity still have not zero load or utilization, we have to
4680 * decay it:
4681 */
4682 if (se->avg.load_avg || se->avg.util_avg)
4683 return false;
4684
4685 /*
4686 * If there is a pending propagation, we have to update the load and
4687 * the utilization of the sched_entity:
4688 */
4689 if (gcfs_rq->propagate)
4690 return false;
4691
4692 /*
4693 * Otherwise, the load and the utilization of the sched_entity is
4694 * already zero and there is no pending propagation, so it will be a
4695 * waste of time to try to decay it:
4696 */
4697 return true;
4698 }
4699
4700 #else /* !CONFIG_FAIR_GROUP_SCHED: */
4701
update_tg_load_avg(struct cfs_rq * cfs_rq)4702 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4703
clear_tg_offline_cfs_rqs(struct rq * rq)4704 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4705
propagate_entity_load_avg(struct sched_entity * se)4706 static inline int propagate_entity_load_avg(struct sched_entity *se)
4707 {
4708 return 0;
4709 }
4710
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4711 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4712
4713 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4714
4715 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4716 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4717 {
4718 u64 throttled = 0, now, lut;
4719 struct cfs_rq *cfs_rq;
4720 struct rq *rq;
4721 bool is_idle;
4722
4723 if (load_avg_is_decayed(&se->avg))
4724 return;
4725
4726 cfs_rq = cfs_rq_of(se);
4727 rq = rq_of(cfs_rq);
4728
4729 rcu_read_lock();
4730 is_idle = is_idle_task(rcu_dereference_all(rq->curr));
4731 rcu_read_unlock();
4732
4733 /*
4734 * The lag estimation comes with a cost we don't want to pay all the
4735 * time. Hence, limiting to the case where the source CPU is idle and
4736 * we know we are at the greatest risk to have an outdated clock.
4737 */
4738 if (!is_idle)
4739 return;
4740
4741 /*
4742 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4743 *
4744 * last_update_time (the cfs_rq's last_update_time)
4745 * = cfs_rq_clock_pelt()@cfs_rq_idle
4746 * = rq_clock_pelt()@cfs_rq_idle
4747 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4748 *
4749 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4750 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4751 *
4752 * rq_idle_lag (delta between now and rq's update)
4753 * = sched_clock_cpu() - rq_clock()@rq_idle
4754 *
4755 * We can then write:
4756 *
4757 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4758 * sched_clock_cpu() - rq_clock()@rq_idle
4759 * Where:
4760 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4761 * rq_clock()@rq_idle is rq->clock_idle
4762 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4763 * is cfs_rq->throttled_pelt_idle
4764 */
4765
4766 #ifdef CONFIG_CFS_BANDWIDTH
4767 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4768 /* The clock has been stopped for throttling */
4769 if (throttled == U64_MAX)
4770 return;
4771 #endif
4772 now = u64_u32_load(rq->clock_pelt_idle);
4773 /*
4774 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4775 * is observed the old clock_pelt_idle value and the new clock_idle,
4776 * which lead to an underestimation. The opposite would lead to an
4777 * overestimation.
4778 */
4779 smp_rmb();
4780 lut = cfs_rq_last_update_time(cfs_rq);
4781
4782 now -= throttled;
4783 if (now < lut)
4784 /*
4785 * cfs_rq->avg.last_update_time is more recent than our
4786 * estimation, let's use it.
4787 */
4788 now = lut;
4789 else
4790 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4791
4792 __update_load_avg_blocked_se(now, se);
4793 }
4794 #else /* !CONFIG_NO_HZ_COMMON: */
migrate_se_pelt_lag(struct sched_entity * se)4795 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4796 #endif /* !CONFIG_NO_HZ_COMMON */
4797
4798 /**
4799 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4800 * @now: current time, as per cfs_rq_clock_pelt()
4801 * @cfs_rq: cfs_rq to update
4802 *
4803 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4804 * avg. The immediate corollary is that all (fair) tasks must be attached.
4805 *
4806 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4807 *
4808 * Return: true if the load decayed or we removed load.
4809 *
4810 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4811 * call update_tg_load_avg() when this function returns true.
4812 */
4813 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4814 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4815 {
4816 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4817 struct sched_avg *sa = &cfs_rq->avg;
4818 int decayed = 0;
4819
4820 if (cfs_rq->removed.nr) {
4821 unsigned long r;
4822 u32 divider = get_pelt_divider(&cfs_rq->avg);
4823
4824 raw_spin_lock(&cfs_rq->removed.lock);
4825 swap(cfs_rq->removed.util_avg, removed_util);
4826 swap(cfs_rq->removed.load_avg, removed_load);
4827 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4828 cfs_rq->removed.nr = 0;
4829 raw_spin_unlock(&cfs_rq->removed.lock);
4830
4831 r = removed_load;
4832 __update_sa(sa, load, -r, -r*divider);
4833
4834 r = removed_util;
4835 __update_sa(sa, util, -r, -r*divider);
4836
4837 r = removed_runnable;
4838 __update_sa(sa, runnable, -r, -r*divider);
4839
4840 /*
4841 * removed_runnable is the unweighted version of removed_load so we
4842 * can use it to estimate removed_load_sum.
4843 */
4844 add_tg_cfs_propagate(cfs_rq,
4845 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4846
4847 decayed = 1;
4848 }
4849
4850 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4851 u64_u32_store_copy(sa->last_update_time,
4852 cfs_rq->last_update_time_copy,
4853 sa->last_update_time);
4854 return decayed;
4855 }
4856
4857 /**
4858 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4859 * @cfs_rq: cfs_rq to attach to
4860 * @se: sched_entity to attach
4861 *
4862 * Must call update_cfs_rq_load_avg() before this, since we rely on
4863 * cfs_rq->avg.last_update_time being current.
4864 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4865 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4866 {
4867 /*
4868 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4869 * See ___update_load_avg() for details.
4870 */
4871 u32 divider = get_pelt_divider(&cfs_rq->avg);
4872
4873 /*
4874 * When we attach the @se to the @cfs_rq, we must align the decay
4875 * window because without that, really weird and wonderful things can
4876 * happen.
4877 *
4878 * XXX illustrate
4879 */
4880 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4881 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4882
4883 /*
4884 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4885 * period_contrib. This isn't strictly correct, but since we're
4886 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4887 * _sum a little.
4888 */
4889 se->avg.util_sum = se->avg.util_avg * divider;
4890
4891 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4892
4893 se->avg.load_sum = se->avg.load_avg * divider;
4894 if (se_weight(se) < se->avg.load_sum)
4895 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4896 else
4897 se->avg.load_sum = 1;
4898
4899 enqueue_load_avg(cfs_rq, se);
4900 cfs_rq->avg.util_avg += se->avg.util_avg;
4901 cfs_rq->avg.util_sum += se->avg.util_sum;
4902 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4903 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4904
4905 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4906
4907 cfs_rq_util_change(cfs_rq, 0);
4908
4909 trace_pelt_cfs_tp(cfs_rq);
4910 }
4911
4912 /**
4913 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4914 * @cfs_rq: cfs_rq to detach from
4915 * @se: sched_entity to detach
4916 *
4917 * Must call update_cfs_rq_load_avg() before this, since we rely on
4918 * cfs_rq->avg.last_update_time being current.
4919 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4920 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4921 {
4922 dequeue_load_avg(cfs_rq, se);
4923 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum);
4924 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum);
4925
4926 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4927
4928 cfs_rq_util_change(cfs_rq, 0);
4929
4930 trace_pelt_cfs_tp(cfs_rq);
4931 }
4932
4933 /*
4934 * Optional action to be done while updating the load average
4935 */
4936 #define UPDATE_TG 0x1
4937 #define SKIP_AGE_LOAD 0x2
4938 #define DO_ATTACH 0x4
4939 #define DO_DETACH 0x8
4940
4941 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4942 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4943 {
4944 u64 now = cfs_rq_clock_pelt(cfs_rq);
4945 int decayed;
4946
4947 /*
4948 * Track task load average for carrying it to new CPU after migrated, and
4949 * track group sched_entity load average for task_h_load calculation in migration
4950 */
4951 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4952 __update_load_avg_se(now, cfs_rq, se);
4953
4954 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4955 decayed |= propagate_entity_load_avg(se);
4956
4957 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4958
4959 /*
4960 * DO_ATTACH means we're here from enqueue_entity().
4961 * !last_update_time means we've passed through
4962 * migrate_task_rq_fair() indicating we migrated.
4963 *
4964 * IOW we're enqueueing a task on a new CPU.
4965 */
4966 attach_entity_load_avg(cfs_rq, se);
4967 update_tg_load_avg(cfs_rq);
4968
4969 } else if (flags & DO_DETACH) {
4970 /*
4971 * DO_DETACH means we're here from dequeue_entity()
4972 * and we are migrating task out of the CPU.
4973 */
4974 detach_entity_load_avg(cfs_rq, se);
4975 update_tg_load_avg(cfs_rq);
4976 } else if (decayed) {
4977 cfs_rq_util_change(cfs_rq, 0);
4978
4979 if (flags & UPDATE_TG)
4980 update_tg_load_avg(cfs_rq);
4981 }
4982 }
4983
4984 /*
4985 * Synchronize entity load avg of dequeued entity without locking
4986 * the previous rq.
4987 */
sync_entity_load_avg(struct sched_entity * se)4988 static void sync_entity_load_avg(struct sched_entity *se)
4989 {
4990 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4991 u64 last_update_time;
4992
4993 last_update_time = cfs_rq_last_update_time(cfs_rq);
4994 __update_load_avg_blocked_se(last_update_time, se);
4995 }
4996
4997 /*
4998 * Task first catches up with cfs_rq, and then subtract
4999 * itself from the cfs_rq (task must be off the queue now).
5000 */
remove_entity_load_avg(struct sched_entity * se)5001 static void remove_entity_load_avg(struct sched_entity *se)
5002 {
5003 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5004 unsigned long flags;
5005
5006 /*
5007 * tasks cannot exit without having gone through wake_up_new_task() ->
5008 * enqueue_task_fair() which will have added things to the cfs_rq,
5009 * so we can remove unconditionally.
5010 */
5011
5012 sync_entity_load_avg(se);
5013
5014 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
5015 ++cfs_rq->removed.nr;
5016 cfs_rq->removed.util_avg += se->avg.util_avg;
5017 cfs_rq->removed.load_avg += se->avg.load_avg;
5018 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
5019 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
5020 }
5021
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)5022 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
5023 {
5024 return cfs_rq->avg.runnable_avg;
5025 }
5026
cfs_rq_load_avg(struct cfs_rq * cfs_rq)5027 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
5028 {
5029 return cfs_rq->avg.load_avg;
5030 }
5031
5032 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
5033 __must_hold(__rq_lockp(this_rq));
5034
task_util(struct task_struct * p)5035 static inline unsigned long task_util(struct task_struct *p)
5036 {
5037 return READ_ONCE(p->se.avg.util_avg);
5038 }
5039
task_runnable(struct task_struct * p)5040 static inline unsigned long task_runnable(struct task_struct *p)
5041 {
5042 return READ_ONCE(p->se.avg.runnable_avg);
5043 }
5044
_task_util_est(struct task_struct * p)5045 static inline unsigned long _task_util_est(struct task_struct *p)
5046 {
5047 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
5048 }
5049
task_util_est(struct task_struct * p)5050 static inline unsigned long task_util_est(struct task_struct *p)
5051 {
5052 return max(task_util(p), _task_util_est(p));
5053 }
5054
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5055 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
5056 struct task_struct *p)
5057 {
5058 unsigned int enqueued;
5059
5060 if (!sched_feat(UTIL_EST))
5061 return;
5062
5063 /* Update root cfs_rq's estimated utilization */
5064 enqueued = cfs_rq->avg.util_est;
5065 enqueued += _task_util_est(p);
5066 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5067
5068 trace_sched_util_est_cfs_tp(cfs_rq);
5069 }
5070
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5071 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
5072 struct task_struct *p)
5073 {
5074 unsigned int enqueued;
5075
5076 if (!sched_feat(UTIL_EST))
5077 return;
5078
5079 /* Update root cfs_rq's estimated utilization */
5080 enqueued = cfs_rq->avg.util_est;
5081 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
5082 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
5083
5084 trace_sched_util_est_cfs_tp(cfs_rq);
5085 }
5086
5087 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
5088
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5089 static inline void util_est_update(struct cfs_rq *cfs_rq,
5090 struct task_struct *p,
5091 bool task_sleep)
5092 {
5093 unsigned int ewma, dequeued, last_ewma_diff;
5094
5095 if (!sched_feat(UTIL_EST))
5096 return;
5097
5098 /*
5099 * Skip update of task's estimated utilization when the task has not
5100 * yet completed an activation, e.g. being migrated.
5101 */
5102 if (!task_sleep)
5103 return;
5104
5105 /* Get current estimate of utilization */
5106 ewma = READ_ONCE(p->se.avg.util_est);
5107
5108 /*
5109 * If the PELT values haven't changed since enqueue time,
5110 * skip the util_est update.
5111 */
5112 if (ewma & UTIL_AVG_UNCHANGED)
5113 return;
5114
5115 /* Get utilization at dequeue */
5116 dequeued = task_util(p);
5117
5118 /*
5119 * Reset EWMA on utilization increases, the moving average is used only
5120 * to smooth utilization decreases.
5121 */
5122 if (ewma <= dequeued) {
5123 ewma = dequeued;
5124 goto done;
5125 }
5126
5127 /*
5128 * Skip update of task's estimated utilization when its members are
5129 * already ~1% close to its last activation value.
5130 */
5131 last_ewma_diff = ewma - dequeued;
5132 if (last_ewma_diff < UTIL_EST_MARGIN)
5133 goto done;
5134
5135 /*
5136 * To avoid underestimate of task utilization, skip updates of EWMA if
5137 * we cannot grant that thread got all CPU time it wanted.
5138 */
5139 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
5140 goto done;
5141
5142
5143 /*
5144 * Update Task's estimated utilization
5145 *
5146 * When *p completes an activation we can consolidate another sample
5147 * of the task size. This is done by using this value to update the
5148 * Exponential Weighted Moving Average (EWMA):
5149 *
5150 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
5151 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
5152 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
5153 * = w * ( -last_ewma_diff ) + ewma(t-1)
5154 * = w * (-last_ewma_diff + ewma(t-1) / w)
5155 *
5156 * Where 'w' is the weight of new samples, which is configured to be
5157 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
5158 */
5159 ewma <<= UTIL_EST_WEIGHT_SHIFT;
5160 ewma -= last_ewma_diff;
5161 ewma >>= UTIL_EST_WEIGHT_SHIFT;
5162 done:
5163 ewma |= UTIL_AVG_UNCHANGED;
5164 WRITE_ONCE(p->se.avg.util_est, ewma);
5165
5166 trace_sched_util_est_se_tp(&p->se);
5167 }
5168
get_actual_cpu_capacity(int cpu)5169 static inline unsigned long get_actual_cpu_capacity(int cpu)
5170 {
5171 unsigned long capacity = arch_scale_cpu_capacity(cpu);
5172
5173 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
5174
5175 return capacity;
5176 }
5177
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)5178 static inline int util_fits_cpu(unsigned long util,
5179 unsigned long uclamp_min,
5180 unsigned long uclamp_max,
5181 int cpu)
5182 {
5183 unsigned long capacity = capacity_of(cpu);
5184 unsigned long capacity_orig;
5185 bool fits, uclamp_max_fits;
5186
5187 /*
5188 * Check if the real util fits without any uclamp boost/cap applied.
5189 */
5190 fits = fits_capacity(util, capacity);
5191
5192 if (!uclamp_is_used())
5193 return fits;
5194
5195 /*
5196 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
5197 * uclamp_max. We only care about capacity pressure (by using
5198 * capacity_of()) for comparing against the real util.
5199 *
5200 * If a task is boosted to 1024 for example, we don't want a tiny
5201 * pressure to skew the check whether it fits a CPU or not.
5202 *
5203 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
5204 * should fit a little cpu even if there's some pressure.
5205 *
5206 * Only exception is for HW or cpufreq pressure since it has a direct impact
5207 * on available OPP of the system.
5208 *
5209 * We honour it for uclamp_min only as a drop in performance level
5210 * could result in not getting the requested minimum performance level.
5211 *
5212 * For uclamp_max, we can tolerate a drop in performance level as the
5213 * goal is to cap the task. So it's okay if it's getting less.
5214 */
5215 capacity_orig = arch_scale_cpu_capacity(cpu);
5216
5217 /*
5218 * We want to force a task to fit a cpu as implied by uclamp_max.
5219 * But we do have some corner cases to cater for..
5220 *
5221 *
5222 * C=z
5223 * | ___
5224 * | C=y | |
5225 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5226 * | C=x | | | |
5227 * | ___ | | | |
5228 * | | | | | | | (util somewhere in this region)
5229 * | | | | | | |
5230 * | | | | | | |
5231 * +----------------------------------------
5232 * CPU0 CPU1 CPU2
5233 *
5234 * In the above example if a task is capped to a specific performance
5235 * point, y, then when:
5236 *
5237 * * util = 80% of x then it does not fit on CPU0 and should migrate
5238 * to CPU1
5239 * * util = 80% of y then it is forced to fit on CPU1 to honour
5240 * uclamp_max request.
5241 *
5242 * which is what we're enforcing here. A task always fits if
5243 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
5244 * the normal upmigration rules should withhold still.
5245 *
5246 * Only exception is when we are on max capacity, then we need to be
5247 * careful not to block overutilized state. This is so because:
5248 *
5249 * 1. There's no concept of capping at max_capacity! We can't go
5250 * beyond this performance level anyway.
5251 * 2. The system is being saturated when we're operating near
5252 * max capacity, it doesn't make sense to block overutilized.
5253 */
5254 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5255 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5256 fits = fits || uclamp_max_fits;
5257
5258 /*
5259 *
5260 * C=z
5261 * | ___ (region a, capped, util >= uclamp_max)
5262 * | C=y | |
5263 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5264 * | C=x | | | |
5265 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
5266 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5267 * | | | | | | |
5268 * | | | | | | | (region c, boosted, util < uclamp_min)
5269 * +----------------------------------------
5270 * CPU0 CPU1 CPU2
5271 *
5272 * a) If util > uclamp_max, then we're capped, we don't care about
5273 * actual fitness value here. We only care if uclamp_max fits
5274 * capacity without taking margin/pressure into account.
5275 * See comment above.
5276 *
5277 * b) If uclamp_min <= util <= uclamp_max, then the normal
5278 * fits_capacity() rules apply. Except we need to ensure that we
5279 * enforce we remain within uclamp_max, see comment above.
5280 *
5281 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5282 * need to take into account the boosted value fits the CPU without
5283 * taking margin/pressure into account.
5284 *
5285 * Cases (a) and (b) are handled in the 'fits' variable already. We
5286 * just need to consider an extra check for case (c) after ensuring we
5287 * handle the case uclamp_min > uclamp_max.
5288 */
5289 uclamp_min = min(uclamp_min, uclamp_max);
5290 if (fits && (util < uclamp_min) &&
5291 (uclamp_min > get_actual_cpu_capacity(cpu)))
5292 return -1;
5293
5294 return fits;
5295 }
5296
task_fits_cpu(struct task_struct * p,int cpu)5297 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5298 {
5299 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5300 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5301 unsigned long util = task_util_est(p);
5302 /*
5303 * Return true only if the cpu fully fits the task requirements, which
5304 * include the utilization but also the performance hints.
5305 */
5306 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5307 }
5308
update_misfit_status(struct task_struct * p,struct rq * rq)5309 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5310 {
5311 int cpu = cpu_of(rq);
5312
5313 if (!sched_asym_cpucap_active())
5314 return;
5315
5316 /*
5317 * Affinity allows us to go somewhere higher? Or are we on biggest
5318 * available CPU already? Or do we fit into this CPU ?
5319 */
5320 if (!p || (p->nr_cpus_allowed == 1) ||
5321 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5322 task_fits_cpu(p, cpu)) {
5323
5324 rq->misfit_task_load = 0;
5325 return;
5326 }
5327
5328 /*
5329 * Make sure that misfit_task_load will not be null even if
5330 * task_h_load() returns 0.
5331 */
5332 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5333 }
5334
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)5335 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5336 {
5337 struct sched_entity *se = &p->se;
5338
5339 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5340 if (attr->sched_runtime) {
5341 se->custom_slice = 1;
5342 se->slice = clamp_t(u64, attr->sched_runtime,
5343 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */
5344 NSEC_PER_MSEC*100); /* HZ=100 / 10 */
5345 } else {
5346 se->custom_slice = 0;
5347 se->slice = sysctl_sched_base_slice;
5348 }
5349 }
5350
5351 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5352 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5353 {
5354 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5355 bool update_zero = false;
5356 s64 lag = 0;
5357
5358 if (!se->custom_slice)
5359 se->slice = sysctl_sched_base_slice;
5360 vslice = calc_delta_fair(se->slice, se);
5361
5362 /*
5363 * Due to how V is constructed as the weighted average of entities,
5364 * adding tasks with positive lag, or removing tasks with negative lag
5365 * will move 'time' backwards, this can screw around with the lag of
5366 * other tasks.
5367 *
5368 * EEVDF: placement strategy #1 / #2
5369 */
5370 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5371 struct sched_entity *curr = cfs_rq->curr;
5372 long load, weight;
5373
5374 lag = se->vlag;
5375
5376 /*
5377 * If we want to place a task and preserve lag, we have to
5378 * consider the effect of the new entity on the weighted
5379 * average and compensate for this, otherwise lag can quickly
5380 * evaporate.
5381 *
5382 * Lag is defined as:
5383 *
5384 * lag_i = S - s_i = w_i * (V - v_i)
5385 *
5386 * To avoid the 'w_i' term all over the place, we only track
5387 * the virtual lag:
5388 *
5389 * vl_i = V - v_i <=> v_i = V - vl_i
5390 *
5391 * And we take V to be the weighted average of all v:
5392 *
5393 * V = (\Sum w_j*v_j) / W
5394 *
5395 * Where W is: \Sum w_j
5396 *
5397 * Then, the weighted average after adding an entity with lag
5398 * vl_i is given by:
5399 *
5400 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5401 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5402 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5403 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
5404 * = V - w_i*vl_i / (W + w_i)
5405 *
5406 * And the actual lag after adding an entity with vl_i is:
5407 *
5408 * vl'_i = V' - v_i
5409 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5410 * = vl_i - w_i*vl_i / (W + w_i)
5411 *
5412 * Which is strictly less than vl_i. So in order to preserve lag
5413 * we should inflate the lag before placement such that the
5414 * effective lag after placement comes out right.
5415 *
5416 * As such, invert the above relation for vl'_i to get the vl_i
5417 * we need to use such that the lag after placement is the lag
5418 * we computed before dequeue.
5419 *
5420 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5421 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5422 *
5423 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5424 * = W*vl_i
5425 *
5426 * vl_i = (W + w_i)*vl'_i / W
5427 */
5428 load = cfs_rq->sum_weight;
5429 if (curr && curr->on_rq)
5430 load += avg_vruntime_weight(cfs_rq, curr->load.weight);
5431
5432 weight = avg_vruntime_weight(cfs_rq, se->load.weight);
5433 lag *= load + weight;
5434 if (WARN_ON_ONCE(!load))
5435 load = 1;
5436 lag = div64_long(lag, load);
5437
5438 /*
5439 * A heavy entity (relative to the tree) will pull the
5440 * avg_vruntime close to its vruntime position on enqueue. But
5441 * the zero_vruntime point is only updated at the next
5442 * update_deadline()/place_entity()/update_entity_lag().
5443 *
5444 * Specifically (see the comment near avg_vruntime_weight()):
5445 *
5446 * sum_w_vruntime = \Sum (v_i - v0) * w_i
5447 *
5448 * Note that if v0 is near a light entity, both terms will be
5449 * small for the light entity, while in that case both terms
5450 * are large for the heavy entity, leading to risk of
5451 * overflow.
5452 *
5453 * OTOH if v0 is near the heavy entity, then the difference is
5454 * larger for the light entity, but the factor is small, while
5455 * for the heavy entity the difference is small but the factor
5456 * is large. Avoiding the multiplication overflow.
5457 */
5458 if (weight > load)
5459 update_zero = true;
5460 }
5461
5462 se->vruntime = vruntime - lag;
5463
5464 if (update_zero)
5465 update_zero_vruntime(cfs_rq, -lag);
5466
5467 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) {
5468 se->deadline += se->vruntime;
5469 se->rel_deadline = 0;
5470 return;
5471 }
5472
5473 /*
5474 * When joining the competition; the existing tasks will be,
5475 * on average, halfway through their slice, as such start tasks
5476 * off with half a slice to ease into the competition.
5477 */
5478 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5479 vslice /= 2;
5480
5481 /*
5482 * EEVDF: vd_i = ve_i + r_i/w_i
5483 */
5484 se->deadline = se->vruntime + vslice;
5485 }
5486
5487 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5488 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5489
5490 static void
5491 requeue_delayed_entity(struct sched_entity *se);
5492
5493 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5494 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5495 {
5496 bool curr = cfs_rq->curr == se;
5497
5498 /*
5499 * If we're the current task, we must renormalise before calling
5500 * update_curr().
5501 */
5502 if (curr)
5503 place_entity(cfs_rq, se, flags);
5504
5505 update_curr(cfs_rq);
5506
5507 /*
5508 * When enqueuing a sched_entity, we must:
5509 * - Update loads to have both entity and cfs_rq synced with now.
5510 * - For group_entity, update its runnable_weight to reflect the new
5511 * h_nr_runnable of its group cfs_rq.
5512 * - For group_entity, update its weight to reflect the new share of
5513 * its group cfs_rq
5514 * - Add its new weight to cfs_rq->load.weight
5515 */
5516 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5517 se_update_runnable(se);
5518 /*
5519 * XXX update_load_avg() above will have attached us to the pelt sum;
5520 * but update_cfs_group() here will re-adjust the weight and have to
5521 * undo/redo all that. Seems wasteful.
5522 */
5523 update_cfs_group(se);
5524
5525 /*
5526 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5527 * we can place the entity.
5528 */
5529 if (!curr)
5530 place_entity(cfs_rq, se, flags);
5531
5532 account_entity_enqueue(cfs_rq, se);
5533
5534 /* Entity has migrated, no longer consider this task hot */
5535 if (flags & ENQUEUE_MIGRATED)
5536 se->exec_start = 0;
5537
5538 check_schedstat_required();
5539 update_stats_enqueue_fair(cfs_rq, se, flags);
5540 if (!curr)
5541 __enqueue_entity(cfs_rq, se);
5542 se->on_rq = 1;
5543
5544 if (cfs_rq->nr_queued == 1) {
5545 check_enqueue_throttle(cfs_rq);
5546 list_add_leaf_cfs_rq(cfs_rq);
5547 #ifdef CONFIG_CFS_BANDWIDTH
5548 if (cfs_rq->pelt_clock_throttled) {
5549 struct rq *rq = rq_of(cfs_rq);
5550
5551 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5552 cfs_rq->throttled_clock_pelt;
5553 cfs_rq->pelt_clock_throttled = 0;
5554 }
5555 #endif
5556 }
5557 }
5558
__clear_buddies_next(struct sched_entity * se)5559 static void __clear_buddies_next(struct sched_entity *se)
5560 {
5561 for_each_sched_entity(se) {
5562 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5563 if (cfs_rq->next != se)
5564 break;
5565
5566 cfs_rq->next = NULL;
5567 }
5568 }
5569
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5570 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5571 {
5572 if (cfs_rq->next == se)
5573 __clear_buddies_next(se);
5574 }
5575
5576 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5577
set_delayed(struct sched_entity * se)5578 static void set_delayed(struct sched_entity *se)
5579 {
5580 se->sched_delayed = 1;
5581
5582 /*
5583 * Delayed se of cfs_rq have no tasks queued on them.
5584 * Do not adjust h_nr_runnable since dequeue_entities()
5585 * will account it for blocked tasks.
5586 */
5587 if (!entity_is_task(se))
5588 return;
5589
5590 for_each_sched_entity(se) {
5591 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5592
5593 cfs_rq->h_nr_runnable--;
5594 }
5595 }
5596
clear_delayed(struct sched_entity * se)5597 static void clear_delayed(struct sched_entity *se)
5598 {
5599 se->sched_delayed = 0;
5600
5601 /*
5602 * Delayed se of cfs_rq have no tasks queued on them.
5603 * Do not adjust h_nr_runnable since a dequeue has
5604 * already accounted for it or an enqueue of a task
5605 * below it will account for it in enqueue_task_fair().
5606 */
5607 if (!entity_is_task(se))
5608 return;
5609
5610 for_each_sched_entity(se) {
5611 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5612
5613 cfs_rq->h_nr_runnable++;
5614 }
5615 }
5616
5617 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5618 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5619 {
5620 bool sleep = flags & DEQUEUE_SLEEP;
5621 int action = UPDATE_TG;
5622
5623 update_curr(cfs_rq);
5624 clear_buddies(cfs_rq, se);
5625
5626 if (flags & DEQUEUE_DELAYED) {
5627 WARN_ON_ONCE(!se->sched_delayed);
5628 } else {
5629 bool delay = sleep;
5630 /*
5631 * DELAY_DEQUEUE relies on spurious wakeups, special task
5632 * states must not suffer spurious wakeups, excempt them.
5633 */
5634 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
5635 delay = false;
5636
5637 WARN_ON_ONCE(delay && se->sched_delayed);
5638
5639 if (sched_feat(DELAY_DEQUEUE) && delay &&
5640 !entity_eligible(cfs_rq, se)) {
5641 update_load_avg(cfs_rq, se, 0);
5642 update_entity_lag(cfs_rq, se);
5643 set_delayed(se);
5644 return false;
5645 }
5646 }
5647
5648 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5649 action |= DO_DETACH;
5650
5651 /*
5652 * When dequeuing a sched_entity, we must:
5653 * - Update loads to have both entity and cfs_rq synced with now.
5654 * - For group_entity, update its runnable_weight to reflect the new
5655 * h_nr_runnable of its group cfs_rq.
5656 * - Subtract its previous weight from cfs_rq->load.weight.
5657 * - For group entity, update its weight to reflect the new share
5658 * of its group cfs_rq.
5659 */
5660 update_load_avg(cfs_rq, se, action);
5661 se_update_runnable(se);
5662
5663 update_stats_dequeue_fair(cfs_rq, se, flags);
5664
5665 update_entity_lag(cfs_rq, se);
5666 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5667 se->deadline -= se->vruntime;
5668 se->rel_deadline = 1;
5669 }
5670
5671 if (se != cfs_rq->curr)
5672 __dequeue_entity(cfs_rq, se);
5673 se->on_rq = 0;
5674 account_entity_dequeue(cfs_rq, se);
5675
5676 /* return excess runtime on last dequeue */
5677 return_cfs_rq_runtime(cfs_rq);
5678
5679 update_cfs_group(se);
5680
5681 if (flags & DEQUEUE_DELAYED)
5682 clear_delayed(se);
5683
5684 if (cfs_rq->nr_queued == 0) {
5685 update_idle_cfs_rq_clock_pelt(cfs_rq);
5686 #ifdef CONFIG_CFS_BANDWIDTH
5687 if (throttled_hierarchy(cfs_rq)) {
5688 struct rq *rq = rq_of(cfs_rq);
5689
5690 list_del_leaf_cfs_rq(cfs_rq);
5691 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5692 cfs_rq->pelt_clock_throttled = 1;
5693 }
5694 #endif
5695 }
5696
5697 return true;
5698 }
5699
5700 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,bool first)5701 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, bool first)
5702 {
5703 clear_buddies(cfs_rq, se);
5704
5705 /* 'current' is not kept within the tree. */
5706 if (se->on_rq) {
5707 /*
5708 * Any task has to be enqueued before it get to execute on
5709 * a CPU. So account for the time it spent waiting on the
5710 * runqueue.
5711 */
5712 update_stats_wait_end_fair(cfs_rq, se);
5713 __dequeue_entity(cfs_rq, se);
5714 update_load_avg(cfs_rq, se, UPDATE_TG);
5715
5716 if (first)
5717 set_protect_slice(cfs_rq, se);
5718 }
5719
5720 update_stats_curr_start(cfs_rq, se);
5721 WARN_ON_ONCE(cfs_rq->curr);
5722 cfs_rq->curr = se;
5723
5724 /*
5725 * Track our maximum slice length, if the CPU's load is at
5726 * least twice that of our own weight (i.e. don't track it
5727 * when there are only lesser-weight tasks around):
5728 */
5729 if (schedstat_enabled() &&
5730 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5731 struct sched_statistics *stats;
5732
5733 stats = __schedstats_from_se(se);
5734 __schedstat_set(stats->slice_max,
5735 max((u64)stats->slice_max,
5736 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5737 }
5738
5739 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5740 }
5741
5742 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5743
5744 /*
5745 * Pick the next process, keeping these things in mind, in this order:
5746 * 1) keep things fair between processes/task groups
5747 * 2) pick the "next" process, since someone really wants that to run
5748 * 3) pick the "last" process, for cache locality
5749 * 4) do not run the "skip" process, if something else is available
5750 */
5751 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5752 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5753 {
5754 struct sched_entity *se;
5755
5756 se = pick_eevdf(cfs_rq);
5757 if (se->sched_delayed) {
5758 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5759 /*
5760 * Must not reference @se again, see __block_task().
5761 */
5762 return NULL;
5763 }
5764 return se;
5765 }
5766
5767 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5768
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5769 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5770 {
5771 /*
5772 * If still on the runqueue then deactivate_task()
5773 * was not called and update_curr() has to be done:
5774 */
5775 if (prev->on_rq)
5776 update_curr(cfs_rq);
5777
5778 /* throttle cfs_rqs exceeding runtime */
5779 check_cfs_rq_runtime(cfs_rq);
5780
5781 if (prev->on_rq) {
5782 update_stats_wait_start_fair(cfs_rq, prev);
5783 /* Put 'current' back into the tree. */
5784 __enqueue_entity(cfs_rq, prev);
5785 /* in !on_rq case, update occurred at dequeue */
5786 update_load_avg(cfs_rq, prev, 0);
5787 }
5788 WARN_ON_ONCE(cfs_rq->curr != prev);
5789 cfs_rq->curr = NULL;
5790 }
5791
5792 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5793 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5794 {
5795 /*
5796 * Update run-time statistics of the 'current'.
5797 */
5798 update_curr(cfs_rq);
5799
5800 /*
5801 * Ensure that runnable average is periodically updated.
5802 */
5803 update_load_avg(cfs_rq, curr, UPDATE_TG);
5804 update_cfs_group(curr);
5805
5806 #ifdef CONFIG_SCHED_HRTICK
5807 /*
5808 * queued ticks are scheduled to match the slice, so don't bother
5809 * validating it and just reschedule.
5810 */
5811 if (queued) {
5812 resched_curr(rq_of(cfs_rq));
5813 return;
5814 }
5815 #endif
5816 }
5817
5818
5819 /**************************************************
5820 * CFS bandwidth control machinery
5821 */
5822
5823 #ifdef CONFIG_CFS_BANDWIDTH
5824
5825 #ifdef CONFIG_JUMP_LABEL
5826 static struct static_key __cfs_bandwidth_used;
5827
cfs_bandwidth_used(void)5828 static inline bool cfs_bandwidth_used(void)
5829 {
5830 return static_key_false(&__cfs_bandwidth_used);
5831 }
5832
cfs_bandwidth_usage_inc(void)5833 void cfs_bandwidth_usage_inc(void)
5834 {
5835 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5836 }
5837
cfs_bandwidth_usage_dec(void)5838 void cfs_bandwidth_usage_dec(void)
5839 {
5840 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5841 }
5842 #else /* !CONFIG_JUMP_LABEL: */
cfs_bandwidth_used(void)5843 static bool cfs_bandwidth_used(void)
5844 {
5845 return true;
5846 }
5847
cfs_bandwidth_usage_inc(void)5848 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5849 void cfs_bandwidth_usage_dec(void) {}
5850 #endif /* !CONFIG_JUMP_LABEL */
5851
sched_cfs_bandwidth_slice(void)5852 static inline u64 sched_cfs_bandwidth_slice(void)
5853 {
5854 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5855 }
5856
5857 /*
5858 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5859 * directly instead of rq->clock to avoid adding additional synchronization
5860 * around rq->lock.
5861 *
5862 * requires cfs_b->lock
5863 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5864 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5865 {
5866 s64 runtime;
5867
5868 if (unlikely(cfs_b->quota == RUNTIME_INF))
5869 return;
5870
5871 cfs_b->runtime += cfs_b->quota;
5872 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5873 if (runtime > 0) {
5874 cfs_b->burst_time += runtime;
5875 cfs_b->nr_burst++;
5876 }
5877
5878 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5879 cfs_b->runtime_snap = cfs_b->runtime;
5880 }
5881
tg_cfs_bandwidth(struct task_group * tg)5882 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5883 {
5884 return &tg->cfs_bandwidth;
5885 }
5886
5887 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5888 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5889 struct cfs_rq *cfs_rq, u64 target_runtime)
5890 {
5891 u64 min_amount, amount = 0;
5892
5893 lockdep_assert_held(&cfs_b->lock);
5894
5895 /* note: this is a positive sum as runtime_remaining <= 0 */
5896 min_amount = target_runtime - cfs_rq->runtime_remaining;
5897
5898 if (cfs_b->quota == RUNTIME_INF)
5899 amount = min_amount;
5900 else {
5901 start_cfs_bandwidth(cfs_b);
5902
5903 if (cfs_b->runtime > 0) {
5904 amount = min(cfs_b->runtime, min_amount);
5905 cfs_b->runtime -= amount;
5906 cfs_b->idle = 0;
5907 }
5908 }
5909
5910 cfs_rq->runtime_remaining += amount;
5911
5912 return cfs_rq->runtime_remaining > 0;
5913 }
5914
5915 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5916 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5917 {
5918 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5919 int ret;
5920
5921 raw_spin_lock(&cfs_b->lock);
5922 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5923 raw_spin_unlock(&cfs_b->lock);
5924
5925 return ret;
5926 }
5927
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5928 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5929 {
5930 /* dock delta_exec before expiring quota (as it could span periods) */
5931 cfs_rq->runtime_remaining -= delta_exec;
5932
5933 if (likely(cfs_rq->runtime_remaining > 0))
5934 return;
5935
5936 if (cfs_rq->throttled)
5937 return;
5938 /*
5939 * if we're unable to extend our runtime we resched so that the active
5940 * hierarchy can be throttled
5941 */
5942 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5943 resched_curr(rq_of(cfs_rq));
5944 }
5945
5946 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5947 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5948 {
5949 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5950 return;
5951
5952 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5953 }
5954
cfs_rq_throttled(struct cfs_rq * cfs_rq)5955 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5956 {
5957 return cfs_bandwidth_used() && cfs_rq->throttled;
5958 }
5959
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)5960 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
5961 {
5962 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
5963 }
5964
5965 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5966 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5967 {
5968 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5969 }
5970
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)5971 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
5972 {
5973 return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]);
5974 }
5975
task_is_throttled(struct task_struct * p)5976 static inline bool task_is_throttled(struct task_struct *p)
5977 {
5978 return cfs_bandwidth_used() && p->throttled;
5979 }
5980
5981 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
throttle_cfs_rq_work(struct callback_head * work)5982 static void throttle_cfs_rq_work(struct callback_head *work)
5983 {
5984 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
5985 struct sched_entity *se;
5986 struct cfs_rq *cfs_rq;
5987 struct rq *rq;
5988
5989 WARN_ON_ONCE(p != current);
5990 p->sched_throttle_work.next = &p->sched_throttle_work;
5991
5992 /*
5993 * If task is exiting, then there won't be a return to userspace, so we
5994 * don't have to bother with any of this.
5995 */
5996 if ((p->flags & PF_EXITING))
5997 return;
5998
5999 scoped_guard(task_rq_lock, p) {
6000 se = &p->se;
6001 cfs_rq = cfs_rq_of(se);
6002
6003 /* Raced, forget */
6004 if (p->sched_class != &fair_sched_class)
6005 return;
6006
6007 /*
6008 * If not in limbo, then either replenish has happened or this
6009 * task got migrated out of the throttled cfs_rq, move along.
6010 */
6011 if (!cfs_rq->throttle_count)
6012 return;
6013 rq = scope.rq;
6014 update_rq_clock(rq);
6015 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
6016 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
6017 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6018 /*
6019 * Must not set throttled before dequeue or dequeue will
6020 * mistakenly regard this task as an already throttled one.
6021 */
6022 p->throttled = true;
6023 resched_curr(rq);
6024 }
6025 }
6026
init_cfs_throttle_work(struct task_struct * p)6027 void init_cfs_throttle_work(struct task_struct *p)
6028 {
6029 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
6030 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
6031 p->sched_throttle_work.next = &p->sched_throttle_work;
6032 INIT_LIST_HEAD(&p->throttle_node);
6033 }
6034
6035 /*
6036 * Task is throttled and someone wants to dequeue it again:
6037 * it could be sched/core when core needs to do things like
6038 * task affinity change, task group change, task sched class
6039 * change etc. and in these cases, DEQUEUE_SLEEP is not set;
6040 * or the task is blocked after throttled due to freezer etc.
6041 * and in these cases, DEQUEUE_SLEEP is set.
6042 */
6043 static void detach_task_cfs_rq(struct task_struct *p);
dequeue_throttled_task(struct task_struct * p,int flags)6044 static void dequeue_throttled_task(struct task_struct *p, int flags)
6045 {
6046 WARN_ON_ONCE(p->se.on_rq);
6047 list_del_init(&p->throttle_node);
6048
6049 /* task blocked after throttled */
6050 if (flags & DEQUEUE_SLEEP) {
6051 p->throttled = false;
6052 return;
6053 }
6054
6055 /*
6056 * task is migrating off its old cfs_rq, detach
6057 * the task's load from its old cfs_rq.
6058 */
6059 if (task_on_rq_migrating(p))
6060 detach_task_cfs_rq(p);
6061 }
6062
enqueue_throttled_task(struct task_struct * p)6063 static bool enqueue_throttled_task(struct task_struct *p)
6064 {
6065 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
6066
6067 /* @p should have gone through dequeue_throttled_task() first */
6068 WARN_ON_ONCE(!list_empty(&p->throttle_node));
6069
6070 /*
6071 * If the throttled task @p is enqueued to a throttled cfs_rq,
6072 * take the fast path by directly putting the task on the
6073 * target cfs_rq's limbo list.
6074 *
6075 * Do not do that when @p is current because the following race can
6076 * cause @p's group_node to be incorectly re-insterted in its rq's
6077 * cfs_tasks list, despite being throttled:
6078 *
6079 * cpuX cpuY
6080 * p ret2user
6081 * throttle_cfs_rq_work() sched_move_task(p)
6082 * LOCK task_rq_lock
6083 * dequeue_task_fair(p)
6084 * UNLOCK task_rq_lock
6085 * LOCK task_rq_lock
6086 * task_current_donor(p) == true
6087 * task_on_rq_queued(p) == true
6088 * dequeue_task(p)
6089 * put_prev_task(p)
6090 * sched_change_group()
6091 * enqueue_task(p) -> p's new cfs_rq
6092 * is throttled, go
6093 * fast path and skip
6094 * actual enqueue
6095 * set_next_task(p)
6096 * list_move(&se->group_node, &rq->cfs_tasks); // bug
6097 * schedule()
6098 *
6099 * In the above race case, @p current cfs_rq is in the same rq as
6100 * its previous cfs_rq because sched_move_task() only moves a task
6101 * to a different group from the same rq, so we can use its current
6102 * cfs_rq to derive rq and test if the task is current.
6103 */
6104 if (throttled_hierarchy(cfs_rq) &&
6105 !task_current_donor(rq_of(cfs_rq), p)) {
6106 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
6107 return true;
6108 }
6109
6110 /* we can't take the fast path, do an actual enqueue*/
6111 p->throttled = false;
6112 return false;
6113 }
6114
6115 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
tg_unthrottle_up(struct task_group * tg,void * data)6116 static int tg_unthrottle_up(struct task_group *tg, void *data)
6117 {
6118 struct rq *rq = data;
6119 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6120 struct task_struct *p, *tmp;
6121
6122 if (--cfs_rq->throttle_count)
6123 return 0;
6124
6125 if (cfs_rq->pelt_clock_throttled) {
6126 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
6127 cfs_rq->throttled_clock_pelt;
6128 cfs_rq->pelt_clock_throttled = 0;
6129 }
6130
6131 if (cfs_rq->throttled_clock_self) {
6132 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
6133
6134 cfs_rq->throttled_clock_self = 0;
6135
6136 if (WARN_ON_ONCE((s64)delta < 0))
6137 delta = 0;
6138
6139 cfs_rq->throttled_clock_self_time += delta;
6140 }
6141
6142 /* Re-enqueue the tasks that have been throttled at this level. */
6143 list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) {
6144 list_del_init(&p->throttle_node);
6145 p->throttled = false;
6146 enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP);
6147 }
6148
6149 /* Add cfs_rq with load or one or more already running entities to the list */
6150 if (!cfs_rq_is_decayed(cfs_rq))
6151 list_add_leaf_cfs_rq(cfs_rq);
6152
6153 return 0;
6154 }
6155
task_has_throttle_work(struct task_struct * p)6156 static inline bool task_has_throttle_work(struct task_struct *p)
6157 {
6158 return p->sched_throttle_work.next != &p->sched_throttle_work;
6159 }
6160
task_throttle_setup_work(struct task_struct * p)6161 static inline void task_throttle_setup_work(struct task_struct *p)
6162 {
6163 if (task_has_throttle_work(p))
6164 return;
6165
6166 /*
6167 * Kthreads and exiting tasks don't return to userspace, so adding the
6168 * work is pointless
6169 */
6170 if ((p->flags & (PF_EXITING | PF_KTHREAD)))
6171 return;
6172
6173 task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
6174 }
6175
record_throttle_clock(struct cfs_rq * cfs_rq)6176 static void record_throttle_clock(struct cfs_rq *cfs_rq)
6177 {
6178 struct rq *rq = rq_of(cfs_rq);
6179
6180 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
6181 cfs_rq->throttled_clock = rq_clock(rq);
6182
6183 if (!cfs_rq->throttled_clock_self)
6184 cfs_rq->throttled_clock_self = rq_clock(rq);
6185 }
6186
tg_throttle_down(struct task_group * tg,void * data)6187 static int tg_throttle_down(struct task_group *tg, void *data)
6188 {
6189 struct rq *rq = data;
6190 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6191
6192 if (cfs_rq->throttle_count++)
6193 return 0;
6194
6195 /*
6196 * For cfs_rqs that still have entities enqueued, PELT clock
6197 * stop happens at dequeue time when all entities are dequeued.
6198 */
6199 if (!cfs_rq->nr_queued) {
6200 list_del_leaf_cfs_rq(cfs_rq);
6201 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
6202 cfs_rq->pelt_clock_throttled = 1;
6203 }
6204
6205 WARN_ON_ONCE(cfs_rq->throttled_clock_self);
6206 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
6207 return 0;
6208 }
6209
throttle_cfs_rq(struct cfs_rq * cfs_rq)6210 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
6211 {
6212 struct rq *rq = rq_of(cfs_rq);
6213 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6214 int dequeue = 1;
6215
6216 raw_spin_lock(&cfs_b->lock);
6217 /* This will start the period timer if necessary */
6218 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
6219 /*
6220 * We have raced with bandwidth becoming available, and if we
6221 * actually throttled the timer might not unthrottle us for an
6222 * entire period. We additionally needed to make sure that any
6223 * subsequent check_cfs_rq_runtime calls agree not to throttle
6224 * us, as we may commit to do cfs put_prev+pick_next, so we ask
6225 * for 1ns of runtime rather than just check cfs_b.
6226 */
6227 dequeue = 0;
6228 } else {
6229 list_add_tail_rcu(&cfs_rq->throttled_list,
6230 &cfs_b->throttled_cfs_rq);
6231 }
6232 raw_spin_unlock(&cfs_b->lock);
6233
6234 if (!dequeue)
6235 return false; /* Throttle no longer required. */
6236
6237 /* freeze hierarchy runnable averages while throttled */
6238 rcu_read_lock();
6239 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
6240 rcu_read_unlock();
6241
6242 /*
6243 * Note: distribution will already see us throttled via the
6244 * throttled-list. rq->lock protects completion.
6245 */
6246 cfs_rq->throttled = 1;
6247 WARN_ON_ONCE(cfs_rq->throttled_clock);
6248 return true;
6249 }
6250
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)6251 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
6252 {
6253 struct rq *rq = rq_of(cfs_rq);
6254 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6255 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
6256
6257 /*
6258 * It's possible we are called with runtime_remaining < 0 due to things
6259 * like async unthrottled us with a positive runtime_remaining but other
6260 * still running entities consumed those runtime before we reached here.
6261 *
6262 * We can't unthrottle this cfs_rq without any runtime remaining because
6263 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
6264 * which is not supposed to happen on unthrottle path.
6265 */
6266 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
6267 return;
6268
6269 cfs_rq->throttled = 0;
6270
6271 update_rq_clock(rq);
6272
6273 raw_spin_lock(&cfs_b->lock);
6274 if (cfs_rq->throttled_clock) {
6275 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6276 cfs_rq->throttled_clock = 0;
6277 }
6278 list_del_rcu(&cfs_rq->throttled_list);
6279 raw_spin_unlock(&cfs_b->lock);
6280
6281 /* update hierarchical throttle state */
6282 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6283
6284 if (!cfs_rq->load.weight) {
6285 if (!cfs_rq->on_list)
6286 return;
6287 /*
6288 * Nothing to run but something to decay (on_list)?
6289 * Complete the branch.
6290 */
6291 for_each_sched_entity(se) {
6292 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6293 break;
6294 }
6295 }
6296
6297 assert_list_leaf_cfs_rq(rq);
6298
6299 /* Determine whether we need to wake up potentially idle CPU: */
6300 if (rq->curr == rq->idle && rq->cfs.nr_queued)
6301 resched_curr(rq);
6302 }
6303
__cfsb_csd_unthrottle(void * arg)6304 static void __cfsb_csd_unthrottle(void *arg)
6305 {
6306 struct cfs_rq *cursor, *tmp;
6307 struct rq *rq = arg;
6308 struct rq_flags rf;
6309
6310 rq_lock(rq, &rf);
6311
6312 /*
6313 * Iterating over the list can trigger several call to
6314 * update_rq_clock() in unthrottle_cfs_rq().
6315 * Do it once and skip the potential next ones.
6316 */
6317 update_rq_clock(rq);
6318 rq_clock_start_loop_update(rq);
6319
6320 /*
6321 * Since we hold rq lock we're safe from concurrent manipulation of
6322 * the CSD list. However, this RCU critical section annotates the
6323 * fact that we pair with sched_free_group_rcu(), so that we cannot
6324 * race with group being freed in the window between removing it
6325 * from the list and advancing to the next entry in the list.
6326 */
6327 rcu_read_lock();
6328
6329 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6330 throttled_csd_list) {
6331 list_del_init(&cursor->throttled_csd_list);
6332
6333 if (cfs_rq_throttled(cursor))
6334 unthrottle_cfs_rq(cursor);
6335 }
6336
6337 rcu_read_unlock();
6338
6339 rq_clock_stop_loop_update(rq);
6340 rq_unlock(rq, &rf);
6341 }
6342
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6343 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6344 {
6345 struct rq *rq = rq_of(cfs_rq);
6346 bool first;
6347
6348 if (rq == this_rq()) {
6349 unthrottle_cfs_rq(cfs_rq);
6350 return;
6351 }
6352
6353 /* Already enqueued */
6354 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
6355 return;
6356
6357 first = list_empty(&rq->cfsb_csd_list);
6358 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6359 if (first)
6360 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6361 }
6362
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6363 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6364 {
6365 lockdep_assert_rq_held(rq_of(cfs_rq));
6366
6367 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
6368 cfs_rq->runtime_remaining <= 0))
6369 return;
6370
6371 __unthrottle_cfs_rq_async(cfs_rq);
6372 }
6373
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6374 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6375 {
6376 int this_cpu = smp_processor_id();
6377 u64 runtime, remaining = 1;
6378 bool throttled = false;
6379 struct cfs_rq *cfs_rq, *tmp;
6380 struct rq_flags rf;
6381 struct rq *rq;
6382 LIST_HEAD(local_unthrottle);
6383
6384 rcu_read_lock();
6385 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6386 throttled_list) {
6387 rq = rq_of(cfs_rq);
6388
6389 if (!remaining) {
6390 throttled = true;
6391 break;
6392 }
6393
6394 rq_lock_irqsave(rq, &rf);
6395 if (!cfs_rq_throttled(cfs_rq))
6396 goto next;
6397
6398 /* Already queued for async unthrottle */
6399 if (!list_empty(&cfs_rq->throttled_csd_list))
6400 goto next;
6401
6402 /* By the above checks, this should never be true */
6403 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
6404
6405 raw_spin_lock(&cfs_b->lock);
6406 runtime = -cfs_rq->runtime_remaining + 1;
6407 if (runtime > cfs_b->runtime)
6408 runtime = cfs_b->runtime;
6409 cfs_b->runtime -= runtime;
6410 remaining = cfs_b->runtime;
6411 raw_spin_unlock(&cfs_b->lock);
6412
6413 cfs_rq->runtime_remaining += runtime;
6414
6415 /* we check whether we're throttled above */
6416 if (cfs_rq->runtime_remaining > 0) {
6417 if (cpu_of(rq) != this_cpu) {
6418 unthrottle_cfs_rq_async(cfs_rq);
6419 } else {
6420 /*
6421 * We currently only expect to be unthrottling
6422 * a single cfs_rq locally.
6423 */
6424 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6425 list_add_tail(&cfs_rq->throttled_csd_list,
6426 &local_unthrottle);
6427 }
6428 } else {
6429 throttled = true;
6430 }
6431
6432 next:
6433 rq_unlock_irqrestore(rq, &rf);
6434 }
6435
6436 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6437 throttled_csd_list) {
6438 struct rq *rq = rq_of(cfs_rq);
6439
6440 rq_lock_irqsave(rq, &rf);
6441
6442 list_del_init(&cfs_rq->throttled_csd_list);
6443
6444 if (cfs_rq_throttled(cfs_rq))
6445 unthrottle_cfs_rq(cfs_rq);
6446
6447 rq_unlock_irqrestore(rq, &rf);
6448 }
6449 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6450
6451 rcu_read_unlock();
6452
6453 return throttled;
6454 }
6455
6456 /*
6457 * Responsible for refilling a task_group's bandwidth and unthrottling its
6458 * cfs_rqs as appropriate. If there has been no activity within the last
6459 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6460 * used to track this state.
6461 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6462 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6463 __must_hold(&cfs_b->lock)
6464 {
6465 int throttled;
6466
6467 /* no need to continue the timer with no bandwidth constraint */
6468 if (cfs_b->quota == RUNTIME_INF)
6469 goto out_deactivate;
6470
6471 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6472 cfs_b->nr_periods += overrun;
6473
6474 /* Refill extra burst quota even if cfs_b->idle */
6475 __refill_cfs_bandwidth_runtime(cfs_b);
6476
6477 /*
6478 * idle depends on !throttled (for the case of a large deficit), and if
6479 * we're going inactive then everything else can be deferred
6480 */
6481 if (cfs_b->idle && !throttled)
6482 goto out_deactivate;
6483
6484 if (!throttled) {
6485 /* mark as potentially idle for the upcoming period */
6486 cfs_b->idle = 1;
6487 return 0;
6488 }
6489
6490 /* account preceding periods in which throttling occurred */
6491 cfs_b->nr_throttled += overrun;
6492
6493 /*
6494 * This check is repeated as we release cfs_b->lock while we unthrottle.
6495 */
6496 while (throttled && cfs_b->runtime > 0) {
6497 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6498 /* we can't nest cfs_b->lock while distributing bandwidth */
6499 throttled = distribute_cfs_runtime(cfs_b);
6500 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6501 }
6502
6503 /*
6504 * While we are ensured activity in the period following an
6505 * unthrottle, this also covers the case in which the new bandwidth is
6506 * insufficient to cover the existing bandwidth deficit. (Forcing the
6507 * timer to remain active while there are any throttled entities.)
6508 */
6509 cfs_b->idle = 0;
6510
6511 return 0;
6512
6513 out_deactivate:
6514 return 1;
6515 }
6516
6517 /* a cfs_rq won't donate quota below this amount */
6518 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6519 /* minimum remaining period time to redistribute slack quota */
6520 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6521 /* how long we wait to gather additional slack before distributing */
6522 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6523
6524 /*
6525 * Are we near the end of the current quota period?
6526 *
6527 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6528 * hrtimer base being cleared by hrtimer_start. In the case of
6529 * migrate_hrtimers, base is never cleared, so we are fine.
6530 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6531 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6532 {
6533 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6534 s64 remaining;
6535
6536 /* if the call-back is running a quota refresh is already occurring */
6537 if (hrtimer_callback_running(refresh_timer))
6538 return 1;
6539
6540 /* is a quota refresh about to occur? */
6541 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6542 if (remaining < (s64)min_expire)
6543 return 1;
6544
6545 return 0;
6546 }
6547
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6548 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6549 {
6550 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6551
6552 /* if there's a quota refresh soon don't bother with slack */
6553 if (runtime_refresh_within(cfs_b, min_left))
6554 return;
6555
6556 /* don't push forwards an existing deferred unthrottle */
6557 if (cfs_b->slack_started)
6558 return;
6559 cfs_b->slack_started = true;
6560
6561 hrtimer_start(&cfs_b->slack_timer,
6562 ns_to_ktime(cfs_bandwidth_slack_period),
6563 HRTIMER_MODE_REL);
6564 }
6565
6566 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6567 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6568 {
6569 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6570 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6571
6572 if (slack_runtime <= 0)
6573 return;
6574
6575 raw_spin_lock(&cfs_b->lock);
6576 if (cfs_b->quota != RUNTIME_INF) {
6577 cfs_b->runtime += slack_runtime;
6578
6579 /* we are under rq->lock, defer unthrottling using a timer */
6580 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6581 !list_empty(&cfs_b->throttled_cfs_rq))
6582 start_cfs_slack_bandwidth(cfs_b);
6583 }
6584 raw_spin_unlock(&cfs_b->lock);
6585
6586 /* even if it's not valid for return we don't want to try again */
6587 cfs_rq->runtime_remaining -= slack_runtime;
6588 }
6589
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6590 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6591 {
6592 if (!cfs_bandwidth_used())
6593 return;
6594
6595 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6596 return;
6597
6598 __return_cfs_rq_runtime(cfs_rq);
6599 }
6600
6601 /*
6602 * This is done with a timer (instead of inline with bandwidth return) since
6603 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6604 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6605 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6606 {
6607 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6608 unsigned long flags;
6609
6610 /* confirm we're still not at a refresh boundary */
6611 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6612 cfs_b->slack_started = false;
6613
6614 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6615 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6616 return;
6617 }
6618
6619 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6620 runtime = cfs_b->runtime;
6621
6622 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6623
6624 if (!runtime)
6625 return;
6626
6627 distribute_cfs_runtime(cfs_b);
6628 }
6629
6630 /*
6631 * When a group wakes up we want to make sure that its quota is not already
6632 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6633 * runtime as update_curr() throttling can not trigger until it's on-rq.
6634 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6635 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6636 {
6637 if (!cfs_bandwidth_used())
6638 return;
6639
6640 /* an active group must be handled by the update_curr()->put() path */
6641 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6642 return;
6643
6644 /* ensure the group is not already throttled */
6645 if (cfs_rq_throttled(cfs_rq))
6646 return;
6647
6648 /* update runtime allocation */
6649 account_cfs_rq_runtime(cfs_rq, 0);
6650 if (cfs_rq->runtime_remaining <= 0)
6651 throttle_cfs_rq(cfs_rq);
6652 }
6653
sync_throttle(struct task_group * tg,int cpu)6654 static void sync_throttle(struct task_group *tg, int cpu)
6655 {
6656 struct cfs_rq *pcfs_rq, *cfs_rq;
6657
6658 if (!cfs_bandwidth_used())
6659 return;
6660
6661 if (!tg->parent)
6662 return;
6663
6664 cfs_rq = tg->cfs_rq[cpu];
6665 pcfs_rq = tg->parent->cfs_rq[cpu];
6666
6667 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6668 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6669
6670 /*
6671 * It is not enough to sync the "pelt_clock_throttled" indicator
6672 * with the parent cfs_rq when the hierarchy is not queued.
6673 * Always join a throttled hierarchy with PELT clock throttled
6674 * and leaf it to the first enqueue, or distribution to
6675 * unthrottle the PELT clock.
6676 */
6677 if (cfs_rq->throttle_count)
6678 cfs_rq->pelt_clock_throttled = 1;
6679 }
6680
6681 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6682 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6683 {
6684 if (!cfs_bandwidth_used())
6685 return false;
6686
6687 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6688 return false;
6689
6690 /*
6691 * it's possible for a throttled entity to be forced into a running
6692 * state (e.g. set_curr_task), in this case we're finished.
6693 */
6694 if (cfs_rq_throttled(cfs_rq))
6695 return true;
6696
6697 return throttle_cfs_rq(cfs_rq);
6698 }
6699
sched_cfs_slack_timer(struct hrtimer * timer)6700 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6701 {
6702 struct cfs_bandwidth *cfs_b =
6703 container_of(timer, struct cfs_bandwidth, slack_timer);
6704
6705 do_sched_cfs_slack_timer(cfs_b);
6706
6707 return HRTIMER_NORESTART;
6708 }
6709
sched_cfs_period_timer(struct hrtimer * timer)6710 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6711 {
6712 struct cfs_bandwidth *cfs_b =
6713 container_of(timer, struct cfs_bandwidth, period_timer);
6714 unsigned long flags;
6715 int overrun;
6716 int idle = 0;
6717 int count = 0;
6718
6719 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6720 for (;;) {
6721 overrun = hrtimer_forward_now(timer, cfs_b->period);
6722 if (!overrun)
6723 break;
6724
6725 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6726
6727 if (++count > 3) {
6728 u64 new, old = ktime_to_ns(cfs_b->period);
6729
6730 /*
6731 * Grow period by a factor of 2 to avoid losing precision.
6732 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6733 * to fail.
6734 */
6735 new = old * 2;
6736 if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
6737 cfs_b->period = ns_to_ktime(new);
6738 cfs_b->quota *= 2;
6739 cfs_b->burst *= 2;
6740
6741 pr_warn_ratelimited(
6742 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6743 smp_processor_id(),
6744 div_u64(new, NSEC_PER_USEC),
6745 div_u64(cfs_b->quota, NSEC_PER_USEC));
6746 } else {
6747 pr_warn_ratelimited(
6748 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6749 smp_processor_id(),
6750 div_u64(old, NSEC_PER_USEC),
6751 div_u64(cfs_b->quota, NSEC_PER_USEC));
6752 }
6753
6754 /* reset count so we don't come right back in here */
6755 count = 0;
6756 }
6757 }
6758 if (idle)
6759 cfs_b->period_active = 0;
6760 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6761
6762 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6763 }
6764
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6765 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6766 {
6767 raw_spin_lock_init(&cfs_b->lock);
6768 cfs_b->runtime = 0;
6769 cfs_b->quota = RUNTIME_INF;
6770 cfs_b->period = us_to_ktime(default_bw_period_us());
6771 cfs_b->burst = 0;
6772 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6773
6774 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6775 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
6776 HRTIMER_MODE_ABS_PINNED);
6777
6778 /* Add a random offset so that timers interleave */
6779 hrtimer_set_expires(&cfs_b->period_timer,
6780 get_random_u32_below(cfs_b->period));
6781 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
6782 HRTIMER_MODE_REL);
6783 cfs_b->slack_started = false;
6784 }
6785
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6786 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6787 {
6788 cfs_rq->runtime_enabled = 0;
6789 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6790 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6791 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
6792 }
6793
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6794 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6795 {
6796 lockdep_assert_held(&cfs_b->lock);
6797
6798 if (cfs_b->period_active)
6799 return;
6800
6801 cfs_b->period_active = 1;
6802 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6803 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6804 }
6805
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6806 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6807 {
6808 int __maybe_unused i;
6809
6810 /* init_cfs_bandwidth() was not called */
6811 if (!cfs_b->throttled_cfs_rq.next)
6812 return;
6813
6814 hrtimer_cancel(&cfs_b->period_timer);
6815 hrtimer_cancel(&cfs_b->slack_timer);
6816
6817 /*
6818 * It is possible that we still have some cfs_rq's pending on a CSD
6819 * list, though this race is very rare. In order for this to occur, we
6820 * must have raced with the last task leaving the group while there
6821 * exist throttled cfs_rq(s), and the period_timer must have queued the
6822 * CSD item but the remote cpu has not yet processed it. To handle this,
6823 * we can simply flush all pending CSD work inline here. We're
6824 * guaranteed at this point that no additional cfs_rq of this group can
6825 * join a CSD list.
6826 */
6827 for_each_possible_cpu(i) {
6828 struct rq *rq = cpu_rq(i);
6829 unsigned long flags;
6830
6831 if (list_empty(&rq->cfsb_csd_list))
6832 continue;
6833
6834 local_irq_save(flags);
6835 __cfsb_csd_unthrottle(rq);
6836 local_irq_restore(flags);
6837 }
6838 }
6839
6840 /*
6841 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6842 *
6843 * The race is harmless, since modifying bandwidth settings of unhooked group
6844 * bits doesn't do much.
6845 */
6846
6847 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6848 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6849 {
6850 struct task_group *tg;
6851
6852 lockdep_assert_rq_held(rq);
6853
6854 rcu_read_lock();
6855 list_for_each_entry_rcu(tg, &task_groups, list) {
6856 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6857 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6858
6859 raw_spin_lock(&cfs_b->lock);
6860 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6861 raw_spin_unlock(&cfs_b->lock);
6862 }
6863 rcu_read_unlock();
6864 }
6865
6866 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6867 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6868 {
6869 struct task_group *tg;
6870
6871 lockdep_assert_rq_held(rq);
6872
6873 // Do not unthrottle for an active CPU
6874 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6875 return;
6876
6877 /*
6878 * The rq clock has already been updated in the
6879 * set_rq_offline(), so we should skip updating
6880 * the rq clock again in unthrottle_cfs_rq().
6881 */
6882 rq_clock_start_loop_update(rq);
6883
6884 rcu_read_lock();
6885 list_for_each_entry_rcu(tg, &task_groups, list) {
6886 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6887
6888 if (!cfs_rq->runtime_enabled)
6889 continue;
6890
6891 /*
6892 * Offline rq is schedulable till CPU is completely disabled
6893 * in take_cpu_down(), so we prevent new cfs throttling here.
6894 */
6895 cfs_rq->runtime_enabled = 0;
6896
6897 if (!cfs_rq_throttled(cfs_rq))
6898 continue;
6899
6900 /*
6901 * clock_task is not advancing so we just need to make sure
6902 * there's some valid quota amount
6903 */
6904 cfs_rq->runtime_remaining = 1;
6905 unthrottle_cfs_rq(cfs_rq);
6906 }
6907 rcu_read_unlock();
6908
6909 rq_clock_stop_loop_update(rq);
6910 }
6911
cfs_task_bw_constrained(struct task_struct * p)6912 bool cfs_task_bw_constrained(struct task_struct *p)
6913 {
6914 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6915
6916 if (!cfs_bandwidth_used())
6917 return false;
6918
6919 if (cfs_rq->runtime_enabled ||
6920 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6921 return true;
6922
6923 return false;
6924 }
6925
6926 #ifdef CONFIG_NO_HZ_FULL
6927 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6928 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6929 {
6930 int cpu = cpu_of(rq);
6931
6932 if (!cfs_bandwidth_used())
6933 return;
6934
6935 if (!tick_nohz_full_cpu(cpu))
6936 return;
6937
6938 if (rq->nr_running != 1)
6939 return;
6940
6941 /*
6942 * We know there is only one task runnable and we've just picked it. The
6943 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6944 * be otherwise able to stop the tick. Just need to check if we are using
6945 * bandwidth control.
6946 */
6947 if (cfs_task_bw_constrained(p))
6948 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6949 }
6950 #endif /* CONFIG_NO_HZ_FULL */
6951
6952 #else /* !CONFIG_CFS_BANDWIDTH: */
6953
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6954 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6955 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6956 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6957 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6958 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
task_throttle_setup_work(struct task_struct * p)6959 static void task_throttle_setup_work(struct task_struct *p) {}
task_is_throttled(struct task_struct * p)6960 static bool task_is_throttled(struct task_struct *p) { return false; }
dequeue_throttled_task(struct task_struct * p,int flags)6961 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
enqueue_throttled_task(struct task_struct * p)6962 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
record_throttle_clock(struct cfs_rq * cfs_rq)6963 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
6964
cfs_rq_throttled(struct cfs_rq * cfs_rq)6965 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6966 {
6967 return 0;
6968 }
6969
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)6970 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6971 {
6972 return false;
6973 }
6974
throttled_hierarchy(struct cfs_rq * cfs_rq)6975 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6976 {
6977 return 0;
6978 }
6979
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)6980 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6981 {
6982 return 0;
6983 }
6984
6985 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6986 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6987 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6988 #endif
6989
tg_cfs_bandwidth(struct task_group * tg)6990 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6991 {
6992 return NULL;
6993 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6994 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6995 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6996 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6997 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6998 bool cfs_task_bw_constrained(struct task_struct *p)
6999 {
7000 return false;
7001 }
7002 #endif
7003 #endif /* !CONFIG_CFS_BANDWIDTH */
7004
7005 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)7006 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
7007 #endif
7008
7009 /**************************************************
7010 * CFS operations on tasks:
7011 */
7012
7013 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)7014 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
7015 {
7016 struct sched_entity *se = &p->se;
7017 unsigned long scale = 1024;
7018 unsigned long util = 0;
7019 u64 vdelta;
7020 u64 delta;
7021
7022 WARN_ON_ONCE(task_rq(p) != rq);
7023
7024 if (rq->cfs.h_nr_queued <= 1)
7025 return;
7026
7027 /*
7028 * Compute time until virtual deadline
7029 */
7030 vdelta = se->deadline - se->vruntime;
7031 if ((s64)vdelta < 0) {
7032 if (task_current_donor(rq, p))
7033 resched_curr(rq);
7034 return;
7035 }
7036 delta = (se->load.weight * vdelta) / NICE_0_LOAD;
7037
7038 /*
7039 * Correct for instantaneous load of other classes.
7040 */
7041 util += cpu_util_irq(rq);
7042 if (util && util < 1024) {
7043 scale *= 1024;
7044 scale /= (1024 - util);
7045 }
7046
7047 hrtick_start(rq, (scale * delta) / 1024);
7048 }
7049
7050 /*
7051 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1.
7052 */
hrtick_update(struct rq * rq)7053 static void hrtick_update(struct rq *rq)
7054 {
7055 struct task_struct *donor = rq->donor;
7056
7057 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
7058 return;
7059
7060 if (hrtick_active(rq))
7061 return;
7062
7063 hrtick_start_fair(rq, donor);
7064 }
7065 #else /* !CONFIG_SCHED_HRTICK: */
7066 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)7067 hrtick_start_fair(struct rq *rq, struct task_struct *p)
7068 {
7069 }
7070
hrtick_update(struct rq * rq)7071 static inline void hrtick_update(struct rq *rq)
7072 {
7073 }
7074 #endif /* !CONFIG_SCHED_HRTICK */
7075
cpu_overutilized(int cpu)7076 static inline bool cpu_overutilized(int cpu)
7077 {
7078 unsigned long rq_util_max;
7079
7080 if (!sched_energy_enabled())
7081 return false;
7082
7083 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
7084
7085 /* Return true only if the utilization doesn't fit CPU's capacity */
7086 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu);
7087 }
7088
7089 /*
7090 * overutilized value make sense only if EAS is enabled
7091 */
is_rd_overutilized(struct root_domain * rd)7092 static inline bool is_rd_overutilized(struct root_domain *rd)
7093 {
7094 return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
7095 }
7096
set_rd_overutilized(struct root_domain * rd,bool flag)7097 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
7098 {
7099 if (!sched_energy_enabled())
7100 return;
7101
7102 WRITE_ONCE(rd->overutilized, flag);
7103 trace_sched_overutilized_tp(rd, flag);
7104 }
7105
check_update_overutilized_status(struct rq * rq)7106 static inline void check_update_overutilized_status(struct rq *rq)
7107 {
7108 /*
7109 * overutilized field is used for load balancing decisions only
7110 * if energy aware scheduler is being used
7111 */
7112
7113 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
7114 set_rd_overutilized(rq->rd, 1);
7115 }
7116
7117 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)7118 static int sched_idle_rq(struct rq *rq)
7119 {
7120 return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
7121 rq->nr_running);
7122 }
7123
choose_sched_idle_rq(struct rq * rq,struct task_struct * p)7124 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p)
7125 {
7126 return sched_idle_rq(rq) && !task_has_idle_policy(p);
7127 }
7128
choose_idle_cpu(int cpu,struct task_struct * p)7129 static int choose_idle_cpu(int cpu, struct task_struct *p)
7130 {
7131 return available_idle_cpu(cpu) ||
7132 choose_sched_idle_rq(cpu_rq(cpu), p);
7133 }
7134
7135 static void
requeue_delayed_entity(struct sched_entity * se)7136 requeue_delayed_entity(struct sched_entity *se)
7137 {
7138 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7139
7140 /*
7141 * se->sched_delayed should imply: se->on_rq == 1.
7142 * Because a delayed entity is one that is still on
7143 * the runqueue competing until elegibility.
7144 */
7145 WARN_ON_ONCE(!se->sched_delayed);
7146 WARN_ON_ONCE(!se->on_rq);
7147
7148 if (update_entity_lag(cfs_rq, se)) {
7149 cfs_rq->nr_queued--;
7150 if (se != cfs_rq->curr)
7151 __dequeue_entity(cfs_rq, se);
7152 place_entity(cfs_rq, se, 0);
7153 if (se != cfs_rq->curr)
7154 __enqueue_entity(cfs_rq, se);
7155 cfs_rq->nr_queued++;
7156 }
7157
7158 update_load_avg(cfs_rq, se, 0);
7159 clear_delayed(se);
7160 }
7161
7162 /*
7163 * The enqueue_task method is called before nr_running is
7164 * increased. Here we update the fair scheduling stats and
7165 * then put the task into the rbtree:
7166 */
7167 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)7168 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7169 {
7170 struct cfs_rq *cfs_rq;
7171 struct sched_entity *se = &p->se;
7172 int h_nr_idle = task_has_idle_policy(p);
7173 int h_nr_runnable = 1;
7174 int task_new = !(flags & ENQUEUE_WAKEUP);
7175 int rq_h_nr_queued = rq->cfs.h_nr_queued;
7176 u64 slice = 0;
7177
7178 if (task_is_throttled(p) && enqueue_throttled_task(p))
7179 return;
7180
7181 /*
7182 * The code below (indirectly) updates schedutil which looks at
7183 * the cfs_rq utilization to select a frequency.
7184 * Let's add the task's estimated utilization to the cfs_rq's
7185 * estimated utilization, before we update schedutil.
7186 */
7187 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
7188 util_est_enqueue(&rq->cfs, p);
7189
7190 if (flags & ENQUEUE_DELAYED) {
7191 requeue_delayed_entity(se);
7192 return;
7193 }
7194
7195 /*
7196 * If in_iowait is set, the code below may not trigger any cpufreq
7197 * utilization updates, so do it here explicitly with the IOWAIT flag
7198 * passed.
7199 */
7200 if (p->in_iowait)
7201 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
7202
7203 if (task_new && se->sched_delayed)
7204 h_nr_runnable = 0;
7205
7206 for_each_sched_entity(se) {
7207 if (se->on_rq) {
7208 if (se->sched_delayed)
7209 requeue_delayed_entity(se);
7210 break;
7211 }
7212 cfs_rq = cfs_rq_of(se);
7213
7214 /*
7215 * Basically set the slice of group entries to the min_slice of
7216 * their respective cfs_rq. This ensures the group can service
7217 * its entities in the desired time-frame.
7218 */
7219 if (slice) {
7220 se->slice = slice;
7221 se->custom_slice = 1;
7222 }
7223 enqueue_entity(cfs_rq, se, flags);
7224 slice = cfs_rq_min_slice(cfs_rq);
7225
7226 cfs_rq->h_nr_runnable += h_nr_runnable;
7227 cfs_rq->h_nr_queued++;
7228 cfs_rq->h_nr_idle += h_nr_idle;
7229
7230 if (cfs_rq_is_idle(cfs_rq))
7231 h_nr_idle = 1;
7232
7233 flags = ENQUEUE_WAKEUP;
7234 }
7235
7236 for_each_sched_entity(se) {
7237 cfs_rq = cfs_rq_of(se);
7238
7239 update_load_avg(cfs_rq, se, UPDATE_TG);
7240 se_update_runnable(se);
7241 update_cfs_group(se);
7242
7243 se->slice = slice;
7244 if (se != cfs_rq->curr)
7245 min_vruntime_cb_propagate(&se->run_node, NULL);
7246 slice = cfs_rq_min_slice(cfs_rq);
7247
7248 cfs_rq->h_nr_runnable += h_nr_runnable;
7249 cfs_rq->h_nr_queued++;
7250 cfs_rq->h_nr_idle += h_nr_idle;
7251
7252 if (cfs_rq_is_idle(cfs_rq))
7253 h_nr_idle = 1;
7254 }
7255
7256 if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
7257 dl_server_start(&rq->fair_server);
7258
7259 /* At this point se is NULL and we are at root level*/
7260 add_nr_running(rq, 1);
7261
7262 /*
7263 * Since new tasks are assigned an initial util_avg equal to
7264 * half of the spare capacity of their CPU, tiny tasks have the
7265 * ability to cross the overutilized threshold, which will
7266 * result in the load balancer ruining all the task placement
7267 * done by EAS. As a way to mitigate that effect, do not account
7268 * for the first enqueue operation of new tasks during the
7269 * overutilized flag detection.
7270 *
7271 * A better way of solving this problem would be to wait for
7272 * the PELT signals of tasks to converge before taking them
7273 * into account, but that is not straightforward to implement,
7274 * and the following generally works well enough in practice.
7275 */
7276 if (!task_new)
7277 check_update_overutilized_status(rq);
7278
7279 assert_list_leaf_cfs_rq(rq);
7280
7281 hrtick_update(rq);
7282 }
7283
7284 /*
7285 * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
7286 * failing half-way through and resume the dequeue later.
7287 *
7288 * Returns:
7289 * -1 - dequeue delayed
7290 * 0 - dequeue throttled
7291 * 1 - dequeue complete
7292 */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)7293 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7294 {
7295 bool was_sched_idle = sched_idle_rq(rq);
7296 bool task_sleep = flags & DEQUEUE_SLEEP;
7297 bool task_delayed = flags & DEQUEUE_DELAYED;
7298 bool task_throttled = flags & DEQUEUE_THROTTLE;
7299 struct task_struct *p = NULL;
7300 int h_nr_idle = 0;
7301 int h_nr_queued = 0;
7302 int h_nr_runnable = 0;
7303 struct cfs_rq *cfs_rq;
7304 u64 slice = 0;
7305
7306 if (entity_is_task(se)) {
7307 p = task_of(se);
7308 h_nr_queued = 1;
7309 h_nr_idle = task_has_idle_policy(p);
7310 if (task_sleep || task_delayed || !se->sched_delayed)
7311 h_nr_runnable = 1;
7312 }
7313
7314 for_each_sched_entity(se) {
7315 cfs_rq = cfs_rq_of(se);
7316
7317 if (!dequeue_entity(cfs_rq, se, flags)) {
7318 if (p && &p->se == se)
7319 return -1;
7320
7321 slice = cfs_rq_min_slice(cfs_rq);
7322 break;
7323 }
7324
7325 cfs_rq->h_nr_runnable -= h_nr_runnable;
7326 cfs_rq->h_nr_queued -= h_nr_queued;
7327 cfs_rq->h_nr_idle -= h_nr_idle;
7328
7329 if (cfs_rq_is_idle(cfs_rq))
7330 h_nr_idle = h_nr_queued;
7331
7332 if (throttled_hierarchy(cfs_rq) && task_throttled)
7333 record_throttle_clock(cfs_rq);
7334
7335 /* Don't dequeue parent if it has other entities besides us */
7336 if (cfs_rq->load.weight) {
7337 slice = cfs_rq_min_slice(cfs_rq);
7338
7339 /* Avoid re-evaluating load for this entity: */
7340 se = parent_entity(se);
7341 /*
7342 * Bias pick_next to pick a task from this cfs_rq, as
7343 * p is sleeping when it is within its sched_slice.
7344 */
7345 if (task_sleep && se)
7346 set_next_buddy(se);
7347 break;
7348 }
7349 flags |= DEQUEUE_SLEEP;
7350 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7351 }
7352
7353 for_each_sched_entity(se) {
7354 cfs_rq = cfs_rq_of(se);
7355
7356 update_load_avg(cfs_rq, se, UPDATE_TG);
7357 se_update_runnable(se);
7358 update_cfs_group(se);
7359
7360 se->slice = slice;
7361 if (se != cfs_rq->curr)
7362 min_vruntime_cb_propagate(&se->run_node, NULL);
7363 slice = cfs_rq_min_slice(cfs_rq);
7364
7365 cfs_rq->h_nr_runnable -= h_nr_runnable;
7366 cfs_rq->h_nr_queued -= h_nr_queued;
7367 cfs_rq->h_nr_idle -= h_nr_idle;
7368
7369 if (cfs_rq_is_idle(cfs_rq))
7370 h_nr_idle = h_nr_queued;
7371
7372 if (throttled_hierarchy(cfs_rq) && task_throttled)
7373 record_throttle_clock(cfs_rq);
7374 }
7375
7376 sub_nr_running(rq, h_nr_queued);
7377
7378 /* balance early to pull high priority tasks */
7379 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7380 rq->next_balance = jiffies;
7381
7382 if (p && task_delayed) {
7383 WARN_ON_ONCE(!task_sleep);
7384 WARN_ON_ONCE(p->on_rq != 1);
7385
7386 /*
7387 * Fix-up what block_task() skipped.
7388 *
7389 * Must be last, @p might not be valid after this.
7390 */
7391 __block_task(rq, p);
7392 }
7393
7394 return 1;
7395 }
7396
7397 /*
7398 * The dequeue_task method is called before nr_running is
7399 * decreased. We remove the task from the rbtree and
7400 * update the fair scheduling stats:
7401 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7402 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7403 {
7404 if (task_is_throttled(p)) {
7405 dequeue_throttled_task(p, flags);
7406 return true;
7407 }
7408
7409 if (!p->se.sched_delayed)
7410 util_est_dequeue(&rq->cfs, p);
7411
7412 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7413 if (dequeue_entities(rq, &p->se, flags) < 0)
7414 return false;
7415
7416 /*
7417 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7418 */
7419 return true;
7420 }
7421
cfs_h_nr_delayed(struct rq * rq)7422 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
7423 {
7424 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
7425 }
7426
7427 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7428 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7429 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7430 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7431
7432 #ifdef CONFIG_NO_HZ_COMMON
7433
7434 static struct {
7435 cpumask_var_t idle_cpus_mask;
7436 int has_blocked_load; /* Idle CPUS has blocked load */
7437 int needs_update; /* Newly idle CPUs need their next_balance collated */
7438 unsigned long next_balance; /* in jiffy units */
7439 unsigned long next_blocked; /* Next update of blocked load in jiffies */
7440 } nohz ____cacheline_aligned;
7441
7442 #endif /* CONFIG_NO_HZ_COMMON */
7443
cpu_load(struct rq * rq)7444 static unsigned long cpu_load(struct rq *rq)
7445 {
7446 return cfs_rq_load_avg(&rq->cfs);
7447 }
7448
7449 /*
7450 * cpu_load_without - compute CPU load without any contributions from *p
7451 * @cpu: the CPU which load is requested
7452 * @p: the task which load should be discounted
7453 *
7454 * The load of a CPU is defined by the load of tasks currently enqueued on that
7455 * CPU as well as tasks which are currently sleeping after an execution on that
7456 * CPU.
7457 *
7458 * This method returns the load of the specified CPU by discounting the load of
7459 * the specified task, whenever the task is currently contributing to the CPU
7460 * load.
7461 */
cpu_load_without(struct rq * rq,struct task_struct * p)7462 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7463 {
7464 struct cfs_rq *cfs_rq;
7465 unsigned int load;
7466
7467 /* Task has no contribution or is new */
7468 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7469 return cpu_load(rq);
7470
7471 cfs_rq = &rq->cfs;
7472 load = READ_ONCE(cfs_rq->avg.load_avg);
7473
7474 /* Discount task's util from CPU's util */
7475 lsub_positive(&load, task_h_load(p));
7476
7477 return load;
7478 }
7479
cpu_runnable(struct rq * rq)7480 static unsigned long cpu_runnable(struct rq *rq)
7481 {
7482 return cfs_rq_runnable_avg(&rq->cfs);
7483 }
7484
cpu_runnable_without(struct rq * rq,struct task_struct * p)7485 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7486 {
7487 struct cfs_rq *cfs_rq;
7488 unsigned int runnable;
7489
7490 /* Task has no contribution or is new */
7491 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7492 return cpu_runnable(rq);
7493
7494 cfs_rq = &rq->cfs;
7495 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7496
7497 /* Discount task's runnable from CPU's runnable */
7498 lsub_positive(&runnable, p->se.avg.runnable_avg);
7499
7500 return runnable;
7501 }
7502
capacity_of(int cpu)7503 static unsigned long capacity_of(int cpu)
7504 {
7505 return cpu_rq(cpu)->cpu_capacity;
7506 }
7507
record_wakee(struct task_struct * p)7508 static void record_wakee(struct task_struct *p)
7509 {
7510 /*
7511 * Only decay a single time; tasks that have less then 1 wakeup per
7512 * jiffy will not have built up many flips.
7513 */
7514 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7515 current->wakee_flips >>= 1;
7516 current->wakee_flip_decay_ts = jiffies;
7517 }
7518
7519 if (current->last_wakee != p) {
7520 current->last_wakee = p;
7521 current->wakee_flips++;
7522 }
7523 }
7524
7525 /*
7526 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7527 *
7528 * A waker of many should wake a different task than the one last awakened
7529 * at a frequency roughly N times higher than one of its wakees.
7530 *
7531 * In order to determine whether we should let the load spread vs consolidating
7532 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7533 * partner, and a factor of lls_size higher frequency in the other.
7534 *
7535 * With both conditions met, we can be relatively sure that the relationship is
7536 * non-monogamous, with partner count exceeding socket size.
7537 *
7538 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7539 * whatever is irrelevant, spread criteria is apparent partner count exceeds
7540 * socket size.
7541 */
wake_wide(struct task_struct * p)7542 static int wake_wide(struct task_struct *p)
7543 {
7544 unsigned int master = current->wakee_flips;
7545 unsigned int slave = p->wakee_flips;
7546 int factor = __this_cpu_read(sd_llc_size);
7547
7548 if (master < slave)
7549 swap(master, slave);
7550 if (slave < factor || master < slave * factor)
7551 return 0;
7552 return 1;
7553 }
7554
7555 /*
7556 * The purpose of wake_affine() is to quickly determine on which CPU we can run
7557 * soonest. For the purpose of speed we only consider the waking and previous
7558 * CPU.
7559 *
7560 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7561 * cache-affine and is (or will be) idle.
7562 *
7563 * wake_affine_weight() - considers the weight to reflect the average
7564 * scheduling latency of the CPUs. This seems to work
7565 * for the overloaded case.
7566 */
7567 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7568 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7569 {
7570 /*
7571 * If this_cpu is idle, it implies the wakeup is from interrupt
7572 * context. Only allow the move if cache is shared. Otherwise an
7573 * interrupt intensive workload could force all tasks onto one
7574 * node depending on the IO topology or IRQ affinity settings.
7575 *
7576 * If the prev_cpu is idle and cache affine then avoid a migration.
7577 * There is no guarantee that the cache hot data from an interrupt
7578 * is more important than cache hot data on the prev_cpu and from
7579 * a cpufreq perspective, it's better to have higher utilisation
7580 * on one CPU.
7581 */
7582 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7583 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7584
7585 if (sync) {
7586 struct rq *rq = cpu_rq(this_cpu);
7587
7588 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
7589 return this_cpu;
7590 }
7591
7592 if (available_idle_cpu(prev_cpu))
7593 return prev_cpu;
7594
7595 return nr_cpumask_bits;
7596 }
7597
7598 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7599 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7600 int this_cpu, int prev_cpu, int sync)
7601 {
7602 s64 this_eff_load, prev_eff_load;
7603 unsigned long task_load;
7604
7605 this_eff_load = cpu_load(cpu_rq(this_cpu));
7606
7607 if (sync) {
7608 unsigned long current_load = task_h_load(current);
7609
7610 if (current_load > this_eff_load)
7611 return this_cpu;
7612
7613 this_eff_load -= current_load;
7614 }
7615
7616 task_load = task_h_load(p);
7617
7618 this_eff_load += task_load;
7619 if (sched_feat(WA_BIAS))
7620 this_eff_load *= 100;
7621 this_eff_load *= capacity_of(prev_cpu);
7622
7623 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7624 prev_eff_load -= task_load;
7625 if (sched_feat(WA_BIAS))
7626 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7627 prev_eff_load *= capacity_of(this_cpu);
7628
7629 /*
7630 * If sync, adjust the weight of prev_eff_load such that if
7631 * prev_eff == this_eff that select_idle_sibling() will consider
7632 * stacking the wakee on top of the waker if no other CPU is
7633 * idle.
7634 */
7635 if (sync)
7636 prev_eff_load += 1;
7637
7638 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7639 }
7640
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7641 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7642 int this_cpu, int prev_cpu, int sync)
7643 {
7644 int target = nr_cpumask_bits;
7645
7646 if (sched_feat(WA_IDLE))
7647 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7648
7649 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7650 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7651
7652 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7653 if (target != this_cpu)
7654 return prev_cpu;
7655
7656 schedstat_inc(sd->ttwu_move_affine);
7657 schedstat_inc(p->stats.nr_wakeups_affine);
7658 return target;
7659 }
7660
7661 static struct sched_group *
7662 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7663
7664 /*
7665 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7666 */
7667 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7668 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7669 {
7670 unsigned long load, min_load = ULONG_MAX;
7671 unsigned int min_exit_latency = UINT_MAX;
7672 u64 latest_idle_timestamp = 0;
7673 int least_loaded_cpu = this_cpu;
7674 int shallowest_idle_cpu = -1;
7675 int i;
7676
7677 /* Check if we have any choice: */
7678 if (group->group_weight == 1)
7679 return cpumask_first(sched_group_span(group));
7680
7681 /* Traverse only the allowed CPUs */
7682 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7683 struct rq *rq = cpu_rq(i);
7684
7685 if (!sched_core_cookie_match(rq, p))
7686 continue;
7687
7688 if (choose_sched_idle_rq(rq, p))
7689 return i;
7690
7691 if (available_idle_cpu(i)) {
7692 struct cpuidle_state *idle = idle_get_state(rq);
7693 if (idle && idle->exit_latency < min_exit_latency) {
7694 /*
7695 * We give priority to a CPU whose idle state
7696 * has the smallest exit latency irrespective
7697 * of any idle timestamp.
7698 */
7699 min_exit_latency = idle->exit_latency;
7700 latest_idle_timestamp = rq->idle_stamp;
7701 shallowest_idle_cpu = i;
7702 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7703 rq->idle_stamp > latest_idle_timestamp) {
7704 /*
7705 * If equal or no active idle state, then
7706 * the most recently idled CPU might have
7707 * a warmer cache.
7708 */
7709 latest_idle_timestamp = rq->idle_stamp;
7710 shallowest_idle_cpu = i;
7711 }
7712 } else if (shallowest_idle_cpu == -1) {
7713 load = cpu_load(cpu_rq(i));
7714 if (load < min_load) {
7715 min_load = load;
7716 least_loaded_cpu = i;
7717 }
7718 }
7719 }
7720
7721 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7722 }
7723
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7724 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7725 int cpu, int prev_cpu, int sd_flag)
7726 {
7727 int new_cpu = cpu;
7728
7729 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7730 return prev_cpu;
7731
7732 /*
7733 * We need task's util for cpu_util_without, sync it up to
7734 * prev_cpu's last_update_time.
7735 */
7736 if (!(sd_flag & SD_BALANCE_FORK))
7737 sync_entity_load_avg(&p->se);
7738
7739 while (sd) {
7740 struct sched_group *group;
7741 struct sched_domain *tmp;
7742 int weight;
7743
7744 if (!(sd->flags & sd_flag)) {
7745 sd = sd->child;
7746 continue;
7747 }
7748
7749 group = sched_balance_find_dst_group(sd, p, cpu);
7750 if (!group) {
7751 sd = sd->child;
7752 continue;
7753 }
7754
7755 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7756 if (new_cpu == cpu) {
7757 /* Now try balancing at a lower domain level of 'cpu': */
7758 sd = sd->child;
7759 continue;
7760 }
7761
7762 /* Now try balancing at a lower domain level of 'new_cpu': */
7763 cpu = new_cpu;
7764 weight = sd->span_weight;
7765 sd = NULL;
7766 for_each_domain(cpu, tmp) {
7767 if (weight <= tmp->span_weight)
7768 break;
7769 if (tmp->flags & sd_flag)
7770 sd = tmp;
7771 }
7772 }
7773
7774 return new_cpu;
7775 }
7776
__select_idle_cpu(int cpu,struct task_struct * p)7777 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7778 {
7779 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p))
7780 return cpu;
7781
7782 return -1;
7783 }
7784
7785 #ifdef CONFIG_SCHED_SMT
7786 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7787 EXPORT_SYMBOL_GPL(sched_smt_present);
7788
set_idle_cores(int cpu,int val)7789 static inline void set_idle_cores(int cpu, int val)
7790 {
7791 struct sched_domain_shared *sds;
7792
7793 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
7794 if (sds)
7795 WRITE_ONCE(sds->has_idle_cores, val);
7796 }
7797
test_idle_cores(int cpu)7798 static inline bool test_idle_cores(int cpu)
7799 {
7800 struct sched_domain_shared *sds;
7801
7802 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
7803 if (sds)
7804 return READ_ONCE(sds->has_idle_cores);
7805
7806 return false;
7807 }
7808
7809 /*
7810 * Scans the local SMT mask to see if the entire core is idle, and records this
7811 * information in sd_llc_shared->has_idle_cores.
7812 *
7813 * Since SMT siblings share all cache levels, inspecting this limited remote
7814 * state should be fairly cheap.
7815 */
__update_idle_core(struct rq * rq)7816 void __update_idle_core(struct rq *rq)
7817 {
7818 int core = cpu_of(rq);
7819 int cpu;
7820
7821 rcu_read_lock();
7822 if (test_idle_cores(core))
7823 goto unlock;
7824
7825 for_each_cpu(cpu, cpu_smt_mask(core)) {
7826 if (cpu == core)
7827 continue;
7828
7829 if (!available_idle_cpu(cpu))
7830 goto unlock;
7831 }
7832
7833 set_idle_cores(core, 1);
7834 unlock:
7835 rcu_read_unlock();
7836 }
7837
7838 /*
7839 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7840 * there are no idle cores left in the system; tracked through
7841 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7842 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7843 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7844 {
7845 bool idle = true;
7846 int cpu;
7847
7848 for_each_cpu(cpu, cpu_smt_mask(core)) {
7849 if (!available_idle_cpu(cpu)) {
7850 idle = false;
7851 if (*idle_cpu == -1) {
7852 if (choose_sched_idle_rq(cpu_rq(cpu), p) &&
7853 cpumask_test_cpu(cpu, cpus)) {
7854 *idle_cpu = cpu;
7855 break;
7856 }
7857 continue;
7858 }
7859 break;
7860 }
7861 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7862 *idle_cpu = cpu;
7863 }
7864
7865 if (idle)
7866 return core;
7867
7868 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7869 return -1;
7870 }
7871
7872 /*
7873 * Scan the local SMT mask for idle CPUs.
7874 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7875 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7876 {
7877 int cpu;
7878
7879 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7880 if (cpu == target)
7881 continue;
7882 /*
7883 * Check if the CPU is in the LLC scheduling domain of @target.
7884 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7885 */
7886 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7887 continue;
7888 if (choose_idle_cpu(cpu, p))
7889 return cpu;
7890 }
7891
7892 return -1;
7893 }
7894
7895 #else /* !CONFIG_SCHED_SMT: */
7896
set_idle_cores(int cpu,int val)7897 static inline void set_idle_cores(int cpu, int val)
7898 {
7899 }
7900
test_idle_cores(int cpu)7901 static inline bool test_idle_cores(int cpu)
7902 {
7903 return false;
7904 }
7905
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7906 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7907 {
7908 return __select_idle_cpu(core, p);
7909 }
7910
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7911 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7912 {
7913 return -1;
7914 }
7915
7916 #endif /* !CONFIG_SCHED_SMT */
7917
7918 /*
7919 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7920 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7921 * average idle time for this rq (as found in rq->avg_idle).
7922 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7923 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7924 {
7925 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7926 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7927
7928 if (sched_feat(SIS_UTIL)) {
7929 /*
7930 * Increment because !--nr is the condition to stop scan.
7931 *
7932 * Since "sd" is "sd_llc" for target CPU dereferenced in the
7933 * caller, it is safe to directly dereference "sd->shared".
7934 * Topology bits always ensure it assigned for "sd_llc" abd it
7935 * cannot disappear as long as we have a RCU protected
7936 * reference to one the associated "sd" here.
7937 */
7938 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1;
7939 /* overloaded LLC is unlikely to have idle cpu/core */
7940 if (nr == 1)
7941 return -1;
7942 }
7943
7944 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr))
7945 return -1;
7946
7947 if (static_branch_unlikely(&sched_cluster_active)) {
7948 struct sched_group *sg = sd->groups;
7949
7950 if (sg->flags & SD_CLUSTER) {
7951 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7952 if (!cpumask_test_cpu(cpu, cpus))
7953 continue;
7954
7955 if (has_idle_core) {
7956 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7957 if ((unsigned int)i < nr_cpumask_bits)
7958 return i;
7959 } else {
7960 if (--nr <= 0)
7961 return -1;
7962 idle_cpu = __select_idle_cpu(cpu, p);
7963 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7964 return idle_cpu;
7965 }
7966 }
7967 cpumask_andnot(cpus, cpus, sched_group_span(sg));
7968 }
7969 }
7970
7971 for_each_cpu_wrap(cpu, cpus, target + 1) {
7972 if (has_idle_core) {
7973 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7974 if ((unsigned int)i < nr_cpumask_bits)
7975 return i;
7976
7977 } else {
7978 if (--nr <= 0)
7979 return -1;
7980 idle_cpu = __select_idle_cpu(cpu, p);
7981 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7982 break;
7983 }
7984 }
7985
7986 if (has_idle_core)
7987 set_idle_cores(target, false);
7988
7989 return idle_cpu;
7990 }
7991
7992 /*
7993 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7994 * the task fits. If no CPU is big enough, but there are idle ones, try to
7995 * maximize capacity.
7996 */
7997 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7998 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7999 {
8000 unsigned long task_util, util_min, util_max, best_cap = 0;
8001 int fits, best_fits = 0;
8002 int cpu, best_cpu = -1;
8003 struct cpumask *cpus;
8004
8005 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8006 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
8007
8008 task_util = task_util_est(p);
8009 util_min = uclamp_eff_value(p, UCLAMP_MIN);
8010 util_max = uclamp_eff_value(p, UCLAMP_MAX);
8011
8012 for_each_cpu_wrap(cpu, cpus, target) {
8013 unsigned long cpu_cap = capacity_of(cpu);
8014
8015 if (!choose_idle_cpu(cpu, p))
8016 continue;
8017
8018 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
8019
8020 /* This CPU fits with all requirements */
8021 if (fits > 0)
8022 return cpu;
8023 /*
8024 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
8025 * Look for the CPU with best capacity.
8026 */
8027 else if (fits < 0)
8028 cpu_cap = get_actual_cpu_capacity(cpu);
8029
8030 /*
8031 * First, select CPU which fits better (-1 being better than 0).
8032 * Then, select the one with best capacity at same level.
8033 */
8034 if ((fits < best_fits) ||
8035 ((fits == best_fits) && (cpu_cap > best_cap))) {
8036 best_cap = cpu_cap;
8037 best_cpu = cpu;
8038 best_fits = fits;
8039 }
8040 }
8041
8042 return best_cpu;
8043 }
8044
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)8045 static inline bool asym_fits_cpu(unsigned long util,
8046 unsigned long util_min,
8047 unsigned long util_max,
8048 int cpu)
8049 {
8050 if (sched_asym_cpucap_active())
8051 /*
8052 * Return true only if the cpu fully fits the task requirements
8053 * which include the utilization and the performance hints.
8054 */
8055 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
8056
8057 return true;
8058 }
8059
8060 /*
8061 * Try and locate an idle core/thread in the LLC cache domain.
8062 */
select_idle_sibling(struct task_struct * p,int prev,int target)8063 static int select_idle_sibling(struct task_struct *p, int prev, int target)
8064 {
8065 bool has_idle_core = false;
8066 struct sched_domain *sd;
8067 unsigned long task_util, util_min, util_max;
8068 int i, recent_used_cpu, prev_aff = -1;
8069
8070 /*
8071 * On asymmetric system, update task utilization because we will check
8072 * that the task fits with CPU's capacity.
8073 */
8074 if (sched_asym_cpucap_active()) {
8075 sync_entity_load_avg(&p->se);
8076 task_util = task_util_est(p);
8077 util_min = uclamp_eff_value(p, UCLAMP_MIN);
8078 util_max = uclamp_eff_value(p, UCLAMP_MAX);
8079 }
8080
8081 /*
8082 * per-cpu select_rq_mask usage
8083 */
8084 lockdep_assert_irqs_disabled();
8085
8086 if (choose_idle_cpu(target, p) &&
8087 asym_fits_cpu(task_util, util_min, util_max, target))
8088 return target;
8089
8090 /*
8091 * If the previous CPU is cache affine and idle, don't be stupid:
8092 */
8093 if (prev != target && cpus_share_cache(prev, target) &&
8094 choose_idle_cpu(prev, p) &&
8095 asym_fits_cpu(task_util, util_min, util_max, prev)) {
8096
8097 if (!static_branch_unlikely(&sched_cluster_active) ||
8098 cpus_share_resources(prev, target))
8099 return prev;
8100
8101 prev_aff = prev;
8102 }
8103
8104 /*
8105 * Allow a per-cpu kthread to stack with the wakee if the
8106 * kworker thread and the tasks previous CPUs are the same.
8107 * The assumption is that the wakee queued work for the
8108 * per-cpu kthread that is now complete and the wakeup is
8109 * essentially a sync wakeup. An obvious example of this
8110 * pattern is IO completions.
8111 */
8112 if (is_per_cpu_kthread(current) &&
8113 in_task() &&
8114 prev == smp_processor_id() &&
8115 this_rq()->nr_running <= 1 &&
8116 asym_fits_cpu(task_util, util_min, util_max, prev)) {
8117 return prev;
8118 }
8119
8120 /* Check a recently used CPU as a potential idle candidate: */
8121 recent_used_cpu = p->recent_used_cpu;
8122 p->recent_used_cpu = prev;
8123 if (recent_used_cpu != prev &&
8124 recent_used_cpu != target &&
8125 cpus_share_cache(recent_used_cpu, target) &&
8126 choose_idle_cpu(recent_used_cpu, p) &&
8127 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
8128 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
8129
8130 if (!static_branch_unlikely(&sched_cluster_active) ||
8131 cpus_share_resources(recent_used_cpu, target))
8132 return recent_used_cpu;
8133
8134 } else {
8135 recent_used_cpu = -1;
8136 }
8137
8138 /*
8139 * For asymmetric CPU capacity systems, our domain of interest is
8140 * sd_asym_cpucapacity rather than sd_llc.
8141 */
8142 if (sched_asym_cpucap_active()) {
8143 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target));
8144 /*
8145 * On an asymmetric CPU capacity system where an exclusive
8146 * cpuset defines a symmetric island (i.e. one unique
8147 * capacity_orig value through the cpuset), the key will be set
8148 * but the CPUs within that cpuset will not have a domain with
8149 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
8150 * capacity path.
8151 */
8152 if (sd) {
8153 i = select_idle_capacity(p, sd, target);
8154 return ((unsigned)i < nr_cpumask_bits) ? i : target;
8155 }
8156 }
8157
8158 sd = rcu_dereference_all(per_cpu(sd_llc, target));
8159 if (!sd)
8160 return target;
8161
8162 if (sched_smt_active()) {
8163 has_idle_core = test_idle_cores(target);
8164
8165 if (!has_idle_core && cpus_share_cache(prev, target)) {
8166 i = select_idle_smt(p, sd, prev);
8167 if ((unsigned int)i < nr_cpumask_bits)
8168 return i;
8169 }
8170 }
8171
8172 i = select_idle_cpu(p, sd, has_idle_core, target);
8173 if ((unsigned)i < nr_cpumask_bits)
8174 return i;
8175
8176 /*
8177 * For cluster machines which have lower sharing cache like L2 or
8178 * LLC Tag, we tend to find an idle CPU in the target's cluster
8179 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
8180 * use them if possible when no idle CPU found in select_idle_cpu().
8181 */
8182 if ((unsigned int)prev_aff < nr_cpumask_bits)
8183 return prev_aff;
8184 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
8185 return recent_used_cpu;
8186
8187 return target;
8188 }
8189
8190 /**
8191 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
8192 * @cpu: the CPU to get the utilization for
8193 * @p: task for which the CPU utilization should be predicted or NULL
8194 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
8195 * @boost: 1 to enable boosting, otherwise 0
8196 *
8197 * The unit of the return value must be the same as the one of CPU capacity
8198 * so that CPU utilization can be compared with CPU capacity.
8199 *
8200 * CPU utilization is the sum of running time of runnable tasks plus the
8201 * recent utilization of currently non-runnable tasks on that CPU.
8202 * It represents the amount of CPU capacity currently used by CFS tasks in
8203 * the range [0..max CPU capacity] with max CPU capacity being the CPU
8204 * capacity at f_max.
8205 *
8206 * The estimated CPU utilization is defined as the maximum between CPU
8207 * utilization and sum of the estimated utilization of the currently
8208 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
8209 * previously-executed tasks, which helps better deduce how busy a CPU will
8210 * be when a long-sleeping task wakes up. The contribution to CPU utilization
8211 * of such a task would be significantly decayed at this point of time.
8212 *
8213 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
8214 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
8215 * utilization. Boosting is implemented in cpu_util() so that internal
8216 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
8217 * latter via cpu_util_cfs_boost().
8218 *
8219 * CPU utilization can be higher than the current CPU capacity
8220 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
8221 * of rounding errors as well as task migrations or wakeups of new tasks.
8222 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
8223 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
8224 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
8225 * capacity. CPU utilization is allowed to overshoot current CPU capacity
8226 * though since this is useful for predicting the CPU capacity required
8227 * after task migrations (scheduler-driven DVFS).
8228 *
8229 * Return: (Boosted) (estimated) utilization for the specified CPU.
8230 */
8231 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)8232 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
8233 {
8234 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
8235 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
8236 unsigned long runnable;
8237
8238 if (boost) {
8239 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
8240 util = max(util, runnable);
8241 }
8242
8243 /*
8244 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
8245 * contribution. If @p migrates from another CPU to @cpu add its
8246 * contribution. In all the other cases @cpu is not impacted by the
8247 * migration so its util_avg is already correct.
8248 */
8249 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
8250 lsub_positive(&util, task_util(p));
8251 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
8252 util += task_util(p);
8253
8254 if (sched_feat(UTIL_EST)) {
8255 unsigned long util_est;
8256
8257 util_est = READ_ONCE(cfs_rq->avg.util_est);
8258
8259 /*
8260 * During wake-up @p isn't enqueued yet and doesn't contribute
8261 * to any cpu_rq(cpu)->cfs.avg.util_est.
8262 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
8263 * has been enqueued.
8264 *
8265 * During exec (@dst_cpu = -1) @p is enqueued and does
8266 * contribute to cpu_rq(cpu)->cfs.util_est.
8267 * Remove it to "simulate" cpu_util without @p's contribution.
8268 *
8269 * Despite the task_on_rq_queued(@p) check there is still a
8270 * small window for a possible race when an exec
8271 * select_task_rq_fair() races with LB's detach_task().
8272 *
8273 * detach_task()
8274 * deactivate_task()
8275 * p->on_rq = TASK_ON_RQ_MIGRATING;
8276 * -------------------------------- A
8277 * dequeue_task() \
8278 * dequeue_task_fair() + Race Time
8279 * util_est_dequeue() /
8280 * -------------------------------- B
8281 *
8282 * The additional check "current == p" is required to further
8283 * reduce the race window.
8284 */
8285 if (dst_cpu == cpu)
8286 util_est += _task_util_est(p);
8287 else if (p && unlikely(task_on_rq_queued(p) || current == p))
8288 lsub_positive(&util_est, _task_util_est(p));
8289
8290 util = max(util, util_est);
8291 }
8292
8293 return min(util, arch_scale_cpu_capacity(cpu));
8294 }
8295
cpu_util_cfs(int cpu)8296 unsigned long cpu_util_cfs(int cpu)
8297 {
8298 return cpu_util(cpu, NULL, -1, 0);
8299 }
8300
cpu_util_cfs_boost(int cpu)8301 unsigned long cpu_util_cfs_boost(int cpu)
8302 {
8303 return cpu_util(cpu, NULL, -1, 1);
8304 }
8305
8306 /*
8307 * cpu_util_without: compute cpu utilization without any contributions from *p
8308 * @cpu: the CPU which utilization is requested
8309 * @p: the task which utilization should be discounted
8310 *
8311 * The utilization of a CPU is defined by the utilization of tasks currently
8312 * enqueued on that CPU as well as tasks which are currently sleeping after an
8313 * execution on that CPU.
8314 *
8315 * This method returns the utilization of the specified CPU by discounting the
8316 * utilization of the specified task, whenever the task is currently
8317 * contributing to the CPU utilization.
8318 */
cpu_util_without(int cpu,struct task_struct * p)8319 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8320 {
8321 /* Task has no contribution or is new */
8322 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8323 p = NULL;
8324
8325 return cpu_util(cpu, p, -1, 0);
8326 }
8327
8328 /*
8329 * This function computes an effective utilization for the given CPU, to be
8330 * used for frequency selection given the linear relation: f = u * f_max.
8331 *
8332 * The scheduler tracks the following metrics:
8333 *
8334 * cpu_util_{cfs,rt,dl,irq}()
8335 * cpu_bw_dl()
8336 *
8337 * Where the cfs,rt and dl util numbers are tracked with the same metric and
8338 * synchronized windows and are thus directly comparable.
8339 *
8340 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8341 * which excludes things like IRQ and steal-time. These latter are then accrued
8342 * in the IRQ utilization.
8343 *
8344 * The DL bandwidth number OTOH is not a measured metric but a value computed
8345 * based on the task model parameters and gives the minimal utilization
8346 * required to meet deadlines.
8347 */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8348 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8349 unsigned long *min,
8350 unsigned long *max)
8351 {
8352 unsigned long util, irq, scale;
8353 struct rq *rq = cpu_rq(cpu);
8354
8355 scale = arch_scale_cpu_capacity(cpu);
8356
8357 /*
8358 * Early check to see if IRQ/steal time saturates the CPU, can be
8359 * because of inaccuracies in how we track these -- see
8360 * update_irq_load_avg().
8361 */
8362 irq = cpu_util_irq(rq);
8363 if (unlikely(irq >= scale)) {
8364 if (min)
8365 *min = scale;
8366 if (max)
8367 *max = scale;
8368 return scale;
8369 }
8370
8371 if (min) {
8372 /*
8373 * The minimum utilization returns the highest level between:
8374 * - the computed DL bandwidth needed with the IRQ pressure which
8375 * steals time to the deadline task.
8376 * - The minimum performance requirement for CFS and/or RT.
8377 */
8378 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8379
8380 /*
8381 * When an RT task is runnable and uclamp is not used, we must
8382 * ensure that the task will run at maximum compute capacity.
8383 */
8384 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8385 *min = max(*min, scale);
8386 }
8387
8388 /*
8389 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8390 * CFS tasks and we use the same metric to track the effective
8391 * utilization (PELT windows are synchronized) we can directly add them
8392 * to obtain the CPU's actual utilization.
8393 */
8394 util = util_cfs + cpu_util_rt(rq);
8395 util += cpu_util_dl(rq);
8396
8397 /*
8398 * The maximum hint is a soft bandwidth requirement, which can be lower
8399 * than the actual utilization because of uclamp_max requirements.
8400 */
8401 if (max)
8402 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8403
8404 if (util >= scale)
8405 return scale;
8406
8407 /*
8408 * There is still idle time; further improve the number by using the
8409 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8410 * need to scale the task numbers:
8411 *
8412 * max - irq
8413 * U' = irq + --------- * U
8414 * max
8415 */
8416 util = scale_irq_capacity(util, irq, scale);
8417 util += irq;
8418
8419 return min(scale, util);
8420 }
8421
sched_cpu_util(int cpu)8422 unsigned long sched_cpu_util(int cpu)
8423 {
8424 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8425 }
8426
8427 /*
8428 * energy_env - Utilization landscape for energy estimation.
8429 * @task_busy_time: Utilization contribution by the task for which we test the
8430 * placement. Given by eenv_task_busy_time().
8431 * @pd_busy_time: Utilization of the whole perf domain without the task
8432 * contribution. Given by eenv_pd_busy_time().
8433 * @cpu_cap: Maximum CPU capacity for the perf domain.
8434 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8435 */
8436 struct energy_env {
8437 unsigned long task_busy_time;
8438 unsigned long pd_busy_time;
8439 unsigned long cpu_cap;
8440 unsigned long pd_cap;
8441 };
8442
8443 /*
8444 * Compute the task busy time for compute_energy(). This time cannot be
8445 * injected directly into effective_cpu_util() because of the IRQ scaling.
8446 * The latter only makes sense with the most recent CPUs where the task has
8447 * run.
8448 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8449 static inline void eenv_task_busy_time(struct energy_env *eenv,
8450 struct task_struct *p, int prev_cpu)
8451 {
8452 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8453 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8454
8455 if (unlikely(irq >= max_cap))
8456 busy_time = max_cap;
8457 else
8458 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8459
8460 eenv->task_busy_time = busy_time;
8461 }
8462
8463 /*
8464 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8465 * utilization for each @pd_cpus, it however doesn't take into account
8466 * clamping since the ratio (utilization / cpu_capacity) is already enough to
8467 * scale the EM reported power consumption at the (eventually clamped)
8468 * cpu_capacity.
8469 *
8470 * The contribution of the task @p for which we want to estimate the
8471 * energy cost is removed (by cpu_util()) and must be calculated
8472 * separately (see eenv_task_busy_time). This ensures:
8473 *
8474 * - A stable PD utilization, no matter which CPU of that PD we want to place
8475 * the task on.
8476 *
8477 * - A fair comparison between CPUs as the task contribution (task_util())
8478 * will always be the same no matter which CPU utilization we rely on
8479 * (util_avg or util_est).
8480 *
8481 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8482 * exceed @eenv->pd_cap.
8483 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8484 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8485 struct cpumask *pd_cpus,
8486 struct task_struct *p)
8487 {
8488 unsigned long busy_time = 0;
8489 int cpu;
8490
8491 for_each_cpu(cpu, pd_cpus) {
8492 unsigned long util = cpu_util(cpu, p, -1, 0);
8493
8494 busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8495 }
8496
8497 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8498 }
8499
8500 /*
8501 * Compute the maximum utilization for compute_energy() when the task @p
8502 * is placed on the cpu @dst_cpu.
8503 *
8504 * Returns the maximum utilization among @eenv->cpus. This utilization can't
8505 * exceed @eenv->cpu_cap.
8506 */
8507 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8508 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8509 struct task_struct *p, int dst_cpu)
8510 {
8511 unsigned long max_util = 0;
8512 int cpu;
8513
8514 for_each_cpu(cpu, pd_cpus) {
8515 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8516 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8517 unsigned long eff_util, min, max;
8518
8519 /*
8520 * Performance domain frequency: utilization clamping
8521 * must be considered since it affects the selection
8522 * of the performance domain frequency.
8523 * NOTE: in case RT tasks are running, by default the min
8524 * utilization can be max OPP.
8525 */
8526 eff_util = effective_cpu_util(cpu, util, &min, &max);
8527
8528 /* Task's uclamp can modify min and max value */
8529 if (tsk && uclamp_is_used()) {
8530 min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8531
8532 /*
8533 * If there is no active max uclamp constraint,
8534 * directly use task's one, otherwise keep max.
8535 */
8536 if (uclamp_rq_is_idle(cpu_rq(cpu)))
8537 max = uclamp_eff_value(p, UCLAMP_MAX);
8538 else
8539 max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8540 }
8541
8542 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8543 max_util = max(max_util, eff_util);
8544 }
8545
8546 return min(max_util, eenv->cpu_cap);
8547 }
8548
8549 /*
8550 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8551 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8552 * contribution is ignored.
8553 */
8554 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)8555 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8556 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8557 {
8558 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8559 unsigned long busy_time = eenv->pd_busy_time;
8560 unsigned long energy;
8561
8562 if (dst_cpu >= 0)
8563 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8564
8565 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8566
8567 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8568
8569 return energy;
8570 }
8571
8572 /*
8573 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8574 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8575 * spare capacity in each performance domain and uses it as a potential
8576 * candidate to execute the task. Then, it uses the Energy Model to figure
8577 * out which of the CPU candidates is the most energy-efficient.
8578 *
8579 * The rationale for this heuristic is as follows. In a performance domain,
8580 * all the most energy efficient CPU candidates (according to the Energy
8581 * Model) are those for which we'll request a low frequency. When there are
8582 * several CPUs for which the frequency request will be the same, we don't
8583 * have enough data to break the tie between them, because the Energy Model
8584 * only includes active power costs. With this model, if we assume that
8585 * frequency requests follow utilization (e.g. using schedutil), the CPU with
8586 * the maximum spare capacity in a performance domain is guaranteed to be among
8587 * the best candidates of the performance domain.
8588 *
8589 * In practice, it could be preferable from an energy standpoint to pack
8590 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8591 * but that could also hurt our chances to go cluster idle, and we have no
8592 * ways to tell with the current Energy Model if this is actually a good
8593 * idea or not. So, find_energy_efficient_cpu() basically favors
8594 * cluster-packing, and spreading inside a cluster. That should at least be
8595 * a good thing for latency, and this is consistent with the idea that most
8596 * of the energy savings of EAS come from the asymmetry of the system, and
8597 * not so much from breaking the tie between identical CPUs. That's also the
8598 * reason why EAS is enabled in the topology code only for systems where
8599 * SD_ASYM_CPUCAPACITY is set.
8600 *
8601 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8602 * they don't have any useful utilization data yet and it's not possible to
8603 * forecast their impact on energy consumption. Consequently, they will be
8604 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8605 * to be energy-inefficient in some use-cases. The alternative would be to
8606 * bias new tasks towards specific types of CPUs first, or to try to infer
8607 * their util_avg from the parent task, but those heuristics could hurt
8608 * other use-cases too. So, until someone finds a better way to solve this,
8609 * let's keep things simple by re-using the existing slow path.
8610 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8611 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8612 {
8613 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8614 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8615 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8616 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8617 struct root_domain *rd = this_rq()->rd;
8618 int cpu, best_energy_cpu, target = -1;
8619 int prev_fits = -1, best_fits = -1;
8620 unsigned long best_actual_cap = 0;
8621 unsigned long prev_actual_cap = 0;
8622 struct sched_domain *sd;
8623 struct perf_domain *pd;
8624 struct energy_env eenv;
8625
8626 pd = rcu_dereference_all(rd->pd);
8627 if (!pd)
8628 return target;
8629
8630 /*
8631 * Energy-aware wake-up happens on the lowest sched_domain starting
8632 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8633 */
8634 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity));
8635 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8636 sd = sd->parent;
8637 if (!sd)
8638 return target;
8639
8640 target = prev_cpu;
8641
8642 sync_entity_load_avg(&p->se);
8643 if (!task_util_est(p) && p_util_min == 0)
8644 return target;
8645
8646 eenv_task_busy_time(&eenv, p, prev_cpu);
8647
8648 for (; pd; pd = pd->next) {
8649 unsigned long util_min = p_util_min, util_max = p_util_max;
8650 unsigned long cpu_cap, cpu_actual_cap, util;
8651 long prev_spare_cap = -1, max_spare_cap = -1;
8652 unsigned long rq_util_min, rq_util_max;
8653 unsigned long cur_delta, base_energy;
8654 int max_spare_cap_cpu = -1;
8655 int fits, max_fits = -1;
8656
8657 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask))
8658 continue;
8659
8660 /* Account external pressure for the energy estimation */
8661 cpu = cpumask_first(cpus);
8662 cpu_actual_cap = get_actual_cpu_capacity(cpu);
8663
8664 eenv.cpu_cap = cpu_actual_cap;
8665 eenv.pd_cap = 0;
8666
8667 for_each_cpu(cpu, cpus) {
8668 struct rq *rq = cpu_rq(cpu);
8669
8670 eenv.pd_cap += cpu_actual_cap;
8671
8672 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8673 continue;
8674
8675 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8676 continue;
8677
8678 util = cpu_util(cpu, p, cpu, 0);
8679 cpu_cap = capacity_of(cpu);
8680
8681 /*
8682 * Skip CPUs that cannot satisfy the capacity request.
8683 * IOW, placing the task there would make the CPU
8684 * overutilized. Take uclamp into account to see how
8685 * much capacity we can get out of the CPU; this is
8686 * aligned with sched_cpu_util().
8687 */
8688 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8689 /*
8690 * Open code uclamp_rq_util_with() except for
8691 * the clamp() part. I.e.: apply max aggregation
8692 * only. util_fits_cpu() logic requires to
8693 * operate on non clamped util but must use the
8694 * max-aggregated uclamp_{min, max}.
8695 */
8696 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8697 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8698
8699 util_min = max(rq_util_min, p_util_min);
8700 util_max = max(rq_util_max, p_util_max);
8701 }
8702
8703 fits = util_fits_cpu(util, util_min, util_max, cpu);
8704 if (!fits)
8705 continue;
8706
8707 lsub_positive(&cpu_cap, util);
8708
8709 if (cpu == prev_cpu) {
8710 /* Always use prev_cpu as a candidate. */
8711 prev_spare_cap = cpu_cap;
8712 prev_fits = fits;
8713 } else if ((fits > max_fits) ||
8714 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8715 /*
8716 * Find the CPU with the maximum spare capacity
8717 * among the remaining CPUs in the performance
8718 * domain.
8719 */
8720 max_spare_cap = cpu_cap;
8721 max_spare_cap_cpu = cpu;
8722 max_fits = fits;
8723 }
8724 }
8725
8726 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8727 continue;
8728
8729 eenv_pd_busy_time(&eenv, cpus, p);
8730 /* Compute the 'base' energy of the pd, without @p */
8731 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8732
8733 /* Evaluate the energy impact of using prev_cpu. */
8734 if (prev_spare_cap > -1) {
8735 prev_delta = compute_energy(&eenv, pd, cpus, p,
8736 prev_cpu);
8737 /* CPU utilization has changed */
8738 if (prev_delta < base_energy)
8739 return target;
8740 prev_delta -= base_energy;
8741 prev_actual_cap = cpu_actual_cap;
8742 best_delta = min(best_delta, prev_delta);
8743 }
8744
8745 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8746 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8747 /* Current best energy cpu fits better */
8748 if (max_fits < best_fits)
8749 continue;
8750
8751 /*
8752 * Both don't fit performance hint (i.e. uclamp_min)
8753 * but best energy cpu has better capacity.
8754 */
8755 if ((max_fits < 0) &&
8756 (cpu_actual_cap <= best_actual_cap))
8757 continue;
8758
8759 cur_delta = compute_energy(&eenv, pd, cpus, p,
8760 max_spare_cap_cpu);
8761 /* CPU utilization has changed */
8762 if (cur_delta < base_energy)
8763 return target;
8764 cur_delta -= base_energy;
8765
8766 /*
8767 * Both fit for the task but best energy cpu has lower
8768 * energy impact.
8769 */
8770 if ((max_fits > 0) && (best_fits > 0) &&
8771 (cur_delta >= best_delta))
8772 continue;
8773
8774 best_delta = cur_delta;
8775 best_energy_cpu = max_spare_cap_cpu;
8776 best_fits = max_fits;
8777 best_actual_cap = cpu_actual_cap;
8778 }
8779 }
8780
8781 if ((best_fits > prev_fits) ||
8782 ((best_fits > 0) && (best_delta < prev_delta)) ||
8783 ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8784 target = best_energy_cpu;
8785
8786 return target;
8787 }
8788
8789 /*
8790 * select_task_rq_fair: Select target runqueue for the waking task in domains
8791 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8792 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8793 *
8794 * Balances load by selecting the idlest CPU in the idlest group, or under
8795 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8796 *
8797 * Returns the target CPU number.
8798 */
8799 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8800 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8801 {
8802 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8803 struct sched_domain *tmp, *sd = NULL;
8804 int cpu = smp_processor_id();
8805 int new_cpu = prev_cpu;
8806 int want_affine = 0;
8807 /* SD_flags and WF_flags share the first nibble */
8808 int sd_flag = wake_flags & 0xF;
8809
8810 /*
8811 * required for stable ->cpus_allowed
8812 */
8813 lockdep_assert_held(&p->pi_lock);
8814 if (wake_flags & WF_TTWU) {
8815 record_wakee(p);
8816
8817 if ((wake_flags & WF_CURRENT_CPU) &&
8818 cpumask_test_cpu(cpu, p->cpus_ptr))
8819 return cpu;
8820
8821 if (!is_rd_overutilized(this_rq()->rd)) {
8822 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8823 if (new_cpu >= 0)
8824 return new_cpu;
8825 new_cpu = prev_cpu;
8826 }
8827
8828 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8829 }
8830
8831 for_each_domain(cpu, tmp) {
8832 /*
8833 * If both 'cpu' and 'prev_cpu' are part of this domain,
8834 * cpu is a valid SD_WAKE_AFFINE target.
8835 */
8836 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8837 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8838 if (cpu != prev_cpu)
8839 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8840
8841 sd = NULL; /* Prefer wake_affine over balance flags */
8842 break;
8843 }
8844
8845 /*
8846 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8847 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8848 * will usually go to the fast path.
8849 */
8850 if (tmp->flags & sd_flag)
8851 sd = tmp;
8852 else if (!want_affine)
8853 break;
8854 }
8855
8856 /* Slow path */
8857 if (unlikely(sd))
8858 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8859
8860 /* Fast path */
8861 if (wake_flags & WF_TTWU)
8862 return select_idle_sibling(p, prev_cpu, new_cpu);
8863
8864 return new_cpu;
8865 }
8866
8867 /*
8868 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8869 * cfs_rq_of(p) references at time of call are still valid and identify the
8870 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8871 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8872 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8873 {
8874 struct sched_entity *se = &p->se;
8875
8876 if (!task_on_rq_migrating(p)) {
8877 remove_entity_load_avg(se);
8878
8879 /*
8880 * Here, the task's PELT values have been updated according to
8881 * the current rq's clock. But if that clock hasn't been
8882 * updated in a while, a substantial idle time will be missed,
8883 * leading to an inflation after wake-up on the new rq.
8884 *
8885 * Estimate the missing time from the cfs_rq last_update_time
8886 * and update sched_avg to improve the PELT continuity after
8887 * migration.
8888 */
8889 migrate_se_pelt_lag(se);
8890 }
8891
8892 /* Tell new CPU we are migrated */
8893 se->avg.last_update_time = 0;
8894
8895 update_scan_period(p, new_cpu);
8896 }
8897
task_dead_fair(struct task_struct * p)8898 static void task_dead_fair(struct task_struct *p)
8899 {
8900 struct sched_entity *se = &p->se;
8901
8902 if (se->sched_delayed) {
8903 struct rq_flags rf;
8904 struct rq *rq;
8905
8906 rq = task_rq_lock(p, &rf);
8907 if (se->sched_delayed) {
8908 update_rq_clock(rq);
8909 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8910 }
8911 task_rq_unlock(rq, p, &rf);
8912 }
8913
8914 remove_entity_load_avg(se);
8915 }
8916
8917 /*
8918 * Set the max capacity the task is allowed to run at for misfit detection.
8919 */
set_task_max_allowed_capacity(struct task_struct * p)8920 static void set_task_max_allowed_capacity(struct task_struct *p)
8921 {
8922 struct asym_cap_data *entry;
8923
8924 if (!sched_asym_cpucap_active())
8925 return;
8926
8927 rcu_read_lock();
8928 list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8929 cpumask_t *cpumask;
8930
8931 cpumask = cpu_capacity_span(entry);
8932 if (!cpumask_intersects(p->cpus_ptr, cpumask))
8933 continue;
8934
8935 p->max_allowed_capacity = entry->capacity;
8936 break;
8937 }
8938 rcu_read_unlock();
8939 }
8940
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8941 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8942 {
8943 set_cpus_allowed_common(p, ctx);
8944 set_task_max_allowed_capacity(p);
8945 }
8946
set_next_buddy(struct sched_entity * se)8947 static void set_next_buddy(struct sched_entity *se)
8948 {
8949 for_each_sched_entity(se) {
8950 if (WARN_ON_ONCE(!se->on_rq))
8951 return;
8952 if (se_is_idle(se))
8953 return;
8954 cfs_rq_of(se)->next = se;
8955 }
8956 }
8957
8958 enum preempt_wakeup_action {
8959 PREEMPT_WAKEUP_NONE, /* No preemption. */
8960 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */
8961 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */
8962 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */
8963 };
8964
8965 static inline bool
set_preempt_buddy(struct cfs_rq * cfs_rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8966 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags,
8967 struct sched_entity *pse, struct sched_entity *se)
8968 {
8969 /*
8970 * Keep existing buddy if the deadline is sooner than pse.
8971 * The older buddy may be cache cold and completely unrelated
8972 * to the current wakeup but that is unpredictable where as
8973 * obeying the deadline is more in line with EEVDF objectives.
8974 */
8975 if (cfs_rq->next && entity_before(cfs_rq->next, pse))
8976 return false;
8977
8978 set_next_buddy(pse);
8979 return true;
8980 }
8981
8982 /*
8983 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
8984 * strictly enforced because the hint is either misunderstood or
8985 * multiple tasks must be woken up.
8986 */
8987 static inline enum preempt_wakeup_action
preempt_sync(struct rq * rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8988 preempt_sync(struct rq *rq, int wake_flags,
8989 struct sched_entity *pse, struct sched_entity *se)
8990 {
8991 u64 threshold, delta;
8992
8993 /*
8994 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
8995 * though it is likely harmless.
8996 */
8997 WARN_ON_ONCE(!(wake_flags & WF_TTWU));
8998
8999 threshold = sysctl_sched_migration_cost;
9000 delta = rq_clock_task(rq) - se->exec_start;
9001 if ((s64)delta < 0)
9002 delta = 0;
9003
9004 /*
9005 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
9006 * could run on other CPUs. Reduce the threshold before preemption is
9007 * allowed to an arbitrary lower value as it is more likely (but not
9008 * guaranteed) the waker requires the wakee to finish.
9009 */
9010 if (wake_flags & WF_RQ_SELECTED)
9011 threshold >>= 2;
9012
9013 /*
9014 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
9015 * wakeups to be issued.
9016 */
9017 if (entity_before(pse, se) && delta >= threshold)
9018 return PREEMPT_WAKEUP_RESCHED;
9019
9020 return PREEMPT_WAKEUP_NONE;
9021 }
9022
9023 /*
9024 * Preempt the current task with a newly woken task if needed:
9025 */
wakeup_preempt_fair(struct rq * rq,struct task_struct * p,int wake_flags)9026 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags)
9027 {
9028 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
9029 struct task_struct *donor = rq->donor;
9030 struct sched_entity *se = &donor->se, *pse = &p->se;
9031 struct cfs_rq *cfs_rq = task_cfs_rq(donor);
9032 int cse_is_idle, pse_is_idle;
9033
9034 /*
9035 * XXX Getting preempted by higher class, try and find idle CPU?
9036 */
9037 if (p->sched_class != &fair_sched_class)
9038 return;
9039
9040 if (unlikely(se == pse))
9041 return;
9042
9043 /*
9044 * This is possible from callers such as attach_tasks(), in which we
9045 * unconditionally wakeup_preempt() after an enqueue (which may have
9046 * lead to a throttle). This both saves work and prevents false
9047 * next-buddy nomination below.
9048 */
9049 if (task_is_throttled(p))
9050 return;
9051
9052 /*
9053 * We can come here with TIF_NEED_RESCHED already set from new task
9054 * wake up path.
9055 *
9056 * Note: this also catches the edge-case of curr being in a throttled
9057 * group (e.g. via set_curr_task), since update_curr() (in the
9058 * enqueue of curr) will have resulted in resched being set. This
9059 * prevents us from potentially nominating it as a false LAST_BUDDY
9060 * below.
9061 */
9062 if (test_tsk_need_resched(rq->curr))
9063 return;
9064
9065 if (!sched_feat(WAKEUP_PREEMPTION))
9066 return;
9067
9068 find_matching_se(&se, &pse);
9069 WARN_ON_ONCE(!pse);
9070
9071 cse_is_idle = se_is_idle(se);
9072 pse_is_idle = se_is_idle(pse);
9073
9074 /*
9075 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
9076 * in the inverse case).
9077 */
9078 if (cse_is_idle && !pse_is_idle) {
9079 /*
9080 * When non-idle entity preempt an idle entity,
9081 * don't give idle entity slice protection.
9082 */
9083 preempt_action = PREEMPT_WAKEUP_SHORT;
9084 goto preempt;
9085 }
9086
9087 if (cse_is_idle != pse_is_idle)
9088 return;
9089
9090 /*
9091 * BATCH and IDLE tasks do not preempt others.
9092 */
9093 if (unlikely(!normal_policy(p->policy)))
9094 return;
9095
9096 cfs_rq = cfs_rq_of(se);
9097 update_curr(cfs_rq);
9098 /*
9099 * If @p has a shorter slice than current and @p is eligible, override
9100 * current's slice protection in order to allow preemption.
9101 */
9102 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
9103 preempt_action = PREEMPT_WAKEUP_SHORT;
9104 goto pick;
9105 }
9106
9107 /*
9108 * Ignore wakee preemption on WF_FORK as it is less likely that
9109 * there is shared data as exec often follow fork. Do not
9110 * preempt for tasks that are sched_delayed as it would violate
9111 * EEVDF to forcibly queue an ineligible task.
9112 */
9113 if ((wake_flags & WF_FORK) || pse->sched_delayed)
9114 return;
9115
9116 /* Prefer picking wakee soon if appropriate. */
9117 if (sched_feat(NEXT_BUDDY) &&
9118 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) {
9119
9120 /*
9121 * Decide whether to obey WF_SYNC hint for a new buddy. Old
9122 * buddies are ignored as they may not be relevant to the
9123 * waker and less likely to be cache hot.
9124 */
9125 if (wake_flags & WF_SYNC)
9126 preempt_action = preempt_sync(rq, wake_flags, pse, se);
9127 }
9128
9129 switch (preempt_action) {
9130 case PREEMPT_WAKEUP_NONE:
9131 return;
9132 case PREEMPT_WAKEUP_RESCHED:
9133 goto preempt;
9134 case PREEMPT_WAKEUP_SHORT:
9135 fallthrough;
9136 case PREEMPT_WAKEUP_PICK:
9137 break;
9138 }
9139
9140 pick:
9141 /*
9142 * If @p has become the most eligible task, force preemption.
9143 */
9144 if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse)
9145 goto preempt;
9146
9147 if (sched_feat(RUN_TO_PARITY))
9148 update_protect_slice(cfs_rq, se);
9149
9150 return;
9151
9152 preempt:
9153 if (preempt_action == PREEMPT_WAKEUP_SHORT) {
9154 cancel_protect_slice(se);
9155 clear_buddies(cfs_rq, se);
9156 }
9157
9158 resched_curr_lazy(rq);
9159 }
9160
pick_task_fair(struct rq * rq,struct rq_flags * rf)9161 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
9162 {
9163 struct sched_entity *se;
9164 struct cfs_rq *cfs_rq;
9165 struct task_struct *p;
9166 bool throttled;
9167
9168 again:
9169 cfs_rq = &rq->cfs;
9170 if (!cfs_rq->nr_queued)
9171 return NULL;
9172
9173 throttled = false;
9174
9175 do {
9176 /* Might not have done put_prev_entity() */
9177 if (cfs_rq->curr && cfs_rq->curr->on_rq)
9178 update_curr(cfs_rq);
9179
9180 throttled |= check_cfs_rq_runtime(cfs_rq);
9181
9182 se = pick_next_entity(rq, cfs_rq);
9183 if (!se)
9184 goto again;
9185 cfs_rq = group_cfs_rq(se);
9186 } while (cfs_rq);
9187
9188 p = task_of(se);
9189 if (unlikely(throttled))
9190 task_throttle_setup_work(p);
9191 return p;
9192 }
9193
9194 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
9195 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
9196
9197 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)9198 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
9199 __must_hold(__rq_lockp(rq))
9200 {
9201 struct sched_entity *se;
9202 struct task_struct *p;
9203 int new_tasks;
9204
9205 again:
9206 p = pick_task_fair(rq, rf);
9207 if (!p)
9208 goto idle;
9209 se = &p->se;
9210
9211 #ifdef CONFIG_FAIR_GROUP_SCHED
9212 if (prev->sched_class != &fair_sched_class)
9213 goto simple;
9214
9215 __put_prev_set_next_dl_server(rq, prev, p);
9216
9217 /*
9218 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
9219 * likely that a next task is from the same cgroup as the current.
9220 *
9221 * Therefore attempt to avoid putting and setting the entire cgroup
9222 * hierarchy, only change the part that actually changes.
9223 *
9224 * Since we haven't yet done put_prev_entity and if the selected task
9225 * is a different task than we started out with, try and touch the
9226 * least amount of cfs_rqs.
9227 */
9228 if (prev != p) {
9229 struct sched_entity *pse = &prev->se;
9230 struct cfs_rq *cfs_rq;
9231
9232 while (!(cfs_rq = is_same_group(se, pse))) {
9233 int se_depth = se->depth;
9234 int pse_depth = pse->depth;
9235
9236 if (se_depth <= pse_depth) {
9237 put_prev_entity(cfs_rq_of(pse), pse);
9238 pse = parent_entity(pse);
9239 }
9240 if (se_depth >= pse_depth) {
9241 set_next_entity(cfs_rq_of(se), se, true);
9242 se = parent_entity(se);
9243 }
9244 }
9245
9246 put_prev_entity(cfs_rq, pse);
9247 set_next_entity(cfs_rq, se, true);
9248
9249 __set_next_task_fair(rq, p, true);
9250 }
9251
9252 return p;
9253
9254 simple:
9255 #endif /* CONFIG_FAIR_GROUP_SCHED */
9256 put_prev_set_next_task(rq, prev, p);
9257 return p;
9258
9259 idle:
9260 if (rf) {
9261 new_tasks = sched_balance_newidle(rq, rf);
9262
9263 /*
9264 * Because sched_balance_newidle() releases (and re-acquires)
9265 * rq->lock, it is possible for any higher priority task to
9266 * appear. In that case we must re-start the pick_next_entity()
9267 * loop.
9268 */
9269 if (new_tasks < 0)
9270 return RETRY_TASK;
9271
9272 if (new_tasks > 0)
9273 goto again;
9274 }
9275
9276 return NULL;
9277 }
9278
9279 static struct task_struct *
fair_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)9280 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
9281 {
9282 return pick_task_fair(dl_se->rq, rf);
9283 }
9284
fair_server_init(struct rq * rq)9285 void fair_server_init(struct rq *rq)
9286 {
9287 struct sched_dl_entity *dl_se = &rq->fair_server;
9288
9289 init_dl_entity(dl_se);
9290
9291 dl_server_init(dl_se, rq, fair_server_pick_task);
9292 }
9293
9294 /*
9295 * Account for a descheduled task:
9296 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)9297 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9298 {
9299 struct sched_entity *se = &prev->se;
9300 struct cfs_rq *cfs_rq;
9301
9302 for_each_sched_entity(se) {
9303 cfs_rq = cfs_rq_of(se);
9304 put_prev_entity(cfs_rq, se);
9305 }
9306 }
9307
9308 /*
9309 * sched_yield() is very simple
9310 */
yield_task_fair(struct rq * rq)9311 static void yield_task_fair(struct rq *rq)
9312 {
9313 struct task_struct *curr = rq->donor;
9314 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9315 struct sched_entity *se = &curr->se;
9316
9317 /*
9318 * Are we the only task in the tree?
9319 */
9320 if (unlikely(rq->nr_running == 1))
9321 return;
9322
9323 clear_buddies(cfs_rq, se);
9324
9325 update_rq_clock(rq);
9326 /*
9327 * Update run-time statistics of the 'current'.
9328 */
9329 update_curr(cfs_rq);
9330 /*
9331 * Tell update_rq_clock() that we've just updated,
9332 * so we don't do microscopic update in schedule()
9333 * and double the fastpath cost.
9334 */
9335 rq_clock_skip_update(rq);
9336
9337 /*
9338 * Forfeit the remaining vruntime, only if the entity is eligible. This
9339 * condition is necessary because in core scheduling we prefer to run
9340 * ineligible tasks rather than force idling. If this happens we may
9341 * end up in a loop where the core scheduler picks the yielding task,
9342 * which yields immediately again; without the condition the vruntime
9343 * ends up quickly running away.
9344 */
9345 if (entity_eligible(cfs_rq, se)) {
9346 se->vruntime = se->deadline;
9347 update_deadline(cfs_rq, se);
9348 }
9349 }
9350
yield_to_task_fair(struct rq * rq,struct task_struct * p)9351 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9352 {
9353 struct sched_entity *se = &p->se;
9354
9355 /* !se->on_rq also covers throttled task */
9356 if (!se->on_rq)
9357 return false;
9358
9359 /* Tell the scheduler that we'd really like se to run next. */
9360 set_next_buddy(se);
9361
9362 yield_task_fair(rq);
9363
9364 return true;
9365 }
9366
9367 /**************************************************
9368 * Fair scheduling class load-balancing methods.
9369 *
9370 * BASICS
9371 *
9372 * The purpose of load-balancing is to achieve the same basic fairness the
9373 * per-CPU scheduler provides, namely provide a proportional amount of compute
9374 * time to each task. This is expressed in the following equation:
9375 *
9376 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
9377 *
9378 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9379 * W_i,0 is defined as:
9380 *
9381 * W_i,0 = \Sum_j w_i,j (2)
9382 *
9383 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9384 * is derived from the nice value as per sched_prio_to_weight[].
9385 *
9386 * The weight average is an exponential decay average of the instantaneous
9387 * weight:
9388 *
9389 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
9390 *
9391 * C_i is the compute capacity of CPU i, typically it is the
9392 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9393 * can also include other factors [XXX].
9394 *
9395 * To achieve this balance we define a measure of imbalance which follows
9396 * directly from (1):
9397 *
9398 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
9399 *
9400 * We them move tasks around to minimize the imbalance. In the continuous
9401 * function space it is obvious this converges, in the discrete case we get
9402 * a few fun cases generally called infeasible weight scenarios.
9403 *
9404 * [XXX expand on:
9405 * - infeasible weights;
9406 * - local vs global optima in the discrete case. ]
9407 *
9408 *
9409 * SCHED DOMAINS
9410 *
9411 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9412 * for all i,j solution, we create a tree of CPUs that follows the hardware
9413 * topology where each level pairs two lower groups (or better). This results
9414 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9415 * tree to only the first of the previous level and we decrease the frequency
9416 * of load-balance at each level inversely proportional to the number of CPUs in
9417 * the groups.
9418 *
9419 * This yields:
9420 *
9421 * log_2 n 1 n
9422 * \Sum { --- * --- * 2^i } = O(n) (5)
9423 * i = 0 2^i 2^i
9424 * `- size of each group
9425 * | | `- number of CPUs doing load-balance
9426 * | `- freq
9427 * `- sum over all levels
9428 *
9429 * Coupled with a limit on how many tasks we can migrate every balance pass,
9430 * this makes (5) the runtime complexity of the balancer.
9431 *
9432 * An important property here is that each CPU is still (indirectly) connected
9433 * to every other CPU in at most O(log n) steps:
9434 *
9435 * The adjacency matrix of the resulting graph is given by:
9436 *
9437 * log_2 n
9438 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
9439 * k = 0
9440 *
9441 * And you'll find that:
9442 *
9443 * A^(log_2 n)_i,j != 0 for all i,j (7)
9444 *
9445 * Showing there's indeed a path between every CPU in at most O(log n) steps.
9446 * The task movement gives a factor of O(m), giving a convergence complexity
9447 * of:
9448 *
9449 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
9450 *
9451 *
9452 * WORK CONSERVING
9453 *
9454 * In order to avoid CPUs going idle while there's still work to do, new idle
9455 * balancing is more aggressive and has the newly idle CPU iterate up the domain
9456 * tree itself instead of relying on other CPUs to bring it work.
9457 *
9458 * This adds some complexity to both (5) and (8) but it reduces the total idle
9459 * time.
9460 *
9461 * [XXX more?]
9462 *
9463 *
9464 * CGROUPS
9465 *
9466 * Cgroups make a horror show out of (2), instead of a simple sum we get:
9467 *
9468 * s_k,i
9469 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
9470 * S_k
9471 *
9472 * Where
9473 *
9474 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
9475 *
9476 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9477 *
9478 * The big problem is S_k, its a global sum needed to compute a local (W_i)
9479 * property.
9480 *
9481 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9482 * rewrite all of this once again.]
9483 */
9484
9485 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9486
9487 enum fbq_type { regular, remote, all };
9488
9489 /*
9490 * 'group_type' describes the group of CPUs at the moment of load balancing.
9491 *
9492 * The enum is ordered by pulling priority, with the group with lowest priority
9493 * first so the group_type can simply be compared when selecting the busiest
9494 * group. See update_sd_pick_busiest().
9495 */
9496 enum group_type {
9497 /* The group has spare capacity that can be used to run more tasks. */
9498 group_has_spare = 0,
9499 /*
9500 * The group is fully used and the tasks don't compete for more CPU
9501 * cycles. Nevertheless, some tasks might wait before running.
9502 */
9503 group_fully_busy,
9504 /*
9505 * One task doesn't fit with CPU's capacity and must be migrated to a
9506 * more powerful CPU.
9507 */
9508 group_misfit_task,
9509 /*
9510 * Balance SMT group that's fully busy. Can benefit from migration
9511 * a task on SMT with busy sibling to another CPU on idle core.
9512 */
9513 group_smt_balance,
9514 /*
9515 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9516 * and the task should be migrated to it instead of running on the
9517 * current CPU.
9518 */
9519 group_asym_packing,
9520 /*
9521 * The tasks' affinity constraints previously prevented the scheduler
9522 * from balancing the load across the system.
9523 */
9524 group_imbalanced,
9525 /*
9526 * The CPU is overloaded and can't provide expected CPU cycles to all
9527 * tasks.
9528 */
9529 group_overloaded
9530 };
9531
9532 enum migration_type {
9533 migrate_load = 0,
9534 migrate_util,
9535 migrate_task,
9536 migrate_misfit
9537 };
9538
9539 #define LBF_ALL_PINNED 0x01
9540 #define LBF_NEED_BREAK 0x02
9541 #define LBF_DST_PINNED 0x04
9542 #define LBF_SOME_PINNED 0x08
9543 #define LBF_ACTIVE_LB 0x10
9544
9545 struct lb_env {
9546 struct sched_domain *sd;
9547
9548 struct rq *src_rq;
9549 int src_cpu;
9550
9551 int dst_cpu;
9552 struct rq *dst_rq;
9553
9554 struct cpumask *dst_grpmask;
9555 int new_dst_cpu;
9556 enum cpu_idle_type idle;
9557 long imbalance;
9558 /* The set of CPUs under consideration for load-balancing */
9559 struct cpumask *cpus;
9560
9561 unsigned int flags;
9562
9563 unsigned int loop;
9564 unsigned int loop_break;
9565 unsigned int loop_max;
9566
9567 enum fbq_type fbq_type;
9568 enum migration_type migration_type;
9569 struct list_head tasks;
9570 };
9571
9572 /*
9573 * Is this task likely cache-hot:
9574 */
task_hot(struct task_struct * p,struct lb_env * env)9575 static int task_hot(struct task_struct *p, struct lb_env *env)
9576 {
9577 s64 delta;
9578
9579 lockdep_assert_rq_held(env->src_rq);
9580
9581 if (p->sched_class != &fair_sched_class)
9582 return 0;
9583
9584 if (unlikely(task_has_idle_policy(p)))
9585 return 0;
9586
9587 /* SMT siblings share cache */
9588 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9589 return 0;
9590
9591 /*
9592 * Buddy candidates are cache hot:
9593 */
9594 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9595 (&p->se == cfs_rq_of(&p->se)->next))
9596 return 1;
9597
9598 if (sysctl_sched_migration_cost == -1)
9599 return 1;
9600
9601 /*
9602 * Don't migrate task if the task's cookie does not match
9603 * with the destination CPU's core cookie.
9604 */
9605 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9606 return 1;
9607
9608 if (sysctl_sched_migration_cost == 0)
9609 return 0;
9610
9611 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9612
9613 return delta < (s64)sysctl_sched_migration_cost;
9614 }
9615
9616 #ifdef CONFIG_NUMA_BALANCING
9617 /*
9618 * Returns a positive value, if task migration degrades locality.
9619 * Returns 0, if task migration is not affected by locality.
9620 * Returns a negative value, if task migration improves locality i.e migration preferred.
9621 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9622 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9623 {
9624 struct numa_group *numa_group = rcu_dereference_all(p->numa_group);
9625 unsigned long src_weight, dst_weight;
9626 int src_nid, dst_nid, dist;
9627
9628 if (!static_branch_likely(&sched_numa_balancing))
9629 return 0;
9630
9631 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9632 return 0;
9633
9634 src_nid = cpu_to_node(env->src_cpu);
9635 dst_nid = cpu_to_node(env->dst_cpu);
9636
9637 if (src_nid == dst_nid)
9638 return 0;
9639
9640 /* Migrating away from the preferred node is always bad. */
9641 if (src_nid == p->numa_preferred_nid) {
9642 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9643 return 1;
9644 else
9645 return 0;
9646 }
9647
9648 /* Encourage migration to the preferred node. */
9649 if (dst_nid == p->numa_preferred_nid)
9650 return -1;
9651
9652 /* Leaving a core idle is often worse than degrading locality. */
9653 if (env->idle == CPU_IDLE)
9654 return 0;
9655
9656 dist = node_distance(src_nid, dst_nid);
9657 if (numa_group) {
9658 src_weight = group_weight(p, src_nid, dist);
9659 dst_weight = group_weight(p, dst_nid, dist);
9660 } else {
9661 src_weight = task_weight(p, src_nid, dist);
9662 dst_weight = task_weight(p, dst_nid, dist);
9663 }
9664
9665 return src_weight - dst_weight;
9666 }
9667
9668 #else /* !CONFIG_NUMA_BALANCING: */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9669 static inline long migrate_degrades_locality(struct task_struct *p,
9670 struct lb_env *env)
9671 {
9672 return 0;
9673 }
9674 #endif /* !CONFIG_NUMA_BALANCING */
9675
9676 /*
9677 * Check whether the task is ineligible on the destination cpu
9678 *
9679 * When the PLACE_LAG scheduling feature is enabled and
9680 * dst_cfs_rq->nr_queued is greater than 1, if the task
9681 * is ineligible, it will also be ineligible when
9682 * it is migrated to the destination cpu.
9683 */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9684 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9685 {
9686 struct cfs_rq *dst_cfs_rq;
9687
9688 #ifdef CONFIG_FAIR_GROUP_SCHED
9689 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9690 #else
9691 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9692 #endif
9693 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9694 !entity_eligible(task_cfs_rq(p), &p->se))
9695 return 1;
9696
9697 return 0;
9698 }
9699
9700 /*
9701 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9702 */
9703 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9704 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9705 {
9706 long degrades, hot;
9707
9708 lockdep_assert_rq_held(env->src_rq);
9709 if (p->sched_task_hot)
9710 p->sched_task_hot = 0;
9711
9712 /*
9713 * We do not migrate tasks that are:
9714 * 1) delayed dequeued unless we migrate load, or
9715 * 2) target cfs_rq is in throttled hierarchy, or
9716 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9717 * 4) running (obviously), or
9718 * 5) are cache-hot on their current CPU, or
9719 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9720 */
9721 if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9722 return 0;
9723
9724 if (lb_throttled_hierarchy(p, env->dst_cpu))
9725 return 0;
9726
9727 /*
9728 * We want to prioritize the migration of eligible tasks.
9729 * For ineligible tasks we soft-limit them and only allow
9730 * them to migrate when nr_balance_failed is non-zero to
9731 * avoid load-balancing trying very hard to balance the load.
9732 */
9733 if (!env->sd->nr_balance_failed &&
9734 task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9735 return 0;
9736
9737 /* Disregard percpu kthreads; they are where they need to be. */
9738 if (kthread_is_per_cpu(p))
9739 return 0;
9740
9741 if (task_is_blocked(p))
9742 return 0;
9743
9744 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9745 int cpu;
9746
9747 schedstat_inc(p->stats.nr_failed_migrations_affine);
9748
9749 env->flags |= LBF_SOME_PINNED;
9750
9751 /*
9752 * Remember if this task can be migrated to any other CPU in
9753 * our sched_group. We may want to revisit it if we couldn't
9754 * meet load balance goals by pulling other tasks on src_cpu.
9755 *
9756 * Avoid computing new_dst_cpu
9757 * - for NEWLY_IDLE
9758 * - if we have already computed one in current iteration
9759 * - if it's an active balance
9760 */
9761 if (env->idle == CPU_NEWLY_IDLE ||
9762 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9763 return 0;
9764
9765 /* Prevent to re-select dst_cpu via env's CPUs: */
9766 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
9767
9768 if (cpu < nr_cpu_ids) {
9769 env->flags |= LBF_DST_PINNED;
9770 env->new_dst_cpu = cpu;
9771 }
9772
9773 return 0;
9774 }
9775
9776 /* Record that we found at least one task that could run on dst_cpu */
9777 env->flags &= ~LBF_ALL_PINNED;
9778
9779 if (task_on_cpu(env->src_rq, p) ||
9780 task_current_donor(env->src_rq, p)) {
9781 schedstat_inc(p->stats.nr_failed_migrations_running);
9782 return 0;
9783 }
9784
9785 /*
9786 * Aggressive migration if:
9787 * 1) active balance
9788 * 2) destination numa is preferred
9789 * 3) task is cache cold, or
9790 * 4) too many balance attempts have failed.
9791 */
9792 if (env->flags & LBF_ACTIVE_LB)
9793 return 1;
9794
9795 degrades = migrate_degrades_locality(p, env);
9796 if (!degrades)
9797 hot = task_hot(p, env);
9798 else
9799 hot = degrades > 0;
9800
9801 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9802 if (hot)
9803 p->sched_task_hot = 1;
9804 return 1;
9805 }
9806
9807 schedstat_inc(p->stats.nr_failed_migrations_hot);
9808 return 0;
9809 }
9810
9811 /*
9812 * detach_task() -- detach the task for the migration specified in env
9813 */
detach_task(struct task_struct * p,struct lb_env * env)9814 static void detach_task(struct task_struct *p, struct lb_env *env)
9815 {
9816 lockdep_assert_rq_held(env->src_rq);
9817
9818 if (p->sched_task_hot) {
9819 p->sched_task_hot = 0;
9820 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9821 schedstat_inc(p->stats.nr_forced_migrations);
9822 }
9823
9824 WARN_ON(task_current(env->src_rq, p));
9825 WARN_ON(task_current_donor(env->src_rq, p));
9826
9827 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9828 set_task_cpu(p, env->dst_cpu);
9829 }
9830
9831 /*
9832 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9833 * part of active balancing operations within "domain".
9834 *
9835 * Returns a task if successful and NULL otherwise.
9836 */
detach_one_task(struct lb_env * env)9837 static struct task_struct *detach_one_task(struct lb_env *env)
9838 {
9839 struct task_struct *p;
9840
9841 lockdep_assert_rq_held(env->src_rq);
9842
9843 list_for_each_entry_reverse(p,
9844 &env->src_rq->cfs_tasks, se.group_node) {
9845 if (!can_migrate_task(p, env))
9846 continue;
9847
9848 detach_task(p, env);
9849
9850 /*
9851 * Right now, this is only the second place where
9852 * lb_gained[env->idle] is updated (other is detach_tasks)
9853 * so we can safely collect stats here rather than
9854 * inside detach_tasks().
9855 */
9856 schedstat_inc(env->sd->lb_gained[env->idle]);
9857 return p;
9858 }
9859 return NULL;
9860 }
9861
9862 /*
9863 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9864 * busiest_rq, as part of a balancing operation within domain "sd".
9865 *
9866 * Returns number of detached tasks if successful and 0 otherwise.
9867 */
detach_tasks(struct lb_env * env)9868 static int detach_tasks(struct lb_env *env)
9869 {
9870 struct list_head *tasks = &env->src_rq->cfs_tasks;
9871 unsigned long util, load;
9872 struct task_struct *p;
9873 int detached = 0;
9874
9875 lockdep_assert_rq_held(env->src_rq);
9876
9877 /*
9878 * Source run queue has been emptied by another CPU, clear
9879 * LBF_ALL_PINNED flag as we will not test any task.
9880 */
9881 if (env->src_rq->nr_running <= 1) {
9882 env->flags &= ~LBF_ALL_PINNED;
9883 return 0;
9884 }
9885
9886 if (env->imbalance <= 0)
9887 return 0;
9888
9889 while (!list_empty(tasks)) {
9890 /*
9891 * We don't want to steal all, otherwise we may be treated likewise,
9892 * which could at worst lead to a livelock crash.
9893 */
9894 if (env->idle && env->src_rq->nr_running <= 1)
9895 break;
9896
9897 env->loop++;
9898 /* We've more or less seen every task there is, call it quits */
9899 if (env->loop > env->loop_max)
9900 break;
9901
9902 /* take a breather every nr_migrate tasks */
9903 if (env->loop > env->loop_break) {
9904 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9905 env->flags |= LBF_NEED_BREAK;
9906 break;
9907 }
9908
9909 p = list_last_entry(tasks, struct task_struct, se.group_node);
9910
9911 if (!can_migrate_task(p, env))
9912 goto next;
9913
9914 switch (env->migration_type) {
9915 case migrate_load:
9916 /*
9917 * Depending of the number of CPUs and tasks and the
9918 * cgroup hierarchy, task_h_load() can return a null
9919 * value. Make sure that env->imbalance decreases
9920 * otherwise detach_tasks() will stop only after
9921 * detaching up to loop_max tasks.
9922 */
9923 load = max_t(unsigned long, task_h_load(p), 1);
9924
9925 if (sched_feat(LB_MIN) &&
9926 load < 16 && !env->sd->nr_balance_failed)
9927 goto next;
9928
9929 /*
9930 * Make sure that we don't migrate too much load.
9931 * Nevertheless, let relax the constraint if
9932 * scheduler fails to find a good waiting task to
9933 * migrate.
9934 */
9935 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9936 goto next;
9937
9938 env->imbalance -= load;
9939 break;
9940
9941 case migrate_util:
9942 util = task_util_est(p);
9943
9944 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9945 goto next;
9946
9947 env->imbalance -= util;
9948 break;
9949
9950 case migrate_task:
9951 env->imbalance--;
9952 break;
9953
9954 case migrate_misfit:
9955 /* This is not a misfit task */
9956 if (task_fits_cpu(p, env->src_cpu))
9957 goto next;
9958
9959 env->imbalance = 0;
9960 break;
9961 }
9962
9963 detach_task(p, env);
9964 list_add(&p->se.group_node, &env->tasks);
9965
9966 detached++;
9967
9968 #ifdef CONFIG_PREEMPTION
9969 /*
9970 * NEWIDLE balancing is a source of latency, so preemptible
9971 * kernels will stop after the first task is detached to minimize
9972 * the critical section.
9973 */
9974 if (env->idle == CPU_NEWLY_IDLE)
9975 break;
9976 #endif
9977
9978 /*
9979 * We only want to steal up to the prescribed amount of
9980 * load/util/tasks.
9981 */
9982 if (env->imbalance <= 0)
9983 break;
9984
9985 continue;
9986 next:
9987 if (p->sched_task_hot)
9988 schedstat_inc(p->stats.nr_failed_migrations_hot);
9989
9990 list_move(&p->se.group_node, tasks);
9991 }
9992
9993 /*
9994 * Right now, this is one of only two places we collect this stat
9995 * so we can safely collect detach_one_task() stats here rather
9996 * than inside detach_one_task().
9997 */
9998 schedstat_add(env->sd->lb_gained[env->idle], detached);
9999
10000 return detached;
10001 }
10002
10003 /*
10004 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
10005 * new rq.
10006 */
attach_tasks(struct lb_env * env)10007 static void attach_tasks(struct lb_env *env)
10008 {
10009 struct list_head *tasks = &env->tasks;
10010 struct task_struct *p;
10011 struct rq_flags rf;
10012
10013 rq_lock(env->dst_rq, &rf);
10014 update_rq_clock(env->dst_rq);
10015
10016 while (!list_empty(tasks)) {
10017 p = list_first_entry(tasks, struct task_struct, se.group_node);
10018 list_del_init(&p->se.group_node);
10019
10020 attach_task(env->dst_rq, p);
10021 }
10022
10023 rq_unlock(env->dst_rq, &rf);
10024 }
10025
10026 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked_load(struct cfs_rq * cfs_rq)10027 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq)
10028 {
10029 if (cfs_rq->avg.load_avg)
10030 return true;
10031
10032 if (cfs_rq->avg.util_avg)
10033 return true;
10034
10035 return false;
10036 }
10037
others_have_blocked(struct rq * rq)10038 static inline bool others_have_blocked(struct rq *rq)
10039 {
10040 if (cpu_util_rt(rq))
10041 return true;
10042
10043 if (cpu_util_dl(rq))
10044 return true;
10045
10046 if (hw_load_avg(rq))
10047 return true;
10048
10049 if (cpu_util_irq(rq))
10050 return true;
10051
10052 return false;
10053 }
10054
update_blocked_load_tick(struct rq * rq)10055 static inline void update_blocked_load_tick(struct rq *rq)
10056 {
10057 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
10058 }
10059
update_has_blocked_load_status(struct rq * rq,bool has_blocked_load)10060 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load)
10061 {
10062 if (!has_blocked_load)
10063 rq->has_blocked_load = 0;
10064 }
10065 #else /* !CONFIG_NO_HZ_COMMON: */
cfs_rq_has_blocked_load(struct cfs_rq * cfs_rq)10066 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)10067 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)10068 static inline void update_blocked_load_tick(struct rq *rq) {}
update_has_blocked_load_status(struct rq * rq,bool has_blocked_load)10069 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {}
10070 #endif /* !CONFIG_NO_HZ_COMMON */
10071
__update_blocked_others(struct rq * rq,bool * done)10072 static bool __update_blocked_others(struct rq *rq, bool *done)
10073 {
10074 bool updated;
10075
10076 /*
10077 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
10078 * DL and IRQ signals have been updated before updating CFS.
10079 */
10080 updated = update_other_load_avgs(rq);
10081
10082 if (others_have_blocked(rq))
10083 *done = false;
10084
10085 return updated;
10086 }
10087
10088 #ifdef CONFIG_FAIR_GROUP_SCHED
10089
__update_blocked_fair(struct rq * rq,bool * done)10090 static bool __update_blocked_fair(struct rq *rq, bool *done)
10091 {
10092 struct cfs_rq *cfs_rq, *pos;
10093 bool decayed = false;
10094 int cpu = cpu_of(rq);
10095
10096 /*
10097 * Iterates the task_group tree in a bottom up fashion, see
10098 * list_add_leaf_cfs_rq() for details.
10099 */
10100 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
10101 struct sched_entity *se;
10102
10103 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
10104 update_tg_load_avg(cfs_rq);
10105
10106 if (cfs_rq->nr_queued == 0)
10107 update_idle_cfs_rq_clock_pelt(cfs_rq);
10108
10109 if (cfs_rq == &rq->cfs)
10110 decayed = true;
10111 }
10112
10113 /* Propagate pending load changes to the parent, if any: */
10114 se = cfs_rq->tg->se[cpu];
10115 if (se && !skip_blocked_update(se))
10116 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
10117
10118 /*
10119 * There can be a lot of idle CPU cgroups. Don't let fully
10120 * decayed cfs_rqs linger on the list.
10121 */
10122 if (cfs_rq_is_decayed(cfs_rq))
10123 list_del_leaf_cfs_rq(cfs_rq);
10124
10125 /* Don't need periodic decay once load/util_avg are null */
10126 if (cfs_rq_has_blocked_load(cfs_rq))
10127 *done = false;
10128 }
10129
10130 return decayed;
10131 }
10132
10133 /*
10134 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
10135 * This needs to be done in a top-down fashion because the load of a child
10136 * group is a fraction of its parents load.
10137 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)10138 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
10139 {
10140 struct rq *rq = rq_of(cfs_rq);
10141 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
10142 unsigned long now = jiffies;
10143 unsigned long load;
10144
10145 if (cfs_rq->last_h_load_update == now)
10146 return;
10147
10148 WRITE_ONCE(cfs_rq->h_load_next, NULL);
10149 for_each_sched_entity(se) {
10150 cfs_rq = cfs_rq_of(se);
10151 WRITE_ONCE(cfs_rq->h_load_next, se);
10152 if (cfs_rq->last_h_load_update == now)
10153 break;
10154 }
10155
10156 if (!se) {
10157 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
10158 cfs_rq->last_h_load_update = now;
10159 }
10160
10161 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
10162 load = cfs_rq->h_load;
10163 load = div64_ul(load * se->avg.load_avg,
10164 cfs_rq_load_avg(cfs_rq) + 1);
10165 cfs_rq = group_cfs_rq(se);
10166 cfs_rq->h_load = load;
10167 cfs_rq->last_h_load_update = now;
10168 }
10169 }
10170
task_h_load(struct task_struct * p)10171 static unsigned long task_h_load(struct task_struct *p)
10172 {
10173 struct cfs_rq *cfs_rq = task_cfs_rq(p);
10174
10175 update_cfs_rq_h_load(cfs_rq);
10176 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
10177 cfs_rq_load_avg(cfs_rq) + 1);
10178 }
10179 #else /* !CONFIG_FAIR_GROUP_SCHED: */
__update_blocked_fair(struct rq * rq,bool * done)10180 static bool __update_blocked_fair(struct rq *rq, bool *done)
10181 {
10182 struct cfs_rq *cfs_rq = &rq->cfs;
10183 bool decayed;
10184
10185 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
10186 if (cfs_rq_has_blocked_load(cfs_rq))
10187 *done = false;
10188
10189 return decayed;
10190 }
10191
task_h_load(struct task_struct * p)10192 static unsigned long task_h_load(struct task_struct *p)
10193 {
10194 return p->se.avg.load_avg;
10195 }
10196 #endif /* !CONFIG_FAIR_GROUP_SCHED */
10197
__sched_balance_update_blocked_averages(struct rq * rq)10198 static void __sched_balance_update_blocked_averages(struct rq *rq)
10199 {
10200 bool decayed = false, done = true;
10201
10202 update_blocked_load_tick(rq);
10203
10204 decayed |= __update_blocked_others(rq, &done);
10205 decayed |= __update_blocked_fair(rq, &done);
10206
10207 update_has_blocked_load_status(rq, !done);
10208 if (decayed)
10209 cpufreq_update_util(rq, 0);
10210 }
10211
sched_balance_update_blocked_averages(int cpu)10212 static void sched_balance_update_blocked_averages(int cpu)
10213 {
10214 struct rq *rq = cpu_rq(cpu);
10215
10216 guard(rq_lock_irqsave)(rq);
10217 update_rq_clock(rq);
10218 __sched_balance_update_blocked_averages(rq);
10219 }
10220
10221 /********** Helpers for sched_balance_find_src_group ************************/
10222
10223 /*
10224 * sg_lb_stats - stats of a sched_group required for load-balancing:
10225 */
10226 struct sg_lb_stats {
10227 unsigned long avg_load; /* Avg load over the CPUs of the group */
10228 unsigned long group_load; /* Total load over the CPUs of the group */
10229 unsigned long group_capacity; /* Capacity over the CPUs of the group */
10230 unsigned long group_util; /* Total utilization over the CPUs of the group */
10231 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
10232 unsigned int sum_nr_running; /* Nr of all tasks running in the group */
10233 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
10234 unsigned int idle_cpus; /* Nr of idle CPUs in the group */
10235 unsigned int group_weight;
10236 enum group_type group_type;
10237 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
10238 unsigned int group_smt_balance; /* Task on busy SMT be moved */
10239 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
10240 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */
10241 #ifdef CONFIG_NUMA_BALANCING
10242 unsigned int nr_numa_running;
10243 unsigned int nr_preferred_running;
10244 #endif
10245 };
10246
10247 /*
10248 * sd_lb_stats - stats of a sched_domain required for load-balancing:
10249 */
10250 struct sd_lb_stats {
10251 struct sched_group *busiest; /* Busiest group in this sd */
10252 struct sched_group *local; /* Local group in this sd */
10253 unsigned long total_load; /* Total load of all groups in sd */
10254 unsigned long total_capacity; /* Total capacity of all groups in sd */
10255 unsigned long avg_load; /* Average load across all groups in sd */
10256 unsigned int prefer_sibling; /* Tasks should go to sibling first */
10257
10258 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
10259 struct sg_lb_stats local_stat; /* Statistics of the local group */
10260 };
10261
init_sd_lb_stats(struct sd_lb_stats * sds)10262 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
10263 {
10264 /*
10265 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
10266 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10267 * We must however set busiest_stat::group_type and
10268 * busiest_stat::idle_cpus to the worst busiest group because
10269 * update_sd_pick_busiest() reads these before assignment.
10270 */
10271 *sds = (struct sd_lb_stats){
10272 .busiest = NULL,
10273 .local = NULL,
10274 .total_load = 0UL,
10275 .total_capacity = 0UL,
10276 .busiest_stat = {
10277 .idle_cpus = UINT_MAX,
10278 .group_type = group_has_spare,
10279 },
10280 };
10281 }
10282
scale_rt_capacity(int cpu)10283 static unsigned long scale_rt_capacity(int cpu)
10284 {
10285 unsigned long max = get_actual_cpu_capacity(cpu);
10286 struct rq *rq = cpu_rq(cpu);
10287 unsigned long used, free;
10288 unsigned long irq;
10289
10290 irq = cpu_util_irq(rq);
10291
10292 if (unlikely(irq >= max))
10293 return 1;
10294
10295 /*
10296 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10297 * (running and not running) with weights 0 and 1024 respectively.
10298 */
10299 used = cpu_util_rt(rq);
10300 used += cpu_util_dl(rq);
10301
10302 if (unlikely(used >= max))
10303 return 1;
10304
10305 free = max - used;
10306
10307 return scale_irq_capacity(free, irq, max);
10308 }
10309
update_cpu_capacity(struct sched_domain * sd,int cpu)10310 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10311 {
10312 unsigned long capacity = scale_rt_capacity(cpu);
10313 struct sched_group *sdg = sd->groups;
10314
10315 if (!capacity)
10316 capacity = 1;
10317
10318 cpu_rq(cpu)->cpu_capacity = capacity;
10319 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10320
10321 sdg->sgc->capacity = capacity;
10322 sdg->sgc->min_capacity = capacity;
10323 sdg->sgc->max_capacity = capacity;
10324 }
10325
update_group_capacity(struct sched_domain * sd,int cpu)10326 void update_group_capacity(struct sched_domain *sd, int cpu)
10327 {
10328 struct sched_domain *child = sd->child;
10329 struct sched_group *group, *sdg = sd->groups;
10330 unsigned long capacity, min_capacity, max_capacity;
10331 unsigned long interval;
10332
10333 interval = msecs_to_jiffies(sd->balance_interval);
10334 interval = clamp(interval, 1UL, max_load_balance_interval);
10335 sdg->sgc->next_update = jiffies + interval;
10336
10337 if (!child) {
10338 update_cpu_capacity(sd, cpu);
10339 return;
10340 }
10341
10342 capacity = 0;
10343 min_capacity = ULONG_MAX;
10344 max_capacity = 0;
10345
10346 if (child->flags & SD_NUMA) {
10347 /*
10348 * SD_NUMA domains cannot assume that child groups
10349 * span the current group.
10350 */
10351
10352 for_each_cpu(cpu, sched_group_span(sdg)) {
10353 unsigned long cpu_cap = capacity_of(cpu);
10354
10355 capacity += cpu_cap;
10356 min_capacity = min(cpu_cap, min_capacity);
10357 max_capacity = max(cpu_cap, max_capacity);
10358 }
10359 } else {
10360 /*
10361 * !SD_NUMA domains can assume that child groups
10362 * span the current group.
10363 */
10364
10365 group = child->groups;
10366 do {
10367 struct sched_group_capacity *sgc = group->sgc;
10368
10369 capacity += sgc->capacity;
10370 min_capacity = min(sgc->min_capacity, min_capacity);
10371 max_capacity = max(sgc->max_capacity, max_capacity);
10372 group = group->next;
10373 } while (group != child->groups);
10374 }
10375
10376 sdg->sgc->capacity = capacity;
10377 sdg->sgc->min_capacity = min_capacity;
10378 sdg->sgc->max_capacity = max_capacity;
10379 }
10380
10381 /*
10382 * Check whether the capacity of the rq has been noticeably reduced by side
10383 * activity. The imbalance_pct is used for the threshold.
10384 * Return true is the capacity is reduced
10385 */
10386 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10387 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10388 {
10389 return ((rq->cpu_capacity * sd->imbalance_pct) <
10390 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10391 }
10392
10393 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10394 static inline bool check_misfit_status(struct rq *rq)
10395 {
10396 return rq->misfit_task_load;
10397 }
10398
10399 /*
10400 * Group imbalance indicates (and tries to solve) the problem where balancing
10401 * groups is inadequate due to ->cpus_ptr constraints.
10402 *
10403 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10404 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10405 * Something like:
10406 *
10407 * { 0 1 2 3 } { 4 5 6 7 }
10408 * * * * *
10409 *
10410 * If we were to balance group-wise we'd place two tasks in the first group and
10411 * two tasks in the second group. Clearly this is undesired as it will overload
10412 * cpu 3 and leave one of the CPUs in the second group unused.
10413 *
10414 * The current solution to this issue is detecting the skew in the first group
10415 * by noticing the lower domain failed to reach balance and had difficulty
10416 * moving tasks due to affinity constraints.
10417 *
10418 * When this is so detected; this group becomes a candidate for busiest; see
10419 * update_sd_pick_busiest(). And calculate_imbalance() and
10420 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10421 * to create an effective group imbalance.
10422 *
10423 * This is a somewhat tricky proposition since the next run might not find the
10424 * group imbalance and decide the groups need to be balanced again. A most
10425 * subtle and fragile situation.
10426 */
10427
sg_imbalanced(struct sched_group * group)10428 static inline int sg_imbalanced(struct sched_group *group)
10429 {
10430 return group->sgc->imbalance;
10431 }
10432
10433 /*
10434 * group_has_capacity returns true if the group has spare capacity that could
10435 * be used by some tasks.
10436 * We consider that a group has spare capacity if the number of task is
10437 * smaller than the number of CPUs or if the utilization is lower than the
10438 * available capacity for CFS tasks.
10439 * For the latter, we use a threshold to stabilize the state, to take into
10440 * account the variance of the tasks' load and to return true if the available
10441 * capacity in meaningful for the load balancer.
10442 * As an example, an available capacity of 1% can appear but it doesn't make
10443 * any benefit for the load balance.
10444 */
10445 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10446 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10447 {
10448 if (sgs->sum_nr_running < sgs->group_weight)
10449 return true;
10450
10451 if ((sgs->group_capacity * imbalance_pct) <
10452 (sgs->group_runnable * 100))
10453 return false;
10454
10455 if ((sgs->group_capacity * 100) >
10456 (sgs->group_util * imbalance_pct))
10457 return true;
10458
10459 return false;
10460 }
10461
10462 /*
10463 * group_is_overloaded returns true if the group has more tasks than it can
10464 * handle.
10465 * group_is_overloaded is not equals to !group_has_capacity because a group
10466 * with the exact right number of tasks, has no more spare capacity but is not
10467 * overloaded so both group_has_capacity and group_is_overloaded return
10468 * false.
10469 */
10470 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10471 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10472 {
10473 /*
10474 * With EAS and uclamp, 1 CPU in the group must be overutilized to
10475 * consider the group overloaded.
10476 */
10477 if (sched_energy_enabled() && !sgs->group_overutilized)
10478 return false;
10479
10480 if (sgs->sum_nr_running <= sgs->group_weight)
10481 return false;
10482
10483 if ((sgs->group_capacity * 100) <
10484 (sgs->group_util * imbalance_pct))
10485 return true;
10486
10487 if ((sgs->group_capacity * imbalance_pct) <
10488 (sgs->group_runnable * 100))
10489 return true;
10490
10491 return false;
10492 }
10493
10494 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10495 group_type group_classify(unsigned int imbalance_pct,
10496 struct sched_group *group,
10497 struct sg_lb_stats *sgs)
10498 {
10499 if (group_is_overloaded(imbalance_pct, sgs))
10500 return group_overloaded;
10501
10502 if (sg_imbalanced(group))
10503 return group_imbalanced;
10504
10505 if (sgs->group_asym_packing)
10506 return group_asym_packing;
10507
10508 if (sgs->group_smt_balance)
10509 return group_smt_balance;
10510
10511 if (sgs->group_misfit_task_load)
10512 return group_misfit_task;
10513
10514 if (!group_has_capacity(imbalance_pct, sgs))
10515 return group_fully_busy;
10516
10517 return group_has_spare;
10518 }
10519
10520 /**
10521 * sched_use_asym_prio - Check whether asym_packing priority must be used
10522 * @sd: The scheduling domain of the load balancing
10523 * @cpu: A CPU
10524 *
10525 * Always use CPU priority when balancing load between SMT siblings. When
10526 * balancing load between cores, it is not sufficient that @cpu is idle. Only
10527 * use CPU priority if the whole core is idle.
10528 *
10529 * Returns: True if the priority of @cpu must be followed. False otherwise.
10530 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10531 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10532 {
10533 if (!(sd->flags & SD_ASYM_PACKING))
10534 return false;
10535
10536 if (!sched_smt_active())
10537 return true;
10538
10539 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10540 }
10541
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10542 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10543 {
10544 /*
10545 * First check if @dst_cpu can do asym_packing load balance. Only do it
10546 * if it has higher priority than @src_cpu.
10547 */
10548 return sched_use_asym_prio(sd, dst_cpu) &&
10549 sched_asym_prefer(dst_cpu, src_cpu);
10550 }
10551
10552 /**
10553 * sched_group_asym - Check if the destination CPU can do asym_packing balance
10554 * @env: The load balancing environment
10555 * @sgs: Load-balancing statistics of the candidate busiest group
10556 * @group: The candidate busiest group
10557 *
10558 * @env::dst_cpu can do asym_packing if it has higher priority than the
10559 * preferred CPU of @group.
10560 *
10561 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10562 * otherwise.
10563 */
10564 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10565 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10566 {
10567 /*
10568 * CPU priorities do not make sense for SMT cores with more than one
10569 * busy sibling.
10570 */
10571 if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10572 (sgs->group_weight - sgs->idle_cpus != 1))
10573 return false;
10574
10575 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
10576 }
10577
10578 /* 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)10579 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10580 struct sched_group *sg2)
10581 {
10582 if (!sg1 || !sg2)
10583 return false;
10584
10585 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10586 (sg2->flags & SD_SHARE_CPUCAPACITY);
10587 }
10588
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10589 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10590 struct sched_group *group)
10591 {
10592 if (!env->idle)
10593 return false;
10594
10595 /*
10596 * For SMT source group, it is better to move a task
10597 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10598 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10599 * will not be on.
10600 */
10601 if (group->flags & SD_SHARE_CPUCAPACITY &&
10602 sgs->sum_h_nr_running > 1)
10603 return true;
10604
10605 return false;
10606 }
10607
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10608 static inline long sibling_imbalance(struct lb_env *env,
10609 struct sd_lb_stats *sds,
10610 struct sg_lb_stats *busiest,
10611 struct sg_lb_stats *local)
10612 {
10613 int ncores_busiest, ncores_local;
10614 long imbalance;
10615
10616 if (!env->idle || !busiest->sum_nr_running)
10617 return 0;
10618
10619 ncores_busiest = sds->busiest->cores;
10620 ncores_local = sds->local->cores;
10621
10622 if (ncores_busiest == ncores_local) {
10623 imbalance = busiest->sum_nr_running;
10624 lsub_positive(&imbalance, local->sum_nr_running);
10625 return imbalance;
10626 }
10627
10628 /* Balance such that nr_running/ncores ratio are same on both groups */
10629 imbalance = ncores_local * busiest->sum_nr_running;
10630 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10631 /* Normalize imbalance and do rounding on normalization */
10632 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10633 imbalance /= ncores_local + ncores_busiest;
10634
10635 /* Take advantage of resource in an empty sched group */
10636 if (imbalance <= 1 && local->sum_nr_running == 0 &&
10637 busiest->sum_nr_running > 1)
10638 imbalance = 2;
10639
10640 return imbalance;
10641 }
10642
10643 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10644 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10645 {
10646 /*
10647 * When there is more than 1 task, the group_overloaded case already
10648 * takes care of cpu with reduced capacity
10649 */
10650 if (rq->cfs.h_nr_runnable != 1)
10651 return false;
10652
10653 return check_cpu_capacity(rq, sd);
10654 }
10655
10656 /**
10657 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10658 * @env: The load balancing environment.
10659 * @sds: Load-balancing data with statistics of the local group.
10660 * @group: sched_group whose statistics are to be updated.
10661 * @sgs: variable to hold the statistics for this group.
10662 * @sg_overloaded: sched_group is overloaded
10663 */
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)10664 static inline void update_sg_lb_stats(struct lb_env *env,
10665 struct sd_lb_stats *sds,
10666 struct sched_group *group,
10667 struct sg_lb_stats *sgs,
10668 bool *sg_overloaded)
10669 {
10670 int i, nr_running, local_group, sd_flags = env->sd->flags;
10671 bool balancing_at_rd = !env->sd->parent;
10672
10673 memset(sgs, 0, sizeof(*sgs));
10674
10675 local_group = group == sds->local;
10676
10677 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10678 struct rq *rq = cpu_rq(i);
10679 unsigned long load = cpu_load(rq);
10680
10681 sgs->group_load += load;
10682 sgs->group_util += cpu_util_cfs(i);
10683 sgs->group_runnable += cpu_runnable(rq);
10684 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10685
10686 nr_running = rq->nr_running;
10687 sgs->sum_nr_running += nr_running;
10688
10689 if (cpu_overutilized(i))
10690 sgs->group_overutilized = 1;
10691
10692 /*
10693 * No need to call idle_cpu() if nr_running is not 0
10694 */
10695 if (!nr_running && idle_cpu(i)) {
10696 sgs->idle_cpus++;
10697 /* Idle cpu can't have misfit task */
10698 continue;
10699 }
10700
10701 /* Overload indicator is only updated at root domain */
10702 if (balancing_at_rd && nr_running > 1)
10703 *sg_overloaded = 1;
10704
10705 #ifdef CONFIG_NUMA_BALANCING
10706 /* Only fbq_classify_group() uses this to classify NUMA groups */
10707 if (sd_flags & SD_NUMA) {
10708 sgs->nr_numa_running += rq->nr_numa_running;
10709 sgs->nr_preferred_running += rq->nr_preferred_running;
10710 }
10711 #endif
10712 if (local_group)
10713 continue;
10714
10715 if (sd_flags & SD_ASYM_CPUCAPACITY) {
10716 /* Check for a misfit task on the cpu */
10717 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10718 sgs->group_misfit_task_load = rq->misfit_task_load;
10719 *sg_overloaded = 1;
10720 }
10721 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10722 /* Check for a task running on a CPU with reduced capacity */
10723 if (sgs->group_misfit_task_load < load)
10724 sgs->group_misfit_task_load = load;
10725 }
10726 }
10727
10728 sgs->group_capacity = group->sgc->capacity;
10729
10730 sgs->group_weight = group->group_weight;
10731
10732 /* Check if dst CPU is idle and preferred to this group */
10733 if (!local_group && env->idle && sgs->sum_h_nr_running &&
10734 sched_group_asym(env, sgs, group))
10735 sgs->group_asym_packing = 1;
10736
10737 /* Check for loaded SMT group to be balanced to dst CPU */
10738 if (!local_group && smt_balance(env, sgs, group))
10739 sgs->group_smt_balance = 1;
10740
10741 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10742
10743 /* Computing avg_load makes sense only when group is overloaded */
10744 if (sgs->group_type == group_overloaded)
10745 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10746 sgs->group_capacity;
10747 }
10748
10749 /**
10750 * update_sd_pick_busiest - return 1 on busiest group
10751 * @env: The load balancing environment.
10752 * @sds: sched_domain statistics
10753 * @sg: sched_group candidate to be checked for being the busiest
10754 * @sgs: sched_group statistics
10755 *
10756 * Determine if @sg is a busier group than the previously selected
10757 * busiest group.
10758 *
10759 * Return: %true if @sg is a busier group than the previously selected
10760 * busiest group. %false otherwise.
10761 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10762 static bool update_sd_pick_busiest(struct lb_env *env,
10763 struct sd_lb_stats *sds,
10764 struct sched_group *sg,
10765 struct sg_lb_stats *sgs)
10766 {
10767 struct sg_lb_stats *busiest = &sds->busiest_stat;
10768
10769 /* Make sure that there is at least one task to pull */
10770 if (!sgs->sum_h_nr_running)
10771 return false;
10772
10773 /*
10774 * Don't try to pull misfit tasks we can't help.
10775 * We can use max_capacity here as reduction in capacity on some
10776 * CPUs in the group should either be possible to resolve
10777 * internally or be covered by avg_load imbalance (eventually).
10778 */
10779 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10780 (sgs->group_type == group_misfit_task) &&
10781 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10782 sds->local_stat.group_type != group_has_spare))
10783 return false;
10784
10785 if (sgs->group_type > busiest->group_type)
10786 return true;
10787
10788 if (sgs->group_type < busiest->group_type)
10789 return false;
10790
10791 /*
10792 * The candidate and the current busiest group are the same type of
10793 * group. Let check which one is the busiest according to the type.
10794 */
10795
10796 switch (sgs->group_type) {
10797 case group_overloaded:
10798 /* Select the overloaded group with highest avg_load. */
10799 return sgs->avg_load > busiest->avg_load;
10800
10801 case group_imbalanced:
10802 /*
10803 * Select the 1st imbalanced group as we don't have any way to
10804 * choose one more than another.
10805 */
10806 return false;
10807
10808 case group_asym_packing:
10809 /* Prefer to move from lowest priority CPU's work */
10810 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
10811 READ_ONCE(sg->asym_prefer_cpu));
10812
10813 case group_misfit_task:
10814 /*
10815 * If we have more than one misfit sg go with the biggest
10816 * misfit.
10817 */
10818 return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10819
10820 case group_smt_balance:
10821 /*
10822 * Check if we have spare CPUs on either SMT group to
10823 * choose has spare or fully busy handling.
10824 */
10825 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10826 goto has_spare;
10827
10828 fallthrough;
10829
10830 case group_fully_busy:
10831 /*
10832 * Select the fully busy group with highest avg_load. In
10833 * theory, there is no need to pull task from such kind of
10834 * group because tasks have all compute capacity that they need
10835 * but we can still improve the overall throughput by reducing
10836 * contention when accessing shared HW resources.
10837 *
10838 * XXX for now avg_load is not computed and always 0 so we
10839 * select the 1st one, except if @sg is composed of SMT
10840 * siblings.
10841 */
10842
10843 if (sgs->avg_load < busiest->avg_load)
10844 return false;
10845
10846 if (sgs->avg_load == busiest->avg_load) {
10847 /*
10848 * SMT sched groups need more help than non-SMT groups.
10849 * If @sg happens to also be SMT, either choice is good.
10850 */
10851 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10852 return false;
10853 }
10854
10855 break;
10856
10857 case group_has_spare:
10858 /*
10859 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10860 * as we do not want to pull task off SMT core with one task
10861 * and make the core idle.
10862 */
10863 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10864 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10865 return false;
10866 else
10867 return true;
10868 }
10869 has_spare:
10870
10871 /*
10872 * Select not overloaded group with lowest number of idle CPUs
10873 * and highest number of running tasks. We could also compare
10874 * the spare capacity which is more stable but it can end up
10875 * that the group has less spare capacity but finally more idle
10876 * CPUs which means less opportunity to pull tasks.
10877 */
10878 if (sgs->idle_cpus > busiest->idle_cpus)
10879 return false;
10880 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10881 (sgs->sum_nr_running <= busiest->sum_nr_running))
10882 return false;
10883
10884 break;
10885 }
10886
10887 /*
10888 * Candidate sg has no more than one task per CPU and has higher
10889 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10890 * throughput. Maximize throughput, power/energy consequences are not
10891 * considered.
10892 */
10893 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10894 (sgs->group_type <= group_fully_busy) &&
10895 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10896 return false;
10897
10898 return true;
10899 }
10900
10901 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10902 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10903 {
10904 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10905 return regular;
10906 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10907 return remote;
10908 return all;
10909 }
10910
fbq_classify_rq(struct rq * rq)10911 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10912 {
10913 if (rq->nr_running > rq->nr_numa_running)
10914 return regular;
10915 if (rq->nr_running > rq->nr_preferred_running)
10916 return remote;
10917 return all;
10918 }
10919 #else /* !CONFIG_NUMA_BALANCING: */
fbq_classify_group(struct sg_lb_stats * sgs)10920 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10921 {
10922 return all;
10923 }
10924
fbq_classify_rq(struct rq * rq)10925 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10926 {
10927 return regular;
10928 }
10929 #endif /* !CONFIG_NUMA_BALANCING */
10930
10931
10932 struct sg_lb_stats;
10933
10934 /*
10935 * task_running_on_cpu - return 1 if @p is running on @cpu.
10936 */
10937
task_running_on_cpu(int cpu,struct task_struct * p)10938 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10939 {
10940 /* Task has no contribution or is new */
10941 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10942 return 0;
10943
10944 if (task_on_rq_queued(p))
10945 return 1;
10946
10947 return 0;
10948 }
10949
10950 /**
10951 * idle_cpu_without - would a given CPU be idle without p ?
10952 * @cpu: the processor on which idleness is tested.
10953 * @p: task which should be ignored.
10954 *
10955 * Return: 1 if the CPU would be idle. 0 otherwise.
10956 */
idle_cpu_without(int cpu,struct task_struct * p)10957 static int idle_cpu_without(int cpu, struct task_struct *p)
10958 {
10959 struct rq *rq = cpu_rq(cpu);
10960
10961 if (rq->curr != rq->idle && rq->curr != p)
10962 return 0;
10963
10964 /*
10965 * rq->nr_running can't be used but an updated version without the
10966 * impact of p on cpu must be used instead. The updated nr_running
10967 * be computed and tested before calling idle_cpu_without().
10968 */
10969
10970 if (rq->ttwu_pending)
10971 return 0;
10972
10973 return 1;
10974 }
10975
10976 /*
10977 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10978 * @sd: The sched_domain level to look for idlest group.
10979 * @group: sched_group whose statistics are to be updated.
10980 * @sgs: variable to hold the statistics for this group.
10981 * @p: The task for which we look for the idlest group/CPU.
10982 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10983 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10984 struct sched_group *group,
10985 struct sg_lb_stats *sgs,
10986 struct task_struct *p)
10987 {
10988 int i, nr_running;
10989
10990 memset(sgs, 0, sizeof(*sgs));
10991
10992 /* Assume that task can't fit any CPU of the group */
10993 if (sd->flags & SD_ASYM_CPUCAPACITY)
10994 sgs->group_misfit_task_load = 1;
10995
10996 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
10997 struct rq *rq = cpu_rq(i);
10998 unsigned int local;
10999
11000 sgs->group_load += cpu_load_without(rq, p);
11001 sgs->group_util += cpu_util_without(i, p);
11002 sgs->group_runnable += cpu_runnable_without(rq, p);
11003 local = task_running_on_cpu(i, p);
11004 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
11005
11006 nr_running = rq->nr_running - local;
11007 sgs->sum_nr_running += nr_running;
11008
11009 /*
11010 * No need to call idle_cpu_without() if nr_running is not 0
11011 */
11012 if (!nr_running && idle_cpu_without(i, p))
11013 sgs->idle_cpus++;
11014
11015 /* Check if task fits in the CPU */
11016 if (sd->flags & SD_ASYM_CPUCAPACITY &&
11017 sgs->group_misfit_task_load &&
11018 task_fits_cpu(p, i))
11019 sgs->group_misfit_task_load = 0;
11020
11021 }
11022
11023 sgs->group_capacity = group->sgc->capacity;
11024
11025 sgs->group_weight = group->group_weight;
11026
11027 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
11028
11029 /*
11030 * Computing avg_load makes sense only when group is fully busy or
11031 * overloaded
11032 */
11033 if (sgs->group_type == group_fully_busy ||
11034 sgs->group_type == group_overloaded)
11035 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
11036 sgs->group_capacity;
11037 }
11038
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)11039 static bool update_pick_idlest(struct sched_group *idlest,
11040 struct sg_lb_stats *idlest_sgs,
11041 struct sched_group *group,
11042 struct sg_lb_stats *sgs)
11043 {
11044 if (sgs->group_type < idlest_sgs->group_type)
11045 return true;
11046
11047 if (sgs->group_type > idlest_sgs->group_type)
11048 return false;
11049
11050 /*
11051 * The candidate and the current idlest group are the same type of
11052 * group. Let check which one is the idlest according to the type.
11053 */
11054
11055 switch (sgs->group_type) {
11056 case group_overloaded:
11057 case group_fully_busy:
11058 /* Select the group with lowest avg_load. */
11059 if (idlest_sgs->avg_load <= sgs->avg_load)
11060 return false;
11061 break;
11062
11063 case group_imbalanced:
11064 case group_asym_packing:
11065 case group_smt_balance:
11066 /* Those types are not used in the slow wakeup path */
11067 return false;
11068
11069 case group_misfit_task:
11070 /* Select group with the highest max capacity */
11071 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
11072 return false;
11073 break;
11074
11075 case group_has_spare:
11076 /* Select group with most idle CPUs */
11077 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
11078 return false;
11079
11080 /* Select group with lowest group_util */
11081 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
11082 idlest_sgs->group_util <= sgs->group_util)
11083 return false;
11084
11085 break;
11086 }
11087
11088 return true;
11089 }
11090
11091 /*
11092 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
11093 * domain.
11094 *
11095 * Assumes p is allowed on at least one CPU in sd.
11096 */
11097 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)11098 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
11099 {
11100 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
11101 struct sg_lb_stats local_sgs, tmp_sgs;
11102 struct sg_lb_stats *sgs;
11103 unsigned long imbalance;
11104 struct sg_lb_stats idlest_sgs = {
11105 .avg_load = UINT_MAX,
11106 .group_type = group_overloaded,
11107 };
11108
11109 do {
11110 int local_group;
11111
11112 /* Skip over this group if it has no CPUs allowed */
11113 if (!cpumask_intersects(sched_group_span(group),
11114 p->cpus_ptr))
11115 continue;
11116
11117 /* Skip over this group if no cookie matched */
11118 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
11119 continue;
11120
11121 local_group = cpumask_test_cpu(this_cpu,
11122 sched_group_span(group));
11123
11124 if (local_group) {
11125 sgs = &local_sgs;
11126 local = group;
11127 } else {
11128 sgs = &tmp_sgs;
11129 }
11130
11131 update_sg_wakeup_stats(sd, group, sgs, p);
11132
11133 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
11134 idlest = group;
11135 idlest_sgs = *sgs;
11136 }
11137
11138 } while (group = group->next, group != sd->groups);
11139
11140
11141 /* There is no idlest group to push tasks to */
11142 if (!idlest)
11143 return NULL;
11144
11145 /* The local group has been skipped because of CPU affinity */
11146 if (!local)
11147 return idlest;
11148
11149 /*
11150 * If the local group is idler than the selected idlest group
11151 * don't try and push the task.
11152 */
11153 if (local_sgs.group_type < idlest_sgs.group_type)
11154 return NULL;
11155
11156 /*
11157 * If the local group is busier than the selected idlest group
11158 * try and push the task.
11159 */
11160 if (local_sgs.group_type > idlest_sgs.group_type)
11161 return idlest;
11162
11163 switch (local_sgs.group_type) {
11164 case group_overloaded:
11165 case group_fully_busy:
11166
11167 /* Calculate allowed imbalance based on load */
11168 imbalance = scale_load_down(NICE_0_LOAD) *
11169 (sd->imbalance_pct-100) / 100;
11170
11171 /*
11172 * When comparing groups across NUMA domains, it's possible for
11173 * the local domain to be very lightly loaded relative to the
11174 * remote domains but "imbalance" skews the comparison making
11175 * remote CPUs look much more favourable. When considering
11176 * cross-domain, add imbalance to the load on the remote node
11177 * and consider staying local.
11178 */
11179
11180 if ((sd->flags & SD_NUMA) &&
11181 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
11182 return NULL;
11183
11184 /*
11185 * If the local group is less loaded than the selected
11186 * idlest group don't try and push any tasks.
11187 */
11188 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
11189 return NULL;
11190
11191 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
11192 return NULL;
11193 break;
11194
11195 case group_imbalanced:
11196 case group_asym_packing:
11197 case group_smt_balance:
11198 /* Those type are not used in the slow wakeup path */
11199 return NULL;
11200
11201 case group_misfit_task:
11202 /* Select group with the highest max capacity */
11203 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
11204 return NULL;
11205 break;
11206
11207 case group_has_spare:
11208 #ifdef CONFIG_NUMA
11209 if (sd->flags & SD_NUMA) {
11210 int imb_numa_nr = sd->imb_numa_nr;
11211 #ifdef CONFIG_NUMA_BALANCING
11212 int idlest_cpu;
11213 /*
11214 * If there is spare capacity at NUMA, try to select
11215 * the preferred node
11216 */
11217 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
11218 return NULL;
11219
11220 idlest_cpu = cpumask_first(sched_group_span(idlest));
11221 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
11222 return idlest;
11223 #endif /* CONFIG_NUMA_BALANCING */
11224 /*
11225 * Otherwise, keep the task close to the wakeup source
11226 * and improve locality if the number of running tasks
11227 * would remain below threshold where an imbalance is
11228 * allowed while accounting for the possibility the
11229 * task is pinned to a subset of CPUs. If there is a
11230 * real need of migration, periodic load balance will
11231 * take care of it.
11232 */
11233 if (p->nr_cpus_allowed != NR_CPUS) {
11234 unsigned int w = cpumask_weight_and(p->cpus_ptr,
11235 sched_group_span(local));
11236 imb_numa_nr = min(w, sd->imb_numa_nr);
11237 }
11238
11239 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
11240 if (!adjust_numa_imbalance(imbalance,
11241 local_sgs.sum_nr_running + 1,
11242 imb_numa_nr)) {
11243 return NULL;
11244 }
11245 }
11246 #endif /* CONFIG_NUMA */
11247
11248 /*
11249 * Select group with highest number of idle CPUs. We could also
11250 * compare the utilization which is more stable but it can end
11251 * up that the group has less spare capacity but finally more
11252 * idle CPUs which means more opportunity to run task.
11253 */
11254 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
11255 return NULL;
11256 break;
11257 }
11258
11259 return idlest;
11260 }
11261
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)11262 static void update_idle_cpu_scan(struct lb_env *env,
11263 unsigned long sum_util)
11264 {
11265 struct sched_domain_shared *sd_share;
11266 struct sched_domain *sd = env->sd;
11267 int llc_weight, pct;
11268 u64 x, y, tmp;
11269 /*
11270 * Update the number of CPUs to scan in LLC domain, which could
11271 * be used as a hint in select_idle_cpu(). The update of sd_share
11272 * could be expensive because it is within a shared cache line.
11273 * So the write of this hint only occurs during periodic load
11274 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11275 * can fire way more frequently than the former.
11276 */
11277 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11278 return;
11279
11280 sd_share = sd->shared;
11281 if (!sd_share)
11282 return;
11283
11284 /*
11285 * The number of CPUs to search drops as sum_util increases, when
11286 * sum_util hits 85% or above, the scan stops.
11287 * The reason to choose 85% as the threshold is because this is the
11288 * imbalance_pct(117) when a LLC sched group is overloaded.
11289 *
11290 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
11291 * and y'= y / SCHED_CAPACITY_SCALE
11292 *
11293 * x is the ratio of sum_util compared to the CPU capacity:
11294 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11295 * y' is the ratio of CPUs to be scanned in the LLC domain,
11296 * and the number of CPUs to scan is calculated by:
11297 *
11298 * nr_scan = llc_weight * y' [2]
11299 *
11300 * When x hits the threshold of overloaded, AKA, when
11301 * x = 100 / pct, y drops to 0. According to [1],
11302 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11303 *
11304 * Scale x by SCHED_CAPACITY_SCALE:
11305 * x' = sum_util / llc_weight; [3]
11306 *
11307 * and finally [1] becomes:
11308 * y = SCHED_CAPACITY_SCALE -
11309 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
11310 *
11311 */
11312 /* equation [3] */
11313 x = sum_util;
11314 llc_weight = sd->span_weight;
11315 do_div(x, llc_weight);
11316
11317 /* equation [4] */
11318 pct = sd->imbalance_pct;
11319 tmp = x * x * pct * pct;
11320 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11321 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11322 y = SCHED_CAPACITY_SCALE - tmp;
11323
11324 /* equation [2] */
11325 y *= llc_weight;
11326 do_div(y, SCHED_CAPACITY_SCALE);
11327 if ((int)y != sd_share->nr_idle_scan)
11328 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11329 }
11330
11331 /**
11332 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11333 * @env: The load balancing environment.
11334 * @sds: variable to hold the statistics for this sched_domain.
11335 */
11336
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11337 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11338 {
11339 struct sched_group *sg = env->sd->groups;
11340 struct sg_lb_stats *local = &sds->local_stat;
11341 struct sg_lb_stats tmp_sgs;
11342 unsigned long sum_util = 0;
11343 bool sg_overloaded = 0, sg_overutilized = 0;
11344
11345 do {
11346 struct sg_lb_stats *sgs = &tmp_sgs;
11347 int local_group;
11348
11349 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11350 if (local_group) {
11351 sds->local = sg;
11352 sgs = local;
11353
11354 if (env->idle != CPU_NEWLY_IDLE ||
11355 time_after_eq(jiffies, sg->sgc->next_update))
11356 update_group_capacity(env->sd, env->dst_cpu);
11357 }
11358
11359 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded);
11360
11361 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11362 sds->busiest = sg;
11363 sds->busiest_stat = *sgs;
11364 }
11365
11366 sg_overutilized |= sgs->group_overutilized;
11367
11368 /* Now, start updating sd_lb_stats */
11369 sds->total_load += sgs->group_load;
11370 sds->total_capacity += sgs->group_capacity;
11371
11372 sum_util += sgs->group_util;
11373 sg = sg->next;
11374 } while (sg != env->sd->groups);
11375
11376 /*
11377 * Indicate that the child domain of the busiest group prefers tasks
11378 * go to a child's sibling domains first. NB the flags of a sched group
11379 * are those of the child domain.
11380 */
11381 if (sds->busiest)
11382 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11383
11384
11385 if (env->sd->flags & SD_NUMA)
11386 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11387
11388 if (!env->sd->parent) {
11389 /* update overload indicator if we are at root domain */
11390 set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11391
11392 /* Update over-utilization (tipping point, U >= 0) indicator */
11393 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11394 } else if (sg_overutilized) {
11395 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11396 }
11397
11398 update_idle_cpu_scan(env, sum_util);
11399 }
11400
11401 /**
11402 * calculate_imbalance - Calculate the amount of imbalance present within the
11403 * groups of a given sched_domain during load balance.
11404 * @env: load balance environment
11405 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11406 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11407 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11408 {
11409 struct sg_lb_stats *local, *busiest;
11410
11411 local = &sds->local_stat;
11412 busiest = &sds->busiest_stat;
11413
11414 if (busiest->group_type == group_misfit_task) {
11415 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11416 /* Set imbalance to allow misfit tasks to be balanced. */
11417 env->migration_type = migrate_misfit;
11418 env->imbalance = 1;
11419 } else {
11420 /*
11421 * Set load imbalance to allow moving task from cpu
11422 * with reduced capacity.
11423 */
11424 env->migration_type = migrate_load;
11425 env->imbalance = busiest->group_misfit_task_load;
11426 }
11427 return;
11428 }
11429
11430 if (busiest->group_type == group_asym_packing) {
11431 /*
11432 * In case of asym capacity, we will try to migrate all load to
11433 * the preferred CPU.
11434 */
11435 env->migration_type = migrate_task;
11436 env->imbalance = busiest->sum_h_nr_running;
11437 return;
11438 }
11439
11440 if (busiest->group_type == group_smt_balance) {
11441 /* Reduce number of tasks sharing CPU capacity */
11442 env->migration_type = migrate_task;
11443 env->imbalance = 1;
11444 return;
11445 }
11446
11447 if (busiest->group_type == group_imbalanced) {
11448 /*
11449 * In the group_imb case we cannot rely on group-wide averages
11450 * to ensure CPU-load equilibrium, try to move any task to fix
11451 * the imbalance. The next load balance will take care of
11452 * balancing back the system.
11453 */
11454 env->migration_type = migrate_task;
11455 env->imbalance = 1;
11456 return;
11457 }
11458
11459 /*
11460 * Try to use spare capacity of local group without overloading it or
11461 * emptying busiest.
11462 */
11463 if (local->group_type == group_has_spare) {
11464 if ((busiest->group_type > group_fully_busy) &&
11465 !(env->sd->flags & SD_SHARE_LLC)) {
11466 /*
11467 * If busiest is overloaded, try to fill spare
11468 * capacity. This might end up creating spare capacity
11469 * in busiest or busiest still being overloaded but
11470 * there is no simple way to directly compute the
11471 * amount of load to migrate in order to balance the
11472 * system.
11473 */
11474 env->migration_type = migrate_util;
11475 env->imbalance = max(local->group_capacity, local->group_util) -
11476 local->group_util;
11477
11478 /*
11479 * In some cases, the group's utilization is max or even
11480 * higher than capacity because of migrations but the
11481 * local CPU is (newly) idle. There is at least one
11482 * waiting task in this overloaded busiest group. Let's
11483 * try to pull it.
11484 */
11485 if (env->idle && env->imbalance == 0) {
11486 env->migration_type = migrate_task;
11487 env->imbalance = 1;
11488 }
11489
11490 return;
11491 }
11492
11493 if (busiest->group_weight == 1 || sds->prefer_sibling) {
11494 /*
11495 * When prefer sibling, evenly spread running tasks on
11496 * groups.
11497 */
11498 env->migration_type = migrate_task;
11499 env->imbalance = sibling_imbalance(env, sds, busiest, local);
11500 } else {
11501
11502 /*
11503 * If there is no overload, we just want to even the number of
11504 * idle CPUs.
11505 */
11506 env->migration_type = migrate_task;
11507 env->imbalance = max_t(long, 0,
11508 (local->idle_cpus - busiest->idle_cpus));
11509 }
11510
11511 #ifdef CONFIG_NUMA
11512 /* Consider allowing a small imbalance between NUMA groups */
11513 if (env->sd->flags & SD_NUMA) {
11514 env->imbalance = adjust_numa_imbalance(env->imbalance,
11515 local->sum_nr_running + 1,
11516 env->sd->imb_numa_nr);
11517 }
11518 #endif
11519
11520 /* Number of tasks to move to restore balance */
11521 env->imbalance >>= 1;
11522
11523 return;
11524 }
11525
11526 /*
11527 * Local is fully busy but has to take more load to relieve the
11528 * busiest group
11529 */
11530 if (local->group_type < group_overloaded) {
11531 /*
11532 * Local will become overloaded so the avg_load metrics are
11533 * finally needed.
11534 */
11535
11536 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11537 local->group_capacity;
11538
11539 /*
11540 * If the local group is more loaded than the selected
11541 * busiest group don't try to pull any tasks.
11542 */
11543 if (local->avg_load >= busiest->avg_load) {
11544 env->imbalance = 0;
11545 return;
11546 }
11547
11548 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11549 sds->total_capacity;
11550
11551 /*
11552 * If the local group is more loaded than the average system
11553 * load, don't try to pull any tasks.
11554 */
11555 if (local->avg_load >= sds->avg_load) {
11556 env->imbalance = 0;
11557 return;
11558 }
11559
11560 }
11561
11562 /*
11563 * Both group are or will become overloaded and we're trying to get all
11564 * the CPUs to the average_load, so we don't want to push ourselves
11565 * above the average load, nor do we wish to reduce the max loaded CPU
11566 * below the average load. At the same time, we also don't want to
11567 * reduce the group load below the group capacity. Thus we look for
11568 * the minimum possible imbalance.
11569 */
11570 env->migration_type = migrate_load;
11571 env->imbalance = min(
11572 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11573 (sds->avg_load - local->avg_load) * local->group_capacity
11574 ) / SCHED_CAPACITY_SCALE;
11575 }
11576
11577 /******* sched_balance_find_src_group() helpers end here *********************/
11578
11579 /*
11580 * Decision matrix according to the local and busiest group type:
11581 *
11582 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11583 * has_spare nr_idle balanced N/A N/A balanced balanced
11584 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
11585 * misfit_task force N/A N/A N/A N/A N/A
11586 * asym_packing force force N/A N/A force force
11587 * imbalanced force force N/A N/A force force
11588 * overloaded force force N/A N/A force avg_load
11589 *
11590 * N/A : Not Applicable because already filtered while updating
11591 * statistics.
11592 * balanced : The system is balanced for these 2 groups.
11593 * force : Calculate the imbalance as load migration is probably needed.
11594 * avg_load : Only if imbalance is significant enough.
11595 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
11596 * different in groups.
11597 */
11598
11599 /**
11600 * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11601 * if there is an imbalance.
11602 * @env: The load balancing environment.
11603 *
11604 * Also calculates the amount of runnable load which should be moved
11605 * to restore balance.
11606 *
11607 * Return: - The busiest group if imbalance exists.
11608 */
sched_balance_find_src_group(struct lb_env * env)11609 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11610 {
11611 struct sg_lb_stats *local, *busiest;
11612 struct sd_lb_stats sds;
11613
11614 init_sd_lb_stats(&sds);
11615
11616 /*
11617 * Compute the various statistics relevant for load balancing at
11618 * this level.
11619 */
11620 update_sd_lb_stats(env, &sds);
11621
11622 /* There is no busy sibling group to pull tasks from */
11623 if (!sds.busiest)
11624 goto out_balanced;
11625
11626 busiest = &sds.busiest_stat;
11627
11628 /* Misfit tasks should be dealt with regardless of the avg load */
11629 if (busiest->group_type == group_misfit_task)
11630 goto force_balance;
11631
11632 if (!is_rd_overutilized(env->dst_rq->rd) &&
11633 rcu_dereference_all(env->dst_rq->rd->pd))
11634 goto out_balanced;
11635
11636 /* ASYM feature bypasses nice load balance check */
11637 if (busiest->group_type == group_asym_packing)
11638 goto force_balance;
11639
11640 /*
11641 * If the busiest group is imbalanced the below checks don't
11642 * work because they assume all things are equal, which typically
11643 * isn't true due to cpus_ptr constraints and the like.
11644 */
11645 if (busiest->group_type == group_imbalanced)
11646 goto force_balance;
11647
11648 local = &sds.local_stat;
11649 /*
11650 * If the local group is busier than the selected busiest group
11651 * don't try and pull any tasks.
11652 */
11653 if (local->group_type > busiest->group_type)
11654 goto out_balanced;
11655
11656 /*
11657 * When groups are overloaded, use the avg_load to ensure fairness
11658 * between tasks.
11659 */
11660 if (local->group_type == group_overloaded) {
11661 /*
11662 * If the local group is more loaded than the selected
11663 * busiest group don't try to pull any tasks.
11664 */
11665 if (local->avg_load >= busiest->avg_load)
11666 goto out_balanced;
11667
11668 /* XXX broken for overlapping NUMA groups */
11669 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11670 sds.total_capacity;
11671
11672 /*
11673 * Don't pull any tasks if this group is already above the
11674 * domain average load.
11675 */
11676 if (local->avg_load >= sds.avg_load)
11677 goto out_balanced;
11678
11679 /*
11680 * If the busiest group is more loaded, use imbalance_pct to be
11681 * conservative.
11682 */
11683 if (100 * busiest->avg_load <=
11684 env->sd->imbalance_pct * local->avg_load)
11685 goto out_balanced;
11686 }
11687
11688 /*
11689 * Try to move all excess tasks to a sibling domain of the busiest
11690 * group's child domain.
11691 */
11692 if (sds.prefer_sibling && local->group_type == group_has_spare &&
11693 sibling_imbalance(env, &sds, busiest, local) > 1)
11694 goto force_balance;
11695
11696 if (busiest->group_type != group_overloaded) {
11697 if (!env->idle) {
11698 /*
11699 * If the busiest group is not overloaded (and as a
11700 * result the local one too) but this CPU is already
11701 * busy, let another idle CPU try to pull task.
11702 */
11703 goto out_balanced;
11704 }
11705
11706 if (busiest->group_type == group_smt_balance &&
11707 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11708 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
11709 goto force_balance;
11710 }
11711
11712 if (busiest->group_weight > 1 &&
11713 local->idle_cpus <= (busiest->idle_cpus + 1)) {
11714 /*
11715 * If the busiest group is not overloaded
11716 * and there is no imbalance between this and busiest
11717 * group wrt idle CPUs, it is balanced. The imbalance
11718 * becomes significant if the diff is greater than 1
11719 * otherwise we might end up to just move the imbalance
11720 * on another group. Of course this applies only if
11721 * there is more than 1 CPU per group.
11722 */
11723 goto out_balanced;
11724 }
11725
11726 if (busiest->sum_h_nr_running == 1) {
11727 /*
11728 * busiest doesn't have any tasks waiting to run
11729 */
11730 goto out_balanced;
11731 }
11732 }
11733
11734 force_balance:
11735 /* Looks like there is an imbalance. Compute it */
11736 calculate_imbalance(env, &sds);
11737 return env->imbalance ? sds.busiest : NULL;
11738
11739 out_balanced:
11740 env->imbalance = 0;
11741 return NULL;
11742 }
11743
11744 /*
11745 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11746 */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11747 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11748 struct sched_group *group)
11749 {
11750 struct rq *busiest = NULL, *rq;
11751 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11752 unsigned int busiest_nr = 0;
11753 int i;
11754
11755 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11756 unsigned long capacity, load, util;
11757 unsigned int nr_running;
11758 enum fbq_type rt;
11759
11760 rq = cpu_rq(i);
11761 rt = fbq_classify_rq(rq);
11762
11763 /*
11764 * We classify groups/runqueues into three groups:
11765 * - regular: there are !numa tasks
11766 * - remote: there are numa tasks that run on the 'wrong' node
11767 * - all: there is no distinction
11768 *
11769 * In order to avoid migrating ideally placed numa tasks,
11770 * ignore those when there's better options.
11771 *
11772 * If we ignore the actual busiest queue to migrate another
11773 * task, the next balance pass can still reduce the busiest
11774 * queue by moving tasks around inside the node.
11775 *
11776 * If we cannot move enough load due to this classification
11777 * the next pass will adjust the group classification and
11778 * allow migration of more tasks.
11779 *
11780 * Both cases only affect the total convergence complexity.
11781 */
11782 if (rt > env->fbq_type)
11783 continue;
11784
11785 nr_running = rq->cfs.h_nr_runnable;
11786 if (!nr_running)
11787 continue;
11788
11789 capacity = capacity_of(i);
11790
11791 /*
11792 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11793 * eventually lead to active_balancing high->low capacity.
11794 * Higher per-CPU capacity is considered better than balancing
11795 * average load.
11796 */
11797 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11798 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11799 nr_running == 1)
11800 continue;
11801
11802 /*
11803 * Make sure we only pull tasks from a CPU of lower priority
11804 * when balancing between SMT siblings.
11805 *
11806 * If balancing between cores, let lower priority CPUs help
11807 * SMT cores with more than one busy sibling.
11808 */
11809 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11810 continue;
11811
11812 switch (env->migration_type) {
11813 case migrate_load:
11814 /*
11815 * When comparing with load imbalance, use cpu_load()
11816 * which is not scaled with the CPU capacity.
11817 */
11818 load = cpu_load(rq);
11819
11820 if (nr_running == 1 && load > env->imbalance &&
11821 !check_cpu_capacity(rq, env->sd))
11822 break;
11823
11824 /*
11825 * For the load comparisons with the other CPUs,
11826 * consider the cpu_load() scaled with the CPU
11827 * capacity, so that the load can be moved away
11828 * from the CPU that is potentially running at a
11829 * lower capacity.
11830 *
11831 * Thus we're looking for max(load_i / capacity_i),
11832 * crosswise multiplication to rid ourselves of the
11833 * division works out to:
11834 * load_i * capacity_j > load_j * capacity_i;
11835 * where j is our previous maximum.
11836 */
11837 if (load * busiest_capacity > busiest_load * capacity) {
11838 busiest_load = load;
11839 busiest_capacity = capacity;
11840 busiest = rq;
11841 }
11842 break;
11843
11844 case migrate_util:
11845 util = cpu_util_cfs_boost(i);
11846
11847 /*
11848 * Don't try to pull utilization from a CPU with one
11849 * running task. Whatever its utilization, we will fail
11850 * detach the task.
11851 */
11852 if (nr_running <= 1)
11853 continue;
11854
11855 if (busiest_util < util) {
11856 busiest_util = util;
11857 busiest = rq;
11858 }
11859 break;
11860
11861 case migrate_task:
11862 if (busiest_nr < nr_running) {
11863 busiest_nr = nr_running;
11864 busiest = rq;
11865 }
11866 break;
11867
11868 case migrate_misfit:
11869 /*
11870 * For ASYM_CPUCAPACITY domains with misfit tasks we
11871 * simply seek the "biggest" misfit task.
11872 */
11873 if (rq->misfit_task_load > busiest_load) {
11874 busiest_load = rq->misfit_task_load;
11875 busiest = rq;
11876 }
11877
11878 break;
11879
11880 }
11881 }
11882
11883 return busiest;
11884 }
11885
11886 /*
11887 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11888 * so long as it is large enough.
11889 */
11890 #define MAX_PINNED_INTERVAL 512
11891
11892 static inline bool
asym_active_balance(struct lb_env * env)11893 asym_active_balance(struct lb_env *env)
11894 {
11895 /*
11896 * ASYM_PACKING needs to force migrate tasks from busy but lower
11897 * priority CPUs in order to pack all tasks in the highest priority
11898 * CPUs. When done between cores, do it only if the whole core if the
11899 * whole core is idle.
11900 *
11901 * If @env::src_cpu is an SMT core with busy siblings, let
11902 * the lower priority @env::dst_cpu help it. Do not follow
11903 * CPU priority.
11904 */
11905 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11906 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11907 !sched_use_asym_prio(env->sd, env->src_cpu));
11908 }
11909
11910 static inline bool
imbalanced_active_balance(struct lb_env * env)11911 imbalanced_active_balance(struct lb_env *env)
11912 {
11913 struct sched_domain *sd = env->sd;
11914
11915 /*
11916 * The imbalanced case includes the case of pinned tasks preventing a fair
11917 * distribution of the load on the system but also the even distribution of the
11918 * threads on a system with spare capacity
11919 */
11920 if ((env->migration_type == migrate_task) &&
11921 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11922 return 1;
11923
11924 return 0;
11925 }
11926
need_active_balance(struct lb_env * env)11927 static int need_active_balance(struct lb_env *env)
11928 {
11929 struct sched_domain *sd = env->sd;
11930
11931 if (asym_active_balance(env))
11932 return 1;
11933
11934 if (imbalanced_active_balance(env))
11935 return 1;
11936
11937 /*
11938 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11939 * It's worth migrating the task if the src_cpu's capacity is reduced
11940 * because of other sched_class or IRQs if more capacity stays
11941 * available on dst_cpu.
11942 */
11943 if (env->idle &&
11944 (env->src_rq->cfs.h_nr_runnable == 1)) {
11945 if ((check_cpu_capacity(env->src_rq, sd)) &&
11946 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11947 return 1;
11948 }
11949
11950 if (env->migration_type == migrate_misfit)
11951 return 1;
11952
11953 return 0;
11954 }
11955
11956 static int active_load_balance_cpu_stop(void *data);
11957
should_we_balance(struct lb_env * env)11958 static int should_we_balance(struct lb_env *env)
11959 {
11960 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11961 struct sched_group *sg = env->sd->groups;
11962 int cpu, idle_smt = -1;
11963
11964 /*
11965 * Ensure the balancing environment is consistent; can happen
11966 * when the softirq triggers 'during' hotplug.
11967 */
11968 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11969 return 0;
11970
11971 /*
11972 * In the newly idle case, we will allow all the CPUs
11973 * to do the newly idle load balance.
11974 *
11975 * However, we bail out if we already have tasks or a wakeup pending,
11976 * to optimize wakeup latency.
11977 */
11978 if (env->idle == CPU_NEWLY_IDLE) {
11979 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11980 return 0;
11981 return 1;
11982 }
11983
11984 cpumask_copy(swb_cpus, group_balance_mask(sg));
11985 /* Try to find first idle CPU */
11986 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11987 if (!idle_cpu(cpu))
11988 continue;
11989
11990 /*
11991 * Don't balance to idle SMT in busy core right away when
11992 * balancing cores, but remember the first idle SMT CPU for
11993 * later consideration. Find CPU on an idle core first.
11994 */
11995 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11996 if (idle_smt == -1)
11997 idle_smt = cpu;
11998 /*
11999 * If the core is not idle, and first SMT sibling which is
12000 * idle has been found, then its not needed to check other
12001 * SMT siblings for idleness:
12002 */
12003 #ifdef CONFIG_SCHED_SMT
12004 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
12005 #endif
12006 continue;
12007 }
12008
12009 /*
12010 * Are we the first idle core in a non-SMT domain or higher,
12011 * or the first idle CPU in a SMT domain?
12012 */
12013 return cpu == env->dst_cpu;
12014 }
12015
12016 /* Are we the first idle CPU with busy siblings? */
12017 if (idle_smt != -1)
12018 return idle_smt == env->dst_cpu;
12019
12020 /* Are we the first CPU of this group ? */
12021 return group_balance_cpu(sg) == env->dst_cpu;
12022 }
12023
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)12024 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
12025 enum cpu_idle_type idle)
12026 {
12027 if (!schedstat_enabled())
12028 return;
12029
12030 switch (env->migration_type) {
12031 case migrate_load:
12032 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
12033 break;
12034 case migrate_util:
12035 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
12036 break;
12037 case migrate_task:
12038 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
12039 break;
12040 case migrate_misfit:
12041 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
12042 break;
12043 }
12044 }
12045
12046 /*
12047 * This flag serializes load-balancing passes over large domains
12048 * (above the NODE topology level) - only one load-balancing instance
12049 * may run at a time, to reduce overhead on very large systems with
12050 * lots of CPUs and large NUMA distances.
12051 *
12052 * - Note that load-balancing passes triggered while another one
12053 * is executing are skipped and not re-tried.
12054 *
12055 * - Also note that this does not serialize rebalance_domains()
12056 * execution, as non-SD_SERIALIZE domains will still be
12057 * load-balanced in parallel.
12058 */
12059 static atomic_t sched_balance_running = ATOMIC_INIT(0);
12060
12061 /*
12062 * Check this_cpu to ensure it is balanced within domain. Attempt to move
12063 * tasks if there is an imbalance.
12064 */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)12065 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
12066 struct sched_domain *sd, enum cpu_idle_type idle,
12067 int *continue_balancing)
12068 {
12069 int ld_moved, cur_ld_moved, active_balance = 0;
12070 struct sched_domain *sd_parent = sd->parent;
12071 struct sched_group *group;
12072 struct rq *busiest;
12073 struct rq_flags rf;
12074 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
12075 struct lb_env env = {
12076 .sd = sd,
12077 .dst_cpu = this_cpu,
12078 .dst_rq = this_rq,
12079 .dst_grpmask = group_balance_mask(sd->groups),
12080 .idle = idle,
12081 .loop_break = SCHED_NR_MIGRATE_BREAK,
12082 .cpus = cpus,
12083 .fbq_type = all,
12084 .tasks = LIST_HEAD_INIT(env.tasks),
12085 };
12086 bool need_unlock = false;
12087
12088 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
12089
12090 schedstat_inc(sd->lb_count[idle]);
12091
12092 redo:
12093 if (!should_we_balance(&env)) {
12094 *continue_balancing = 0;
12095 goto out_balanced;
12096 }
12097
12098 if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
12099 int zero = 0;
12100 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
12101 goto out_balanced;
12102
12103 need_unlock = true;
12104 }
12105
12106 group = sched_balance_find_src_group(&env);
12107 if (!group) {
12108 schedstat_inc(sd->lb_nobusyg[idle]);
12109 goto out_balanced;
12110 }
12111
12112 busiest = sched_balance_find_src_rq(&env, group);
12113 if (!busiest) {
12114 schedstat_inc(sd->lb_nobusyq[idle]);
12115 goto out_balanced;
12116 }
12117
12118 WARN_ON_ONCE(busiest == env.dst_rq);
12119
12120 update_lb_imbalance_stat(&env, sd, idle);
12121
12122 env.src_cpu = busiest->cpu;
12123 env.src_rq = busiest;
12124
12125 ld_moved = 0;
12126 /* Clear this flag as soon as we find a pullable task */
12127 env.flags |= LBF_ALL_PINNED;
12128 if (busiest->nr_running > 1) {
12129 /*
12130 * Attempt to move tasks. If sched_balance_find_src_group has found
12131 * an imbalance but busiest->nr_running <= 1, the group is
12132 * still unbalanced. ld_moved simply stays zero, so it is
12133 * correctly treated as an imbalance.
12134 */
12135 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
12136
12137 more_balance:
12138 rq_lock_irqsave(busiest, &rf);
12139 update_rq_clock(busiest);
12140
12141 /*
12142 * cur_ld_moved - load moved in current iteration
12143 * ld_moved - cumulative load moved across iterations
12144 */
12145 cur_ld_moved = detach_tasks(&env);
12146
12147 /*
12148 * We've detached some tasks from busiest_rq. Every
12149 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
12150 * unlock busiest->lock, and we are able to be sure
12151 * that nobody can manipulate the tasks in parallel.
12152 * See task_rq_lock() family for the details.
12153 */
12154
12155 rq_unlock(busiest, &rf);
12156
12157 if (cur_ld_moved) {
12158 attach_tasks(&env);
12159 ld_moved += cur_ld_moved;
12160 }
12161
12162 local_irq_restore(rf.flags);
12163
12164 if (env.flags & LBF_NEED_BREAK) {
12165 env.flags &= ~LBF_NEED_BREAK;
12166 goto more_balance;
12167 }
12168
12169 /*
12170 * Revisit (affine) tasks on src_cpu that couldn't be moved to
12171 * us and move them to an alternate dst_cpu in our sched_group
12172 * where they can run. The upper limit on how many times we
12173 * iterate on same src_cpu is dependent on number of CPUs in our
12174 * sched_group.
12175 *
12176 * This changes load balance semantics a bit on who can move
12177 * load to a given_cpu. In addition to the given_cpu itself
12178 * (or a ilb_cpu acting on its behalf where given_cpu is
12179 * nohz-idle), we now have balance_cpu in a position to move
12180 * load to given_cpu. In rare situations, this may cause
12181 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
12182 * _independently_ and at _same_ time to move some load to
12183 * given_cpu) causing excess load to be moved to given_cpu.
12184 * This however should not happen so much in practice and
12185 * moreover subsequent load balance cycles should correct the
12186 * excess load moved.
12187 */
12188 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
12189
12190 /* Prevent to re-select dst_cpu via env's CPUs */
12191 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
12192
12193 env.dst_rq = cpu_rq(env.new_dst_cpu);
12194 env.dst_cpu = env.new_dst_cpu;
12195 env.flags &= ~LBF_DST_PINNED;
12196 env.loop = 0;
12197 env.loop_break = SCHED_NR_MIGRATE_BREAK;
12198
12199 /*
12200 * Go back to "more_balance" rather than "redo" since we
12201 * need to continue with same src_cpu.
12202 */
12203 goto more_balance;
12204 }
12205
12206 /*
12207 * We failed to reach balance because of affinity.
12208 */
12209 if (sd_parent) {
12210 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12211
12212 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
12213 *group_imbalance = 1;
12214 }
12215
12216 /* All tasks on this runqueue were pinned by CPU affinity */
12217 if (unlikely(env.flags & LBF_ALL_PINNED)) {
12218 __cpumask_clear_cpu(cpu_of(busiest), cpus);
12219 /*
12220 * Attempting to continue load balancing at the current
12221 * sched_domain level only makes sense if there are
12222 * active CPUs remaining as possible busiest CPUs to
12223 * pull load from which are not contained within the
12224 * destination group that is receiving any migrated
12225 * load.
12226 */
12227 if (!cpumask_subset(cpus, env.dst_grpmask)) {
12228 env.loop = 0;
12229 env.loop_break = SCHED_NR_MIGRATE_BREAK;
12230 goto redo;
12231 }
12232 goto out_all_pinned;
12233 }
12234 }
12235
12236 if (!ld_moved) {
12237 schedstat_inc(sd->lb_failed[idle]);
12238 /*
12239 * Increment the failure counter only on periodic balance.
12240 * We do not want newidle balance, which can be very
12241 * frequent, pollute the failure counter causing
12242 * excessive cache_hot migrations and active balances.
12243 *
12244 * Similarly for migration_misfit which is not related to
12245 * load/util migration, don't pollute nr_balance_failed.
12246 */
12247 if (idle != CPU_NEWLY_IDLE &&
12248 env.migration_type != migrate_misfit)
12249 sd->nr_balance_failed++;
12250
12251 if (need_active_balance(&env)) {
12252 unsigned long flags;
12253
12254 raw_spin_rq_lock_irqsave(busiest, flags);
12255
12256 /*
12257 * Don't kick the active_load_balance_cpu_stop,
12258 * if the curr task on busiest CPU can't be
12259 * moved to this_cpu:
12260 */
12261 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
12262 raw_spin_rq_unlock_irqrestore(busiest, flags);
12263 goto out_one_pinned;
12264 }
12265
12266 /* Record that we found at least one task that could run on this_cpu */
12267 env.flags &= ~LBF_ALL_PINNED;
12268
12269 /*
12270 * ->active_balance synchronizes accesses to
12271 * ->active_balance_work. Once set, it's cleared
12272 * only after active load balance is finished.
12273 */
12274 if (!busiest->active_balance) {
12275 busiest->active_balance = 1;
12276 busiest->push_cpu = this_cpu;
12277 active_balance = 1;
12278 }
12279
12280 preempt_disable();
12281 raw_spin_rq_unlock_irqrestore(busiest, flags);
12282 if (active_balance) {
12283 stop_one_cpu_nowait(cpu_of(busiest),
12284 active_load_balance_cpu_stop, busiest,
12285 &busiest->active_balance_work);
12286 }
12287 preempt_enable();
12288 }
12289 } else {
12290 sd->nr_balance_failed = 0;
12291 }
12292
12293 if (likely(!active_balance) || need_active_balance(&env)) {
12294 /* We were unbalanced, so reset the balancing interval */
12295 sd->balance_interval = sd->min_interval;
12296 }
12297
12298 goto out;
12299
12300 out_balanced:
12301 /*
12302 * We reach balance although we may have faced some affinity
12303 * constraints. Clear the imbalance flag only if other tasks got
12304 * a chance to move and fix the imbalance.
12305 */
12306 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12307 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12308
12309 if (*group_imbalance)
12310 *group_imbalance = 0;
12311 }
12312
12313 out_all_pinned:
12314 /*
12315 * We reach balance because all tasks are pinned at this level so
12316 * we can't migrate them. Let the imbalance flag set so parent level
12317 * can try to migrate them.
12318 */
12319 schedstat_inc(sd->lb_balanced[idle]);
12320
12321 sd->nr_balance_failed = 0;
12322
12323 out_one_pinned:
12324 ld_moved = 0;
12325
12326 /*
12327 * sched_balance_newidle() disregards balance intervals, so we could
12328 * repeatedly reach this code, which would lead to balance_interval
12329 * skyrocketing in a short amount of time. Skip the balance_interval
12330 * increase logic to avoid that.
12331 *
12332 * Similarly misfit migration which is not necessarily an indication of
12333 * the system being busy and requires lb to backoff to let it settle
12334 * down.
12335 */
12336 if (env.idle == CPU_NEWLY_IDLE ||
12337 env.migration_type == migrate_misfit)
12338 goto out;
12339
12340 /* tune up the balancing interval */
12341 if ((env.flags & LBF_ALL_PINNED &&
12342 sd->balance_interval < MAX_PINNED_INTERVAL) ||
12343 sd->balance_interval < sd->max_interval)
12344 sd->balance_interval *= 2;
12345 out:
12346 if (need_unlock)
12347 atomic_set_release(&sched_balance_running, 0);
12348
12349 return ld_moved;
12350 }
12351
12352 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)12353 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12354 {
12355 unsigned long interval = sd->balance_interval;
12356
12357 if (cpu_busy)
12358 interval *= sd->busy_factor;
12359
12360 /* scale ms to jiffies */
12361 interval = msecs_to_jiffies(interval);
12362
12363 /*
12364 * Reduce likelihood of busy balancing at higher domains racing with
12365 * balancing at lower domains by preventing their balancing periods
12366 * from being multiples of each other.
12367 */
12368 if (cpu_busy)
12369 interval -= 1;
12370
12371 interval = clamp(interval, 1UL, max_load_balance_interval);
12372
12373 return interval;
12374 }
12375
12376 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12377 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12378 {
12379 unsigned long interval, next;
12380
12381 /* used by idle balance, so cpu_busy = 0 */
12382 interval = get_sd_balance_interval(sd, 0);
12383 next = sd->last_balance + interval;
12384
12385 if (time_after(*next_balance, next))
12386 *next_balance = next;
12387 }
12388
12389 /*
12390 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12391 * running tasks off the busiest CPU onto idle CPUs. It requires at
12392 * least 1 task to be running on each physical CPU where possible, and
12393 * avoids physical / logical imbalances.
12394 */
active_load_balance_cpu_stop(void * data)12395 static int active_load_balance_cpu_stop(void *data)
12396 {
12397 struct rq *busiest_rq = data;
12398 int busiest_cpu = cpu_of(busiest_rq);
12399 int target_cpu = busiest_rq->push_cpu;
12400 struct rq *target_rq = cpu_rq(target_cpu);
12401 struct sched_domain *sd;
12402 struct task_struct *p = NULL;
12403 struct rq_flags rf;
12404
12405 rq_lock_irq(busiest_rq, &rf);
12406 /*
12407 * Between queueing the stop-work and running it is a hole in which
12408 * CPUs can become inactive. We should not move tasks from or to
12409 * inactive CPUs.
12410 */
12411 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12412 goto out_unlock;
12413
12414 /* Make sure the requested CPU hasn't gone down in the meantime: */
12415 if (unlikely(busiest_cpu != smp_processor_id() ||
12416 !busiest_rq->active_balance))
12417 goto out_unlock;
12418
12419 /* Is there any task to move? */
12420 if (busiest_rq->nr_running <= 1)
12421 goto out_unlock;
12422
12423 /*
12424 * This condition is "impossible", if it occurs
12425 * we need to fix it. Originally reported by
12426 * Bjorn Helgaas on a 128-CPU setup.
12427 */
12428 WARN_ON_ONCE(busiest_rq == target_rq);
12429
12430 /* Search for an sd spanning us and the target CPU. */
12431 rcu_read_lock();
12432 for_each_domain(target_cpu, sd) {
12433 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12434 break;
12435 }
12436
12437 if (likely(sd)) {
12438 struct lb_env env = {
12439 .sd = sd,
12440 .dst_cpu = target_cpu,
12441 .dst_rq = target_rq,
12442 .src_cpu = busiest_rq->cpu,
12443 .src_rq = busiest_rq,
12444 .idle = CPU_IDLE,
12445 .flags = LBF_ACTIVE_LB,
12446 };
12447
12448 schedstat_inc(sd->alb_count);
12449 update_rq_clock(busiest_rq);
12450
12451 p = detach_one_task(&env);
12452 if (p) {
12453 schedstat_inc(sd->alb_pushed);
12454 /* Active balancing done, reset the failure counter. */
12455 sd->nr_balance_failed = 0;
12456 } else {
12457 schedstat_inc(sd->alb_failed);
12458 }
12459 }
12460 rcu_read_unlock();
12461 out_unlock:
12462 busiest_rq->active_balance = 0;
12463 rq_unlock(busiest_rq, &rf);
12464
12465 if (p)
12466 attach_one_task(target_rq, p);
12467
12468 local_irq_enable();
12469
12470 return 0;
12471 }
12472
12473 /*
12474 * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12475 * This trades load-balance latency on larger machines for less cross talk.
12476 */
update_max_interval(void)12477 void update_max_interval(void)
12478 {
12479 max_load_balance_interval = HZ*num_online_cpus()/10;
12480 }
12481
update_newidle_stats(struct sched_domain * sd,unsigned int success)12482 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
12483 {
12484 sd->newidle_call++;
12485 sd->newidle_success += success;
12486
12487 if (sd->newidle_call >= 1024) {
12488 u64 now = sched_clock();
12489 s64 delta = now - sd->newidle_stamp;
12490 sd->newidle_stamp = now;
12491 int ratio = 0;
12492
12493 if (delta < 0)
12494 delta = 0;
12495
12496 if (sched_feat(NI_RATE)) {
12497 /*
12498 * ratio delta freq
12499 *
12500 * 1024 - 4 s - 128 Hz
12501 * 512 - 2 s - 256 Hz
12502 * 256 - 1 s - 512 Hz
12503 * 128 - .5 s - 1024 Hz
12504 * 64 - .25 s - 2048 Hz
12505 */
12506 ratio = delta >> 22;
12507 }
12508
12509 ratio += sd->newidle_success;
12510
12511 sd->newidle_ratio = min(1024, ratio);
12512 sd->newidle_call /= 2;
12513 sd->newidle_success /= 2;
12514 }
12515 }
12516
12517 static inline bool
update_newidle_cost(struct sched_domain * sd,u64 cost,unsigned int success)12518 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
12519 {
12520 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
12521 unsigned long now = jiffies;
12522
12523 if (cost)
12524 update_newidle_stats(sd, success);
12525
12526 if (cost > sd->max_newidle_lb_cost) {
12527 /*
12528 * Track max cost of a domain to make sure to not delay the
12529 * next wakeup on the CPU.
12530 */
12531 sd->max_newidle_lb_cost = cost;
12532 sd->last_decay_max_lb_cost = now;
12533
12534 } else if (time_after(now, next_decay)) {
12535 /*
12536 * Decay the newidle max times by ~1% per second to ensure that
12537 * it is not outdated and the current max cost is actually
12538 * shorter.
12539 */
12540 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12541 sd->last_decay_max_lb_cost = now;
12542 return true;
12543 }
12544
12545 return false;
12546 }
12547
12548 /*
12549 * It checks each scheduling domain to see if it is due to be balanced,
12550 * and initiates a balancing operation if so.
12551 *
12552 * Balancing parameters are set up in init_sched_domains.
12553 */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12554 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12555 {
12556 int continue_balancing = 1;
12557 int cpu = rq->cpu;
12558 int busy = idle != CPU_IDLE && !sched_idle_rq(rq);
12559 unsigned long interval;
12560 struct sched_domain *sd;
12561 /* Earliest time when we have to do rebalance again */
12562 unsigned long next_balance = jiffies + 60*HZ;
12563 int update_next_balance = 0;
12564 int need_decay = 0;
12565 u64 max_cost = 0;
12566
12567 rcu_read_lock();
12568 for_each_domain(cpu, sd) {
12569 /*
12570 * Decay the newidle max times here because this is a regular
12571 * visit to all the domains.
12572 */
12573 need_decay = update_newidle_cost(sd, 0, 0);
12574 max_cost += sd->max_newidle_lb_cost;
12575
12576 /*
12577 * Stop the load balance at this level. There is another
12578 * CPU in our sched group which is doing load balancing more
12579 * actively.
12580 */
12581 if (!continue_balancing) {
12582 if (need_decay)
12583 continue;
12584 break;
12585 }
12586
12587 interval = get_sd_balance_interval(sd, busy);
12588 if (time_after_eq(jiffies, sd->last_balance + interval)) {
12589 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12590 /*
12591 * The LBF_DST_PINNED logic could have changed
12592 * env->dst_cpu, so we can't know our idle
12593 * state even if we migrated tasks. Update it.
12594 */
12595 idle = idle_cpu(cpu);
12596 busy = !idle && !sched_idle_rq(rq);
12597 }
12598 sd->last_balance = jiffies;
12599 interval = get_sd_balance_interval(sd, busy);
12600 }
12601 if (time_after(next_balance, sd->last_balance + interval)) {
12602 next_balance = sd->last_balance + interval;
12603 update_next_balance = 1;
12604 }
12605 }
12606 if (need_decay) {
12607 /*
12608 * Ensure the rq-wide value also decays but keep it at a
12609 * reasonable floor to avoid funnies with rq->avg_idle.
12610 */
12611 rq->max_idle_balance_cost =
12612 max((u64)sysctl_sched_migration_cost, max_cost);
12613 }
12614 rcu_read_unlock();
12615
12616 /*
12617 * next_balance will be updated only when there is a need.
12618 * When the cpu is attached to null domain for ex, it will not be
12619 * updated.
12620 */
12621 if (likely(update_next_balance))
12622 rq->next_balance = next_balance;
12623
12624 }
12625
on_null_domain(struct rq * rq)12626 static inline int on_null_domain(struct rq *rq)
12627 {
12628 return unlikely(!rcu_dereference_sched(rq->sd));
12629 }
12630
12631 #ifdef CONFIG_NO_HZ_COMMON
12632 /*
12633 * NOHZ idle load balancing (ILB) details:
12634 *
12635 * - When one of the busy CPUs notices that there may be an idle rebalancing
12636 * needed, they will kick the idle load balancer, which then does idle
12637 * load balancing for all the idle CPUs.
12638 */
find_new_ilb(void)12639 static inline int find_new_ilb(void)
12640 {
12641 int this_cpu = smp_processor_id();
12642 const struct cpumask *hk_mask;
12643 int ilb_cpu;
12644
12645 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12646
12647 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12648 if (ilb_cpu == this_cpu)
12649 continue;
12650
12651 if (idle_cpu(ilb_cpu))
12652 return ilb_cpu;
12653 }
12654
12655 return -1;
12656 }
12657
12658 /*
12659 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12660 * SMP function call (IPI).
12661 *
12662 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12663 * (if there is one).
12664 */
kick_ilb(unsigned int flags)12665 static void kick_ilb(unsigned int flags)
12666 {
12667 int ilb_cpu;
12668
12669 /*
12670 * Increase nohz.next_balance only when if full ilb is triggered but
12671 * not if we only update stats.
12672 */
12673 if (flags & NOHZ_BALANCE_KICK)
12674 nohz.next_balance = jiffies+1;
12675
12676 ilb_cpu = find_new_ilb();
12677 if (ilb_cpu < 0)
12678 return;
12679
12680 /*
12681 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12682 * i.e. all bits in flags are already set in ilb_cpu.
12683 */
12684 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12685 return;
12686
12687 /*
12688 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12689 * the first flag owns it; cleared by nohz_csd_func().
12690 */
12691 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12692 if (flags & NOHZ_KICK_MASK)
12693 return;
12694
12695 /*
12696 * This way we generate an IPI on the target CPU which
12697 * is idle, and the softirq performing NOHZ idle load balancing
12698 * will be run before returning from the IPI.
12699 */
12700 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12701 }
12702
12703 /*
12704 * Current decision point for kicking the idle load balancer in the presence
12705 * of idle CPUs in the system.
12706 */
nohz_balancer_kick(struct rq * rq)12707 static void nohz_balancer_kick(struct rq *rq)
12708 {
12709 unsigned long now = jiffies;
12710 struct sched_domain_shared *sds;
12711 struct sched_domain *sd;
12712 int nr_busy, i, cpu = rq->cpu;
12713 unsigned int flags = 0;
12714
12715 if (unlikely(rq->idle_balance))
12716 return;
12717
12718 /*
12719 * We may be recently in ticked or tickless idle mode. At the first
12720 * busy tick after returning from idle, we will update the busy stats.
12721 */
12722 nohz_balance_exit_idle(rq);
12723
12724 if (READ_ONCE(nohz.has_blocked_load) &&
12725 time_after(now, READ_ONCE(nohz.next_blocked)))
12726 flags = NOHZ_STATS_KICK;
12727
12728 /*
12729 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0
12730 * Skip the read if time is not due.
12731 *
12732 * If none are in tickless mode, there maybe a narrow window
12733 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called.
12734 * But idle load balancing is not done as find_new_ilb fails.
12735 * That's very rare. So read nohz.nr_cpus only if time is due.
12736 */
12737 if (time_before(now, nohz.next_balance))
12738 goto out;
12739
12740 /*
12741 * None are in tickless mode and hence no need for NOHZ idle load
12742 * balancing
12743 */
12744 if (unlikely(cpumask_empty(nohz.idle_cpus_mask)))
12745 return;
12746
12747 if (rq->nr_running >= 2) {
12748 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12749 goto out;
12750 }
12751
12752 rcu_read_lock();
12753
12754 sd = rcu_dereference_all(rq->sd);
12755 if (sd) {
12756 /*
12757 * If there's a runnable CFS task and the current CPU has reduced
12758 * capacity, kick the ILB to see if there's a better CPU to run on:
12759 */
12760 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12761 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12762 goto unlock;
12763 }
12764 }
12765
12766 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu));
12767 if (sd) {
12768 /*
12769 * When ASYM_PACKING; see if there's a more preferred CPU
12770 * currently idle; in which case, kick the ILB to move tasks
12771 * around.
12772 *
12773 * When balancing between cores, all the SMT siblings of the
12774 * preferred CPU must be idle.
12775 */
12776 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12777 if (sched_asym(sd, i, cpu)) {
12778 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12779 goto unlock;
12780 }
12781 }
12782 }
12783
12784 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu));
12785 if (sd) {
12786 /*
12787 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12788 * to run the misfit task on.
12789 */
12790 if (check_misfit_status(rq)) {
12791 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12792 goto unlock;
12793 }
12794
12795 /*
12796 * For asymmetric systems, we do not want to nicely balance
12797 * cache use, instead we want to embrace asymmetry and only
12798 * ensure tasks have enough CPU capacity.
12799 *
12800 * Skip the LLC logic because it's not relevant in that case.
12801 */
12802 goto unlock;
12803 }
12804
12805 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu));
12806 if (sds) {
12807 /*
12808 * If there is an imbalance between LLC domains (IOW we could
12809 * increase the overall cache utilization), we need a less-loaded LLC
12810 * domain to pull some load from. Likewise, we may need to spread
12811 * load within the current LLC domain (e.g. packed SMT cores but
12812 * other CPUs are idle). We can't really know from here how busy
12813 * the others are - so just get a NOHZ balance going if it looks
12814 * like this LLC domain has tasks we could move.
12815 */
12816 nr_busy = atomic_read(&sds->nr_busy_cpus);
12817 if (nr_busy > 1) {
12818 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12819 goto unlock;
12820 }
12821 }
12822 unlock:
12823 rcu_read_unlock();
12824 out:
12825 if (READ_ONCE(nohz.needs_update))
12826 flags |= NOHZ_NEXT_KICK;
12827
12828 if (flags)
12829 kick_ilb(flags);
12830 }
12831
set_cpu_sd_state_busy(int cpu)12832 static void set_cpu_sd_state_busy(int cpu)
12833 {
12834 struct sched_domain *sd;
12835
12836 rcu_read_lock();
12837 sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
12838
12839 if (!sd || !sd->nohz_idle)
12840 goto unlock;
12841 sd->nohz_idle = 0;
12842
12843 atomic_inc(&sd->shared->nr_busy_cpus);
12844 unlock:
12845 rcu_read_unlock();
12846 }
12847
nohz_balance_exit_idle(struct rq * rq)12848 void nohz_balance_exit_idle(struct rq *rq)
12849 {
12850 WARN_ON_ONCE(rq != this_rq());
12851
12852 if (likely(!rq->nohz_tick_stopped))
12853 return;
12854
12855 rq->nohz_tick_stopped = 0;
12856 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12857
12858 set_cpu_sd_state_busy(rq->cpu);
12859 }
12860
set_cpu_sd_state_idle(int cpu)12861 static void set_cpu_sd_state_idle(int cpu)
12862 {
12863 struct sched_domain *sd;
12864
12865 rcu_read_lock();
12866 sd = rcu_dereference_all(per_cpu(sd_llc, cpu));
12867
12868 if (!sd || sd->nohz_idle)
12869 goto unlock;
12870 sd->nohz_idle = 1;
12871
12872 atomic_dec(&sd->shared->nr_busy_cpus);
12873 unlock:
12874 rcu_read_unlock();
12875 }
12876
12877 /*
12878 * This routine will record that the CPU is going idle with tick stopped.
12879 * This info will be used in performing idle load balancing in the future.
12880 */
nohz_balance_enter_idle(int cpu)12881 void nohz_balance_enter_idle(int cpu)
12882 {
12883 struct rq *rq = cpu_rq(cpu);
12884
12885 WARN_ON_ONCE(cpu != smp_processor_id());
12886
12887 /* If this CPU is going down, then nothing needs to be done: */
12888 if (!cpu_active(cpu))
12889 return;
12890
12891 /*
12892 * Can be set safely without rq->lock held
12893 * If a clear happens, it will have evaluated last additions because
12894 * rq->lock is held during the check and the clear
12895 */
12896 rq->has_blocked_load = 1;
12897
12898 /*
12899 * The tick is still stopped but load could have been added in the
12900 * meantime. We set the nohz.has_blocked_load flag to trig a check of the
12901 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12902 * of nohz.has_blocked_load can only happen after checking the new load
12903 */
12904 if (rq->nohz_tick_stopped)
12905 goto out;
12906
12907 /* If we're a completely isolated CPU, we don't play: */
12908 if (on_null_domain(rq))
12909 return;
12910
12911 rq->nohz_tick_stopped = 1;
12912
12913 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12914
12915 /*
12916 * Ensures that if nohz_idle_balance() fails to observe our
12917 * @idle_cpus_mask store, it must observe the @has_blocked_load
12918 * and @needs_update stores.
12919 */
12920 smp_mb__after_atomic();
12921
12922 set_cpu_sd_state_idle(cpu);
12923
12924 WRITE_ONCE(nohz.needs_update, 1);
12925 out:
12926 /*
12927 * Each time a cpu enter idle, we assume that it has blocked load and
12928 * enable the periodic update of the load of idle CPUs
12929 */
12930 WRITE_ONCE(nohz.has_blocked_load, 1);
12931 }
12932
update_nohz_stats(struct rq * rq)12933 static bool update_nohz_stats(struct rq *rq)
12934 {
12935 unsigned int cpu = rq->cpu;
12936
12937 if (!rq->has_blocked_load)
12938 return false;
12939
12940 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12941 return false;
12942
12943 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12944 return true;
12945
12946 sched_balance_update_blocked_averages(cpu);
12947
12948 return rq->has_blocked_load;
12949 }
12950
12951 /*
12952 * Internal function that runs load balance for all idle CPUs. The load balance
12953 * can be a simple update of blocked load or a complete load balance with
12954 * tasks movement depending of flags.
12955 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12956 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12957 {
12958 /* Earliest time when we have to do rebalance again */
12959 unsigned long now = jiffies;
12960 unsigned long next_balance = now + 60*HZ;
12961 bool has_blocked_load = false;
12962 int update_next_balance = 0;
12963 int this_cpu = this_rq->cpu;
12964 int balance_cpu;
12965 struct rq *rq;
12966
12967 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12968
12969 /*
12970 * We assume there will be no idle load after this update and clear
12971 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will
12972 * set the has_blocked_load flag and trigger another update of idle load.
12973 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12974 * setting the flag, we are sure to not clear the state and not
12975 * check the load of an idle cpu.
12976 *
12977 * Same applies to idle_cpus_mask vs needs_update.
12978 */
12979 if (flags & NOHZ_STATS_KICK)
12980 WRITE_ONCE(nohz.has_blocked_load, 0);
12981 if (flags & NOHZ_NEXT_KICK)
12982 WRITE_ONCE(nohz.needs_update, 0);
12983
12984 /*
12985 * Ensures that if we miss the CPU, we must see the has_blocked_load
12986 * store from nohz_balance_enter_idle().
12987 */
12988 smp_mb();
12989
12990 /*
12991 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12992 * chance for other idle cpu to pull load.
12993 */
12994 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12995 if (!idle_cpu(balance_cpu))
12996 continue;
12997
12998 /*
12999 * If this CPU gets work to do, stop the load balancing
13000 * work being done for other CPUs. Next load
13001 * balancing owner will pick it up.
13002 */
13003 if (!idle_cpu(this_cpu) && need_resched()) {
13004 if (flags & NOHZ_STATS_KICK)
13005 has_blocked_load = true;
13006 if (flags & NOHZ_NEXT_KICK)
13007 WRITE_ONCE(nohz.needs_update, 1);
13008 goto abort;
13009 }
13010
13011 rq = cpu_rq(balance_cpu);
13012
13013 if (flags & NOHZ_STATS_KICK)
13014 has_blocked_load |= update_nohz_stats(rq);
13015
13016 /*
13017 * If time for next balance is due,
13018 * do the balance.
13019 */
13020 if (time_after_eq(jiffies, rq->next_balance)) {
13021 struct rq_flags rf;
13022
13023 rq_lock_irqsave(rq, &rf);
13024 update_rq_clock(rq);
13025 rq_unlock_irqrestore(rq, &rf);
13026
13027 if (flags & NOHZ_BALANCE_KICK)
13028 sched_balance_domains(rq, CPU_IDLE);
13029 }
13030
13031 if (time_after(next_balance, rq->next_balance)) {
13032 next_balance = rq->next_balance;
13033 update_next_balance = 1;
13034 }
13035 }
13036
13037 /*
13038 * next_balance will be updated only when there is a need.
13039 * When the CPU is attached to null domain for ex, it will not be
13040 * updated.
13041 */
13042 if (likely(update_next_balance))
13043 nohz.next_balance = next_balance;
13044
13045 if (flags & NOHZ_STATS_KICK)
13046 WRITE_ONCE(nohz.next_blocked,
13047 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
13048
13049 abort:
13050 /* There is still blocked load, enable periodic update */
13051 if (has_blocked_load)
13052 WRITE_ONCE(nohz.has_blocked_load, 1);
13053 }
13054
13055 /*
13056 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
13057 * rebalancing for all the CPUs for whom scheduler ticks are stopped.
13058 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)13059 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
13060 {
13061 unsigned int flags = this_rq->nohz_idle_balance;
13062
13063 if (!flags)
13064 return false;
13065
13066 this_rq->nohz_idle_balance = 0;
13067
13068 if (idle != CPU_IDLE)
13069 return false;
13070
13071 _nohz_idle_balance(this_rq, flags);
13072
13073 return true;
13074 }
13075
13076 /*
13077 * Check if we need to directly run the ILB for updating blocked load before
13078 * entering idle state. Here we run ILB directly without issuing IPIs.
13079 *
13080 * Note that when this function is called, the tick may not yet be stopped on
13081 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
13082 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
13083 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
13084 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
13085 * called from this function on (this) CPU that's not yet in the mask. That's
13086 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
13087 * updating the blocked load of already idle CPUs without waking up one of
13088 * those idle CPUs and outside the preempt disable / IRQ off phase of the local
13089 * cpu about to enter idle, because it can take a long time.
13090 */
nohz_run_idle_balance(int cpu)13091 void nohz_run_idle_balance(int cpu)
13092 {
13093 unsigned int flags;
13094
13095 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
13096
13097 /*
13098 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
13099 * (i.e. NOHZ_STATS_KICK set) and will do the same.
13100 */
13101 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
13102 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
13103 }
13104
nohz_newidle_balance(struct rq * this_rq)13105 static void nohz_newidle_balance(struct rq *this_rq)
13106 {
13107 int this_cpu = this_rq->cpu;
13108
13109 /* Will wake up very soon. No time for doing anything else*/
13110 if (this_rq->avg_idle < sysctl_sched_migration_cost)
13111 return;
13112
13113 /* Don't need to update blocked load of idle CPUs*/
13114 if (!READ_ONCE(nohz.has_blocked_load) ||
13115 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
13116 return;
13117
13118 /*
13119 * Set the need to trigger ILB in order to update blocked load
13120 * before entering idle state.
13121 */
13122 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
13123 }
13124
13125 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balancer_kick(struct rq * rq)13126 static inline void nohz_balancer_kick(struct rq *rq) { }
13127
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)13128 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
13129 {
13130 return false;
13131 }
13132
nohz_newidle_balance(struct rq * this_rq)13133 static inline void nohz_newidle_balance(struct rq *this_rq) { }
13134 #endif /* !CONFIG_NO_HZ_COMMON */
13135
13136 /*
13137 * sched_balance_newidle is called by schedule() if this_cpu is about to become
13138 * idle. Attempts to pull tasks from other CPUs.
13139 *
13140 * Returns:
13141 * < 0 - we released the lock and there are !fair tasks present
13142 * 0 - failed, no new tasks
13143 * > 0 - success, new (fair) tasks present
13144 */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)13145 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
13146 __must_hold(__rq_lockp(this_rq))
13147 {
13148 unsigned long next_balance = jiffies + HZ;
13149 int this_cpu = this_rq->cpu;
13150 int continue_balancing = 1;
13151 u64 t0, t1, curr_cost = 0;
13152 struct sched_domain *sd;
13153 int pulled_task = 0;
13154
13155 update_misfit_status(NULL, this_rq);
13156
13157 /*
13158 * There is a task waiting to run. No need to search for one.
13159 * Return 0; the task will be enqueued when switching to idle.
13160 */
13161 if (this_rq->ttwu_pending)
13162 return 0;
13163
13164 /*
13165 * We must set idle_stamp _before_ calling sched_balance_rq()
13166 * for CPU_NEWLY_IDLE, such that we measure the this duration
13167 * as idle time.
13168 */
13169 this_rq->idle_stamp = rq_clock(this_rq);
13170
13171 /*
13172 * Do not pull tasks towards !active CPUs...
13173 */
13174 if (!cpu_active(this_cpu))
13175 return 0;
13176
13177 /*
13178 * This is OK, because current is on_cpu, which avoids it being picked
13179 * for load-balance and preemption/IRQs are still disabled avoiding
13180 * further scheduler activity on it and we're being very careful to
13181 * re-start the picking loop.
13182 */
13183 rq_unpin_lock(this_rq, rf);
13184
13185 sd = rcu_dereference_sched_domain(this_rq->sd);
13186 if (!sd)
13187 goto out;
13188
13189 if (!get_rd_overloaded(this_rq->rd) ||
13190 this_rq->avg_idle < sd->max_newidle_lb_cost) {
13191
13192 update_next_balance(sd, &next_balance);
13193 goto out;
13194 }
13195
13196 /*
13197 * Include sched_balance_update_blocked_averages() in the cost
13198 * calculation because it can be quite costly -- this ensures we skip
13199 * it when avg_idle gets to be very low.
13200 */
13201 t0 = sched_clock_cpu(this_cpu);
13202 __sched_balance_update_blocked_averages(this_rq);
13203
13204 rq_modified_begin(this_rq, &fair_sched_class);
13205 raw_spin_rq_unlock(this_rq);
13206
13207 for_each_domain(this_cpu, sd) {
13208 u64 domain_cost;
13209
13210 update_next_balance(sd, &next_balance);
13211
13212 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
13213 break;
13214
13215 if (sd->flags & SD_BALANCE_NEWIDLE) {
13216 unsigned int weight = 1;
13217
13218 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) {
13219 /*
13220 * Throw a 1k sided dice; and only run
13221 * newidle_balance according to the success
13222 * rate.
13223 */
13224 u32 d1k = sched_rng() % 1024;
13225 weight = 1 + sd->newidle_ratio;
13226 if (d1k > weight) {
13227 update_newidle_stats(sd, 0);
13228 continue;
13229 }
13230 weight = (1024 + weight/2) / weight;
13231 }
13232
13233 pulled_task = sched_balance_rq(this_cpu, this_rq,
13234 sd, CPU_NEWLY_IDLE,
13235 &continue_balancing);
13236
13237 t1 = sched_clock_cpu(this_cpu);
13238 domain_cost = t1 - t0;
13239 curr_cost += domain_cost;
13240 t0 = t1;
13241
13242 /*
13243 * Track max cost of a domain to make sure to not delay the
13244 * next wakeup on the CPU.
13245 */
13246 update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
13247 }
13248
13249 /*
13250 * Stop searching for tasks to pull if there are
13251 * now runnable tasks on this rq.
13252 */
13253 if (pulled_task || !continue_balancing)
13254 break;
13255 }
13256
13257 raw_spin_rq_lock(this_rq);
13258
13259 if (curr_cost > this_rq->max_idle_balance_cost)
13260 this_rq->max_idle_balance_cost = curr_cost;
13261
13262 /*
13263 * While browsing the domains, we released the rq lock, a task could
13264 * have been enqueued in the meantime. Since we're not going idle,
13265 * pretend we pulled a task.
13266 */
13267 if (this_rq->cfs.h_nr_queued && !pulled_task)
13268 pulled_task = 1;
13269
13270 /* If a higher prio class was modified, restart the pick */
13271 if (rq_modified_above(this_rq, &fair_sched_class))
13272 pulled_task = -1;
13273
13274 out:
13275 /* Move the next balance forward */
13276 if (time_after(this_rq->next_balance, next_balance))
13277 this_rq->next_balance = next_balance;
13278
13279 if (pulled_task)
13280 this_rq->idle_stamp = 0;
13281 else
13282 nohz_newidle_balance(this_rq);
13283
13284 rq_repin_lock(this_rq, rf);
13285
13286 return pulled_task;
13287 }
13288
13289 /*
13290 * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
13291 *
13292 * - directly from the local sched_tick() for periodic load balancing
13293 *
13294 * - indirectly from a remote sched_tick() for NOHZ idle balancing
13295 * through the SMP cross-call nohz_csd_func()
13296 */
sched_balance_softirq(void)13297 static __latent_entropy void sched_balance_softirq(void)
13298 {
13299 struct rq *this_rq = this_rq();
13300 enum cpu_idle_type idle = this_rq->idle_balance;
13301 /*
13302 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13303 * balancing on behalf of the other idle CPUs whose ticks are
13304 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13305 * give the idle CPUs a chance to load balance. Else we may
13306 * load balance only within the local sched_domain hierarchy
13307 * and abort nohz_idle_balance altogether if we pull some load.
13308 */
13309 if (nohz_idle_balance(this_rq, idle))
13310 return;
13311
13312 /* normal load balance */
13313 sched_balance_update_blocked_averages(this_rq->cpu);
13314 sched_balance_domains(this_rq, idle);
13315 }
13316
13317 /*
13318 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13319 */
sched_balance_trigger(struct rq * rq)13320 void sched_balance_trigger(struct rq *rq)
13321 {
13322 /*
13323 * Don't need to rebalance while attached to NULL domain or
13324 * runqueue CPU is not active
13325 */
13326 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13327 return;
13328
13329 if (time_after_eq(jiffies, rq->next_balance))
13330 raise_softirq(SCHED_SOFTIRQ);
13331
13332 nohz_balancer_kick(rq);
13333 }
13334
rq_online_fair(struct rq * rq)13335 static void rq_online_fair(struct rq *rq)
13336 {
13337 update_sysctl();
13338
13339 update_runtime_enabled(rq);
13340 }
13341
rq_offline_fair(struct rq * rq)13342 static void rq_offline_fair(struct rq *rq)
13343 {
13344 update_sysctl();
13345
13346 /* Ensure any throttled groups are reachable by pick_next_task */
13347 unthrottle_offline_cfs_rqs(rq);
13348
13349 /* Ensure that we remove rq contribution to group share: */
13350 clear_tg_offline_cfs_rqs(rq);
13351 }
13352
13353 #ifdef CONFIG_SCHED_CORE
13354 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13355 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13356 {
13357 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13358 u64 slice = se->slice;
13359
13360 return (rtime * min_nr_tasks > slice);
13361 }
13362
13363 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)13364 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13365 {
13366 if (!sched_core_enabled(rq))
13367 return;
13368
13369 /*
13370 * If runqueue has only one task which used up its slice and
13371 * if the sibling is forced idle, then trigger schedule to
13372 * give forced idle task a chance.
13373 *
13374 * sched_slice() considers only this active rq and it gets the
13375 * whole slice. But during force idle, we have siblings acting
13376 * like a single runqueue and hence we need to consider runnable
13377 * tasks on this CPU and the forced idle CPU. Ideally, we should
13378 * go through the forced idle rq, but that would be a perf hit.
13379 * We can assume that the forced idle CPU has at least
13380 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13381 * if we need to give up the CPU.
13382 */
13383 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
13384 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13385 resched_curr(rq);
13386 }
13387
13388 /*
13389 * Consider any infeasible weight scenario. Take for instance two tasks,
13390 * each bound to their respective sibling, one with weight 1 and one with
13391 * weight 2. Then the lower weight task will run ahead of the higher weight
13392 * task without bound.
13393 *
13394 * This utterly destroys the concept of a shared time base.
13395 *
13396 * Remember; all this is about a proportionally fair scheduling, where each
13397 * tasks receives:
13398 *
13399 * w_i
13400 * dt_i = ---------- dt (1)
13401 * \Sum_j w_j
13402 *
13403 * which we do by tracking a virtual time, s_i:
13404 *
13405 * 1
13406 * s_i = --- d[t]_i (2)
13407 * w_i
13408 *
13409 * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
13410 * The immediate corollary is that the ideal schedule S, where (2) to use
13411 * an infinitesimal delta, is:
13412 *
13413 * 1
13414 * S = ---------- dt (3)
13415 * \Sum_i w_i
13416 *
13417 * From which we can define the lag, or deviation from the ideal, as:
13418 *
13419 * lag(i) = S - s_i (4)
13420 *
13421 * And since the one and only purpose is to approximate S, we get that:
13422 *
13423 * \Sum_i w_i lag(i) := 0 (5)
13424 *
13425 * If this were not so, we no longer converge to S, and we can no longer
13426 * claim our scheduler has any of the properties we derive from S. This is
13427 * exactly what you did above, you broke it!
13428 *
13429 *
13430 * Let's continue for a while though; to see if there is anything useful to
13431 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
13432 *
13433 * \Sum_i w_i s_i
13434 * S = -------------- (6)
13435 * \Sum_i w_i
13436 *
13437 * Which gives us a way to compute S, given our s_i. Now, if you've read
13438 * our code, you know that we do not in fact do this, the reason for this
13439 * is two-fold. Firstly, computing S in that way requires a 64bit division
13440 * for every time we'd use it (see 12), and secondly, this only describes
13441 * the steady-state, it doesn't handle dynamics.
13442 *
13443 * Anyway, in (6): s_i -> x + (s_i - x), to get:
13444 *
13445 * \Sum_i w_i (s_i - x)
13446 * S - x = -------------------- (7)
13447 * \Sum_i w_i
13448 *
13449 * Which shows that S and s_i transform alike (which makes perfect sense
13450 * given that S is basically the (weighted) average of s_i).
13451 *
13452 * So the thing to remember is that the above is strictly UP. It is
13453 * possible to generalize to multiple runqueues -- however it gets really
13454 * yuck when you have to add affinity support, as illustrated by our very
13455 * first counter-example.
13456 *
13457 * Luckily I think we can avoid needing a full multi-queue variant for
13458 * core-scheduling (or load-balancing). The crucial observation is that we
13459 * only actually need this comparison in the presence of forced-idle; only
13460 * then do we need to tell if the stalled rq has higher priority over the
13461 * other.
13462 *
13463 * [XXX assumes SMT2; better consider the more general case, I suspect
13464 * it'll work out because our comparison is always between 2 rqs and the
13465 * answer is only interesting if one of them is forced-idle]
13466 *
13467 * And (under assumption of SMT2) when there is forced-idle, there is only
13468 * a single queue, so everything works like normal.
13469 *
13470 * Let, for our runqueue 'k':
13471 *
13472 * T_k = \Sum_i w_i s_i
13473 * W_k = \Sum_i w_i ; for all i of k (8)
13474 *
13475 * Then we can write (6) like:
13476 *
13477 * T_k
13478 * S_k = --- (9)
13479 * W_k
13480 *
13481 * From which immediately follows that:
13482 *
13483 * T_k + T_l
13484 * S_k+l = --------- (10)
13485 * W_k + W_l
13486 *
13487 * On which we can define a combined lag:
13488 *
13489 * lag_k+l(i) := S_k+l - s_i (11)
13490 *
13491 * And that gives us the tools to compare tasks across a combined runqueue.
13492 *
13493 *
13494 * Combined this gives the following:
13495 *
13496 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
13497 * using (7); this only requires storing single 'time'-stamps.
13498 *
13499 * b) when comparing tasks between 2 runqueues of which one is forced-idle,
13500 * compare the combined lag, per (11).
13501 *
13502 * Now, of course cgroups (I so hate them) make this more interesting in
13503 * that a) seems to suggest we need to iterate all cgroup on a CPU at such
13504 * boundaries, but I think we can avoid that. The force-idle is for the
13505 * whole CPU, all it's rqs. So we can mark it in the root and lazily
13506 * propagate downward on demand.
13507 */
13508
13509 /*
13510 * So this sync is basically a relative reset of S to 0.
13511 *
13512 * So with 2 queues, when one goes idle, we drop them both to 0 and one
13513 * then increases due to not being idle, and the idle one builds up lag to
13514 * get re-elected. So far so simple, right?
13515 *
13516 * When there's 3, we can have the situation where 2 run and one is idle,
13517 * we sync to 0 and let the idle one build up lag to get re-election. Now
13518 * suppose another one also drops idle. At this point dropping all to 0
13519 * again would destroy the built-up lag from the queue that was already
13520 * idle, not good.
13521 *
13522 * So instead of syncing everything, we can:
13523 *
13524 * less := !((s64)(s_a - s_b) <= 0)
13525 *
13526 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
13527 * == v_a - (v_b - S_a + S_b)
13528 *
13529 * IOW, we can recast the (lag) comparison to a one-sided difference.
13530 * So if then, instead of syncing the whole queue, sync the idle queue
13531 * against the active queue with S_a + S_b at the point where we sync.
13532 *
13533 * (XXX consider the implication of living in a cyclic group: N / 2^n N)
13534 *
13535 * This gives us means of syncing single queues against the active queue,
13536 * and for already idle queues to preserve their build-up lag.
13537 *
13538 * Of course, then we get the situation where there's 2 active and one
13539 * going idle, who do we pick to sync against? Theory would have us sync
13540 * against the combined S, but as we've already demonstrated, there is no
13541 * such thing in infeasible weight scenarios.
13542 *
13543 * One thing I've considered; and this is where that core_active rudiment
13544 * came from, is having active queues sync up between themselves after
13545 * every tick. This limits the observed divergence due to the work
13546 * conservancy.
13547 *
13548 * On top of that, we can improve upon things by employing (10) here.
13549 */
13550
13551 /*
13552 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
13553 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13554 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13555 bool forceidle)
13556 {
13557 for_each_sched_entity(se) {
13558 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13559
13560 if (forceidle) {
13561 if (cfs_rq->forceidle_seq == fi_seq)
13562 break;
13563 cfs_rq->forceidle_seq = fi_seq;
13564 }
13565
13566 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
13567 }
13568 }
13569
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13570 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13571 {
13572 struct sched_entity *se = &p->se;
13573
13574 if (p->sched_class != &fair_sched_class)
13575 return;
13576
13577 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13578 }
13579
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13580 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13581 bool in_fi)
13582 {
13583 struct rq *rq = task_rq(a);
13584 const struct sched_entity *sea = &a->se;
13585 const struct sched_entity *seb = &b->se;
13586 struct cfs_rq *cfs_rqa;
13587 struct cfs_rq *cfs_rqb;
13588 s64 delta;
13589
13590 WARN_ON_ONCE(task_rq(b)->core != rq->core);
13591
13592 #ifdef CONFIG_FAIR_GROUP_SCHED
13593 /*
13594 * Find an se in the hierarchy for tasks a and b, such that the se's
13595 * are immediate siblings.
13596 */
13597 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13598 int sea_depth = sea->depth;
13599 int seb_depth = seb->depth;
13600
13601 if (sea_depth >= seb_depth)
13602 sea = parent_entity(sea);
13603 if (sea_depth <= seb_depth)
13604 seb = parent_entity(seb);
13605 }
13606
13607 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13608 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13609
13610 cfs_rqa = sea->cfs_rq;
13611 cfs_rqb = seb->cfs_rq;
13612 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13613 cfs_rqa = &task_rq(a)->cfs;
13614 cfs_rqb = &task_rq(b)->cfs;
13615 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13616
13617 /*
13618 * Find delta after normalizing se's vruntime with its cfs_rq's
13619 * zero_vruntime_fi, which would have been updated in prior calls
13620 * to se_fi_update().
13621 */
13622 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) +
13623 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi);
13624
13625 return delta > 0;
13626 }
13627
task_is_throttled_fair(struct task_struct * p,int cpu)13628 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13629 {
13630 struct cfs_rq *cfs_rq;
13631
13632 #ifdef CONFIG_FAIR_GROUP_SCHED
13633 cfs_rq = task_group(p)->cfs_rq[cpu];
13634 #else
13635 cfs_rq = &cpu_rq(cpu)->cfs;
13636 #endif
13637 return throttled_hierarchy(cfs_rq);
13638 }
13639 #else /* !CONFIG_SCHED_CORE: */
task_tick_core(struct rq * rq,struct task_struct * curr)13640 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13641 #endif /* !CONFIG_SCHED_CORE */
13642
13643 /*
13644 * scheduler tick hitting a task of our scheduling class.
13645 *
13646 * NOTE: This function can be called remotely by the tick offload that
13647 * goes along full dynticks. Therefore no local assumption can be made
13648 * and everything must be accessed through the @rq and @curr passed in
13649 * parameters.
13650 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13651 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13652 {
13653 struct cfs_rq *cfs_rq;
13654 struct sched_entity *se = &curr->se;
13655
13656 for_each_sched_entity(se) {
13657 cfs_rq = cfs_rq_of(se);
13658 entity_tick(cfs_rq, se, queued);
13659 }
13660
13661 if (queued)
13662 return;
13663
13664 if (static_branch_unlikely(&sched_numa_balancing))
13665 task_tick_numa(rq, curr);
13666
13667 update_misfit_status(curr, rq);
13668 check_update_overutilized_status(task_rq(curr));
13669
13670 task_tick_core(rq, curr);
13671 }
13672
13673 /*
13674 * called on fork with the child task as argument from the parent's context
13675 * - child not yet on the tasklist
13676 * - preemption disabled
13677 */
task_fork_fair(struct task_struct * p)13678 static void task_fork_fair(struct task_struct *p)
13679 {
13680 set_task_max_allowed_capacity(p);
13681 }
13682
13683 /*
13684 * Priority of the task has changed. Check to see if we preempt
13685 * the current task.
13686 */
13687 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,u64 oldprio)13688 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
13689 {
13690 if (!task_on_rq_queued(p))
13691 return;
13692
13693 if (p->prio == oldprio)
13694 return;
13695
13696 if (rq->cfs.nr_queued == 1)
13697 return;
13698
13699 /*
13700 * Reschedule if we are currently running on this runqueue and
13701 * our priority decreased, or if we are not currently running on
13702 * this runqueue and our priority is higher than the current's
13703 */
13704 if (task_current_donor(rq, p)) {
13705 if (p->prio > oldprio)
13706 resched_curr(rq);
13707 } else {
13708 wakeup_preempt(rq, p, 0);
13709 }
13710 }
13711
13712 #ifdef CONFIG_FAIR_GROUP_SCHED
13713 /*
13714 * Propagate the changes of the sched_entity across the tg tree to make it
13715 * visible to the root
13716 */
propagate_entity_cfs_rq(struct sched_entity * se)13717 static void propagate_entity_cfs_rq(struct sched_entity *se)
13718 {
13719 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13720
13721 /*
13722 * If a task gets attached to this cfs_rq and before being queued,
13723 * it gets migrated to another CPU due to reasons like affinity
13724 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
13725 * that removed load decayed or it can cause faireness problem.
13726 */
13727 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13728 list_add_leaf_cfs_rq(cfs_rq);
13729
13730 /* Start to propagate at parent */
13731 se = se->parent;
13732
13733 for_each_sched_entity(se) {
13734 cfs_rq = cfs_rq_of(se);
13735
13736 update_load_avg(cfs_rq, se, UPDATE_TG);
13737
13738 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13739 list_add_leaf_cfs_rq(cfs_rq);
13740 }
13741
13742 assert_list_leaf_cfs_rq(rq_of(cfs_rq));
13743 }
13744 #else /* !CONFIG_FAIR_GROUP_SCHED: */
propagate_entity_cfs_rq(struct sched_entity * se)13745 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13746 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13747
detach_entity_cfs_rq(struct sched_entity * se)13748 static void detach_entity_cfs_rq(struct sched_entity *se)
13749 {
13750 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13751
13752 /*
13753 * In case the task sched_avg hasn't been attached:
13754 * - A forked task which hasn't been woken up by wake_up_new_task().
13755 * - A task which has been woken up by try_to_wake_up() but is
13756 * waiting for actually being woken up by sched_ttwu_pending().
13757 */
13758 if (!se->avg.last_update_time)
13759 return;
13760
13761 /* Catch up with the cfs_rq and remove our load when we leave */
13762 update_load_avg(cfs_rq, se, 0);
13763 detach_entity_load_avg(cfs_rq, se);
13764 update_tg_load_avg(cfs_rq);
13765 propagate_entity_cfs_rq(se);
13766 }
13767
attach_entity_cfs_rq(struct sched_entity * se)13768 static void attach_entity_cfs_rq(struct sched_entity *se)
13769 {
13770 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13771
13772 /* Synchronize entity with its cfs_rq */
13773 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13774 attach_entity_load_avg(cfs_rq, se);
13775 update_tg_load_avg(cfs_rq);
13776 propagate_entity_cfs_rq(se);
13777 }
13778
detach_task_cfs_rq(struct task_struct * p)13779 static void detach_task_cfs_rq(struct task_struct *p)
13780 {
13781 struct sched_entity *se = &p->se;
13782
13783 detach_entity_cfs_rq(se);
13784 }
13785
attach_task_cfs_rq(struct task_struct * p)13786 static void attach_task_cfs_rq(struct task_struct *p)
13787 {
13788 struct sched_entity *se = &p->se;
13789
13790 attach_entity_cfs_rq(se);
13791 }
13792
switching_from_fair(struct rq * rq,struct task_struct * p)13793 static void switching_from_fair(struct rq *rq, struct task_struct *p)
13794 {
13795 if (p->se.sched_delayed)
13796 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
13797 }
13798
switched_from_fair(struct rq * rq,struct task_struct * p)13799 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13800 {
13801 detach_task_cfs_rq(p);
13802 }
13803
switched_to_fair(struct rq * rq,struct task_struct * p)13804 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13805 {
13806 WARN_ON_ONCE(p->se.sched_delayed);
13807
13808 attach_task_cfs_rq(p);
13809
13810 set_task_max_allowed_capacity(p);
13811
13812 if (task_on_rq_queued(p)) {
13813 /*
13814 * We were most likely switched from sched_rt, so
13815 * kick off the schedule if running, otherwise just see
13816 * if we can still preempt the current task.
13817 */
13818 if (task_current_donor(rq, p))
13819 resched_curr(rq);
13820 else
13821 wakeup_preempt(rq, p, 0);
13822 }
13823 }
13824
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13825 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13826 {
13827 struct sched_entity *se = &p->se;
13828
13829 if (task_on_rq_queued(p)) {
13830 /*
13831 * Move the next running task to the front of the list, so our
13832 * cfs_tasks list becomes MRU one.
13833 */
13834 list_move(&se->group_node, &rq->cfs_tasks);
13835 }
13836 if (!first)
13837 return;
13838
13839 WARN_ON_ONCE(se->sched_delayed);
13840
13841 if (hrtick_enabled_fair(rq))
13842 hrtick_start_fair(rq, p);
13843
13844 update_misfit_status(p, rq);
13845 sched_fair_update_stop_tick(rq, p);
13846 }
13847
13848 /*
13849 * Account for a task changing its policy or group.
13850 *
13851 * This routine is mostly called to set cfs_rq->curr field when a task
13852 * migrates between groups/classes.
13853 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13854 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13855 {
13856 struct sched_entity *se = &p->se;
13857
13858 for_each_sched_entity(se) {
13859 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13860
13861 set_next_entity(cfs_rq, se, first);
13862 /* ensure bandwidth has been allocated on our new cfs_rq */
13863 account_cfs_rq_runtime(cfs_rq, 0);
13864 }
13865
13866 __set_next_task_fair(rq, p, first);
13867 }
13868
init_cfs_rq(struct cfs_rq * cfs_rq)13869 void init_cfs_rq(struct cfs_rq *cfs_rq)
13870 {
13871 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13872 cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
13873 raw_spin_lock_init(&cfs_rq->removed.lock);
13874 }
13875
13876 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13877 static void task_change_group_fair(struct task_struct *p)
13878 {
13879 /*
13880 * We couldn't detach or attach a forked task which
13881 * hasn't been woken up by wake_up_new_task().
13882 */
13883 if (READ_ONCE(p->__state) == TASK_NEW)
13884 return;
13885
13886 detach_task_cfs_rq(p);
13887
13888 /* Tell se's cfs_rq has been changed -- migrated */
13889 p->se.avg.last_update_time = 0;
13890 set_task_rq(p, task_cpu(p));
13891 attach_task_cfs_rq(p);
13892 }
13893
free_fair_sched_group(struct task_group * tg)13894 void free_fair_sched_group(struct task_group *tg)
13895 {
13896 int i;
13897
13898 for_each_possible_cpu(i) {
13899 if (tg->cfs_rq)
13900 kfree(tg->cfs_rq[i]);
13901 if (tg->se)
13902 kfree(tg->se[i]);
13903 }
13904
13905 kfree(tg->cfs_rq);
13906 kfree(tg->se);
13907 }
13908
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13909 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13910 {
13911 struct sched_entity *se;
13912 struct cfs_rq *cfs_rq;
13913 int i;
13914
13915 tg->cfs_rq = kzalloc_objs(cfs_rq, nr_cpu_ids);
13916 if (!tg->cfs_rq)
13917 goto err;
13918 tg->se = kzalloc_objs(se, nr_cpu_ids);
13919 if (!tg->se)
13920 goto err;
13921
13922 tg->shares = NICE_0_LOAD;
13923
13924 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13925
13926 for_each_possible_cpu(i) {
13927 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13928 GFP_KERNEL, cpu_to_node(i));
13929 if (!cfs_rq)
13930 goto err;
13931
13932 se = kzalloc_node(sizeof(struct sched_entity_stats),
13933 GFP_KERNEL, cpu_to_node(i));
13934 if (!se)
13935 goto err_free_rq;
13936
13937 init_cfs_rq(cfs_rq);
13938 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13939 init_entity_runnable_average(se);
13940 }
13941
13942 return 1;
13943
13944 err_free_rq:
13945 kfree(cfs_rq);
13946 err:
13947 return 0;
13948 }
13949
online_fair_sched_group(struct task_group * tg)13950 void online_fair_sched_group(struct task_group *tg)
13951 {
13952 struct sched_entity *se;
13953 struct rq_flags rf;
13954 struct rq *rq;
13955 int i;
13956
13957 for_each_possible_cpu(i) {
13958 rq = cpu_rq(i);
13959 se = tg->se[i];
13960 rq_lock_irq(rq, &rf);
13961 update_rq_clock(rq);
13962 attach_entity_cfs_rq(se);
13963 sync_throttle(tg, i);
13964 rq_unlock_irq(rq, &rf);
13965 }
13966 }
13967
unregister_fair_sched_group(struct task_group * tg)13968 void unregister_fair_sched_group(struct task_group *tg)
13969 {
13970 int cpu;
13971
13972 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13973
13974 for_each_possible_cpu(cpu) {
13975 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13976 struct sched_entity *se = tg->se[cpu];
13977 struct rq *rq = cpu_rq(cpu);
13978
13979 if (se) {
13980 if (se->sched_delayed) {
13981 guard(rq_lock_irqsave)(rq);
13982 if (se->sched_delayed) {
13983 update_rq_clock(rq);
13984 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13985 }
13986 list_del_leaf_cfs_rq(cfs_rq);
13987 }
13988 remove_entity_load_avg(se);
13989 }
13990
13991 /*
13992 * Only empty task groups can be destroyed; so we can speculatively
13993 * check on_list without danger of it being re-added.
13994 */
13995 if (cfs_rq->on_list) {
13996 guard(rq_lock_irqsave)(rq);
13997 list_del_leaf_cfs_rq(cfs_rq);
13998 }
13999 }
14000 }
14001
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)14002 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
14003 struct sched_entity *se, int cpu,
14004 struct sched_entity *parent)
14005 {
14006 struct rq *rq = cpu_rq(cpu);
14007
14008 cfs_rq->tg = tg;
14009 cfs_rq->rq = rq;
14010 init_cfs_rq_runtime(cfs_rq);
14011
14012 tg->cfs_rq[cpu] = cfs_rq;
14013 tg->se[cpu] = se;
14014
14015 /* se could be NULL for root_task_group */
14016 if (!se)
14017 return;
14018
14019 if (!parent) {
14020 se->cfs_rq = &rq->cfs;
14021 se->depth = 0;
14022 } else {
14023 se->cfs_rq = parent->my_q;
14024 se->depth = parent->depth + 1;
14025 }
14026
14027 se->my_q = cfs_rq;
14028 /* guarantee group entities always have weight */
14029 update_load_set(&se->load, NICE_0_LOAD);
14030 se->parent = parent;
14031 }
14032
14033 static DEFINE_MUTEX(shares_mutex);
14034
__sched_group_set_shares(struct task_group * tg,unsigned long shares)14035 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
14036 {
14037 int i;
14038
14039 lockdep_assert_held(&shares_mutex);
14040
14041 /*
14042 * We can't change the weight of the root cgroup.
14043 */
14044 if (!tg->se[0])
14045 return -EINVAL;
14046
14047 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
14048
14049 if (tg->shares == shares)
14050 return 0;
14051
14052 tg->shares = shares;
14053 for_each_possible_cpu(i) {
14054 struct rq *rq = cpu_rq(i);
14055 struct sched_entity *se = tg->se[i];
14056 struct rq_flags rf;
14057
14058 /* Propagate contribution to hierarchy */
14059 rq_lock_irqsave(rq, &rf);
14060 update_rq_clock(rq);
14061 for_each_sched_entity(se) {
14062 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
14063 update_cfs_group(se);
14064 }
14065 rq_unlock_irqrestore(rq, &rf);
14066 }
14067
14068 return 0;
14069 }
14070
sched_group_set_shares(struct task_group * tg,unsigned long shares)14071 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
14072 {
14073 int ret;
14074
14075 mutex_lock(&shares_mutex);
14076 if (tg_is_idle(tg))
14077 ret = -EINVAL;
14078 else
14079 ret = __sched_group_set_shares(tg, shares);
14080 mutex_unlock(&shares_mutex);
14081
14082 return ret;
14083 }
14084
sched_group_set_idle(struct task_group * tg,long idle)14085 int sched_group_set_idle(struct task_group *tg, long idle)
14086 {
14087 int i;
14088
14089 if (tg == &root_task_group)
14090 return -EINVAL;
14091
14092 if (idle < 0 || idle > 1)
14093 return -EINVAL;
14094
14095 mutex_lock(&shares_mutex);
14096
14097 if (tg->idle == idle) {
14098 mutex_unlock(&shares_mutex);
14099 return 0;
14100 }
14101
14102 tg->idle = idle;
14103
14104 for_each_possible_cpu(i) {
14105 struct rq *rq = cpu_rq(i);
14106 struct sched_entity *se = tg->se[i];
14107 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
14108 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
14109 long idle_task_delta;
14110 struct rq_flags rf;
14111
14112 rq_lock_irqsave(rq, &rf);
14113
14114 grp_cfs_rq->idle = idle;
14115 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
14116 goto next_cpu;
14117
14118 idle_task_delta = grp_cfs_rq->h_nr_queued -
14119 grp_cfs_rq->h_nr_idle;
14120 if (!cfs_rq_is_idle(grp_cfs_rq))
14121 idle_task_delta *= -1;
14122
14123 for_each_sched_entity(se) {
14124 struct cfs_rq *cfs_rq = cfs_rq_of(se);
14125
14126 if (!se->on_rq)
14127 break;
14128
14129 cfs_rq->h_nr_idle += idle_task_delta;
14130
14131 /* Already accounted at parent level and above. */
14132 if (cfs_rq_is_idle(cfs_rq))
14133 break;
14134 }
14135
14136 next_cpu:
14137 rq_unlock_irqrestore(rq, &rf);
14138 }
14139
14140 /* Idle groups have minimum weight. */
14141 if (tg_is_idle(tg))
14142 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
14143 else
14144 __sched_group_set_shares(tg, NICE_0_LOAD);
14145
14146 mutex_unlock(&shares_mutex);
14147 return 0;
14148 }
14149
14150 #endif /* CONFIG_FAIR_GROUP_SCHED */
14151
14152
get_rr_interval_fair(struct rq * rq,struct task_struct * task)14153 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
14154 {
14155 struct sched_entity *se = &task->se;
14156 unsigned int rr_interval = 0;
14157
14158 /*
14159 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
14160 * idle runqueue:
14161 */
14162 if (rq->cfs.load.weight)
14163 rr_interval = NS_TO_JIFFIES(se->slice);
14164
14165 return rr_interval;
14166 }
14167
14168 /*
14169 * All the scheduling class methods:
14170 */
14171 DEFINE_SCHED_CLASS(fair) = {
14172 .enqueue_task = enqueue_task_fair,
14173 .dequeue_task = dequeue_task_fair,
14174 .yield_task = yield_task_fair,
14175 .yield_to_task = yield_to_task_fair,
14176
14177 .wakeup_preempt = wakeup_preempt_fair,
14178
14179 .pick_task = pick_task_fair,
14180 .pick_next_task = pick_next_task_fair,
14181 .put_prev_task = put_prev_task_fair,
14182 .set_next_task = set_next_task_fair,
14183
14184 .select_task_rq = select_task_rq_fair,
14185 .migrate_task_rq = migrate_task_rq_fair,
14186
14187 .rq_online = rq_online_fair,
14188 .rq_offline = rq_offline_fair,
14189
14190 .task_dead = task_dead_fair,
14191 .set_cpus_allowed = set_cpus_allowed_fair,
14192
14193 .task_tick = task_tick_fair,
14194 .task_fork = task_fork_fair,
14195
14196 .reweight_task = reweight_task_fair,
14197 .prio_changed = prio_changed_fair,
14198 .switching_from = switching_from_fair,
14199 .switched_from = switched_from_fair,
14200 .switched_to = switched_to_fair,
14201
14202 .get_rr_interval = get_rr_interval_fair,
14203
14204 .update_curr = update_curr_fair,
14205
14206 #ifdef CONFIG_FAIR_GROUP_SCHED
14207 .task_change_group = task_change_group_fair,
14208 #endif
14209
14210 #ifdef CONFIG_SCHED_CORE
14211 .task_is_throttled = task_is_throttled_fair,
14212 #endif
14213
14214 #ifdef CONFIG_UCLAMP_TASK
14215 .uclamp_enabled = 1,
14216 #endif
14217 };
14218
print_cfs_stats(struct seq_file * m,int cpu)14219 void print_cfs_stats(struct seq_file *m, int cpu)
14220 {
14221 struct cfs_rq *cfs_rq, *pos;
14222
14223 rcu_read_lock();
14224 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
14225 print_cfs_rq(m, cpu, cfs_rq);
14226 rcu_read_unlock();
14227 }
14228
14229 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)14230 void show_numa_stats(struct task_struct *p, struct seq_file *m)
14231 {
14232 int node;
14233 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
14234 struct numa_group *ng;
14235
14236 rcu_read_lock();
14237 ng = rcu_dereference_all(p->numa_group);
14238 for_each_online_node(node) {
14239 if (p->numa_faults) {
14240 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
14241 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
14242 }
14243 if (ng) {
14244 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
14245 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
14246 }
14247 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
14248 }
14249 rcu_read_unlock();
14250 }
14251 #endif /* CONFIG_NUMA_BALANCING */
14252
init_sched_fair_class(void)14253 __init void init_sched_fair_class(void)
14254 {
14255 int i;
14256
14257 for_each_possible_cpu(i) {
14258 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
14259 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
14260 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
14261 GFP_KERNEL, cpu_to_node(i));
14262
14263 #ifdef CONFIG_CFS_BANDWIDTH
14264 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
14265 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
14266 #endif
14267 }
14268
14269 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
14270
14271 #ifdef CONFIG_NO_HZ_COMMON
14272 nohz.next_balance = jiffies;
14273 nohz.next_blocked = jiffies;
14274 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
14275 #endif
14276 }
14277