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, Thomas Gleixner <tglx@linutronix.de>
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.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
78 */
79 unsigned int sysctl_sched_base_slice = 750000ULL;
80 static unsigned int normalized_sysctl_sched_base_slice = 750000ULL;
81
82 const_debug 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 #ifdef CONFIG_SMP
92 /*
93 * For asym packing, by default the lower numbered CPU has higher priority.
94 */
arch_asym_cpu_priority(int cpu)95 int __weak arch_asym_cpu_priority(int cpu)
96 {
97 return -cpu;
98 }
99
100 /*
101 * The margin used when comparing utilization with CPU capacity.
102 *
103 * (default: ~20%)
104 */
105 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
106
107 /*
108 * The margin used when comparing CPU capacities.
109 * is 'cap1' noticeably greater than 'cap2'
110 *
111 * (default: ~5%)
112 */
113 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
114 #endif
115
116 #ifdef CONFIG_CFS_BANDWIDTH
117 /*
118 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
119 * each time a cfs_rq requests quota.
120 *
121 * Note: in the case that the slice exceeds the runtime remaining (either due
122 * to consumption or the quota being specified to be smaller than the slice)
123 * we will always only issue the remaining available time.
124 *
125 * (default: 5 msec, units: microseconds)
126 */
127 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
128 #endif
129
130 #ifdef CONFIG_NUMA_BALANCING
131 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
132 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
133 #endif
134
135 #ifdef CONFIG_SYSCTL
136 static const struct ctl_table sched_fair_sysctls[] = {
137 #ifdef CONFIG_CFS_BANDWIDTH
138 {
139 .procname = "sched_cfs_bandwidth_slice_us",
140 .data = &sysctl_sched_cfs_bandwidth_slice,
141 .maxlen = sizeof(unsigned int),
142 .mode = 0644,
143 .proc_handler = proc_dointvec_minmax,
144 .extra1 = SYSCTL_ONE,
145 },
146 #endif
147 #ifdef CONFIG_NUMA_BALANCING
148 {
149 .procname = "numa_balancing_promote_rate_limit_MBps",
150 .data = &sysctl_numa_balancing_promote_rate_limit,
151 .maxlen = sizeof(unsigned int),
152 .mode = 0644,
153 .proc_handler = proc_dointvec_minmax,
154 .extra1 = SYSCTL_ZERO,
155 },
156 #endif /* CONFIG_NUMA_BALANCING */
157 };
158
sched_fair_sysctl_init(void)159 static int __init sched_fair_sysctl_init(void)
160 {
161 register_sysctl_init("kernel", sched_fair_sysctls);
162 return 0;
163 }
164 late_initcall(sched_fair_sysctl_init);
165 #endif
166
update_load_add(struct load_weight * lw,unsigned long inc)167 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
168 {
169 lw->weight += inc;
170 lw->inv_weight = 0;
171 }
172
update_load_sub(struct load_weight * lw,unsigned long dec)173 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
174 {
175 lw->weight -= dec;
176 lw->inv_weight = 0;
177 }
178
update_load_set(struct load_weight * lw,unsigned long w)179 static inline void update_load_set(struct load_weight *lw, unsigned long w)
180 {
181 lw->weight = w;
182 lw->inv_weight = 0;
183 }
184
185 /*
186 * Increase the granularity value when there are more CPUs,
187 * because with more CPUs the 'effective latency' as visible
188 * to users decreases. But the relationship is not linear,
189 * so pick a second-best guess by going with the log2 of the
190 * number of CPUs.
191 *
192 * This idea comes from the SD scheduler of Con Kolivas:
193 */
get_update_sysctl_factor(void)194 static unsigned int get_update_sysctl_factor(void)
195 {
196 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
197 unsigned int factor;
198
199 switch (sysctl_sched_tunable_scaling) {
200 case SCHED_TUNABLESCALING_NONE:
201 factor = 1;
202 break;
203 case SCHED_TUNABLESCALING_LINEAR:
204 factor = cpus;
205 break;
206 case SCHED_TUNABLESCALING_LOG:
207 default:
208 factor = 1 + ilog2(cpus);
209 break;
210 }
211
212 return factor;
213 }
214
update_sysctl(void)215 static void update_sysctl(void)
216 {
217 unsigned int factor = get_update_sysctl_factor();
218
219 #define SET_SYSCTL(name) \
220 (sysctl_##name = (factor) * normalized_sysctl_##name)
221 SET_SYSCTL(sched_base_slice);
222 #undef SET_SYSCTL
223 }
224
sched_init_granularity(void)225 void __init sched_init_granularity(void)
226 {
227 update_sysctl();
228 }
229
230 #define WMULT_CONST (~0U)
231 #define WMULT_SHIFT 32
232
__update_inv_weight(struct load_weight * lw)233 static void __update_inv_weight(struct load_weight *lw)
234 {
235 unsigned long w;
236
237 if (likely(lw->inv_weight))
238 return;
239
240 w = scale_load_down(lw->weight);
241
242 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
243 lw->inv_weight = 1;
244 else if (unlikely(!w))
245 lw->inv_weight = WMULT_CONST;
246 else
247 lw->inv_weight = WMULT_CONST / w;
248 }
249
250 /*
251 * delta_exec * weight / lw.weight
252 * OR
253 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
254 *
255 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
256 * we're guaranteed shift stays positive because inv_weight is guaranteed to
257 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
258 *
259 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
260 * weight/lw.weight <= 1, and therefore our shift will also be positive.
261 */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)262 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
263 {
264 u64 fact = scale_load_down(weight);
265 u32 fact_hi = (u32)(fact >> 32);
266 int shift = WMULT_SHIFT;
267 int fs;
268
269 __update_inv_weight(lw);
270
271 if (unlikely(fact_hi)) {
272 fs = fls(fact_hi);
273 shift -= fs;
274 fact >>= fs;
275 }
276
277 fact = mul_u32_u32(fact, lw->inv_weight);
278
279 fact_hi = (u32)(fact >> 32);
280 if (fact_hi) {
281 fs = fls(fact_hi);
282 shift -= fs;
283 fact >>= fs;
284 }
285
286 return mul_u64_u32_shr(delta_exec, fact, shift);
287 }
288
289 /*
290 * delta /= w
291 */
calc_delta_fair(u64 delta,struct sched_entity * se)292 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
293 {
294 if (unlikely(se->load.weight != NICE_0_LOAD))
295 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
296
297 return delta;
298 }
299
300 const struct sched_class fair_sched_class;
301
302 /**************************************************************
303 * CFS operations on generic schedulable entities:
304 */
305
306 #ifdef CONFIG_FAIR_GROUP_SCHED
307
308 /* Walk up scheduling entities hierarchy */
309 #define for_each_sched_entity(se) \
310 for (; se; se = se->parent)
311
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)312 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
313 {
314 struct rq *rq = rq_of(cfs_rq);
315 int cpu = cpu_of(rq);
316
317 if (cfs_rq->on_list)
318 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
319
320 cfs_rq->on_list = 1;
321
322 /*
323 * Ensure we either appear before our parent (if already
324 * enqueued) or force our parent to appear after us when it is
325 * enqueued. The fact that we always enqueue bottom-up
326 * reduces this to two cases and a special case for the root
327 * cfs_rq. Furthermore, it also means that we will always reset
328 * tmp_alone_branch either when the branch is connected
329 * to a tree or when we reach the top of the tree
330 */
331 if (cfs_rq->tg->parent &&
332 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
333 /*
334 * If parent is already on the list, we add the child
335 * just before. Thanks to circular linked property of
336 * the list, this means to put the child at the tail
337 * of the list that starts by parent.
338 */
339 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
340 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
341 /*
342 * The branch is now connected to its tree so we can
343 * reset tmp_alone_branch to the beginning of the
344 * list.
345 */
346 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
347 return true;
348 }
349
350 if (!cfs_rq->tg->parent) {
351 /*
352 * cfs rq without parent should be put
353 * at the tail of the list.
354 */
355 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
356 &rq->leaf_cfs_rq_list);
357 /*
358 * We have reach the top of a tree so we can reset
359 * tmp_alone_branch to the beginning of the list.
360 */
361 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
362 return true;
363 }
364
365 /*
366 * The parent has not already been added so we want to
367 * make sure that it will be put after us.
368 * tmp_alone_branch points to the begin of the branch
369 * where we will add parent.
370 */
371 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
372 /*
373 * update tmp_alone_branch to points to the new begin
374 * of the branch
375 */
376 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
377 return false;
378 }
379
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)380 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
381 {
382 if (cfs_rq->on_list) {
383 struct rq *rq = rq_of(cfs_rq);
384
385 /*
386 * With cfs_rq being unthrottled/throttled during an enqueue,
387 * it can happen the tmp_alone_branch points to the leaf that
388 * we finally want to delete. In this case, tmp_alone_branch moves
389 * to the prev element but it will point to rq->leaf_cfs_rq_list
390 * at the end of the enqueue.
391 */
392 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
393 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
394
395 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
396 cfs_rq->on_list = 0;
397 }
398 }
399
assert_list_leaf_cfs_rq(struct rq * rq)400 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
401 {
402 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
403 }
404
405 /* Iterate through all leaf cfs_rq's on a runqueue */
406 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
407 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
408 leaf_cfs_rq_list)
409
410 /* Do the two (enqueued) entities belong to the same group ? */
411 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)412 is_same_group(struct sched_entity *se, struct sched_entity *pse)
413 {
414 if (se->cfs_rq == pse->cfs_rq)
415 return se->cfs_rq;
416
417 return NULL;
418 }
419
parent_entity(const struct sched_entity * se)420 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
421 {
422 return se->parent;
423 }
424
425 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)426 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
427 {
428 int se_depth, pse_depth;
429
430 /*
431 * preemption test can be made between sibling entities who are in the
432 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
433 * both tasks until we find their ancestors who are siblings of common
434 * parent.
435 */
436
437 /* First walk up until both entities are at same depth */
438 se_depth = (*se)->depth;
439 pse_depth = (*pse)->depth;
440
441 while (se_depth > pse_depth) {
442 se_depth--;
443 *se = parent_entity(*se);
444 }
445
446 while (pse_depth > se_depth) {
447 pse_depth--;
448 *pse = parent_entity(*pse);
449 }
450
451 while (!is_same_group(*se, *pse)) {
452 *se = parent_entity(*se);
453 *pse = parent_entity(*pse);
454 }
455 }
456
tg_is_idle(struct task_group * tg)457 static int tg_is_idle(struct task_group *tg)
458 {
459 return tg->idle > 0;
460 }
461
cfs_rq_is_idle(struct cfs_rq * cfs_rq)462 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
463 {
464 return cfs_rq->idle > 0;
465 }
466
se_is_idle(struct sched_entity * se)467 static int se_is_idle(struct sched_entity *se)
468 {
469 if (entity_is_task(se))
470 return task_has_idle_policy(task_of(se));
471 return cfs_rq_is_idle(group_cfs_rq(se));
472 }
473
474 #else /* !CONFIG_FAIR_GROUP_SCHED */
475
476 #define for_each_sched_entity(se) \
477 for (; se; se = NULL)
478
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)479 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
480 {
481 return true;
482 }
483
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)484 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
485 {
486 }
487
assert_list_leaf_cfs_rq(struct rq * rq)488 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
489 {
490 }
491
492 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
493 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
494
parent_entity(struct sched_entity * se)495 static inline struct sched_entity *parent_entity(struct sched_entity *se)
496 {
497 return NULL;
498 }
499
500 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)501 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
502 {
503 }
504
tg_is_idle(struct task_group * tg)505 static inline int tg_is_idle(struct task_group *tg)
506 {
507 return 0;
508 }
509
cfs_rq_is_idle(struct cfs_rq * cfs_rq)510 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
511 {
512 return 0;
513 }
514
se_is_idle(struct sched_entity * se)515 static int se_is_idle(struct sched_entity *se)
516 {
517 return task_has_idle_policy(task_of(se));
518 }
519
520 #endif /* CONFIG_FAIR_GROUP_SCHED */
521
522 static __always_inline
523 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
524
525 /**************************************************************
526 * Scheduling class tree data structure manipulation methods:
527 */
528
max_vruntime(u64 max_vruntime,u64 vruntime)529 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
530 {
531 s64 delta = (s64)(vruntime - max_vruntime);
532 if (delta > 0)
533 max_vruntime = vruntime;
534
535 return max_vruntime;
536 }
537
min_vruntime(u64 min_vruntime,u64 vruntime)538 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
539 {
540 s64 delta = (s64)(vruntime - min_vruntime);
541 if (delta < 0)
542 min_vruntime = vruntime;
543
544 return min_vruntime;
545 }
546
entity_before(const struct sched_entity * a,const struct sched_entity * b)547 static inline bool entity_before(const struct sched_entity *a,
548 const struct sched_entity *b)
549 {
550 /*
551 * Tiebreak on vruntime seems unnecessary since it can
552 * hardly happen.
553 */
554 return (s64)(a->deadline - b->deadline) < 0;
555 }
556
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)557 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
558 {
559 return (s64)(se->vruntime - cfs_rq->min_vruntime);
560 }
561
562 #define __node_2_se(node) \
563 rb_entry((node), struct sched_entity, run_node)
564
565 /*
566 * Compute virtual time from the per-task service numbers:
567 *
568 * Fair schedulers conserve lag:
569 *
570 * \Sum lag_i = 0
571 *
572 * Where lag_i is given by:
573 *
574 * lag_i = S - s_i = w_i * (V - v_i)
575 *
576 * Where S is the ideal service time and V is it's virtual time counterpart.
577 * Therefore:
578 *
579 * \Sum lag_i = 0
580 * \Sum w_i * (V - v_i) = 0
581 * \Sum w_i * V - w_i * v_i = 0
582 *
583 * From which we can solve an expression for V in v_i (which we have in
584 * se->vruntime):
585 *
586 * \Sum v_i * w_i \Sum v_i * w_i
587 * V = -------------- = --------------
588 * \Sum w_i W
589 *
590 * Specifically, this is the weighted average of all entity virtual runtimes.
591 *
592 * [[ NOTE: this is only equal to the ideal scheduler under the condition
593 * that join/leave operations happen at lag_i = 0, otherwise the
594 * virtual time has non-contiguous motion equivalent to:
595 *
596 * V +-= lag_i / W
597 *
598 * Also see the comment in place_entity() that deals with this. ]]
599 *
600 * However, since v_i is u64, and the multiplication could easily overflow
601 * transform it into a relative form that uses smaller quantities:
602 *
603 * Substitute: v_i == (v_i - v0) + v0
604 *
605 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
606 * V = ---------------------------- = --------------------- + v0
607 * W W
608 *
609 * Which we track using:
610 *
611 * v0 := cfs_rq->min_vruntime
612 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
613 * \Sum w_i := cfs_rq->avg_load
614 *
615 * Since min_vruntime is a monotonic increasing variable that closely tracks
616 * the per-task service, these deltas: (v_i - v), will be in the order of the
617 * maximal (virtual) lag induced in the system due to quantisation.
618 *
619 * Also, we use scale_load_down() to reduce the size.
620 *
621 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
622 */
623 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)624 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
625 {
626 unsigned long weight = scale_load_down(se->load.weight);
627 s64 key = entity_key(cfs_rq, se);
628
629 cfs_rq->avg_vruntime += key * weight;
630 cfs_rq->avg_load += weight;
631 }
632
633 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)634 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
635 {
636 unsigned long weight = scale_load_down(se->load.weight);
637 s64 key = entity_key(cfs_rq, se);
638
639 cfs_rq->avg_vruntime -= key * weight;
640 cfs_rq->avg_load -= weight;
641 }
642
643 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)644 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
645 {
646 /*
647 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
648 */
649 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
650 }
651
652 /*
653 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
654 * For this to be so, the result of this function must have a left bias.
655 */
avg_vruntime(struct cfs_rq * cfs_rq)656 u64 avg_vruntime(struct cfs_rq *cfs_rq)
657 {
658 struct sched_entity *curr = cfs_rq->curr;
659 s64 avg = cfs_rq->avg_vruntime;
660 long load = cfs_rq->avg_load;
661
662 if (curr && curr->on_rq) {
663 unsigned long weight = scale_load_down(curr->load.weight);
664
665 avg += entity_key(cfs_rq, curr) * weight;
666 load += weight;
667 }
668
669 if (load) {
670 /* sign flips effective floor / ceiling */
671 if (avg < 0)
672 avg -= (load - 1);
673 avg = div_s64(avg, load);
674 }
675
676 return cfs_rq->min_vruntime + avg;
677 }
678
679 /*
680 * lag_i = S - s_i = w_i * (V - v_i)
681 *
682 * However, since V is approximated by the weighted average of all entities it
683 * is possible -- by addition/removal/reweight to the tree -- to move V around
684 * and end up with a larger lag than we started with.
685 *
686 * Limit this to either double the slice length with a minimum of TICK_NSEC
687 * since that is the timing granularity.
688 *
689 * EEVDF gives the following limit for a steady state system:
690 *
691 * -r_max < lag < max(r_max, q)
692 *
693 * XXX could add max_slice to the augmented data to track this.
694 */
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)695 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
696 {
697 s64 vlag, limit;
698
699 SCHED_WARN_ON(!se->on_rq);
700
701 vlag = avg_vruntime(cfs_rq) - se->vruntime;
702 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
703
704 se->vlag = clamp(vlag, -limit, limit);
705 }
706
707 /*
708 * Entity is eligible once it received less service than it ought to have,
709 * eg. lag >= 0.
710 *
711 * lag_i = S - s_i = w_i*(V - v_i)
712 *
713 * lag_i >= 0 -> V >= v_i
714 *
715 * \Sum (v_i - v)*w_i
716 * V = ------------------ + v
717 * \Sum w_i
718 *
719 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
720 *
721 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
722 * to the loss in precision caused by the division.
723 */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)724 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
725 {
726 struct sched_entity *curr = cfs_rq->curr;
727 s64 avg = cfs_rq->avg_vruntime;
728 long load = cfs_rq->avg_load;
729
730 if (curr && curr->on_rq) {
731 unsigned long weight = scale_load_down(curr->load.weight);
732
733 avg += entity_key(cfs_rq, curr) * weight;
734 load += weight;
735 }
736
737 return avg >= (s64)(vruntime - cfs_rq->min_vruntime) * load;
738 }
739
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)740 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
741 {
742 return vruntime_eligible(cfs_rq, se->vruntime);
743 }
744
__update_min_vruntime(struct cfs_rq * cfs_rq,u64 vruntime)745 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
746 {
747 u64 min_vruntime = cfs_rq->min_vruntime;
748 /*
749 * open coded max_vruntime() to allow updating avg_vruntime
750 */
751 s64 delta = (s64)(vruntime - min_vruntime);
752 if (delta > 0) {
753 avg_vruntime_update(cfs_rq, delta);
754 min_vruntime = vruntime;
755 }
756 return min_vruntime;
757 }
758
update_min_vruntime(struct cfs_rq * cfs_rq)759 static void update_min_vruntime(struct cfs_rq *cfs_rq)
760 {
761 struct sched_entity *se = __pick_root_entity(cfs_rq);
762 struct sched_entity *curr = cfs_rq->curr;
763 u64 vruntime = cfs_rq->min_vruntime;
764
765 if (curr) {
766 if (curr->on_rq)
767 vruntime = curr->vruntime;
768 else
769 curr = NULL;
770 }
771
772 if (se) {
773 if (!curr)
774 vruntime = se->min_vruntime;
775 else
776 vruntime = min_vruntime(vruntime, se->min_vruntime);
777 }
778
779 /* ensure we never gain time by being placed backwards. */
780 cfs_rq->min_vruntime = __update_min_vruntime(cfs_rq, vruntime);
781 }
782
cfs_rq_min_slice(struct cfs_rq * cfs_rq)783 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
784 {
785 struct sched_entity *root = __pick_root_entity(cfs_rq);
786 struct sched_entity *curr = cfs_rq->curr;
787 u64 min_slice = ~0ULL;
788
789 if (curr && curr->on_rq)
790 min_slice = curr->slice;
791
792 if (root)
793 min_slice = min(min_slice, root->min_slice);
794
795 return min_slice;
796 }
797
__entity_less(struct rb_node * a,const struct rb_node * b)798 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
799 {
800 return entity_before(__node_2_se(a), __node_2_se(b));
801 }
802
803 #define vruntime_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
804
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)805 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
806 {
807 if (node) {
808 struct sched_entity *rse = __node_2_se(node);
809 if (vruntime_gt(min_vruntime, se, rse))
810 se->min_vruntime = rse->min_vruntime;
811 }
812 }
813
__min_slice_update(struct sched_entity * se,struct rb_node * node)814 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
815 {
816 if (node) {
817 struct sched_entity *rse = __node_2_se(node);
818 if (rse->min_slice < se->min_slice)
819 se->min_slice = rse->min_slice;
820 }
821 }
822
823 /*
824 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
825 */
min_vruntime_update(struct sched_entity * se,bool exit)826 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
827 {
828 u64 old_min_vruntime = se->min_vruntime;
829 u64 old_min_slice = se->min_slice;
830 struct rb_node *node = &se->run_node;
831
832 se->min_vruntime = se->vruntime;
833 __min_vruntime_update(se, node->rb_right);
834 __min_vruntime_update(se, node->rb_left);
835
836 se->min_slice = se->slice;
837 __min_slice_update(se, node->rb_right);
838 __min_slice_update(se, node->rb_left);
839
840 return se->min_vruntime == old_min_vruntime &&
841 se->min_slice == old_min_slice;
842 }
843
844 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
845 run_node, min_vruntime, min_vruntime_update);
846
847 /*
848 * Enqueue an entity into the rb-tree:
849 */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)850 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
851 {
852 avg_vruntime_add(cfs_rq, se);
853 se->min_vruntime = se->vruntime;
854 se->min_slice = se->slice;
855 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
856 __entity_less, &min_vruntime_cb);
857 }
858
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)859 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
860 {
861 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
862 &min_vruntime_cb);
863 avg_vruntime_sub(cfs_rq, se);
864 }
865
__pick_root_entity(struct cfs_rq * cfs_rq)866 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
867 {
868 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
869
870 if (!root)
871 return NULL;
872
873 return __node_2_se(root);
874 }
875
__pick_first_entity(struct cfs_rq * cfs_rq)876 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
877 {
878 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
879
880 if (!left)
881 return NULL;
882
883 return __node_2_se(left);
884 }
885
886 /*
887 * Earliest Eligible Virtual Deadline First
888 *
889 * In order to provide latency guarantees for different request sizes
890 * EEVDF selects the best runnable task from two criteria:
891 *
892 * 1) the task must be eligible (must be owed service)
893 *
894 * 2) from those tasks that meet 1), we select the one
895 * with the earliest virtual deadline.
896 *
897 * We can do this in O(log n) time due to an augmented RB-tree. The
898 * tree keeps the entries sorted on deadline, but also functions as a
899 * heap based on the vruntime by keeping:
900 *
901 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
902 *
903 * Which allows tree pruning through eligibility.
904 */
pick_eevdf(struct cfs_rq * cfs_rq)905 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
906 {
907 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
908 struct sched_entity *se = __pick_first_entity(cfs_rq);
909 struct sched_entity *curr = cfs_rq->curr;
910 struct sched_entity *best = NULL;
911
912 /*
913 * We can safely skip eligibility check if there is only one entity
914 * in this cfs_rq, saving some cycles.
915 */
916 if (cfs_rq->nr_queued == 1)
917 return curr && curr->on_rq ? curr : se;
918
919 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
920 curr = NULL;
921
922 /*
923 * Once selected, run a task until it either becomes non-eligible or
924 * until it gets a new slice. See the HACK in set_next_entity().
925 */
926 if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
927 return curr;
928
929 /* Pick the leftmost entity if it's eligible */
930 if (se && entity_eligible(cfs_rq, se)) {
931 best = se;
932 goto found;
933 }
934
935 /* Heap search for the EEVD entity */
936 while (node) {
937 struct rb_node *left = node->rb_left;
938
939 /*
940 * Eligible entities in left subtree are always better
941 * choices, since they have earlier deadlines.
942 */
943 if (left && vruntime_eligible(cfs_rq,
944 __node_2_se(left)->min_vruntime)) {
945 node = left;
946 continue;
947 }
948
949 se = __node_2_se(node);
950
951 /*
952 * The left subtree either is empty or has no eligible
953 * entity, so check the current node since it is the one
954 * with earliest deadline that might be eligible.
955 */
956 if (entity_eligible(cfs_rq, se)) {
957 best = se;
958 break;
959 }
960
961 node = node->rb_right;
962 }
963 found:
964 if (!best || (curr && entity_before(curr, best)))
965 best = curr;
966
967 return best;
968 }
969
970 #ifdef CONFIG_SCHED_DEBUG
__pick_last_entity(struct cfs_rq * cfs_rq)971 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
972 {
973 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
974
975 if (!last)
976 return NULL;
977
978 return __node_2_se(last);
979 }
980
981 /**************************************************************
982 * Scheduling class statistics methods:
983 */
984 #ifdef CONFIG_SMP
sched_update_scaling(void)985 int sched_update_scaling(void)
986 {
987 unsigned int factor = get_update_sysctl_factor();
988
989 #define WRT_SYSCTL(name) \
990 (normalized_sysctl_##name = sysctl_##name / (factor))
991 WRT_SYSCTL(sched_base_slice);
992 #undef WRT_SYSCTL
993
994 return 0;
995 }
996 #endif
997 #endif
998
999 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1000
1001 /*
1002 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1003 * this is probably good enough.
1004 */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1005 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1006 {
1007 if ((s64)(se->vruntime - se->deadline) < 0)
1008 return false;
1009
1010 /*
1011 * For EEVDF the virtual time slope is determined by w_i (iow.
1012 * nice) while the request time r_i is determined by
1013 * sysctl_sched_base_slice.
1014 */
1015 if (!se->custom_slice)
1016 se->slice = sysctl_sched_base_slice;
1017
1018 /*
1019 * EEVDF: vd_i = ve_i + r_i / w_i
1020 */
1021 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1022
1023 /*
1024 * The task has consumed its request, reschedule.
1025 */
1026 return true;
1027 }
1028
1029 #include "pelt.h"
1030 #ifdef CONFIG_SMP
1031
1032 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1033 static unsigned long task_h_load(struct task_struct *p);
1034 static unsigned long capacity_of(int cpu);
1035
1036 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1037 void init_entity_runnable_average(struct sched_entity *se)
1038 {
1039 struct sched_avg *sa = &se->avg;
1040
1041 memset(sa, 0, sizeof(*sa));
1042
1043 /*
1044 * Tasks are initialized with full load to be seen as heavy tasks until
1045 * they get a chance to stabilize to their real load level.
1046 * Group entities are initialized with zero load to reflect the fact that
1047 * nothing has been attached to the task group yet.
1048 */
1049 if (entity_is_task(se))
1050 sa->load_avg = scale_load_down(se->load.weight);
1051
1052 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1053 }
1054
1055 /*
1056 * With new tasks being created, their initial util_avgs are extrapolated
1057 * based on the cfs_rq's current util_avg:
1058 *
1059 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1060 * * se_weight(se)
1061 *
1062 * However, in many cases, the above util_avg does not give a desired
1063 * value. Moreover, the sum of the util_avgs may be divergent, such
1064 * as when the series is a harmonic series.
1065 *
1066 * To solve this problem, we also cap the util_avg of successive tasks to
1067 * only 1/2 of the left utilization budget:
1068 *
1069 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1070 *
1071 * where n denotes the nth task and cpu_scale the CPU capacity.
1072 *
1073 * For example, for a CPU with 1024 of capacity, a simplest series from
1074 * the beginning would be like:
1075 *
1076 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1077 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1078 *
1079 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1080 * if util_avg > util_avg_cap.
1081 */
post_init_entity_util_avg(struct task_struct * p)1082 void post_init_entity_util_avg(struct task_struct *p)
1083 {
1084 struct sched_entity *se = &p->se;
1085 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1086 struct sched_avg *sa = &se->avg;
1087 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1088 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1089
1090 if (p->sched_class != &fair_sched_class) {
1091 /*
1092 * For !fair tasks do:
1093 *
1094 update_cfs_rq_load_avg(now, cfs_rq);
1095 attach_entity_load_avg(cfs_rq, se);
1096 switched_from_fair(rq, p);
1097 *
1098 * such that the next switched_to_fair() has the
1099 * expected state.
1100 */
1101 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1102 return;
1103 }
1104
1105 if (cap > 0) {
1106 if (cfs_rq->avg.util_avg != 0) {
1107 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se);
1108 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1109
1110 if (sa->util_avg > cap)
1111 sa->util_avg = cap;
1112 } else {
1113 sa->util_avg = cap;
1114 }
1115 }
1116
1117 sa->runnable_avg = sa->util_avg;
1118 }
1119
1120 #else /* !CONFIG_SMP */
init_entity_runnable_average(struct sched_entity * se)1121 void init_entity_runnable_average(struct sched_entity *se)
1122 {
1123 }
post_init_entity_util_avg(struct task_struct * p)1124 void post_init_entity_util_avg(struct task_struct *p)
1125 {
1126 }
update_tg_load_avg(struct cfs_rq * cfs_rq)1127 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1128 {
1129 }
1130 #endif /* CONFIG_SMP */
1131
update_curr_se(struct rq * rq,struct sched_entity * curr)1132 static s64 update_curr_se(struct rq *rq, struct sched_entity *curr)
1133 {
1134 u64 now = rq_clock_task(rq);
1135 s64 delta_exec;
1136
1137 delta_exec = now - curr->exec_start;
1138 if (unlikely(delta_exec <= 0))
1139 return delta_exec;
1140
1141 curr->exec_start = now;
1142 curr->sum_exec_runtime += delta_exec;
1143
1144 if (schedstat_enabled()) {
1145 struct sched_statistics *stats;
1146
1147 stats = __schedstats_from_se(curr);
1148 __schedstat_set(stats->exec_max,
1149 max(delta_exec, stats->exec_max));
1150 }
1151
1152 return delta_exec;
1153 }
1154
update_curr_task(struct task_struct * p,s64 delta_exec)1155 static inline void update_curr_task(struct task_struct *p, s64 delta_exec)
1156 {
1157 trace_sched_stat_runtime(p, delta_exec);
1158 account_group_exec_runtime(p, delta_exec);
1159 cgroup_account_cputime(p, delta_exec);
1160 }
1161
did_preempt_short(struct cfs_rq * cfs_rq,struct sched_entity * curr)1162 static inline bool did_preempt_short(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1163 {
1164 if (!sched_feat(PREEMPT_SHORT))
1165 return false;
1166
1167 if (curr->vlag == curr->deadline)
1168 return false;
1169
1170 return !entity_eligible(cfs_rq, curr);
1171 }
1172
do_preempt_short(struct cfs_rq * cfs_rq,struct sched_entity * pse,struct sched_entity * se)1173 static inline bool do_preempt_short(struct cfs_rq *cfs_rq,
1174 struct sched_entity *pse, struct sched_entity *se)
1175 {
1176 if (!sched_feat(PREEMPT_SHORT))
1177 return false;
1178
1179 if (pse->slice >= se->slice)
1180 return false;
1181
1182 if (!entity_eligible(cfs_rq, pse))
1183 return false;
1184
1185 if (entity_before(pse, se))
1186 return true;
1187
1188 if (!entity_eligible(cfs_rq, se))
1189 return true;
1190
1191 return false;
1192 }
1193
1194 /*
1195 * Used by other classes to account runtime.
1196 */
update_curr_common(struct rq * rq)1197 s64 update_curr_common(struct rq *rq)
1198 {
1199 struct task_struct *donor = rq->donor;
1200 s64 delta_exec;
1201
1202 delta_exec = update_curr_se(rq, &donor->se);
1203 if (likely(delta_exec > 0))
1204 update_curr_task(donor, delta_exec);
1205
1206 return delta_exec;
1207 }
1208
1209 /*
1210 * Update the current task's runtime statistics.
1211 */
update_curr(struct cfs_rq * cfs_rq)1212 static void update_curr(struct cfs_rq *cfs_rq)
1213 {
1214 struct sched_entity *curr = cfs_rq->curr;
1215 struct rq *rq = rq_of(cfs_rq);
1216 s64 delta_exec;
1217 bool resched;
1218
1219 if (unlikely(!curr))
1220 return;
1221
1222 delta_exec = update_curr_se(rq, curr);
1223 if (unlikely(delta_exec <= 0))
1224 return;
1225
1226 curr->vruntime += calc_delta_fair(delta_exec, curr);
1227 resched = update_deadline(cfs_rq, curr);
1228 update_min_vruntime(cfs_rq);
1229
1230 if (entity_is_task(curr)) {
1231 struct task_struct *p = task_of(curr);
1232
1233 update_curr_task(p, delta_exec);
1234
1235 /*
1236 * If the fair_server is active, we need to account for the
1237 * fair_server time whether or not the task is running on
1238 * behalf of fair_server or not:
1239 * - If the task is running on behalf of fair_server, we need
1240 * to limit its time based on the assigned runtime.
1241 * - Fair task that runs outside of fair_server should account
1242 * against fair_server such that it can account for this time
1243 * and possibly avoid running this period.
1244 */
1245 if (dl_server_active(&rq->fair_server))
1246 dl_server_update(&rq->fair_server, delta_exec);
1247 }
1248
1249 account_cfs_rq_runtime(cfs_rq, delta_exec);
1250
1251 if (cfs_rq->nr_queued == 1)
1252 return;
1253
1254 if (resched || did_preempt_short(cfs_rq, curr)) {
1255 resched_curr_lazy(rq);
1256 clear_buddies(cfs_rq, curr);
1257 }
1258 }
1259
update_curr_fair(struct rq * rq)1260 static void update_curr_fair(struct rq *rq)
1261 {
1262 update_curr(cfs_rq_of(&rq->donor->se));
1263 }
1264
1265 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1266 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1267 {
1268 struct sched_statistics *stats;
1269 struct task_struct *p = NULL;
1270
1271 if (!schedstat_enabled())
1272 return;
1273
1274 stats = __schedstats_from_se(se);
1275
1276 if (entity_is_task(se))
1277 p = task_of(se);
1278
1279 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1280 }
1281
1282 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1283 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1284 {
1285 struct sched_statistics *stats;
1286 struct task_struct *p = NULL;
1287
1288 if (!schedstat_enabled())
1289 return;
1290
1291 stats = __schedstats_from_se(se);
1292
1293 /*
1294 * When the sched_schedstat changes from 0 to 1, some sched se
1295 * maybe already in the runqueue, the se->statistics.wait_start
1296 * will be 0.So it will let the delta wrong. We need to avoid this
1297 * scenario.
1298 */
1299 if (unlikely(!schedstat_val(stats->wait_start)))
1300 return;
1301
1302 if (entity_is_task(se))
1303 p = task_of(se);
1304
1305 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1306 }
1307
1308 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1309 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1310 {
1311 struct sched_statistics *stats;
1312 struct task_struct *tsk = NULL;
1313
1314 if (!schedstat_enabled())
1315 return;
1316
1317 stats = __schedstats_from_se(se);
1318
1319 if (entity_is_task(se))
1320 tsk = task_of(se);
1321
1322 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1323 }
1324
1325 /*
1326 * Task is being enqueued - update stats:
1327 */
1328 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1329 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1330 {
1331 if (!schedstat_enabled())
1332 return;
1333
1334 /*
1335 * Are we enqueueing a waiting task? (for current tasks
1336 * a dequeue/enqueue event is a NOP)
1337 */
1338 if (se != cfs_rq->curr)
1339 update_stats_wait_start_fair(cfs_rq, se);
1340
1341 if (flags & ENQUEUE_WAKEUP)
1342 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1343 }
1344
1345 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1346 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1347 {
1348
1349 if (!schedstat_enabled())
1350 return;
1351
1352 /*
1353 * Mark the end of the wait period if dequeueing a
1354 * waiting task:
1355 */
1356 if (se != cfs_rq->curr)
1357 update_stats_wait_end_fair(cfs_rq, se);
1358
1359 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1360 struct task_struct *tsk = task_of(se);
1361 unsigned int state;
1362
1363 /* XXX racy against TTWU */
1364 state = READ_ONCE(tsk->__state);
1365 if (state & TASK_INTERRUPTIBLE)
1366 __schedstat_set(tsk->stats.sleep_start,
1367 rq_clock(rq_of(cfs_rq)));
1368 if (state & TASK_UNINTERRUPTIBLE)
1369 __schedstat_set(tsk->stats.block_start,
1370 rq_clock(rq_of(cfs_rq)));
1371 }
1372 }
1373
1374 /*
1375 * We are picking a new current task - update its stats:
1376 */
1377 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1378 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1379 {
1380 /*
1381 * We are starting a new run period:
1382 */
1383 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1384 }
1385
1386 /**************************************************
1387 * Scheduling class queueing methods:
1388 */
1389
is_core_idle(int cpu)1390 static inline bool is_core_idle(int cpu)
1391 {
1392 #ifdef CONFIG_SCHED_SMT
1393 int sibling;
1394
1395 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1396 if (cpu == sibling)
1397 continue;
1398
1399 if (!idle_cpu(sibling))
1400 return false;
1401 }
1402 #endif
1403
1404 return true;
1405 }
1406
1407 #ifdef CONFIG_NUMA
1408 #define NUMA_IMBALANCE_MIN 2
1409
1410 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1411 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1412 {
1413 /*
1414 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1415 * threshold. Above this threshold, individual tasks may be contending
1416 * for both memory bandwidth and any shared HT resources. This is an
1417 * approximation as the number of running tasks may not be related to
1418 * the number of busy CPUs due to sched_setaffinity.
1419 */
1420 if (dst_running > imb_numa_nr)
1421 return imbalance;
1422
1423 /*
1424 * Allow a small imbalance based on a simple pair of communicating
1425 * tasks that remain local when the destination is lightly loaded.
1426 */
1427 if (imbalance <= NUMA_IMBALANCE_MIN)
1428 return 0;
1429
1430 return imbalance;
1431 }
1432 #endif /* CONFIG_NUMA */
1433
1434 #ifdef CONFIG_NUMA_BALANCING
1435 /*
1436 * Approximate time to scan a full NUMA task in ms. The task scan period is
1437 * calculated based on the tasks virtual memory size and
1438 * numa_balancing_scan_size.
1439 */
1440 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1441 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1442
1443 /* Portion of address space to scan in MB */
1444 unsigned int sysctl_numa_balancing_scan_size = 256;
1445
1446 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1447 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1448
1449 /* The page with hint page fault latency < threshold in ms is considered hot */
1450 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1451
1452 struct numa_group {
1453 refcount_t refcount;
1454
1455 spinlock_t lock; /* nr_tasks, tasks */
1456 int nr_tasks;
1457 pid_t gid;
1458 int active_nodes;
1459
1460 struct rcu_head rcu;
1461 unsigned long total_faults;
1462 unsigned long max_faults_cpu;
1463 /*
1464 * faults[] array is split into two regions: faults_mem and faults_cpu.
1465 *
1466 * Faults_cpu is used to decide whether memory should move
1467 * towards the CPU. As a consequence, these stats are weighted
1468 * more by CPU use than by memory faults.
1469 */
1470 unsigned long faults[];
1471 };
1472
1473 /*
1474 * For functions that can be called in multiple contexts that permit reading
1475 * ->numa_group (see struct task_struct for locking rules).
1476 */
deref_task_numa_group(struct task_struct * p)1477 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1478 {
1479 return rcu_dereference_check(p->numa_group, p == current ||
1480 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1481 }
1482
deref_curr_numa_group(struct task_struct * p)1483 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1484 {
1485 return rcu_dereference_protected(p->numa_group, p == current);
1486 }
1487
1488 static inline unsigned long group_faults_priv(struct numa_group *ng);
1489 static inline unsigned long group_faults_shared(struct numa_group *ng);
1490
task_nr_scan_windows(struct task_struct * p)1491 static unsigned int task_nr_scan_windows(struct task_struct *p)
1492 {
1493 unsigned long rss = 0;
1494 unsigned long nr_scan_pages;
1495
1496 /*
1497 * Calculations based on RSS as non-present and empty pages are skipped
1498 * by the PTE scanner and NUMA hinting faults should be trapped based
1499 * on resident pages
1500 */
1501 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1502 rss = get_mm_rss(p->mm);
1503 if (!rss)
1504 rss = nr_scan_pages;
1505
1506 rss = round_up(rss, nr_scan_pages);
1507 return rss / nr_scan_pages;
1508 }
1509
1510 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1511 #define MAX_SCAN_WINDOW 2560
1512
task_scan_min(struct task_struct * p)1513 static unsigned int task_scan_min(struct task_struct *p)
1514 {
1515 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1516 unsigned int scan, floor;
1517 unsigned int windows = 1;
1518
1519 if (scan_size < MAX_SCAN_WINDOW)
1520 windows = MAX_SCAN_WINDOW / scan_size;
1521 floor = 1000 / windows;
1522
1523 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1524 return max_t(unsigned int, floor, scan);
1525 }
1526
task_scan_start(struct task_struct * p)1527 static unsigned int task_scan_start(struct task_struct *p)
1528 {
1529 unsigned long smin = task_scan_min(p);
1530 unsigned long period = smin;
1531 struct numa_group *ng;
1532
1533 /* Scale the maximum scan period with the amount of shared memory. */
1534 rcu_read_lock();
1535 ng = rcu_dereference(p->numa_group);
1536 if (ng) {
1537 unsigned long shared = group_faults_shared(ng);
1538 unsigned long private = group_faults_priv(ng);
1539
1540 period *= refcount_read(&ng->refcount);
1541 period *= shared + 1;
1542 period /= private + shared + 1;
1543 }
1544 rcu_read_unlock();
1545
1546 return max(smin, period);
1547 }
1548
task_scan_max(struct task_struct * p)1549 static unsigned int task_scan_max(struct task_struct *p)
1550 {
1551 unsigned long smin = task_scan_min(p);
1552 unsigned long smax;
1553 struct numa_group *ng;
1554
1555 /* Watch for min being lower than max due to floor calculations */
1556 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1557
1558 /* Scale the maximum scan period with the amount of shared memory. */
1559 ng = deref_curr_numa_group(p);
1560 if (ng) {
1561 unsigned long shared = group_faults_shared(ng);
1562 unsigned long private = group_faults_priv(ng);
1563 unsigned long period = smax;
1564
1565 period *= refcount_read(&ng->refcount);
1566 period *= shared + 1;
1567 period /= private + shared + 1;
1568
1569 smax = max(smax, period);
1570 }
1571
1572 return max(smin, smax);
1573 }
1574
account_numa_enqueue(struct rq * rq,struct task_struct * p)1575 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1576 {
1577 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1578 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1579 }
1580
account_numa_dequeue(struct rq * rq,struct task_struct * p)1581 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1582 {
1583 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1584 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1585 }
1586
1587 /* Shared or private faults. */
1588 #define NR_NUMA_HINT_FAULT_TYPES 2
1589
1590 /* Memory and CPU locality */
1591 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1592
1593 /* Averaged statistics, and temporary buffers. */
1594 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1595
task_numa_group_id(struct task_struct * p)1596 pid_t task_numa_group_id(struct task_struct *p)
1597 {
1598 struct numa_group *ng;
1599 pid_t gid = 0;
1600
1601 rcu_read_lock();
1602 ng = rcu_dereference(p->numa_group);
1603 if (ng)
1604 gid = ng->gid;
1605 rcu_read_unlock();
1606
1607 return gid;
1608 }
1609
1610 /*
1611 * The averaged statistics, shared & private, memory & CPU,
1612 * occupy the first half of the array. The second half of the
1613 * array is for current counters, which are averaged into the
1614 * first set by task_numa_placement.
1615 */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1616 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1617 {
1618 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1619 }
1620
task_faults(struct task_struct * p,int nid)1621 static inline unsigned long task_faults(struct task_struct *p, int nid)
1622 {
1623 if (!p->numa_faults)
1624 return 0;
1625
1626 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1627 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1628 }
1629
group_faults(struct task_struct * p,int nid)1630 static inline unsigned long group_faults(struct task_struct *p, int nid)
1631 {
1632 struct numa_group *ng = deref_task_numa_group(p);
1633
1634 if (!ng)
1635 return 0;
1636
1637 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1638 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1639 }
1640
group_faults_cpu(struct numa_group * group,int nid)1641 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1642 {
1643 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1644 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1645 }
1646
group_faults_priv(struct numa_group * ng)1647 static inline unsigned long group_faults_priv(struct numa_group *ng)
1648 {
1649 unsigned long faults = 0;
1650 int node;
1651
1652 for_each_online_node(node) {
1653 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1654 }
1655
1656 return faults;
1657 }
1658
group_faults_shared(struct numa_group * ng)1659 static inline unsigned long group_faults_shared(struct numa_group *ng)
1660 {
1661 unsigned long faults = 0;
1662 int node;
1663
1664 for_each_online_node(node) {
1665 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1666 }
1667
1668 return faults;
1669 }
1670
1671 /*
1672 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1673 * considered part of a numa group's pseudo-interleaving set. Migrations
1674 * between these nodes are slowed down, to allow things to settle down.
1675 */
1676 #define ACTIVE_NODE_FRACTION 3
1677
numa_is_active_node(int nid,struct numa_group * ng)1678 static bool numa_is_active_node(int nid, struct numa_group *ng)
1679 {
1680 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1681 }
1682
1683 /* 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)1684 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1685 int lim_dist, bool task)
1686 {
1687 unsigned long score = 0;
1688 int node, max_dist;
1689
1690 /*
1691 * All nodes are directly connected, and the same distance
1692 * from each other. No need for fancy placement algorithms.
1693 */
1694 if (sched_numa_topology_type == NUMA_DIRECT)
1695 return 0;
1696
1697 /* sched_max_numa_distance may be changed in parallel. */
1698 max_dist = READ_ONCE(sched_max_numa_distance);
1699 /*
1700 * This code is called for each node, introducing N^2 complexity,
1701 * which should be OK given the number of nodes rarely exceeds 8.
1702 */
1703 for_each_online_node(node) {
1704 unsigned long faults;
1705 int dist = node_distance(nid, node);
1706
1707 /*
1708 * The furthest away nodes in the system are not interesting
1709 * for placement; nid was already counted.
1710 */
1711 if (dist >= max_dist || node == nid)
1712 continue;
1713
1714 /*
1715 * On systems with a backplane NUMA topology, compare groups
1716 * of nodes, and move tasks towards the group with the most
1717 * memory accesses. When comparing two nodes at distance
1718 * "hoplimit", only nodes closer by than "hoplimit" are part
1719 * of each group. Skip other nodes.
1720 */
1721 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1722 continue;
1723
1724 /* Add up the faults from nearby nodes. */
1725 if (task)
1726 faults = task_faults(p, node);
1727 else
1728 faults = group_faults(p, node);
1729
1730 /*
1731 * On systems with a glueless mesh NUMA topology, there are
1732 * no fixed "groups of nodes". Instead, nodes that are not
1733 * directly connected bounce traffic through intermediate
1734 * nodes; a numa_group can occupy any set of nodes.
1735 * The further away a node is, the less the faults count.
1736 * This seems to result in good task placement.
1737 */
1738 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1739 faults *= (max_dist - dist);
1740 faults /= (max_dist - LOCAL_DISTANCE);
1741 }
1742
1743 score += faults;
1744 }
1745
1746 return score;
1747 }
1748
1749 /*
1750 * These return the fraction of accesses done by a particular task, or
1751 * task group, on a particular numa node. The group weight is given a
1752 * larger multiplier, in order to group tasks together that are almost
1753 * evenly spread out between numa nodes.
1754 */
task_weight(struct task_struct * p,int nid,int dist)1755 static inline unsigned long task_weight(struct task_struct *p, int nid,
1756 int dist)
1757 {
1758 unsigned long faults, total_faults;
1759
1760 if (!p->numa_faults)
1761 return 0;
1762
1763 total_faults = p->total_numa_faults;
1764
1765 if (!total_faults)
1766 return 0;
1767
1768 faults = task_faults(p, nid);
1769 faults += score_nearby_nodes(p, nid, dist, true);
1770
1771 return 1000 * faults / total_faults;
1772 }
1773
group_weight(struct task_struct * p,int nid,int dist)1774 static inline unsigned long group_weight(struct task_struct *p, int nid,
1775 int dist)
1776 {
1777 struct numa_group *ng = deref_task_numa_group(p);
1778 unsigned long faults, total_faults;
1779
1780 if (!ng)
1781 return 0;
1782
1783 total_faults = ng->total_faults;
1784
1785 if (!total_faults)
1786 return 0;
1787
1788 faults = group_faults(p, nid);
1789 faults += score_nearby_nodes(p, nid, dist, false);
1790
1791 return 1000 * faults / total_faults;
1792 }
1793
1794 /*
1795 * If memory tiering mode is enabled, cpupid of slow memory page is
1796 * used to record scan time instead of CPU and PID. When tiering mode
1797 * is disabled at run time, the scan time (in cpupid) will be
1798 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1799 * access out of array bound.
1800 */
cpupid_valid(int cpupid)1801 static inline bool cpupid_valid(int cpupid)
1802 {
1803 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1804 }
1805
1806 /*
1807 * For memory tiering mode, if there are enough free pages (more than
1808 * enough watermark defined here) in fast memory node, to take full
1809 * advantage of fast memory capacity, all recently accessed slow
1810 * memory pages will be migrated to fast memory node without
1811 * considering hot threshold.
1812 */
pgdat_free_space_enough(struct pglist_data * pgdat)1813 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1814 {
1815 int z;
1816 unsigned long enough_wmark;
1817
1818 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1819 pgdat->node_present_pages >> 4);
1820 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1821 struct zone *zone = pgdat->node_zones + z;
1822
1823 if (!populated_zone(zone))
1824 continue;
1825
1826 if (zone_watermark_ok(zone, 0,
1827 promo_wmark_pages(zone) + enough_wmark,
1828 ZONE_MOVABLE, 0))
1829 return true;
1830 }
1831 return false;
1832 }
1833
1834 /*
1835 * For memory tiering mode, when page tables are scanned, the scan
1836 * time will be recorded in struct page in addition to make page
1837 * PROT_NONE for slow memory page. So when the page is accessed, in
1838 * hint page fault handler, the hint page fault latency is calculated
1839 * via,
1840 *
1841 * hint page fault latency = hint page fault time - scan time
1842 *
1843 * The smaller the hint page fault latency, the higher the possibility
1844 * for the page to be hot.
1845 */
numa_hint_fault_latency(struct folio * folio)1846 static int numa_hint_fault_latency(struct folio *folio)
1847 {
1848 int last_time, time;
1849
1850 time = jiffies_to_msecs(jiffies);
1851 last_time = folio_xchg_access_time(folio, time);
1852
1853 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1854 }
1855
1856 /*
1857 * For memory tiering mode, too high promotion/demotion throughput may
1858 * hurt application latency. So we provide a mechanism to rate limit
1859 * the number of pages that are tried to be promoted.
1860 */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1861 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1862 unsigned long rate_limit, int nr)
1863 {
1864 unsigned long nr_cand;
1865 unsigned int now, start;
1866
1867 now = jiffies_to_msecs(jiffies);
1868 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1869 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1870 start = pgdat->nbp_rl_start;
1871 if (now - start > MSEC_PER_SEC &&
1872 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1873 pgdat->nbp_rl_nr_cand = nr_cand;
1874 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1875 return true;
1876 return false;
1877 }
1878
1879 #define NUMA_MIGRATION_ADJUST_STEPS 16
1880
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1881 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1882 unsigned long rate_limit,
1883 unsigned int ref_th)
1884 {
1885 unsigned int now, start, th_period, unit_th, th;
1886 unsigned long nr_cand, ref_cand, diff_cand;
1887
1888 now = jiffies_to_msecs(jiffies);
1889 th_period = sysctl_numa_balancing_scan_period_max;
1890 start = pgdat->nbp_th_start;
1891 if (now - start > th_period &&
1892 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1893 ref_cand = rate_limit *
1894 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1895 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1896 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1897 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1898 th = pgdat->nbp_threshold ? : ref_th;
1899 if (diff_cand > ref_cand * 11 / 10)
1900 th = max(th - unit_th, unit_th);
1901 else if (diff_cand < ref_cand * 9 / 10)
1902 th = min(th + unit_th, ref_th * 2);
1903 pgdat->nbp_th_nr_cand = nr_cand;
1904 pgdat->nbp_threshold = th;
1905 }
1906 }
1907
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)1908 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1909 int src_nid, int dst_cpu)
1910 {
1911 struct numa_group *ng = deref_curr_numa_group(p);
1912 int dst_nid = cpu_to_node(dst_cpu);
1913 int last_cpupid, this_cpupid;
1914
1915 /*
1916 * Cannot migrate to memoryless nodes.
1917 */
1918 if (!node_state(dst_nid, N_MEMORY))
1919 return false;
1920
1921 /*
1922 * The pages in slow memory node should be migrated according
1923 * to hot/cold instead of private/shared.
1924 */
1925 if (folio_use_access_time(folio)) {
1926 struct pglist_data *pgdat;
1927 unsigned long rate_limit;
1928 unsigned int latency, th, def_th;
1929
1930 pgdat = NODE_DATA(dst_nid);
1931 if (pgdat_free_space_enough(pgdat)) {
1932 /* workload changed, reset hot threshold */
1933 pgdat->nbp_threshold = 0;
1934 return true;
1935 }
1936
1937 def_th = sysctl_numa_balancing_hot_threshold;
1938 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1939 (20 - PAGE_SHIFT);
1940 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1941
1942 th = pgdat->nbp_threshold ? : def_th;
1943 latency = numa_hint_fault_latency(folio);
1944 if (latency >= th)
1945 return false;
1946
1947 return !numa_promotion_rate_limit(pgdat, rate_limit,
1948 folio_nr_pages(folio));
1949 }
1950
1951 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1952 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
1953
1954 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1955 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1956 return false;
1957
1958 /*
1959 * Allow first faults or private faults to migrate immediately early in
1960 * the lifetime of a task. The magic number 4 is based on waiting for
1961 * two full passes of the "multi-stage node selection" test that is
1962 * executed below.
1963 */
1964 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1965 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1966 return true;
1967
1968 /*
1969 * Multi-stage node selection is used in conjunction with a periodic
1970 * migration fault to build a temporal task<->page relation. By using
1971 * a two-stage filter we remove short/unlikely relations.
1972 *
1973 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1974 * a task's usage of a particular page (n_p) per total usage of this
1975 * page (n_t) (in a given time-span) to a probability.
1976 *
1977 * Our periodic faults will sample this probability and getting the
1978 * same result twice in a row, given these samples are fully
1979 * independent, is then given by P(n)^2, provided our sample period
1980 * is sufficiently short compared to the usage pattern.
1981 *
1982 * This quadric squishes small probabilities, making it less likely we
1983 * act on an unlikely task<->page relation.
1984 */
1985 if (!cpupid_pid_unset(last_cpupid) &&
1986 cpupid_to_nid(last_cpupid) != dst_nid)
1987 return false;
1988
1989 /* Always allow migrate on private faults */
1990 if (cpupid_match_pid(p, last_cpupid))
1991 return true;
1992
1993 /* A shared fault, but p->numa_group has not been set up yet. */
1994 if (!ng)
1995 return true;
1996
1997 /*
1998 * Destination node is much more heavily used than the source
1999 * node? Allow migration.
2000 */
2001 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
2002 ACTIVE_NODE_FRACTION)
2003 return true;
2004
2005 /*
2006 * Distribute memory according to CPU & memory use on each node,
2007 * with 3/4 hysteresis to avoid unnecessary memory migrations:
2008 *
2009 * faults_cpu(dst) 3 faults_cpu(src)
2010 * --------------- * - > ---------------
2011 * faults_mem(dst) 4 faults_mem(src)
2012 */
2013 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
2014 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
2015 }
2016
2017 /*
2018 * 'numa_type' describes the node at the moment of load balancing.
2019 */
2020 enum numa_type {
2021 /* The node has spare capacity that can be used to run more tasks. */
2022 node_has_spare = 0,
2023 /*
2024 * The node is fully used and the tasks don't compete for more CPU
2025 * cycles. Nevertheless, some tasks might wait before running.
2026 */
2027 node_fully_busy,
2028 /*
2029 * The node is overloaded and can't provide expected CPU cycles to all
2030 * tasks.
2031 */
2032 node_overloaded
2033 };
2034
2035 /* Cached statistics for all CPUs within a node */
2036 struct numa_stats {
2037 unsigned long load;
2038 unsigned long runnable;
2039 unsigned long util;
2040 /* Total compute capacity of CPUs on a node */
2041 unsigned long compute_capacity;
2042 unsigned int nr_running;
2043 unsigned int weight;
2044 enum numa_type node_type;
2045 int idle_cpu;
2046 };
2047
2048 struct task_numa_env {
2049 struct task_struct *p;
2050
2051 int src_cpu, src_nid;
2052 int dst_cpu, dst_nid;
2053 int imb_numa_nr;
2054
2055 struct numa_stats src_stats, dst_stats;
2056
2057 int imbalance_pct;
2058 int dist;
2059
2060 struct task_struct *best_task;
2061 long best_imp;
2062 int best_cpu;
2063 };
2064
2065 static unsigned long cpu_load(struct rq *rq);
2066 static unsigned long cpu_runnable(struct rq *rq);
2067
2068 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2069 numa_type numa_classify(unsigned int imbalance_pct,
2070 struct numa_stats *ns)
2071 {
2072 if ((ns->nr_running > ns->weight) &&
2073 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2074 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2075 return node_overloaded;
2076
2077 if ((ns->nr_running < ns->weight) ||
2078 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2079 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2080 return node_has_spare;
2081
2082 return node_fully_busy;
2083 }
2084
2085 #ifdef CONFIG_SCHED_SMT
2086 /* Forward declarations of select_idle_sibling helpers */
2087 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2088 static inline int numa_idle_core(int idle_core, int cpu)
2089 {
2090 if (!static_branch_likely(&sched_smt_present) ||
2091 idle_core >= 0 || !test_idle_cores(cpu))
2092 return idle_core;
2093
2094 /*
2095 * Prefer cores instead of packing HT siblings
2096 * and triggering future load balancing.
2097 */
2098 if (is_core_idle(cpu))
2099 idle_core = cpu;
2100
2101 return idle_core;
2102 }
2103 #else
numa_idle_core(int idle_core,int cpu)2104 static inline int numa_idle_core(int idle_core, int cpu)
2105 {
2106 return idle_core;
2107 }
2108 #endif
2109
2110 /*
2111 * Gather all necessary information to make NUMA balancing placement
2112 * decisions that are compatible with standard load balancer. This
2113 * borrows code and logic from update_sg_lb_stats but sharing a
2114 * common implementation is impractical.
2115 */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2116 static void update_numa_stats(struct task_numa_env *env,
2117 struct numa_stats *ns, int nid,
2118 bool find_idle)
2119 {
2120 int cpu, idle_core = -1;
2121
2122 memset(ns, 0, sizeof(*ns));
2123 ns->idle_cpu = -1;
2124
2125 rcu_read_lock();
2126 for_each_cpu(cpu, cpumask_of_node(nid)) {
2127 struct rq *rq = cpu_rq(cpu);
2128
2129 ns->load += cpu_load(rq);
2130 ns->runnable += cpu_runnable(rq);
2131 ns->util += cpu_util_cfs(cpu);
2132 ns->nr_running += rq->cfs.h_nr_runnable;
2133 ns->compute_capacity += capacity_of(cpu);
2134
2135 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2136 if (READ_ONCE(rq->numa_migrate_on) ||
2137 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2138 continue;
2139
2140 if (ns->idle_cpu == -1)
2141 ns->idle_cpu = cpu;
2142
2143 idle_core = numa_idle_core(idle_core, cpu);
2144 }
2145 }
2146 rcu_read_unlock();
2147
2148 ns->weight = cpumask_weight(cpumask_of_node(nid));
2149
2150 ns->node_type = numa_classify(env->imbalance_pct, ns);
2151
2152 if (idle_core >= 0)
2153 ns->idle_cpu = idle_core;
2154 }
2155
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2156 static void task_numa_assign(struct task_numa_env *env,
2157 struct task_struct *p, long imp)
2158 {
2159 struct rq *rq = cpu_rq(env->dst_cpu);
2160
2161 /* Check if run-queue part of active NUMA balance. */
2162 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2163 int cpu;
2164 int start = env->dst_cpu;
2165
2166 /* Find alternative idle CPU. */
2167 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2168 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2169 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2170 continue;
2171 }
2172
2173 env->dst_cpu = cpu;
2174 rq = cpu_rq(env->dst_cpu);
2175 if (!xchg(&rq->numa_migrate_on, 1))
2176 goto assign;
2177 }
2178
2179 /* Failed to find an alternative idle CPU */
2180 return;
2181 }
2182
2183 assign:
2184 /*
2185 * Clear previous best_cpu/rq numa-migrate flag, since task now
2186 * found a better CPU to move/swap.
2187 */
2188 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2189 rq = cpu_rq(env->best_cpu);
2190 WRITE_ONCE(rq->numa_migrate_on, 0);
2191 }
2192
2193 if (env->best_task)
2194 put_task_struct(env->best_task);
2195 if (p)
2196 get_task_struct(p);
2197
2198 env->best_task = p;
2199 env->best_imp = imp;
2200 env->best_cpu = env->dst_cpu;
2201 }
2202
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2203 static bool load_too_imbalanced(long src_load, long dst_load,
2204 struct task_numa_env *env)
2205 {
2206 long imb, old_imb;
2207 long orig_src_load, orig_dst_load;
2208 long src_capacity, dst_capacity;
2209
2210 /*
2211 * The load is corrected for the CPU capacity available on each node.
2212 *
2213 * src_load dst_load
2214 * ------------ vs ---------
2215 * src_capacity dst_capacity
2216 */
2217 src_capacity = env->src_stats.compute_capacity;
2218 dst_capacity = env->dst_stats.compute_capacity;
2219
2220 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2221
2222 orig_src_load = env->src_stats.load;
2223 orig_dst_load = env->dst_stats.load;
2224
2225 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2226
2227 /* Would this change make things worse? */
2228 return (imb > old_imb);
2229 }
2230
2231 /*
2232 * Maximum NUMA importance can be 1998 (2*999);
2233 * SMALLIMP @ 30 would be close to 1998/64.
2234 * Used to deter task migration.
2235 */
2236 #define SMALLIMP 30
2237
2238 /*
2239 * This checks if the overall compute and NUMA accesses of the system would
2240 * be improved if the source tasks was migrated to the target dst_cpu taking
2241 * into account that it might be best if task running on the dst_cpu should
2242 * be exchanged with the source task
2243 */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2244 static bool task_numa_compare(struct task_numa_env *env,
2245 long taskimp, long groupimp, bool maymove)
2246 {
2247 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2248 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2249 long imp = p_ng ? groupimp : taskimp;
2250 struct task_struct *cur;
2251 long src_load, dst_load;
2252 int dist = env->dist;
2253 long moveimp = imp;
2254 long load;
2255 bool stopsearch = false;
2256
2257 if (READ_ONCE(dst_rq->numa_migrate_on))
2258 return false;
2259
2260 rcu_read_lock();
2261 cur = rcu_dereference(dst_rq->curr);
2262 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2263 cur = NULL;
2264
2265 /*
2266 * Because we have preemption enabled we can get migrated around and
2267 * end try selecting ourselves (current == env->p) as a swap candidate.
2268 */
2269 if (cur == env->p) {
2270 stopsearch = true;
2271 goto unlock;
2272 }
2273
2274 if (!cur) {
2275 if (maymove && moveimp >= env->best_imp)
2276 goto assign;
2277 else
2278 goto unlock;
2279 }
2280
2281 /* Skip this swap candidate if cannot move to the source cpu. */
2282 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2283 goto unlock;
2284
2285 /*
2286 * Skip this swap candidate if it is not moving to its preferred
2287 * node and the best task is.
2288 */
2289 if (env->best_task &&
2290 env->best_task->numa_preferred_nid == env->src_nid &&
2291 cur->numa_preferred_nid != env->src_nid) {
2292 goto unlock;
2293 }
2294
2295 /*
2296 * "imp" is the fault differential for the source task between the
2297 * source and destination node. Calculate the total differential for
2298 * the source task and potential destination task. The more negative
2299 * the value is, the more remote accesses that would be expected to
2300 * be incurred if the tasks were swapped.
2301 *
2302 * If dst and source tasks are in the same NUMA group, or not
2303 * in any group then look only at task weights.
2304 */
2305 cur_ng = rcu_dereference(cur->numa_group);
2306 if (cur_ng == p_ng) {
2307 /*
2308 * Do not swap within a group or between tasks that have
2309 * no group if there is spare capacity. Swapping does
2310 * not address the load imbalance and helps one task at
2311 * the cost of punishing another.
2312 */
2313 if (env->dst_stats.node_type == node_has_spare)
2314 goto unlock;
2315
2316 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2317 task_weight(cur, env->dst_nid, dist);
2318 /*
2319 * Add some hysteresis to prevent swapping the
2320 * tasks within a group over tiny differences.
2321 */
2322 if (cur_ng)
2323 imp -= imp / 16;
2324 } else {
2325 /*
2326 * Compare the group weights. If a task is all by itself
2327 * (not part of a group), use the task weight instead.
2328 */
2329 if (cur_ng && p_ng)
2330 imp += group_weight(cur, env->src_nid, dist) -
2331 group_weight(cur, env->dst_nid, dist);
2332 else
2333 imp += task_weight(cur, env->src_nid, dist) -
2334 task_weight(cur, env->dst_nid, dist);
2335 }
2336
2337 /* Discourage picking a task already on its preferred node */
2338 if (cur->numa_preferred_nid == env->dst_nid)
2339 imp -= imp / 16;
2340
2341 /*
2342 * Encourage picking a task that moves to its preferred node.
2343 * This potentially makes imp larger than it's maximum of
2344 * 1998 (see SMALLIMP and task_weight for why) but in this
2345 * case, it does not matter.
2346 */
2347 if (cur->numa_preferred_nid == env->src_nid)
2348 imp += imp / 8;
2349
2350 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2351 imp = moveimp;
2352 cur = NULL;
2353 goto assign;
2354 }
2355
2356 /*
2357 * Prefer swapping with a task moving to its preferred node over a
2358 * task that is not.
2359 */
2360 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2361 env->best_task->numa_preferred_nid != env->src_nid) {
2362 goto assign;
2363 }
2364
2365 /*
2366 * If the NUMA importance is less than SMALLIMP,
2367 * task migration might only result in ping pong
2368 * of tasks and also hurt performance due to cache
2369 * misses.
2370 */
2371 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2372 goto unlock;
2373
2374 /*
2375 * In the overloaded case, try and keep the load balanced.
2376 */
2377 load = task_h_load(env->p) - task_h_load(cur);
2378 if (!load)
2379 goto assign;
2380
2381 dst_load = env->dst_stats.load + load;
2382 src_load = env->src_stats.load - load;
2383
2384 if (load_too_imbalanced(src_load, dst_load, env))
2385 goto unlock;
2386
2387 assign:
2388 /* Evaluate an idle CPU for a task numa move. */
2389 if (!cur) {
2390 int cpu = env->dst_stats.idle_cpu;
2391
2392 /* Nothing cached so current CPU went idle since the search. */
2393 if (cpu < 0)
2394 cpu = env->dst_cpu;
2395
2396 /*
2397 * If the CPU is no longer truly idle and the previous best CPU
2398 * is, keep using it.
2399 */
2400 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2401 idle_cpu(env->best_cpu)) {
2402 cpu = env->best_cpu;
2403 }
2404
2405 env->dst_cpu = cpu;
2406 }
2407
2408 task_numa_assign(env, cur, imp);
2409
2410 /*
2411 * If a move to idle is allowed because there is capacity or load
2412 * balance improves then stop the search. While a better swap
2413 * candidate may exist, a search is not free.
2414 */
2415 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2416 stopsearch = true;
2417
2418 /*
2419 * If a swap candidate must be identified and the current best task
2420 * moves its preferred node then stop the search.
2421 */
2422 if (!maymove && env->best_task &&
2423 env->best_task->numa_preferred_nid == env->src_nid) {
2424 stopsearch = true;
2425 }
2426 unlock:
2427 rcu_read_unlock();
2428
2429 return stopsearch;
2430 }
2431
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2432 static void task_numa_find_cpu(struct task_numa_env *env,
2433 long taskimp, long groupimp)
2434 {
2435 bool maymove = false;
2436 int cpu;
2437
2438 /*
2439 * If dst node has spare capacity, then check if there is an
2440 * imbalance that would be overruled by the load balancer.
2441 */
2442 if (env->dst_stats.node_type == node_has_spare) {
2443 unsigned int imbalance;
2444 int src_running, dst_running;
2445
2446 /*
2447 * Would movement cause an imbalance? Note that if src has
2448 * more running tasks that the imbalance is ignored as the
2449 * move improves the imbalance from the perspective of the
2450 * CPU load balancer.
2451 * */
2452 src_running = env->src_stats.nr_running - 1;
2453 dst_running = env->dst_stats.nr_running + 1;
2454 imbalance = max(0, dst_running - src_running);
2455 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2456 env->imb_numa_nr);
2457
2458 /* Use idle CPU if there is no imbalance */
2459 if (!imbalance) {
2460 maymove = true;
2461 if (env->dst_stats.idle_cpu >= 0) {
2462 env->dst_cpu = env->dst_stats.idle_cpu;
2463 task_numa_assign(env, NULL, 0);
2464 return;
2465 }
2466 }
2467 } else {
2468 long src_load, dst_load, load;
2469 /*
2470 * If the improvement from just moving env->p direction is better
2471 * than swapping tasks around, check if a move is possible.
2472 */
2473 load = task_h_load(env->p);
2474 dst_load = env->dst_stats.load + load;
2475 src_load = env->src_stats.load - load;
2476 maymove = !load_too_imbalanced(src_load, dst_load, env);
2477 }
2478
2479 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2480 /* Skip this CPU if the source task cannot migrate */
2481 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2482 continue;
2483
2484 env->dst_cpu = cpu;
2485 if (task_numa_compare(env, taskimp, groupimp, maymove))
2486 break;
2487 }
2488 }
2489
task_numa_migrate(struct task_struct * p)2490 static int task_numa_migrate(struct task_struct *p)
2491 {
2492 struct task_numa_env env = {
2493 .p = p,
2494
2495 .src_cpu = task_cpu(p),
2496 .src_nid = task_node(p),
2497
2498 .imbalance_pct = 112,
2499
2500 .best_task = NULL,
2501 .best_imp = 0,
2502 .best_cpu = -1,
2503 };
2504 unsigned long taskweight, groupweight;
2505 struct sched_domain *sd;
2506 long taskimp, groupimp;
2507 struct numa_group *ng;
2508 struct rq *best_rq;
2509 int nid, ret, dist;
2510
2511 /*
2512 * Pick the lowest SD_NUMA domain, as that would have the smallest
2513 * imbalance and would be the first to start moving tasks about.
2514 *
2515 * And we want to avoid any moving of tasks about, as that would create
2516 * random movement of tasks -- counter the numa conditions we're trying
2517 * to satisfy here.
2518 */
2519 rcu_read_lock();
2520 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2521 if (sd) {
2522 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2523 env.imb_numa_nr = sd->imb_numa_nr;
2524 }
2525 rcu_read_unlock();
2526
2527 /*
2528 * Cpusets can break the scheduler domain tree into smaller
2529 * balance domains, some of which do not cross NUMA boundaries.
2530 * Tasks that are "trapped" in such domains cannot be migrated
2531 * elsewhere, so there is no point in (re)trying.
2532 */
2533 if (unlikely(!sd)) {
2534 sched_setnuma(p, task_node(p));
2535 return -EINVAL;
2536 }
2537
2538 env.dst_nid = p->numa_preferred_nid;
2539 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2540 taskweight = task_weight(p, env.src_nid, dist);
2541 groupweight = group_weight(p, env.src_nid, dist);
2542 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2543 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2544 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2545 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2546
2547 /* Try to find a spot on the preferred nid. */
2548 task_numa_find_cpu(&env, taskimp, groupimp);
2549
2550 /*
2551 * Look at other nodes in these cases:
2552 * - there is no space available on the preferred_nid
2553 * - the task is part of a numa_group that is interleaved across
2554 * multiple NUMA nodes; in order to better consolidate the group,
2555 * we need to check other locations.
2556 */
2557 ng = deref_curr_numa_group(p);
2558 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2559 for_each_node_state(nid, N_CPU) {
2560 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2561 continue;
2562
2563 dist = node_distance(env.src_nid, env.dst_nid);
2564 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2565 dist != env.dist) {
2566 taskweight = task_weight(p, env.src_nid, dist);
2567 groupweight = group_weight(p, env.src_nid, dist);
2568 }
2569
2570 /* Only consider nodes where both task and groups benefit */
2571 taskimp = task_weight(p, nid, dist) - taskweight;
2572 groupimp = group_weight(p, nid, dist) - groupweight;
2573 if (taskimp < 0 && groupimp < 0)
2574 continue;
2575
2576 env.dist = dist;
2577 env.dst_nid = nid;
2578 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2579 task_numa_find_cpu(&env, taskimp, groupimp);
2580 }
2581 }
2582
2583 /*
2584 * If the task is part of a workload that spans multiple NUMA nodes,
2585 * and is migrating into one of the workload's active nodes, remember
2586 * this node as the task's preferred numa node, so the workload can
2587 * settle down.
2588 * A task that migrated to a second choice node will be better off
2589 * trying for a better one later. Do not set the preferred node here.
2590 */
2591 if (ng) {
2592 if (env.best_cpu == -1)
2593 nid = env.src_nid;
2594 else
2595 nid = cpu_to_node(env.best_cpu);
2596
2597 if (nid != p->numa_preferred_nid)
2598 sched_setnuma(p, nid);
2599 }
2600
2601 /* No better CPU than the current one was found. */
2602 if (env.best_cpu == -1) {
2603 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2604 return -EAGAIN;
2605 }
2606
2607 best_rq = cpu_rq(env.best_cpu);
2608 if (env.best_task == NULL) {
2609 ret = migrate_task_to(p, env.best_cpu);
2610 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2611 if (ret != 0)
2612 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2613 return ret;
2614 }
2615
2616 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2617 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2618
2619 if (ret != 0)
2620 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2621 put_task_struct(env.best_task);
2622 return ret;
2623 }
2624
2625 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2626 static void numa_migrate_preferred(struct task_struct *p)
2627 {
2628 unsigned long interval = HZ;
2629
2630 /* This task has no NUMA fault statistics yet */
2631 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2632 return;
2633
2634 /* Periodically retry migrating the task to the preferred node */
2635 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2636 p->numa_migrate_retry = jiffies + interval;
2637
2638 /* Success if task is already running on preferred CPU */
2639 if (task_node(p) == p->numa_preferred_nid)
2640 return;
2641
2642 /* Otherwise, try migrate to a CPU on the preferred node */
2643 task_numa_migrate(p);
2644 }
2645
2646 /*
2647 * Find out how many nodes the workload is actively running on. Do this by
2648 * tracking the nodes from which NUMA hinting faults are triggered. This can
2649 * be different from the set of nodes where the workload's memory is currently
2650 * located.
2651 */
numa_group_count_active_nodes(struct numa_group * numa_group)2652 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2653 {
2654 unsigned long faults, max_faults = 0;
2655 int nid, active_nodes = 0;
2656
2657 for_each_node_state(nid, N_CPU) {
2658 faults = group_faults_cpu(numa_group, nid);
2659 if (faults > max_faults)
2660 max_faults = faults;
2661 }
2662
2663 for_each_node_state(nid, N_CPU) {
2664 faults = group_faults_cpu(numa_group, nid);
2665 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2666 active_nodes++;
2667 }
2668
2669 numa_group->max_faults_cpu = max_faults;
2670 numa_group->active_nodes = active_nodes;
2671 }
2672
2673 /*
2674 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2675 * increments. The more local the fault statistics are, the higher the scan
2676 * period will be for the next scan window. If local/(local+remote) ratio is
2677 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2678 * the scan period will decrease. Aim for 70% local accesses.
2679 */
2680 #define NUMA_PERIOD_SLOTS 10
2681 #define NUMA_PERIOD_THRESHOLD 7
2682
2683 /*
2684 * Increase the scan period (slow down scanning) if the majority of
2685 * our memory is already on our local node, or if the majority of
2686 * the page accesses are shared with other processes.
2687 * Otherwise, decrease the scan period.
2688 */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2689 static void update_task_scan_period(struct task_struct *p,
2690 unsigned long shared, unsigned long private)
2691 {
2692 unsigned int period_slot;
2693 int lr_ratio, ps_ratio;
2694 int diff;
2695
2696 unsigned long remote = p->numa_faults_locality[0];
2697 unsigned long local = p->numa_faults_locality[1];
2698
2699 /*
2700 * If there were no record hinting faults then either the task is
2701 * completely idle or all activity is in areas that are not of interest
2702 * to automatic numa balancing. Related to that, if there were failed
2703 * migration then it implies we are migrating too quickly or the local
2704 * node is overloaded. In either case, scan slower
2705 */
2706 if (local + shared == 0 || p->numa_faults_locality[2]) {
2707 p->numa_scan_period = min(p->numa_scan_period_max,
2708 p->numa_scan_period << 1);
2709
2710 p->mm->numa_next_scan = jiffies +
2711 msecs_to_jiffies(p->numa_scan_period);
2712
2713 return;
2714 }
2715
2716 /*
2717 * Prepare to scale scan period relative to the current period.
2718 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2719 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2720 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2721 */
2722 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2723 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2724 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2725
2726 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2727 /*
2728 * Most memory accesses are local. There is no need to
2729 * do fast NUMA scanning, since memory is already local.
2730 */
2731 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2732 if (!slot)
2733 slot = 1;
2734 diff = slot * period_slot;
2735 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2736 /*
2737 * Most memory accesses are shared with other tasks.
2738 * There is no point in continuing fast NUMA scanning,
2739 * since other tasks may just move the memory elsewhere.
2740 */
2741 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2742 if (!slot)
2743 slot = 1;
2744 diff = slot * period_slot;
2745 } else {
2746 /*
2747 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2748 * yet they are not on the local NUMA node. Speed up
2749 * NUMA scanning to get the memory moved over.
2750 */
2751 int ratio = max(lr_ratio, ps_ratio);
2752 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2753 }
2754
2755 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2756 task_scan_min(p), task_scan_max(p));
2757 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2758 }
2759
2760 /*
2761 * Get the fraction of time the task has been running since the last
2762 * NUMA placement cycle. The scheduler keeps similar statistics, but
2763 * decays those on a 32ms period, which is orders of magnitude off
2764 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2765 * stats only if the task is so new there are no NUMA statistics yet.
2766 */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2767 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2768 {
2769 u64 runtime, delta, now;
2770 /* Use the start of this time slice to avoid calculations. */
2771 now = p->se.exec_start;
2772 runtime = p->se.sum_exec_runtime;
2773
2774 if (p->last_task_numa_placement) {
2775 delta = runtime - p->last_sum_exec_runtime;
2776 *period = now - p->last_task_numa_placement;
2777
2778 /* Avoid time going backwards, prevent potential divide error: */
2779 if (unlikely((s64)*period < 0))
2780 *period = 0;
2781 } else {
2782 delta = p->se.avg.load_sum;
2783 *period = LOAD_AVG_MAX;
2784 }
2785
2786 p->last_sum_exec_runtime = runtime;
2787 p->last_task_numa_placement = now;
2788
2789 return delta;
2790 }
2791
2792 /*
2793 * Determine the preferred nid for a task in a numa_group. This needs to
2794 * be done in a way that produces consistent results with group_weight,
2795 * otherwise workloads might not converge.
2796 */
preferred_group_nid(struct task_struct * p,int nid)2797 static int preferred_group_nid(struct task_struct *p, int nid)
2798 {
2799 nodemask_t nodes;
2800 int dist;
2801
2802 /* Direct connections between all NUMA nodes. */
2803 if (sched_numa_topology_type == NUMA_DIRECT)
2804 return nid;
2805
2806 /*
2807 * On a system with glueless mesh NUMA topology, group_weight
2808 * scores nodes according to the number of NUMA hinting faults on
2809 * both the node itself, and on nearby nodes.
2810 */
2811 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2812 unsigned long score, max_score = 0;
2813 int node, max_node = nid;
2814
2815 dist = sched_max_numa_distance;
2816
2817 for_each_node_state(node, N_CPU) {
2818 score = group_weight(p, node, dist);
2819 if (score > max_score) {
2820 max_score = score;
2821 max_node = node;
2822 }
2823 }
2824 return max_node;
2825 }
2826
2827 /*
2828 * Finding the preferred nid in a system with NUMA backplane
2829 * interconnect topology is more involved. The goal is to locate
2830 * tasks from numa_groups near each other in the system, and
2831 * untangle workloads from different sides of the system. This requires
2832 * searching down the hierarchy of node groups, recursively searching
2833 * inside the highest scoring group of nodes. The nodemask tricks
2834 * keep the complexity of the search down.
2835 */
2836 nodes = node_states[N_CPU];
2837 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2838 unsigned long max_faults = 0;
2839 nodemask_t max_group = NODE_MASK_NONE;
2840 int a, b;
2841
2842 /* Are there nodes at this distance from each other? */
2843 if (!find_numa_distance(dist))
2844 continue;
2845
2846 for_each_node_mask(a, nodes) {
2847 unsigned long faults = 0;
2848 nodemask_t this_group;
2849 nodes_clear(this_group);
2850
2851 /* Sum group's NUMA faults; includes a==b case. */
2852 for_each_node_mask(b, nodes) {
2853 if (node_distance(a, b) < dist) {
2854 faults += group_faults(p, b);
2855 node_set(b, this_group);
2856 node_clear(b, nodes);
2857 }
2858 }
2859
2860 /* Remember the top group. */
2861 if (faults > max_faults) {
2862 max_faults = faults;
2863 max_group = this_group;
2864 /*
2865 * subtle: at the smallest distance there is
2866 * just one node left in each "group", the
2867 * winner is the preferred nid.
2868 */
2869 nid = a;
2870 }
2871 }
2872 /* Next round, evaluate the nodes within max_group. */
2873 if (!max_faults)
2874 break;
2875 nodes = max_group;
2876 }
2877 return nid;
2878 }
2879
task_numa_placement(struct task_struct * p)2880 static void task_numa_placement(struct task_struct *p)
2881 {
2882 int seq, nid, max_nid = NUMA_NO_NODE;
2883 unsigned long max_faults = 0;
2884 unsigned long fault_types[2] = { 0, 0 };
2885 unsigned long total_faults;
2886 u64 runtime, period;
2887 spinlock_t *group_lock = NULL;
2888 struct numa_group *ng;
2889
2890 /*
2891 * The p->mm->numa_scan_seq field gets updated without
2892 * exclusive access. Use READ_ONCE() here to ensure
2893 * that the field is read in a single access:
2894 */
2895 seq = READ_ONCE(p->mm->numa_scan_seq);
2896 if (p->numa_scan_seq == seq)
2897 return;
2898 p->numa_scan_seq = seq;
2899 p->numa_scan_period_max = task_scan_max(p);
2900
2901 total_faults = p->numa_faults_locality[0] +
2902 p->numa_faults_locality[1];
2903 runtime = numa_get_avg_runtime(p, &period);
2904
2905 /* If the task is part of a group prevent parallel updates to group stats */
2906 ng = deref_curr_numa_group(p);
2907 if (ng) {
2908 group_lock = &ng->lock;
2909 spin_lock_irq(group_lock);
2910 }
2911
2912 /* Find the node with the highest number of faults */
2913 for_each_online_node(nid) {
2914 /* Keep track of the offsets in numa_faults array */
2915 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2916 unsigned long faults = 0, group_faults = 0;
2917 int priv;
2918
2919 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2920 long diff, f_diff, f_weight;
2921
2922 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2923 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2924 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2925 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2926
2927 /* Decay existing window, copy faults since last scan */
2928 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2929 fault_types[priv] += p->numa_faults[membuf_idx];
2930 p->numa_faults[membuf_idx] = 0;
2931
2932 /*
2933 * Normalize the faults_from, so all tasks in a group
2934 * count according to CPU use, instead of by the raw
2935 * number of faults. Tasks with little runtime have
2936 * little over-all impact on throughput, and thus their
2937 * faults are less important.
2938 */
2939 f_weight = div64_u64(runtime << 16, period + 1);
2940 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2941 (total_faults + 1);
2942 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2943 p->numa_faults[cpubuf_idx] = 0;
2944
2945 p->numa_faults[mem_idx] += diff;
2946 p->numa_faults[cpu_idx] += f_diff;
2947 faults += p->numa_faults[mem_idx];
2948 p->total_numa_faults += diff;
2949 if (ng) {
2950 /*
2951 * safe because we can only change our own group
2952 *
2953 * mem_idx represents the offset for a given
2954 * nid and priv in a specific region because it
2955 * is at the beginning of the numa_faults array.
2956 */
2957 ng->faults[mem_idx] += diff;
2958 ng->faults[cpu_idx] += f_diff;
2959 ng->total_faults += diff;
2960 group_faults += ng->faults[mem_idx];
2961 }
2962 }
2963
2964 if (!ng) {
2965 if (faults > max_faults) {
2966 max_faults = faults;
2967 max_nid = nid;
2968 }
2969 } else if (group_faults > max_faults) {
2970 max_faults = group_faults;
2971 max_nid = nid;
2972 }
2973 }
2974
2975 /* Cannot migrate task to CPU-less node */
2976 max_nid = numa_nearest_node(max_nid, N_CPU);
2977
2978 if (ng) {
2979 numa_group_count_active_nodes(ng);
2980 spin_unlock_irq(group_lock);
2981 max_nid = preferred_group_nid(p, max_nid);
2982 }
2983
2984 if (max_faults) {
2985 /* Set the new preferred node */
2986 if (max_nid != p->numa_preferred_nid)
2987 sched_setnuma(p, max_nid);
2988 }
2989
2990 update_task_scan_period(p, fault_types[0], fault_types[1]);
2991 }
2992
get_numa_group(struct numa_group * grp)2993 static inline int get_numa_group(struct numa_group *grp)
2994 {
2995 return refcount_inc_not_zero(&grp->refcount);
2996 }
2997
put_numa_group(struct numa_group * grp)2998 static inline void put_numa_group(struct numa_group *grp)
2999 {
3000 if (refcount_dec_and_test(&grp->refcount))
3001 kfree_rcu(grp, rcu);
3002 }
3003
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)3004 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
3005 int *priv)
3006 {
3007 struct numa_group *grp, *my_grp;
3008 struct task_struct *tsk;
3009 bool join = false;
3010 int cpu = cpupid_to_cpu(cpupid);
3011 int i;
3012
3013 if (unlikely(!deref_curr_numa_group(p))) {
3014 unsigned int size = sizeof(struct numa_group) +
3015 NR_NUMA_HINT_FAULT_STATS *
3016 nr_node_ids * sizeof(unsigned long);
3017
3018 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3019 if (!grp)
3020 return;
3021
3022 refcount_set(&grp->refcount, 1);
3023 grp->active_nodes = 1;
3024 grp->max_faults_cpu = 0;
3025 spin_lock_init(&grp->lock);
3026 grp->gid = p->pid;
3027
3028 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3029 grp->faults[i] = p->numa_faults[i];
3030
3031 grp->total_faults = p->total_numa_faults;
3032
3033 grp->nr_tasks++;
3034 rcu_assign_pointer(p->numa_group, grp);
3035 }
3036
3037 rcu_read_lock();
3038 tsk = READ_ONCE(cpu_rq(cpu)->curr);
3039
3040 if (!cpupid_match_pid(tsk, cpupid))
3041 goto no_join;
3042
3043 grp = rcu_dereference(tsk->numa_group);
3044 if (!grp)
3045 goto no_join;
3046
3047 my_grp = deref_curr_numa_group(p);
3048 if (grp == my_grp)
3049 goto no_join;
3050
3051 /*
3052 * Only join the other group if its bigger; if we're the bigger group,
3053 * the other task will join us.
3054 */
3055 if (my_grp->nr_tasks > grp->nr_tasks)
3056 goto no_join;
3057
3058 /*
3059 * Tie-break on the grp address.
3060 */
3061 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3062 goto no_join;
3063
3064 /* Always join threads in the same process. */
3065 if (tsk->mm == current->mm)
3066 join = true;
3067
3068 /* Simple filter to avoid false positives due to PID collisions */
3069 if (flags & TNF_SHARED)
3070 join = true;
3071
3072 /* Update priv based on whether false sharing was detected */
3073 *priv = !join;
3074
3075 if (join && !get_numa_group(grp))
3076 goto no_join;
3077
3078 rcu_read_unlock();
3079
3080 if (!join)
3081 return;
3082
3083 WARN_ON_ONCE(irqs_disabled());
3084 double_lock_irq(&my_grp->lock, &grp->lock);
3085
3086 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3087 my_grp->faults[i] -= p->numa_faults[i];
3088 grp->faults[i] += p->numa_faults[i];
3089 }
3090 my_grp->total_faults -= p->total_numa_faults;
3091 grp->total_faults += p->total_numa_faults;
3092
3093 my_grp->nr_tasks--;
3094 grp->nr_tasks++;
3095
3096 spin_unlock(&my_grp->lock);
3097 spin_unlock_irq(&grp->lock);
3098
3099 rcu_assign_pointer(p->numa_group, grp);
3100
3101 put_numa_group(my_grp);
3102 return;
3103
3104 no_join:
3105 rcu_read_unlock();
3106 return;
3107 }
3108
3109 /*
3110 * Get rid of NUMA statistics associated with a task (either current or dead).
3111 * If @final is set, the task is dead and has reached refcount zero, so we can
3112 * safely free all relevant data structures. Otherwise, there might be
3113 * concurrent reads from places like load balancing and procfs, and we should
3114 * reset the data back to default state without freeing ->numa_faults.
3115 */
task_numa_free(struct task_struct * p,bool final)3116 void task_numa_free(struct task_struct *p, bool final)
3117 {
3118 /* safe: p either is current or is being freed by current */
3119 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3120 unsigned long *numa_faults = p->numa_faults;
3121 unsigned long flags;
3122 int i;
3123
3124 if (!numa_faults)
3125 return;
3126
3127 if (grp) {
3128 spin_lock_irqsave(&grp->lock, flags);
3129 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3130 grp->faults[i] -= p->numa_faults[i];
3131 grp->total_faults -= p->total_numa_faults;
3132
3133 grp->nr_tasks--;
3134 spin_unlock_irqrestore(&grp->lock, flags);
3135 RCU_INIT_POINTER(p->numa_group, NULL);
3136 put_numa_group(grp);
3137 }
3138
3139 if (final) {
3140 p->numa_faults = NULL;
3141 kfree(numa_faults);
3142 } else {
3143 p->total_numa_faults = 0;
3144 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3145 numa_faults[i] = 0;
3146 }
3147 }
3148
3149 /*
3150 * Got a PROT_NONE fault for a page on @node.
3151 */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3152 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3153 {
3154 struct task_struct *p = current;
3155 bool migrated = flags & TNF_MIGRATED;
3156 int cpu_node = task_node(current);
3157 int local = !!(flags & TNF_FAULT_LOCAL);
3158 struct numa_group *ng;
3159 int priv;
3160
3161 if (!static_branch_likely(&sched_numa_balancing))
3162 return;
3163
3164 /* for example, ksmd faulting in a user's mm */
3165 if (!p->mm)
3166 return;
3167
3168 /*
3169 * NUMA faults statistics are unnecessary for the slow memory
3170 * node for memory tiering mode.
3171 */
3172 if (!node_is_toptier(mem_node) &&
3173 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3174 !cpupid_valid(last_cpupid)))
3175 return;
3176
3177 /* Allocate buffer to track faults on a per-node basis */
3178 if (unlikely(!p->numa_faults)) {
3179 int size = sizeof(*p->numa_faults) *
3180 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3181
3182 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3183 if (!p->numa_faults)
3184 return;
3185
3186 p->total_numa_faults = 0;
3187 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3188 }
3189
3190 /*
3191 * First accesses are treated as private, otherwise consider accesses
3192 * to be private if the accessing pid has not changed
3193 */
3194 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3195 priv = 1;
3196 } else {
3197 priv = cpupid_match_pid(p, last_cpupid);
3198 if (!priv && !(flags & TNF_NO_GROUP))
3199 task_numa_group(p, last_cpupid, flags, &priv);
3200 }
3201
3202 /*
3203 * If a workload spans multiple NUMA nodes, a shared fault that
3204 * occurs wholly within the set of nodes that the workload is
3205 * actively using should be counted as local. This allows the
3206 * scan rate to slow down when a workload has settled down.
3207 */
3208 ng = deref_curr_numa_group(p);
3209 if (!priv && !local && ng && ng->active_nodes > 1 &&
3210 numa_is_active_node(cpu_node, ng) &&
3211 numa_is_active_node(mem_node, ng))
3212 local = 1;
3213
3214 /*
3215 * Retry to migrate task to preferred node periodically, in case it
3216 * previously failed, or the scheduler moved us.
3217 */
3218 if (time_after(jiffies, p->numa_migrate_retry)) {
3219 task_numa_placement(p);
3220 numa_migrate_preferred(p);
3221 }
3222
3223 if (migrated)
3224 p->numa_pages_migrated += pages;
3225 if (flags & TNF_MIGRATE_FAIL)
3226 p->numa_faults_locality[2] += pages;
3227
3228 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3229 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3230 p->numa_faults_locality[local] += pages;
3231 }
3232
reset_ptenuma_scan(struct task_struct * p)3233 static void reset_ptenuma_scan(struct task_struct *p)
3234 {
3235 /*
3236 * We only did a read acquisition of the mmap sem, so
3237 * p->mm->numa_scan_seq is written to without exclusive access
3238 * and the update is not guaranteed to be atomic. That's not
3239 * much of an issue though, since this is just used for
3240 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3241 * expensive, to avoid any form of compiler optimizations:
3242 */
3243 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3244 p->mm->numa_scan_offset = 0;
3245 }
3246
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3247 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3248 {
3249 unsigned long pids;
3250 /*
3251 * Allow unconditional access first two times, so that all the (pages)
3252 * of VMAs get prot_none fault introduced irrespective of accesses.
3253 * This is also done to avoid any side effect of task scanning
3254 * amplifying the unfairness of disjoint set of VMAs' access.
3255 */
3256 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3257 return true;
3258
3259 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3260 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3261 return true;
3262
3263 /*
3264 * Complete a scan that has already started regardless of PID access, or
3265 * some VMAs may never be scanned in multi-threaded applications:
3266 */
3267 if (mm->numa_scan_offset > vma->vm_start) {
3268 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3269 return true;
3270 }
3271
3272 /*
3273 * This vma has not been accessed for a while, and if the number
3274 * the threads in the same process is low, which means no other
3275 * threads can help scan this vma, force a vma scan.
3276 */
3277 if (READ_ONCE(mm->numa_scan_seq) >
3278 (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3279 return true;
3280
3281 return false;
3282 }
3283
3284 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3285
3286 /*
3287 * The expensive part of numa migration is done from task_work context.
3288 * Triggered from task_tick_numa().
3289 */
task_numa_work(struct callback_head * work)3290 static void task_numa_work(struct callback_head *work)
3291 {
3292 unsigned long migrate, next_scan, now = jiffies;
3293 struct task_struct *p = current;
3294 struct mm_struct *mm = p->mm;
3295 u64 runtime = p->se.sum_exec_runtime;
3296 struct vm_area_struct *vma;
3297 unsigned long start, end;
3298 unsigned long nr_pte_updates = 0;
3299 long pages, virtpages;
3300 struct vma_iterator vmi;
3301 bool vma_pids_skipped;
3302 bool vma_pids_forced = false;
3303
3304 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3305
3306 work->next = work;
3307 /*
3308 * Who cares about NUMA placement when they're dying.
3309 *
3310 * NOTE: make sure not to dereference p->mm before this check,
3311 * exit_task_work() happens _after_ exit_mm() so we could be called
3312 * without p->mm even though we still had it when we enqueued this
3313 * work.
3314 */
3315 if (p->flags & PF_EXITING)
3316 return;
3317
3318 if (!mm->numa_next_scan) {
3319 mm->numa_next_scan = now +
3320 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3321 }
3322
3323 /*
3324 * Enforce maximal scan/migration frequency..
3325 */
3326 migrate = mm->numa_next_scan;
3327 if (time_before(now, migrate))
3328 return;
3329
3330 if (p->numa_scan_period == 0) {
3331 p->numa_scan_period_max = task_scan_max(p);
3332 p->numa_scan_period = task_scan_start(p);
3333 }
3334
3335 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3336 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3337 return;
3338
3339 /*
3340 * Delay this task enough that another task of this mm will likely win
3341 * the next time around.
3342 */
3343 p->node_stamp += 2 * TICK_NSEC;
3344
3345 pages = sysctl_numa_balancing_scan_size;
3346 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3347 virtpages = pages * 8; /* Scan up to this much virtual space */
3348 if (!pages)
3349 return;
3350
3351
3352 if (!mmap_read_trylock(mm))
3353 return;
3354
3355 /*
3356 * VMAs are skipped if the current PID has not trapped a fault within
3357 * the VMA recently. Allow scanning to be forced if there is no
3358 * suitable VMA remaining.
3359 */
3360 vma_pids_skipped = false;
3361
3362 retry_pids:
3363 start = mm->numa_scan_offset;
3364 vma_iter_init(&vmi, mm, start);
3365 vma = vma_next(&vmi);
3366 if (!vma) {
3367 reset_ptenuma_scan(p);
3368 start = 0;
3369 vma_iter_set(&vmi, start);
3370 vma = vma_next(&vmi);
3371 }
3372
3373 for (; vma; vma = vma_next(&vmi)) {
3374 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3375 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3376 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3377 continue;
3378 }
3379
3380 /*
3381 * Shared library pages mapped by multiple processes are not
3382 * migrated as it is expected they are cache replicated. Avoid
3383 * hinting faults in read-only file-backed mappings or the vDSO
3384 * as migrating the pages will be of marginal benefit.
3385 */
3386 if (!vma->vm_mm ||
3387 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3388 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3389 continue;
3390 }
3391
3392 /*
3393 * Skip inaccessible VMAs to avoid any confusion between
3394 * PROT_NONE and NUMA hinting PTEs
3395 */
3396 if (!vma_is_accessible(vma)) {
3397 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3398 continue;
3399 }
3400
3401 /* Initialise new per-VMA NUMAB state. */
3402 if (!vma->numab_state) {
3403 struct vma_numab_state *ptr;
3404
3405 ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3406 if (!ptr)
3407 continue;
3408
3409 if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3410 kfree(ptr);
3411 continue;
3412 }
3413
3414 vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3415
3416 vma->numab_state->next_scan = now +
3417 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3418
3419 /* Reset happens after 4 times scan delay of scan start */
3420 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
3421 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3422
3423 /*
3424 * Ensure prev_scan_seq does not match numa_scan_seq,
3425 * to prevent VMAs being skipped prematurely on the
3426 * first scan:
3427 */
3428 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3429 }
3430
3431 /*
3432 * Scanning the VMAs of short lived tasks add more overhead. So
3433 * delay the scan for new VMAs.
3434 */
3435 if (mm->numa_scan_seq && time_before(jiffies,
3436 vma->numab_state->next_scan)) {
3437 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3438 continue;
3439 }
3440
3441 /* RESET access PIDs regularly for old VMAs. */
3442 if (mm->numa_scan_seq &&
3443 time_after(jiffies, vma->numab_state->pids_active_reset)) {
3444 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3445 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3446 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3447 vma->numab_state->pids_active[1] = 0;
3448 }
3449
3450 /* Do not rescan VMAs twice within the same sequence. */
3451 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3452 mm->numa_scan_offset = vma->vm_end;
3453 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3454 continue;
3455 }
3456
3457 /*
3458 * Do not scan the VMA if task has not accessed it, unless no other
3459 * VMA candidate exists.
3460 */
3461 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3462 vma_pids_skipped = true;
3463 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3464 continue;
3465 }
3466
3467 do {
3468 start = max(start, vma->vm_start);
3469 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3470 end = min(end, vma->vm_end);
3471 nr_pte_updates = change_prot_numa(vma, start, end);
3472
3473 /*
3474 * Try to scan sysctl_numa_balancing_size worth of
3475 * hpages that have at least one present PTE that
3476 * is not already PTE-numa. If the VMA contains
3477 * areas that are unused or already full of prot_numa
3478 * PTEs, scan up to virtpages, to skip through those
3479 * areas faster.
3480 */
3481 if (nr_pte_updates)
3482 pages -= (end - start) >> PAGE_SHIFT;
3483 virtpages -= (end - start) >> PAGE_SHIFT;
3484
3485 start = end;
3486 if (pages <= 0 || virtpages <= 0)
3487 goto out;
3488
3489 cond_resched();
3490 } while (end != vma->vm_end);
3491
3492 /* VMA scan is complete, do not scan until next sequence. */
3493 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3494
3495 /*
3496 * Only force scan within one VMA at a time, to limit the
3497 * cost of scanning a potentially uninteresting VMA.
3498 */
3499 if (vma_pids_forced)
3500 break;
3501 }
3502
3503 /*
3504 * If no VMAs are remaining and VMAs were skipped due to the PID
3505 * not accessing the VMA previously, then force a scan to ensure
3506 * forward progress:
3507 */
3508 if (!vma && !vma_pids_forced && vma_pids_skipped) {
3509 vma_pids_forced = true;
3510 goto retry_pids;
3511 }
3512
3513 out:
3514 /*
3515 * It is possible to reach the end of the VMA list but the last few
3516 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3517 * would find the !migratable VMA on the next scan but not reset the
3518 * scanner to the start so check it now.
3519 */
3520 if (vma)
3521 mm->numa_scan_offset = start;
3522 else
3523 reset_ptenuma_scan(p);
3524 mmap_read_unlock(mm);
3525
3526 /*
3527 * Make sure tasks use at least 32x as much time to run other code
3528 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3529 * Usually update_task_scan_period slows down scanning enough; on an
3530 * overloaded system we need to limit overhead on a per task basis.
3531 */
3532 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3533 u64 diff = p->se.sum_exec_runtime - runtime;
3534 p->node_stamp += 32 * diff;
3535 }
3536 }
3537
init_numa_balancing(unsigned long clone_flags,struct task_struct * p)3538 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3539 {
3540 int mm_users = 0;
3541 struct mm_struct *mm = p->mm;
3542
3543 if (mm) {
3544 mm_users = atomic_read(&mm->mm_users);
3545 if (mm_users == 1) {
3546 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3547 mm->numa_scan_seq = 0;
3548 }
3549 }
3550 p->node_stamp = 0;
3551 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3552 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3553 p->numa_migrate_retry = 0;
3554 /* Protect against double add, see task_tick_numa and task_numa_work */
3555 p->numa_work.next = &p->numa_work;
3556 p->numa_faults = NULL;
3557 p->numa_pages_migrated = 0;
3558 p->total_numa_faults = 0;
3559 RCU_INIT_POINTER(p->numa_group, NULL);
3560 p->last_task_numa_placement = 0;
3561 p->last_sum_exec_runtime = 0;
3562
3563 init_task_work(&p->numa_work, task_numa_work);
3564
3565 /* New address space, reset the preferred nid */
3566 if (!(clone_flags & CLONE_VM)) {
3567 p->numa_preferred_nid = NUMA_NO_NODE;
3568 return;
3569 }
3570
3571 /*
3572 * New thread, keep existing numa_preferred_nid which should be copied
3573 * already by arch_dup_task_struct but stagger when scans start.
3574 */
3575 if (mm) {
3576 unsigned int delay;
3577
3578 delay = min_t(unsigned int, task_scan_max(current),
3579 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3580 delay += 2 * TICK_NSEC;
3581 p->node_stamp = delay;
3582 }
3583 }
3584
3585 /*
3586 * Drive the periodic memory faults..
3587 */
task_tick_numa(struct rq * rq,struct task_struct * curr)3588 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3589 {
3590 struct callback_head *work = &curr->numa_work;
3591 u64 period, now;
3592
3593 /*
3594 * We don't care about NUMA placement if we don't have memory.
3595 */
3596 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3597 return;
3598
3599 /*
3600 * Using runtime rather than walltime has the dual advantage that
3601 * we (mostly) drive the selection from busy threads and that the
3602 * task needs to have done some actual work before we bother with
3603 * NUMA placement.
3604 */
3605 now = curr->se.sum_exec_runtime;
3606 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3607
3608 if (now > curr->node_stamp + period) {
3609 if (!curr->node_stamp)
3610 curr->numa_scan_period = task_scan_start(curr);
3611 curr->node_stamp += period;
3612
3613 if (!time_before(jiffies, curr->mm->numa_next_scan))
3614 task_work_add(curr, work, TWA_RESUME);
3615 }
3616 }
3617
update_scan_period(struct task_struct * p,int new_cpu)3618 static void update_scan_period(struct task_struct *p, int new_cpu)
3619 {
3620 int src_nid = cpu_to_node(task_cpu(p));
3621 int dst_nid = cpu_to_node(new_cpu);
3622
3623 if (!static_branch_likely(&sched_numa_balancing))
3624 return;
3625
3626 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3627 return;
3628
3629 if (src_nid == dst_nid)
3630 return;
3631
3632 /*
3633 * Allow resets if faults have been trapped before one scan
3634 * has completed. This is most likely due to a new task that
3635 * is pulled cross-node due to wakeups or load balancing.
3636 */
3637 if (p->numa_scan_seq) {
3638 /*
3639 * Avoid scan adjustments if moving to the preferred
3640 * node or if the task was not previously running on
3641 * the preferred node.
3642 */
3643 if (dst_nid == p->numa_preferred_nid ||
3644 (p->numa_preferred_nid != NUMA_NO_NODE &&
3645 src_nid != p->numa_preferred_nid))
3646 return;
3647 }
3648
3649 p->numa_scan_period = task_scan_start(p);
3650 }
3651
3652 #else
task_tick_numa(struct rq * rq,struct task_struct * curr)3653 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3654 {
3655 }
3656
account_numa_enqueue(struct rq * rq,struct task_struct * p)3657 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3658 {
3659 }
3660
account_numa_dequeue(struct rq * rq,struct task_struct * p)3661 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3662 {
3663 }
3664
update_scan_period(struct task_struct * p,int new_cpu)3665 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3666 {
3667 }
3668
3669 #endif /* CONFIG_NUMA_BALANCING */
3670
3671 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3672 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3673 {
3674 update_load_add(&cfs_rq->load, se->load.weight);
3675 #ifdef CONFIG_SMP
3676 if (entity_is_task(se)) {
3677 struct rq *rq = rq_of(cfs_rq);
3678
3679 account_numa_enqueue(rq, task_of(se));
3680 list_add(&se->group_node, &rq->cfs_tasks);
3681 }
3682 #endif
3683 cfs_rq->nr_queued++;
3684 }
3685
3686 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3687 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3688 {
3689 update_load_sub(&cfs_rq->load, se->load.weight);
3690 #ifdef CONFIG_SMP
3691 if (entity_is_task(se)) {
3692 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3693 list_del_init(&se->group_node);
3694 }
3695 #endif
3696 cfs_rq->nr_queued--;
3697 }
3698
3699 /*
3700 * Signed add and clamp on underflow.
3701 *
3702 * Explicitly do a load-store to ensure the intermediate value never hits
3703 * memory. This allows lockless observations without ever seeing the negative
3704 * values.
3705 */
3706 #define add_positive(_ptr, _val) do { \
3707 typeof(_ptr) ptr = (_ptr); \
3708 typeof(_val) val = (_val); \
3709 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3710 \
3711 res = var + val; \
3712 \
3713 if (val < 0 && res > var) \
3714 res = 0; \
3715 \
3716 WRITE_ONCE(*ptr, res); \
3717 } while (0)
3718
3719 /*
3720 * Unsigned subtract and clamp on underflow.
3721 *
3722 * Explicitly do a load-store to ensure the intermediate value never hits
3723 * memory. This allows lockless observations without ever seeing the negative
3724 * values.
3725 */
3726 #define sub_positive(_ptr, _val) do { \
3727 typeof(_ptr) ptr = (_ptr); \
3728 typeof(*ptr) val = (_val); \
3729 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3730 res = var - val; \
3731 if (res > var) \
3732 res = 0; \
3733 WRITE_ONCE(*ptr, res); \
3734 } while (0)
3735
3736 /*
3737 * Remove and clamp on negative, from a local variable.
3738 *
3739 * A variant of sub_positive(), which does not use explicit load-store
3740 * and is thus optimized for local variable updates.
3741 */
3742 #define lsub_positive(_ptr, _val) do { \
3743 typeof(_ptr) ptr = (_ptr); \
3744 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3745 } while (0)
3746
3747 #ifdef CONFIG_SMP
3748 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3749 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3750 {
3751 cfs_rq->avg.load_avg += se->avg.load_avg;
3752 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3753 }
3754
3755 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3756 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3757 {
3758 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3759 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3760 /* See update_cfs_rq_load_avg() */
3761 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3762 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3763 }
3764 #else
3765 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3766 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3767 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3768 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3769 #endif
3770
3771 static void place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags);
3772
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3773 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3774 unsigned long weight)
3775 {
3776 bool curr = cfs_rq->curr == se;
3777
3778 if (se->on_rq) {
3779 /* commit outstanding execution time */
3780 update_curr(cfs_rq);
3781 update_entity_lag(cfs_rq, se);
3782 se->deadline -= se->vruntime;
3783 se->rel_deadline = 1;
3784 if (!curr)
3785 __dequeue_entity(cfs_rq, se);
3786 update_load_sub(&cfs_rq->load, se->load.weight);
3787 }
3788 dequeue_load_avg(cfs_rq, se);
3789
3790 /*
3791 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3792 * we need to scale se->vlag when w_i changes.
3793 */
3794 se->vlag = div_s64(se->vlag * se->load.weight, weight);
3795 if (se->rel_deadline)
3796 se->deadline = div_s64(se->deadline * se->load.weight, weight);
3797
3798 update_load_set(&se->load, weight);
3799
3800 #ifdef CONFIG_SMP
3801 do {
3802 u32 divider = get_pelt_divider(&se->avg);
3803
3804 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3805 } while (0);
3806 #endif
3807
3808 enqueue_load_avg(cfs_rq, se);
3809 if (se->on_rq) {
3810 update_load_add(&cfs_rq->load, se->load.weight);
3811 place_entity(cfs_rq, se, 0);
3812 if (!curr)
3813 __enqueue_entity(cfs_rq, se);
3814
3815 /*
3816 * The entity's vruntime has been adjusted, so let's check
3817 * whether the rq-wide min_vruntime needs updated too. Since
3818 * the calculations above require stable min_vruntime rather
3819 * than up-to-date one, we do the update at the end of the
3820 * reweight process.
3821 */
3822 update_min_vruntime(cfs_rq);
3823 }
3824 }
3825
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)3826 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
3827 const struct load_weight *lw)
3828 {
3829 struct sched_entity *se = &p->se;
3830 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3831 struct load_weight *load = &se->load;
3832
3833 reweight_entity(cfs_rq, se, lw->weight);
3834 load->inv_weight = lw->inv_weight;
3835 }
3836
3837 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3838
3839 #ifdef CONFIG_FAIR_GROUP_SCHED
3840 #ifdef CONFIG_SMP
3841 /*
3842 * All this does is approximate the hierarchical proportion which includes that
3843 * global sum we all love to hate.
3844 *
3845 * That is, the weight of a group entity, is the proportional share of the
3846 * group weight based on the group runqueue weights. That is:
3847 *
3848 * tg->weight * grq->load.weight
3849 * ge->load.weight = ----------------------------- (1)
3850 * \Sum grq->load.weight
3851 *
3852 * Now, because computing that sum is prohibitively expensive to compute (been
3853 * there, done that) we approximate it with this average stuff. The average
3854 * moves slower and therefore the approximation is cheaper and more stable.
3855 *
3856 * So instead of the above, we substitute:
3857 *
3858 * grq->load.weight -> grq->avg.load_avg (2)
3859 *
3860 * which yields the following:
3861 *
3862 * tg->weight * grq->avg.load_avg
3863 * ge->load.weight = ------------------------------ (3)
3864 * tg->load_avg
3865 *
3866 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3867 *
3868 * That is shares_avg, and it is right (given the approximation (2)).
3869 *
3870 * The problem with it is that because the average is slow -- it was designed
3871 * to be exactly that of course -- this leads to transients in boundary
3872 * conditions. In specific, the case where the group was idle and we start the
3873 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3874 * yielding bad latency etc..
3875 *
3876 * Now, in that special case (1) reduces to:
3877 *
3878 * tg->weight * grq->load.weight
3879 * ge->load.weight = ----------------------------- = tg->weight (4)
3880 * grp->load.weight
3881 *
3882 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3883 *
3884 * So what we do is modify our approximation (3) to approach (4) in the (near)
3885 * UP case, like:
3886 *
3887 * ge->load.weight =
3888 *
3889 * tg->weight * grq->load.weight
3890 * --------------------------------------------------- (5)
3891 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3892 *
3893 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3894 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3895 *
3896 *
3897 * tg->weight * grq->load.weight
3898 * ge->load.weight = ----------------------------- (6)
3899 * tg_load_avg'
3900 *
3901 * Where:
3902 *
3903 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3904 * max(grq->load.weight, grq->avg.load_avg)
3905 *
3906 * And that is shares_weight and is icky. In the (near) UP case it approaches
3907 * (4) while in the normal case it approaches (3). It consistently
3908 * overestimates the ge->load.weight and therefore:
3909 *
3910 * \Sum ge->load.weight >= tg->weight
3911 *
3912 * hence icky!
3913 */
calc_group_shares(struct cfs_rq * cfs_rq)3914 static long calc_group_shares(struct cfs_rq *cfs_rq)
3915 {
3916 long tg_weight, tg_shares, load, shares;
3917 struct task_group *tg = cfs_rq->tg;
3918
3919 tg_shares = READ_ONCE(tg->shares);
3920
3921 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3922
3923 tg_weight = atomic_long_read(&tg->load_avg);
3924
3925 /* Ensure tg_weight >= load */
3926 tg_weight -= cfs_rq->tg_load_avg_contrib;
3927 tg_weight += load;
3928
3929 shares = (tg_shares * load);
3930 if (tg_weight)
3931 shares /= tg_weight;
3932
3933 /*
3934 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3935 * of a group with small tg->shares value. It is a floor value which is
3936 * assigned as a minimum load.weight to the sched_entity representing
3937 * the group on a CPU.
3938 *
3939 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3940 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3941 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3942 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3943 * instead of 0.
3944 */
3945 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3946 }
3947 #endif /* CONFIG_SMP */
3948
3949 /*
3950 * Recomputes the group entity based on the current state of its group
3951 * runqueue.
3952 */
update_cfs_group(struct sched_entity * se)3953 static void update_cfs_group(struct sched_entity *se)
3954 {
3955 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3956 long shares;
3957
3958 /*
3959 * When a group becomes empty, preserve its weight. This matters for
3960 * DELAY_DEQUEUE.
3961 */
3962 if (!gcfs_rq || !gcfs_rq->load.weight)
3963 return;
3964
3965 if (throttled_hierarchy(gcfs_rq))
3966 return;
3967
3968 #ifndef CONFIG_SMP
3969 shares = READ_ONCE(gcfs_rq->tg->shares);
3970 #else
3971 shares = calc_group_shares(gcfs_rq);
3972 #endif
3973 if (unlikely(se->load.weight != shares))
3974 reweight_entity(cfs_rq_of(se), se, shares);
3975 }
3976
3977 #else /* CONFIG_FAIR_GROUP_SCHED */
update_cfs_group(struct sched_entity * se)3978 static inline void update_cfs_group(struct sched_entity *se)
3979 {
3980 }
3981 #endif /* CONFIG_FAIR_GROUP_SCHED */
3982
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)3983 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3984 {
3985 struct rq *rq = rq_of(cfs_rq);
3986
3987 if (&rq->cfs == cfs_rq) {
3988 /*
3989 * There are a few boundary cases this might miss but it should
3990 * get called often enough that that should (hopefully) not be
3991 * a real problem.
3992 *
3993 * It will not get called when we go idle, because the idle
3994 * thread is a different class (!fair), nor will the utilization
3995 * number include things like RT tasks.
3996 *
3997 * As is, the util number is not freq-invariant (we'd have to
3998 * implement arch_scale_freq_capacity() for that).
3999 *
4000 * See cpu_util_cfs().
4001 */
4002 cpufreq_update_util(rq, flags);
4003 }
4004 }
4005
4006 #ifdef CONFIG_SMP
load_avg_is_decayed(struct sched_avg * sa)4007 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4008 {
4009 if (sa->load_sum)
4010 return false;
4011
4012 if (sa->util_sum)
4013 return false;
4014
4015 if (sa->runnable_sum)
4016 return false;
4017
4018 /*
4019 * _avg must be null when _sum are null because _avg = _sum / divider
4020 * Make sure that rounding and/or propagation of PELT values never
4021 * break this.
4022 */
4023 SCHED_WARN_ON(sa->load_avg ||
4024 sa->util_avg ||
4025 sa->runnable_avg);
4026
4027 return true;
4028 }
4029
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)4030 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4031 {
4032 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4033 cfs_rq->last_update_time_copy);
4034 }
4035 #ifdef CONFIG_FAIR_GROUP_SCHED
4036 /*
4037 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4038 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4039 * bottom-up, we only have to test whether the cfs_rq before us on the list
4040 * is our child.
4041 * If cfs_rq is not on the list, test whether a child needs its to be added to
4042 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
4043 */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4044 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4045 {
4046 struct cfs_rq *prev_cfs_rq;
4047 struct list_head *prev;
4048 struct rq *rq = rq_of(cfs_rq);
4049
4050 if (cfs_rq->on_list) {
4051 prev = cfs_rq->leaf_cfs_rq_list.prev;
4052 } else {
4053 prev = rq->tmp_alone_branch;
4054 }
4055
4056 if (prev == &rq->leaf_cfs_rq_list)
4057 return false;
4058
4059 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4060
4061 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4062 }
4063
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4064 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4065 {
4066 if (cfs_rq->load.weight)
4067 return false;
4068
4069 if (!load_avg_is_decayed(&cfs_rq->avg))
4070 return false;
4071
4072 if (child_cfs_rq_on_list(cfs_rq))
4073 return false;
4074
4075 return true;
4076 }
4077
4078 /**
4079 * update_tg_load_avg - update the tg's load avg
4080 * @cfs_rq: the cfs_rq whose avg changed
4081 *
4082 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4083 * However, because tg->load_avg is a global value there are performance
4084 * considerations.
4085 *
4086 * In order to avoid having to look at the other cfs_rq's, we use a
4087 * differential update where we store the last value we propagated. This in
4088 * turn allows skipping updates if the differential is 'small'.
4089 *
4090 * Updating tg's load_avg is necessary before update_cfs_share().
4091 */
update_tg_load_avg(struct cfs_rq * cfs_rq)4092 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4093 {
4094 long delta;
4095 u64 now;
4096
4097 /*
4098 * No need to update load_avg for root_task_group as it is not used.
4099 */
4100 if (cfs_rq->tg == &root_task_group)
4101 return;
4102
4103 /* rq has been offline and doesn't contribute to the share anymore: */
4104 if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4105 return;
4106
4107 /*
4108 * For migration heavy workloads, access to tg->load_avg can be
4109 * unbound. Limit the update rate to at most once per ms.
4110 */
4111 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4112 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4113 return;
4114
4115 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4116 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4117 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4118 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4119 cfs_rq->last_update_tg_load_avg = now;
4120 }
4121 }
4122
clear_tg_load_avg(struct cfs_rq * cfs_rq)4123 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4124 {
4125 long delta;
4126 u64 now;
4127
4128 /*
4129 * No need to update load_avg for root_task_group, as it is not used.
4130 */
4131 if (cfs_rq->tg == &root_task_group)
4132 return;
4133
4134 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4135 delta = 0 - cfs_rq->tg_load_avg_contrib;
4136 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4137 cfs_rq->tg_load_avg_contrib = 0;
4138 cfs_rq->last_update_tg_load_avg = now;
4139 }
4140
4141 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4142 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4143 {
4144 struct task_group *tg;
4145
4146 lockdep_assert_rq_held(rq);
4147
4148 /*
4149 * The rq clock has already been updated in
4150 * set_rq_offline(), so we should skip updating
4151 * the rq clock again in unthrottle_cfs_rq().
4152 */
4153 rq_clock_start_loop_update(rq);
4154
4155 rcu_read_lock();
4156 list_for_each_entry_rcu(tg, &task_groups, list) {
4157 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4158
4159 clear_tg_load_avg(cfs_rq);
4160 }
4161 rcu_read_unlock();
4162
4163 rq_clock_stop_loop_update(rq);
4164 }
4165
4166 /*
4167 * Called within set_task_rq() right before setting a task's CPU. The
4168 * caller only guarantees p->pi_lock is held; no other assumptions,
4169 * including the state of rq->lock, should be made.
4170 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4171 void set_task_rq_fair(struct sched_entity *se,
4172 struct cfs_rq *prev, struct cfs_rq *next)
4173 {
4174 u64 p_last_update_time;
4175 u64 n_last_update_time;
4176
4177 if (!sched_feat(ATTACH_AGE_LOAD))
4178 return;
4179
4180 /*
4181 * We are supposed to update the task to "current" time, then its up to
4182 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4183 * getting what current time is, so simply throw away the out-of-date
4184 * time. This will result in the wakee task is less decayed, but giving
4185 * the wakee more load sounds not bad.
4186 */
4187 if (!(se->avg.last_update_time && prev))
4188 return;
4189
4190 p_last_update_time = cfs_rq_last_update_time(prev);
4191 n_last_update_time = cfs_rq_last_update_time(next);
4192
4193 __update_load_avg_blocked_se(p_last_update_time, se);
4194 se->avg.last_update_time = n_last_update_time;
4195 }
4196
4197 /*
4198 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4199 * propagate its contribution. The key to this propagation is the invariant
4200 * that for each group:
4201 *
4202 * ge->avg == grq->avg (1)
4203 *
4204 * _IFF_ we look at the pure running and runnable sums. Because they
4205 * represent the very same entity, just at different points in the hierarchy.
4206 *
4207 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4208 * and simply copies the running/runnable sum over (but still wrong, because
4209 * the group entity and group rq do not have their PELT windows aligned).
4210 *
4211 * However, update_tg_cfs_load() is more complex. So we have:
4212 *
4213 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4214 *
4215 * And since, like util, the runnable part should be directly transferable,
4216 * the following would _appear_ to be the straight forward approach:
4217 *
4218 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4219 *
4220 * And per (1) we have:
4221 *
4222 * ge->avg.runnable_avg == grq->avg.runnable_avg
4223 *
4224 * Which gives:
4225 *
4226 * ge->load.weight * grq->avg.load_avg
4227 * ge->avg.load_avg = ----------------------------------- (4)
4228 * grq->load.weight
4229 *
4230 * Except that is wrong!
4231 *
4232 * Because while for entities historical weight is not important and we
4233 * really only care about our future and therefore can consider a pure
4234 * runnable sum, runqueues can NOT do this.
4235 *
4236 * We specifically want runqueues to have a load_avg that includes
4237 * historical weights. Those represent the blocked load, the load we expect
4238 * to (shortly) return to us. This only works by keeping the weights as
4239 * integral part of the sum. We therefore cannot decompose as per (3).
4240 *
4241 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4242 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4243 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4244 * runnable section of these tasks overlap (or not). If they were to perfectly
4245 * align the rq as a whole would be runnable 2/3 of the time. If however we
4246 * always have at least 1 runnable task, the rq as a whole is always runnable.
4247 *
4248 * So we'll have to approximate.. :/
4249 *
4250 * Given the constraint:
4251 *
4252 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4253 *
4254 * We can construct a rule that adds runnable to a rq by assuming minimal
4255 * overlap.
4256 *
4257 * On removal, we'll assume each task is equally runnable; which yields:
4258 *
4259 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4260 *
4261 * XXX: only do this for the part of runnable > running ?
4262 *
4263 */
4264 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4265 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4266 {
4267 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4268 u32 new_sum, divider;
4269
4270 /* Nothing to update */
4271 if (!delta_avg)
4272 return;
4273
4274 /*
4275 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4276 * See ___update_load_avg() for details.
4277 */
4278 divider = get_pelt_divider(&cfs_rq->avg);
4279
4280
4281 /* Set new sched_entity's utilization */
4282 se->avg.util_avg = gcfs_rq->avg.util_avg;
4283 new_sum = se->avg.util_avg * divider;
4284 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4285 se->avg.util_sum = new_sum;
4286
4287 /* Update parent cfs_rq utilization */
4288 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4289 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4290
4291 /* See update_cfs_rq_load_avg() */
4292 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4293 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4294 }
4295
4296 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4297 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4298 {
4299 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4300 u32 new_sum, divider;
4301
4302 /* Nothing to update */
4303 if (!delta_avg)
4304 return;
4305
4306 /*
4307 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4308 * See ___update_load_avg() for details.
4309 */
4310 divider = get_pelt_divider(&cfs_rq->avg);
4311
4312 /* Set new sched_entity's runnable */
4313 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4314 new_sum = se->avg.runnable_avg * divider;
4315 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4316 se->avg.runnable_sum = new_sum;
4317
4318 /* Update parent cfs_rq runnable */
4319 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4320 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4321 /* See update_cfs_rq_load_avg() */
4322 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4323 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4324 }
4325
4326 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4327 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4328 {
4329 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4330 unsigned long load_avg;
4331 u64 load_sum = 0;
4332 s64 delta_sum;
4333 u32 divider;
4334
4335 if (!runnable_sum)
4336 return;
4337
4338 gcfs_rq->prop_runnable_sum = 0;
4339
4340 /*
4341 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4342 * See ___update_load_avg() for details.
4343 */
4344 divider = get_pelt_divider(&cfs_rq->avg);
4345
4346 if (runnable_sum >= 0) {
4347 /*
4348 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4349 * the CPU is saturated running == runnable.
4350 */
4351 runnable_sum += se->avg.load_sum;
4352 runnable_sum = min_t(long, runnable_sum, divider);
4353 } else {
4354 /*
4355 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4356 * assuming all tasks are equally runnable.
4357 */
4358 if (scale_load_down(gcfs_rq->load.weight)) {
4359 load_sum = div_u64(gcfs_rq->avg.load_sum,
4360 scale_load_down(gcfs_rq->load.weight));
4361 }
4362
4363 /* But make sure to not inflate se's runnable */
4364 runnable_sum = min(se->avg.load_sum, load_sum);
4365 }
4366
4367 /*
4368 * runnable_sum can't be lower than running_sum
4369 * Rescale running sum to be in the same range as runnable sum
4370 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4371 * runnable_sum is in [0 : LOAD_AVG_MAX]
4372 */
4373 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4374 runnable_sum = max(runnable_sum, running_sum);
4375
4376 load_sum = se_weight(se) * runnable_sum;
4377 load_avg = div_u64(load_sum, divider);
4378
4379 delta_avg = load_avg - se->avg.load_avg;
4380 if (!delta_avg)
4381 return;
4382
4383 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4384
4385 se->avg.load_sum = runnable_sum;
4386 se->avg.load_avg = load_avg;
4387 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4388 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4389 /* See update_cfs_rq_load_avg() */
4390 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4391 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4392 }
4393
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4394 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4395 {
4396 cfs_rq->propagate = 1;
4397 cfs_rq->prop_runnable_sum += runnable_sum;
4398 }
4399
4400 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4401 static inline int propagate_entity_load_avg(struct sched_entity *se)
4402 {
4403 struct cfs_rq *cfs_rq, *gcfs_rq;
4404
4405 if (entity_is_task(se))
4406 return 0;
4407
4408 gcfs_rq = group_cfs_rq(se);
4409 if (!gcfs_rq->propagate)
4410 return 0;
4411
4412 gcfs_rq->propagate = 0;
4413
4414 cfs_rq = cfs_rq_of(se);
4415
4416 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4417
4418 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4419 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4420 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4421
4422 trace_pelt_cfs_tp(cfs_rq);
4423 trace_pelt_se_tp(se);
4424
4425 return 1;
4426 }
4427
4428 /*
4429 * Check if we need to update the load and the utilization of a blocked
4430 * group_entity:
4431 */
skip_blocked_update(struct sched_entity * se)4432 static inline bool skip_blocked_update(struct sched_entity *se)
4433 {
4434 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4435
4436 /*
4437 * If sched_entity still have not zero load or utilization, we have to
4438 * decay it:
4439 */
4440 if (se->avg.load_avg || se->avg.util_avg)
4441 return false;
4442
4443 /*
4444 * If there is a pending propagation, we have to update the load and
4445 * the utilization of the sched_entity:
4446 */
4447 if (gcfs_rq->propagate)
4448 return false;
4449
4450 /*
4451 * Otherwise, the load and the utilization of the sched_entity is
4452 * already zero and there is no pending propagation, so it will be a
4453 * waste of time to try to decay it:
4454 */
4455 return true;
4456 }
4457
4458 #else /* CONFIG_FAIR_GROUP_SCHED */
4459
update_tg_load_avg(struct cfs_rq * cfs_rq)4460 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4461
clear_tg_offline_cfs_rqs(struct rq * rq)4462 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4463
propagate_entity_load_avg(struct sched_entity * se)4464 static inline int propagate_entity_load_avg(struct sched_entity *se)
4465 {
4466 return 0;
4467 }
4468
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4469 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4470
4471 #endif /* CONFIG_FAIR_GROUP_SCHED */
4472
4473 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4474 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4475 {
4476 u64 throttled = 0, now, lut;
4477 struct cfs_rq *cfs_rq;
4478 struct rq *rq;
4479 bool is_idle;
4480
4481 if (load_avg_is_decayed(&se->avg))
4482 return;
4483
4484 cfs_rq = cfs_rq_of(se);
4485 rq = rq_of(cfs_rq);
4486
4487 rcu_read_lock();
4488 is_idle = is_idle_task(rcu_dereference(rq->curr));
4489 rcu_read_unlock();
4490
4491 /*
4492 * The lag estimation comes with a cost we don't want to pay all the
4493 * time. Hence, limiting to the case where the source CPU is idle and
4494 * we know we are at the greatest risk to have an outdated clock.
4495 */
4496 if (!is_idle)
4497 return;
4498
4499 /*
4500 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4501 *
4502 * last_update_time (the cfs_rq's last_update_time)
4503 * = cfs_rq_clock_pelt()@cfs_rq_idle
4504 * = rq_clock_pelt()@cfs_rq_idle
4505 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4506 *
4507 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4508 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4509 *
4510 * rq_idle_lag (delta between now and rq's update)
4511 * = sched_clock_cpu() - rq_clock()@rq_idle
4512 *
4513 * We can then write:
4514 *
4515 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4516 * sched_clock_cpu() - rq_clock()@rq_idle
4517 * Where:
4518 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4519 * rq_clock()@rq_idle is rq->clock_idle
4520 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4521 * is cfs_rq->throttled_pelt_idle
4522 */
4523
4524 #ifdef CONFIG_CFS_BANDWIDTH
4525 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4526 /* The clock has been stopped for throttling */
4527 if (throttled == U64_MAX)
4528 return;
4529 #endif
4530 now = u64_u32_load(rq->clock_pelt_idle);
4531 /*
4532 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4533 * is observed the old clock_pelt_idle value and the new clock_idle,
4534 * which lead to an underestimation. The opposite would lead to an
4535 * overestimation.
4536 */
4537 smp_rmb();
4538 lut = cfs_rq_last_update_time(cfs_rq);
4539
4540 now -= throttled;
4541 if (now < lut)
4542 /*
4543 * cfs_rq->avg.last_update_time is more recent than our
4544 * estimation, let's use it.
4545 */
4546 now = lut;
4547 else
4548 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4549
4550 __update_load_avg_blocked_se(now, se);
4551 }
4552 #else
migrate_se_pelt_lag(struct sched_entity * se)4553 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4554 #endif
4555
4556 /**
4557 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4558 * @now: current time, as per cfs_rq_clock_pelt()
4559 * @cfs_rq: cfs_rq to update
4560 *
4561 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4562 * avg. The immediate corollary is that all (fair) tasks must be attached.
4563 *
4564 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4565 *
4566 * Return: true if the load decayed or we removed load.
4567 *
4568 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4569 * call update_tg_load_avg() when this function returns true.
4570 */
4571 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4572 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4573 {
4574 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4575 struct sched_avg *sa = &cfs_rq->avg;
4576 int decayed = 0;
4577
4578 if (cfs_rq->removed.nr) {
4579 unsigned long r;
4580 u32 divider = get_pelt_divider(&cfs_rq->avg);
4581
4582 raw_spin_lock(&cfs_rq->removed.lock);
4583 swap(cfs_rq->removed.util_avg, removed_util);
4584 swap(cfs_rq->removed.load_avg, removed_load);
4585 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4586 cfs_rq->removed.nr = 0;
4587 raw_spin_unlock(&cfs_rq->removed.lock);
4588
4589 r = removed_load;
4590 sub_positive(&sa->load_avg, r);
4591 sub_positive(&sa->load_sum, r * divider);
4592 /* See sa->util_sum below */
4593 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4594
4595 r = removed_util;
4596 sub_positive(&sa->util_avg, r);
4597 sub_positive(&sa->util_sum, r * divider);
4598 /*
4599 * Because of rounding, se->util_sum might ends up being +1 more than
4600 * cfs->util_sum. Although this is not a problem by itself, detaching
4601 * a lot of tasks with the rounding problem between 2 updates of
4602 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4603 * cfs_util_avg is not.
4604 * Check that util_sum is still above its lower bound for the new
4605 * util_avg. Given that period_contrib might have moved since the last
4606 * sync, we are only sure that util_sum must be above or equal to
4607 * util_avg * minimum possible divider
4608 */
4609 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4610
4611 r = removed_runnable;
4612 sub_positive(&sa->runnable_avg, r);
4613 sub_positive(&sa->runnable_sum, r * divider);
4614 /* See sa->util_sum above */
4615 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4616 sa->runnable_avg * PELT_MIN_DIVIDER);
4617
4618 /*
4619 * removed_runnable is the unweighted version of removed_load so we
4620 * can use it to estimate removed_load_sum.
4621 */
4622 add_tg_cfs_propagate(cfs_rq,
4623 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4624
4625 decayed = 1;
4626 }
4627
4628 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4629 u64_u32_store_copy(sa->last_update_time,
4630 cfs_rq->last_update_time_copy,
4631 sa->last_update_time);
4632 return decayed;
4633 }
4634
4635 /**
4636 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4637 * @cfs_rq: cfs_rq to attach to
4638 * @se: sched_entity to attach
4639 *
4640 * Must call update_cfs_rq_load_avg() before this, since we rely on
4641 * cfs_rq->avg.last_update_time being current.
4642 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4643 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4644 {
4645 /*
4646 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4647 * See ___update_load_avg() for details.
4648 */
4649 u32 divider = get_pelt_divider(&cfs_rq->avg);
4650
4651 /*
4652 * When we attach the @se to the @cfs_rq, we must align the decay
4653 * window because without that, really weird and wonderful things can
4654 * happen.
4655 *
4656 * XXX illustrate
4657 */
4658 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4659 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4660
4661 /*
4662 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4663 * period_contrib. This isn't strictly correct, but since we're
4664 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4665 * _sum a little.
4666 */
4667 se->avg.util_sum = se->avg.util_avg * divider;
4668
4669 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4670
4671 se->avg.load_sum = se->avg.load_avg * divider;
4672 if (se_weight(se) < se->avg.load_sum)
4673 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4674 else
4675 se->avg.load_sum = 1;
4676
4677 enqueue_load_avg(cfs_rq, se);
4678 cfs_rq->avg.util_avg += se->avg.util_avg;
4679 cfs_rq->avg.util_sum += se->avg.util_sum;
4680 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4681 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4682
4683 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4684
4685 cfs_rq_util_change(cfs_rq, 0);
4686
4687 trace_pelt_cfs_tp(cfs_rq);
4688 }
4689
4690 /**
4691 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4692 * @cfs_rq: cfs_rq to detach from
4693 * @se: sched_entity to detach
4694 *
4695 * Must call update_cfs_rq_load_avg() before this, since we rely on
4696 * cfs_rq->avg.last_update_time being current.
4697 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4698 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4699 {
4700 dequeue_load_avg(cfs_rq, se);
4701 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4702 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4703 /* See update_cfs_rq_load_avg() */
4704 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4705 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4706
4707 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4708 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4709 /* See update_cfs_rq_load_avg() */
4710 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4711 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4712
4713 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4714
4715 cfs_rq_util_change(cfs_rq, 0);
4716
4717 trace_pelt_cfs_tp(cfs_rq);
4718 }
4719
4720 /*
4721 * Optional action to be done while updating the load average
4722 */
4723 #define UPDATE_TG 0x1
4724 #define SKIP_AGE_LOAD 0x2
4725 #define DO_ATTACH 0x4
4726 #define DO_DETACH 0x8
4727
4728 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4729 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4730 {
4731 u64 now = cfs_rq_clock_pelt(cfs_rq);
4732 int decayed;
4733
4734 /*
4735 * Track task load average for carrying it to new CPU after migrated, and
4736 * track group sched_entity load average for task_h_load calculation in migration
4737 */
4738 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4739 __update_load_avg_se(now, cfs_rq, se);
4740
4741 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4742 decayed |= propagate_entity_load_avg(se);
4743
4744 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4745
4746 /*
4747 * DO_ATTACH means we're here from enqueue_entity().
4748 * !last_update_time means we've passed through
4749 * migrate_task_rq_fair() indicating we migrated.
4750 *
4751 * IOW we're enqueueing a task on a new CPU.
4752 */
4753 attach_entity_load_avg(cfs_rq, se);
4754 update_tg_load_avg(cfs_rq);
4755
4756 } else if (flags & DO_DETACH) {
4757 /*
4758 * DO_DETACH means we're here from dequeue_entity()
4759 * and we are migrating task out of the CPU.
4760 */
4761 detach_entity_load_avg(cfs_rq, se);
4762 update_tg_load_avg(cfs_rq);
4763 } else if (decayed) {
4764 cfs_rq_util_change(cfs_rq, 0);
4765
4766 if (flags & UPDATE_TG)
4767 update_tg_load_avg(cfs_rq);
4768 }
4769 }
4770
4771 /*
4772 * Synchronize entity load avg of dequeued entity without locking
4773 * the previous rq.
4774 */
sync_entity_load_avg(struct sched_entity * se)4775 static void sync_entity_load_avg(struct sched_entity *se)
4776 {
4777 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4778 u64 last_update_time;
4779
4780 last_update_time = cfs_rq_last_update_time(cfs_rq);
4781 __update_load_avg_blocked_se(last_update_time, se);
4782 }
4783
4784 /*
4785 * Task first catches up with cfs_rq, and then subtract
4786 * itself from the cfs_rq (task must be off the queue now).
4787 */
remove_entity_load_avg(struct sched_entity * se)4788 static void remove_entity_load_avg(struct sched_entity *se)
4789 {
4790 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4791 unsigned long flags;
4792
4793 /*
4794 * tasks cannot exit without having gone through wake_up_new_task() ->
4795 * enqueue_task_fair() which will have added things to the cfs_rq,
4796 * so we can remove unconditionally.
4797 */
4798
4799 sync_entity_load_avg(se);
4800
4801 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4802 ++cfs_rq->removed.nr;
4803 cfs_rq->removed.util_avg += se->avg.util_avg;
4804 cfs_rq->removed.load_avg += se->avg.load_avg;
4805 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4806 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4807 }
4808
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4809 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4810 {
4811 return cfs_rq->avg.runnable_avg;
4812 }
4813
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4814 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4815 {
4816 return cfs_rq->avg.load_avg;
4817 }
4818
4819 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
4820
task_util(struct task_struct * p)4821 static inline unsigned long task_util(struct task_struct *p)
4822 {
4823 return READ_ONCE(p->se.avg.util_avg);
4824 }
4825
task_runnable(struct task_struct * p)4826 static inline unsigned long task_runnable(struct task_struct *p)
4827 {
4828 return READ_ONCE(p->se.avg.runnable_avg);
4829 }
4830
_task_util_est(struct task_struct * p)4831 static inline unsigned long _task_util_est(struct task_struct *p)
4832 {
4833 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
4834 }
4835
task_util_est(struct task_struct * p)4836 static inline unsigned long task_util_est(struct task_struct *p)
4837 {
4838 return max(task_util(p), _task_util_est(p));
4839 }
4840
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4841 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4842 struct task_struct *p)
4843 {
4844 unsigned int enqueued;
4845
4846 if (!sched_feat(UTIL_EST))
4847 return;
4848
4849 /* Update root cfs_rq's estimated utilization */
4850 enqueued = cfs_rq->avg.util_est;
4851 enqueued += _task_util_est(p);
4852 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4853
4854 trace_sched_util_est_cfs_tp(cfs_rq);
4855 }
4856
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4857 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4858 struct task_struct *p)
4859 {
4860 unsigned int enqueued;
4861
4862 if (!sched_feat(UTIL_EST))
4863 return;
4864
4865 /* Update root cfs_rq's estimated utilization */
4866 enqueued = cfs_rq->avg.util_est;
4867 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4868 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4869
4870 trace_sched_util_est_cfs_tp(cfs_rq);
4871 }
4872
4873 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4874
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4875 static inline void util_est_update(struct cfs_rq *cfs_rq,
4876 struct task_struct *p,
4877 bool task_sleep)
4878 {
4879 unsigned int ewma, dequeued, last_ewma_diff;
4880
4881 if (!sched_feat(UTIL_EST))
4882 return;
4883
4884 /*
4885 * Skip update of task's estimated utilization when the task has not
4886 * yet completed an activation, e.g. being migrated.
4887 */
4888 if (!task_sleep)
4889 return;
4890
4891 /* Get current estimate of utilization */
4892 ewma = READ_ONCE(p->se.avg.util_est);
4893
4894 /*
4895 * If the PELT values haven't changed since enqueue time,
4896 * skip the util_est update.
4897 */
4898 if (ewma & UTIL_AVG_UNCHANGED)
4899 return;
4900
4901 /* Get utilization at dequeue */
4902 dequeued = task_util(p);
4903
4904 /*
4905 * Reset EWMA on utilization increases, the moving average is used only
4906 * to smooth utilization decreases.
4907 */
4908 if (ewma <= dequeued) {
4909 ewma = dequeued;
4910 goto done;
4911 }
4912
4913 /*
4914 * Skip update of task's estimated utilization when its members are
4915 * already ~1% close to its last activation value.
4916 */
4917 last_ewma_diff = ewma - dequeued;
4918 if (last_ewma_diff < UTIL_EST_MARGIN)
4919 goto done;
4920
4921 /*
4922 * To avoid overestimation of actual task utilization, skip updates if
4923 * we cannot grant there is idle time in this CPU.
4924 */
4925 if (dequeued > arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))))
4926 return;
4927
4928 /*
4929 * To avoid underestimate of task utilization, skip updates of EWMA if
4930 * we cannot grant that thread got all CPU time it wanted.
4931 */
4932 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
4933 goto done;
4934
4935
4936 /*
4937 * Update Task's estimated utilization
4938 *
4939 * When *p completes an activation we can consolidate another sample
4940 * of the task size. This is done by using this value to update the
4941 * Exponential Weighted Moving Average (EWMA):
4942 *
4943 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4944 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4945 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4946 * = w * ( -last_ewma_diff ) + ewma(t-1)
4947 * = w * (-last_ewma_diff + ewma(t-1) / w)
4948 *
4949 * Where 'w' is the weight of new samples, which is configured to be
4950 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4951 */
4952 ewma <<= UTIL_EST_WEIGHT_SHIFT;
4953 ewma -= last_ewma_diff;
4954 ewma >>= UTIL_EST_WEIGHT_SHIFT;
4955 done:
4956 ewma |= UTIL_AVG_UNCHANGED;
4957 WRITE_ONCE(p->se.avg.util_est, ewma);
4958
4959 trace_sched_util_est_se_tp(&p->se);
4960 }
4961
get_actual_cpu_capacity(int cpu)4962 static inline unsigned long get_actual_cpu_capacity(int cpu)
4963 {
4964 unsigned long capacity = arch_scale_cpu_capacity(cpu);
4965
4966 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
4967
4968 return capacity;
4969 }
4970
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4971 static inline int util_fits_cpu(unsigned long util,
4972 unsigned long uclamp_min,
4973 unsigned long uclamp_max,
4974 int cpu)
4975 {
4976 unsigned long capacity = capacity_of(cpu);
4977 unsigned long capacity_orig;
4978 bool fits, uclamp_max_fits;
4979
4980 /*
4981 * Check if the real util fits without any uclamp boost/cap applied.
4982 */
4983 fits = fits_capacity(util, capacity);
4984
4985 if (!uclamp_is_used())
4986 return fits;
4987
4988 /*
4989 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4990 * uclamp_max. We only care about capacity pressure (by using
4991 * capacity_of()) for comparing against the real util.
4992 *
4993 * If a task is boosted to 1024 for example, we don't want a tiny
4994 * pressure to skew the check whether it fits a CPU or not.
4995 *
4996 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4997 * should fit a little cpu even if there's some pressure.
4998 *
4999 * Only exception is for HW or cpufreq pressure since it has a direct impact
5000 * on available OPP of the system.
5001 *
5002 * We honour it for uclamp_min only as a drop in performance level
5003 * could result in not getting the requested minimum performance level.
5004 *
5005 * For uclamp_max, we can tolerate a drop in performance level as the
5006 * goal is to cap the task. So it's okay if it's getting less.
5007 */
5008 capacity_orig = arch_scale_cpu_capacity(cpu);
5009
5010 /*
5011 * We want to force a task to fit a cpu as implied by uclamp_max.
5012 * But we do have some corner cases to cater for..
5013 *
5014 *
5015 * C=z
5016 * | ___
5017 * | C=y | |
5018 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5019 * | C=x | | | |
5020 * | ___ | | | |
5021 * | | | | | | | (util somewhere in this region)
5022 * | | | | | | |
5023 * | | | | | | |
5024 * +----------------------------------------
5025 * CPU0 CPU1 CPU2
5026 *
5027 * In the above example if a task is capped to a specific performance
5028 * point, y, then when:
5029 *
5030 * * util = 80% of x then it does not fit on CPU0 and should migrate
5031 * to CPU1
5032 * * util = 80% of y then it is forced to fit on CPU1 to honour
5033 * uclamp_max request.
5034 *
5035 * which is what we're enforcing here. A task always fits if
5036 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
5037 * the normal upmigration rules should withhold still.
5038 *
5039 * Only exception is when we are on max capacity, then we need to be
5040 * careful not to block overutilized state. This is so because:
5041 *
5042 * 1. There's no concept of capping at max_capacity! We can't go
5043 * beyond this performance level anyway.
5044 * 2. The system is being saturated when we're operating near
5045 * max capacity, it doesn't make sense to block overutilized.
5046 */
5047 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5048 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5049 fits = fits || uclamp_max_fits;
5050
5051 /*
5052 *
5053 * C=z
5054 * | ___ (region a, capped, util >= uclamp_max)
5055 * | C=y | |
5056 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5057 * | C=x | | | |
5058 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
5059 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5060 * | | | | | | |
5061 * | | | | | | | (region c, boosted, util < uclamp_min)
5062 * +----------------------------------------
5063 * CPU0 CPU1 CPU2
5064 *
5065 * a) If util > uclamp_max, then we're capped, we don't care about
5066 * actual fitness value here. We only care if uclamp_max fits
5067 * capacity without taking margin/pressure into account.
5068 * See comment above.
5069 *
5070 * b) If uclamp_min <= util <= uclamp_max, then the normal
5071 * fits_capacity() rules apply. Except we need to ensure that we
5072 * enforce we remain within uclamp_max, see comment above.
5073 *
5074 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5075 * need to take into account the boosted value fits the CPU without
5076 * taking margin/pressure into account.
5077 *
5078 * Cases (a) and (b) are handled in the 'fits' variable already. We
5079 * just need to consider an extra check for case (c) after ensuring we
5080 * handle the case uclamp_min > uclamp_max.
5081 */
5082 uclamp_min = min(uclamp_min, uclamp_max);
5083 if (fits && (util < uclamp_min) &&
5084 (uclamp_min > get_actual_cpu_capacity(cpu)))
5085 return -1;
5086
5087 return fits;
5088 }
5089
task_fits_cpu(struct task_struct * p,int cpu)5090 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5091 {
5092 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5093 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5094 unsigned long util = task_util_est(p);
5095 /*
5096 * Return true only if the cpu fully fits the task requirements, which
5097 * include the utilization but also the performance hints.
5098 */
5099 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5100 }
5101
update_misfit_status(struct task_struct * p,struct rq * rq)5102 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5103 {
5104 int cpu = cpu_of(rq);
5105
5106 if (!sched_asym_cpucap_active())
5107 return;
5108
5109 /*
5110 * Affinity allows us to go somewhere higher? Or are we on biggest
5111 * available CPU already? Or do we fit into this CPU ?
5112 */
5113 if (!p || (p->nr_cpus_allowed == 1) ||
5114 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5115 task_fits_cpu(p, cpu)) {
5116
5117 rq->misfit_task_load = 0;
5118 return;
5119 }
5120
5121 /*
5122 * Make sure that misfit_task_load will not be null even if
5123 * task_h_load() returns 0.
5124 */
5125 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5126 }
5127
5128 #else /* CONFIG_SMP */
5129
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)5130 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5131 {
5132 return !cfs_rq->nr_queued;
5133 }
5134
5135 #define UPDATE_TG 0x0
5136 #define SKIP_AGE_LOAD 0x0
5137 #define DO_ATTACH 0x0
5138 #define DO_DETACH 0x0
5139
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)5140 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
5141 {
5142 cfs_rq_util_change(cfs_rq, 0);
5143 }
5144
remove_entity_load_avg(struct sched_entity * se)5145 static inline void remove_entity_load_avg(struct sched_entity *se) {}
5146
5147 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5148 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5149 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5150 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5151
sched_balance_newidle(struct rq * rq,struct rq_flags * rf)5152 static inline int sched_balance_newidle(struct rq *rq, struct rq_flags *rf)
5153 {
5154 return 0;
5155 }
5156
5157 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5158 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5159
5160 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5161 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5162
5163 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5164 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
5165 bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)5166 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
5167
5168 #endif /* CONFIG_SMP */
5169
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)5170 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5171 {
5172 struct sched_entity *se = &p->se;
5173
5174 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5175 if (attr->sched_runtime) {
5176 se->custom_slice = 1;
5177 se->slice = clamp_t(u64, attr->sched_runtime,
5178 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */
5179 NSEC_PER_MSEC*100); /* HZ=100 / 10 */
5180 } else {
5181 se->custom_slice = 0;
5182 se->slice = sysctl_sched_base_slice;
5183 }
5184 }
5185
5186 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5187 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5188 {
5189 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5190 s64 lag = 0;
5191
5192 if (!se->custom_slice)
5193 se->slice = sysctl_sched_base_slice;
5194 vslice = calc_delta_fair(se->slice, se);
5195
5196 /*
5197 * Due to how V is constructed as the weighted average of entities,
5198 * adding tasks with positive lag, or removing tasks with negative lag
5199 * will move 'time' backwards, this can screw around with the lag of
5200 * other tasks.
5201 *
5202 * EEVDF: placement strategy #1 / #2
5203 */
5204 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5205 struct sched_entity *curr = cfs_rq->curr;
5206 unsigned long load;
5207
5208 lag = se->vlag;
5209
5210 /*
5211 * If we want to place a task and preserve lag, we have to
5212 * consider the effect of the new entity on the weighted
5213 * average and compensate for this, otherwise lag can quickly
5214 * evaporate.
5215 *
5216 * Lag is defined as:
5217 *
5218 * lag_i = S - s_i = w_i * (V - v_i)
5219 *
5220 * To avoid the 'w_i' term all over the place, we only track
5221 * the virtual lag:
5222 *
5223 * vl_i = V - v_i <=> v_i = V - vl_i
5224 *
5225 * And we take V to be the weighted average of all v:
5226 *
5227 * V = (\Sum w_j*v_j) / W
5228 *
5229 * Where W is: \Sum w_j
5230 *
5231 * Then, the weighted average after adding an entity with lag
5232 * vl_i is given by:
5233 *
5234 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5235 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5236 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5237 * = (V*(W + w_i) - w_i*l) / (W + w_i)
5238 * = V - w_i*vl_i / (W + w_i)
5239 *
5240 * And the actual lag after adding an entity with vl_i is:
5241 *
5242 * vl'_i = V' - v_i
5243 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5244 * = vl_i - w_i*vl_i / (W + w_i)
5245 *
5246 * Which is strictly less than vl_i. So in order to preserve lag
5247 * we should inflate the lag before placement such that the
5248 * effective lag after placement comes out right.
5249 *
5250 * As such, invert the above relation for vl'_i to get the vl_i
5251 * we need to use such that the lag after placement is the lag
5252 * we computed before dequeue.
5253 *
5254 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5255 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5256 *
5257 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5258 * = W*vl_i
5259 *
5260 * vl_i = (W + w_i)*vl'_i / W
5261 */
5262 load = cfs_rq->avg_load;
5263 if (curr && curr->on_rq)
5264 load += scale_load_down(curr->load.weight);
5265
5266 lag *= load + scale_load_down(se->load.weight);
5267 if (WARN_ON_ONCE(!load))
5268 load = 1;
5269 lag = div_s64(lag, load);
5270 }
5271
5272 se->vruntime = vruntime - lag;
5273
5274 if (se->rel_deadline) {
5275 se->deadline += se->vruntime;
5276 se->rel_deadline = 0;
5277 return;
5278 }
5279
5280 /*
5281 * When joining the competition; the existing tasks will be,
5282 * on average, halfway through their slice, as such start tasks
5283 * off with half a slice to ease into the competition.
5284 */
5285 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5286 vslice /= 2;
5287
5288 /*
5289 * EEVDF: vd_i = ve_i + r_i/w_i
5290 */
5291 se->deadline = se->vruntime + vslice;
5292 }
5293
5294 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5295 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5296
5297 static void
5298 requeue_delayed_entity(struct sched_entity *se);
5299
5300 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5301 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5302 {
5303 bool curr = cfs_rq->curr == se;
5304
5305 /*
5306 * If we're the current task, we must renormalise before calling
5307 * update_curr().
5308 */
5309 if (curr)
5310 place_entity(cfs_rq, se, flags);
5311
5312 update_curr(cfs_rq);
5313
5314 /*
5315 * When enqueuing a sched_entity, we must:
5316 * - Update loads to have both entity and cfs_rq synced with now.
5317 * - For group_entity, update its runnable_weight to reflect the new
5318 * h_nr_runnable of its group cfs_rq.
5319 * - For group_entity, update its weight to reflect the new share of
5320 * its group cfs_rq
5321 * - Add its new weight to cfs_rq->load.weight
5322 */
5323 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5324 se_update_runnable(se);
5325 /*
5326 * XXX update_load_avg() above will have attached us to the pelt sum;
5327 * but update_cfs_group() here will re-adjust the weight and have to
5328 * undo/redo all that. Seems wasteful.
5329 */
5330 update_cfs_group(se);
5331
5332 /*
5333 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5334 * we can place the entity.
5335 */
5336 if (!curr)
5337 place_entity(cfs_rq, se, flags);
5338
5339 account_entity_enqueue(cfs_rq, se);
5340
5341 /* Entity has migrated, no longer consider this task hot */
5342 if (flags & ENQUEUE_MIGRATED)
5343 se->exec_start = 0;
5344
5345 check_schedstat_required();
5346 update_stats_enqueue_fair(cfs_rq, se, flags);
5347 if (!curr)
5348 __enqueue_entity(cfs_rq, se);
5349 se->on_rq = 1;
5350
5351 if (cfs_rq->nr_queued == 1) {
5352 check_enqueue_throttle(cfs_rq);
5353 if (!throttled_hierarchy(cfs_rq)) {
5354 list_add_leaf_cfs_rq(cfs_rq);
5355 } else {
5356 #ifdef CONFIG_CFS_BANDWIDTH
5357 struct rq *rq = rq_of(cfs_rq);
5358
5359 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5360 cfs_rq->throttled_clock = rq_clock(rq);
5361 if (!cfs_rq->throttled_clock_self)
5362 cfs_rq->throttled_clock_self = rq_clock(rq);
5363 #endif
5364 }
5365 }
5366 }
5367
__clear_buddies_next(struct sched_entity * se)5368 static void __clear_buddies_next(struct sched_entity *se)
5369 {
5370 for_each_sched_entity(se) {
5371 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5372 if (cfs_rq->next != se)
5373 break;
5374
5375 cfs_rq->next = NULL;
5376 }
5377 }
5378
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5379 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5380 {
5381 if (cfs_rq->next == se)
5382 __clear_buddies_next(se);
5383 }
5384
5385 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5386
set_delayed(struct sched_entity * se)5387 static void set_delayed(struct sched_entity *se)
5388 {
5389 se->sched_delayed = 1;
5390
5391 /*
5392 * Delayed se of cfs_rq have no tasks queued on them.
5393 * Do not adjust h_nr_runnable since dequeue_entities()
5394 * will account it for blocked tasks.
5395 */
5396 if (!entity_is_task(se))
5397 return;
5398
5399 for_each_sched_entity(se) {
5400 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5401
5402 cfs_rq->h_nr_runnable--;
5403 if (cfs_rq_throttled(cfs_rq))
5404 break;
5405 }
5406 }
5407
clear_delayed(struct sched_entity * se)5408 static void clear_delayed(struct sched_entity *se)
5409 {
5410 se->sched_delayed = 0;
5411
5412 /*
5413 * Delayed se of cfs_rq have no tasks queued on them.
5414 * Do not adjust h_nr_runnable since a dequeue has
5415 * already accounted for it or an enqueue of a task
5416 * below it will account for it in enqueue_task_fair().
5417 */
5418 if (!entity_is_task(se))
5419 return;
5420
5421 for_each_sched_entity(se) {
5422 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5423
5424 cfs_rq->h_nr_runnable++;
5425 if (cfs_rq_throttled(cfs_rq))
5426 break;
5427 }
5428 }
5429
finish_delayed_dequeue_entity(struct sched_entity * se)5430 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5431 {
5432 clear_delayed(se);
5433 if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5434 se->vlag = 0;
5435 }
5436
5437 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5438 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5439 {
5440 bool sleep = flags & DEQUEUE_SLEEP;
5441 int action = UPDATE_TG;
5442
5443 update_curr(cfs_rq);
5444 clear_buddies(cfs_rq, se);
5445
5446 if (flags & DEQUEUE_DELAYED) {
5447 SCHED_WARN_ON(!se->sched_delayed);
5448 } else {
5449 bool delay = sleep;
5450 /*
5451 * DELAY_DEQUEUE relies on spurious wakeups, special task
5452 * states must not suffer spurious wakeups, excempt them.
5453 */
5454 if (flags & DEQUEUE_SPECIAL)
5455 delay = false;
5456
5457 SCHED_WARN_ON(delay && se->sched_delayed);
5458
5459 if (sched_feat(DELAY_DEQUEUE) && delay &&
5460 !entity_eligible(cfs_rq, se)) {
5461 update_load_avg(cfs_rq, se, 0);
5462 set_delayed(se);
5463 return false;
5464 }
5465 }
5466
5467 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5468 action |= DO_DETACH;
5469
5470 /*
5471 * When dequeuing a sched_entity, we must:
5472 * - Update loads to have both entity and cfs_rq synced with now.
5473 * - For group_entity, update its runnable_weight to reflect the new
5474 * h_nr_runnable of its group cfs_rq.
5475 * - Subtract its previous weight from cfs_rq->load.weight.
5476 * - For group entity, update its weight to reflect the new share
5477 * of its group cfs_rq.
5478 */
5479 update_load_avg(cfs_rq, se, action);
5480 se_update_runnable(se);
5481
5482 update_stats_dequeue_fair(cfs_rq, se, flags);
5483
5484 update_entity_lag(cfs_rq, se);
5485 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5486 se->deadline -= se->vruntime;
5487 se->rel_deadline = 1;
5488 }
5489
5490 if (se != cfs_rq->curr)
5491 __dequeue_entity(cfs_rq, se);
5492 se->on_rq = 0;
5493 account_entity_dequeue(cfs_rq, se);
5494
5495 /* return excess runtime on last dequeue */
5496 return_cfs_rq_runtime(cfs_rq);
5497
5498 update_cfs_group(se);
5499
5500 /*
5501 * Now advance min_vruntime if @se was the entity holding it back,
5502 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5503 * put back on, and if we advance min_vruntime, we'll be placed back
5504 * further than we started -- i.e. we'll be penalized.
5505 */
5506 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5507 update_min_vruntime(cfs_rq);
5508
5509 if (flags & DEQUEUE_DELAYED)
5510 finish_delayed_dequeue_entity(se);
5511
5512 if (cfs_rq->nr_queued == 0)
5513 update_idle_cfs_rq_clock_pelt(cfs_rq);
5514
5515 return true;
5516 }
5517
5518 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5519 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5520 {
5521 clear_buddies(cfs_rq, se);
5522
5523 /* 'current' is not kept within the tree. */
5524 if (se->on_rq) {
5525 /*
5526 * Any task has to be enqueued before it get to execute on
5527 * a CPU. So account for the time it spent waiting on the
5528 * runqueue.
5529 */
5530 update_stats_wait_end_fair(cfs_rq, se);
5531 __dequeue_entity(cfs_rq, se);
5532 update_load_avg(cfs_rq, se, UPDATE_TG);
5533 /*
5534 * HACK, stash a copy of deadline at the point of pick in vlag,
5535 * which isn't used until dequeue.
5536 */
5537 se->vlag = se->deadline;
5538 }
5539
5540 update_stats_curr_start(cfs_rq, se);
5541 SCHED_WARN_ON(cfs_rq->curr);
5542 cfs_rq->curr = se;
5543
5544 /*
5545 * Track our maximum slice length, if the CPU's load is at
5546 * least twice that of our own weight (i.e. don't track it
5547 * when there are only lesser-weight tasks around):
5548 */
5549 if (schedstat_enabled() &&
5550 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5551 struct sched_statistics *stats;
5552
5553 stats = __schedstats_from_se(se);
5554 __schedstat_set(stats->slice_max,
5555 max((u64)stats->slice_max,
5556 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5557 }
5558
5559 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5560 }
5561
5562 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5563
5564 /*
5565 * Pick the next process, keeping these things in mind, in this order:
5566 * 1) keep things fair between processes/task groups
5567 * 2) pick the "next" process, since someone really wants that to run
5568 * 3) pick the "last" process, for cache locality
5569 * 4) do not run the "skip" process, if something else is available
5570 */
5571 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5572 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5573 {
5574 struct sched_entity *se;
5575
5576 /*
5577 * Picking the ->next buddy will affect latency but not fairness.
5578 */
5579 if (sched_feat(PICK_BUDDY) &&
5580 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
5581 /* ->next will never be delayed */
5582 SCHED_WARN_ON(cfs_rq->next->sched_delayed);
5583 return cfs_rq->next;
5584 }
5585
5586 se = pick_eevdf(cfs_rq);
5587 if (se->sched_delayed) {
5588 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5589 /*
5590 * Must not reference @se again, see __block_task().
5591 */
5592 return NULL;
5593 }
5594 return se;
5595 }
5596
5597 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5598
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5599 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5600 {
5601 /*
5602 * If still on the runqueue then deactivate_task()
5603 * was not called and update_curr() has to be done:
5604 */
5605 if (prev->on_rq)
5606 update_curr(cfs_rq);
5607
5608 /* throttle cfs_rqs exceeding runtime */
5609 check_cfs_rq_runtime(cfs_rq);
5610
5611 if (prev->on_rq) {
5612 update_stats_wait_start_fair(cfs_rq, prev);
5613 /* Put 'current' back into the tree. */
5614 __enqueue_entity(cfs_rq, prev);
5615 /* in !on_rq case, update occurred at dequeue */
5616 update_load_avg(cfs_rq, prev, 0);
5617 }
5618 SCHED_WARN_ON(cfs_rq->curr != prev);
5619 cfs_rq->curr = NULL;
5620 }
5621
5622 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5623 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5624 {
5625 /*
5626 * Update run-time statistics of the 'current'.
5627 */
5628 update_curr(cfs_rq);
5629
5630 /*
5631 * Ensure that runnable average is periodically updated.
5632 */
5633 update_load_avg(cfs_rq, curr, UPDATE_TG);
5634 update_cfs_group(curr);
5635
5636 #ifdef CONFIG_SCHED_HRTICK
5637 /*
5638 * queued ticks are scheduled to match the slice, so don't bother
5639 * validating it and just reschedule.
5640 */
5641 if (queued) {
5642 resched_curr_lazy(rq_of(cfs_rq));
5643 return;
5644 }
5645 #endif
5646 }
5647
5648
5649 /**************************************************
5650 * CFS bandwidth control machinery
5651 */
5652
5653 #ifdef CONFIG_CFS_BANDWIDTH
5654
5655 #ifdef CONFIG_JUMP_LABEL
5656 static struct static_key __cfs_bandwidth_used;
5657
cfs_bandwidth_used(void)5658 static inline bool cfs_bandwidth_used(void)
5659 {
5660 return static_key_false(&__cfs_bandwidth_used);
5661 }
5662
cfs_bandwidth_usage_inc(void)5663 void cfs_bandwidth_usage_inc(void)
5664 {
5665 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5666 }
5667
cfs_bandwidth_usage_dec(void)5668 void cfs_bandwidth_usage_dec(void)
5669 {
5670 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5671 }
5672 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)5673 static bool cfs_bandwidth_used(void)
5674 {
5675 return true;
5676 }
5677
cfs_bandwidth_usage_inc(void)5678 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5679 void cfs_bandwidth_usage_dec(void) {}
5680 #endif /* CONFIG_JUMP_LABEL */
5681
5682 /*
5683 * default period for cfs group bandwidth.
5684 * default: 0.1s, units: nanoseconds
5685 */
default_cfs_period(void)5686 static inline u64 default_cfs_period(void)
5687 {
5688 return 100000000ULL;
5689 }
5690
sched_cfs_bandwidth_slice(void)5691 static inline u64 sched_cfs_bandwidth_slice(void)
5692 {
5693 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5694 }
5695
5696 /*
5697 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5698 * directly instead of rq->clock to avoid adding additional synchronization
5699 * around rq->lock.
5700 *
5701 * requires cfs_b->lock
5702 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5703 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5704 {
5705 s64 runtime;
5706
5707 if (unlikely(cfs_b->quota == RUNTIME_INF))
5708 return;
5709
5710 cfs_b->runtime += cfs_b->quota;
5711 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5712 if (runtime > 0) {
5713 cfs_b->burst_time += runtime;
5714 cfs_b->nr_burst++;
5715 }
5716
5717 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5718 cfs_b->runtime_snap = cfs_b->runtime;
5719 }
5720
tg_cfs_bandwidth(struct task_group * tg)5721 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5722 {
5723 return &tg->cfs_bandwidth;
5724 }
5725
5726 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5727 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5728 struct cfs_rq *cfs_rq, u64 target_runtime)
5729 {
5730 u64 min_amount, amount = 0;
5731
5732 lockdep_assert_held(&cfs_b->lock);
5733
5734 /* note: this is a positive sum as runtime_remaining <= 0 */
5735 min_amount = target_runtime - cfs_rq->runtime_remaining;
5736
5737 if (cfs_b->quota == RUNTIME_INF)
5738 amount = min_amount;
5739 else {
5740 start_cfs_bandwidth(cfs_b);
5741
5742 if (cfs_b->runtime > 0) {
5743 amount = min(cfs_b->runtime, min_amount);
5744 cfs_b->runtime -= amount;
5745 cfs_b->idle = 0;
5746 }
5747 }
5748
5749 cfs_rq->runtime_remaining += amount;
5750
5751 return cfs_rq->runtime_remaining > 0;
5752 }
5753
5754 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5755 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5756 {
5757 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5758 int ret;
5759
5760 raw_spin_lock(&cfs_b->lock);
5761 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5762 raw_spin_unlock(&cfs_b->lock);
5763
5764 return ret;
5765 }
5766
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5767 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5768 {
5769 /* dock delta_exec before expiring quota (as it could span periods) */
5770 cfs_rq->runtime_remaining -= delta_exec;
5771
5772 if (likely(cfs_rq->runtime_remaining > 0))
5773 return;
5774
5775 if (cfs_rq->throttled)
5776 return;
5777 /*
5778 * if we're unable to extend our runtime we resched so that the active
5779 * hierarchy can be throttled
5780 */
5781 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5782 resched_curr(rq_of(cfs_rq));
5783 }
5784
5785 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5786 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5787 {
5788 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5789 return;
5790
5791 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5792 }
5793
cfs_rq_throttled(struct cfs_rq * cfs_rq)5794 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5795 {
5796 return cfs_bandwidth_used() && cfs_rq->throttled;
5797 }
5798
5799 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5800 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5801 {
5802 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5803 }
5804
5805 /*
5806 * Ensure that neither of the group entities corresponding to src_cpu or
5807 * dest_cpu are members of a throttled hierarchy when performing group
5808 * load-balance operations.
5809 */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)5810 static inline int throttled_lb_pair(struct task_group *tg,
5811 int src_cpu, int dest_cpu)
5812 {
5813 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5814
5815 src_cfs_rq = tg->cfs_rq[src_cpu];
5816 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5817
5818 return throttled_hierarchy(src_cfs_rq) ||
5819 throttled_hierarchy(dest_cfs_rq);
5820 }
5821
tg_unthrottle_up(struct task_group * tg,void * data)5822 static int tg_unthrottle_up(struct task_group *tg, void *data)
5823 {
5824 struct rq *rq = data;
5825 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5826
5827 cfs_rq->throttle_count--;
5828 if (!cfs_rq->throttle_count) {
5829 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5830 cfs_rq->throttled_clock_pelt;
5831
5832 /* Add cfs_rq with load or one or more already running entities to the list */
5833 if (!cfs_rq_is_decayed(cfs_rq))
5834 list_add_leaf_cfs_rq(cfs_rq);
5835
5836 if (cfs_rq->throttled_clock_self) {
5837 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5838
5839 cfs_rq->throttled_clock_self = 0;
5840
5841 if (SCHED_WARN_ON((s64)delta < 0))
5842 delta = 0;
5843
5844 cfs_rq->throttled_clock_self_time += delta;
5845 }
5846 }
5847
5848 return 0;
5849 }
5850
tg_throttle_down(struct task_group * tg,void * data)5851 static int tg_throttle_down(struct task_group *tg, void *data)
5852 {
5853 struct rq *rq = data;
5854 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5855
5856 /* group is entering throttled state, stop time */
5857 if (!cfs_rq->throttle_count) {
5858 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5859 list_del_leaf_cfs_rq(cfs_rq);
5860
5861 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5862 if (cfs_rq->nr_queued)
5863 cfs_rq->throttled_clock_self = rq_clock(rq);
5864 }
5865 cfs_rq->throttle_count++;
5866
5867 return 0;
5868 }
5869
throttle_cfs_rq(struct cfs_rq * cfs_rq)5870 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5871 {
5872 struct rq *rq = rq_of(cfs_rq);
5873 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5874 struct sched_entity *se;
5875 long queued_delta, runnable_delta, idle_delta, dequeue = 1;
5876 long rq_h_nr_queued = rq->cfs.h_nr_queued;
5877
5878 raw_spin_lock(&cfs_b->lock);
5879 /* This will start the period timer if necessary */
5880 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5881 /*
5882 * We have raced with bandwidth becoming available, and if we
5883 * actually throttled the timer might not unthrottle us for an
5884 * entire period. We additionally needed to make sure that any
5885 * subsequent check_cfs_rq_runtime calls agree not to throttle
5886 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5887 * for 1ns of runtime rather than just check cfs_b.
5888 */
5889 dequeue = 0;
5890 } else {
5891 list_add_tail_rcu(&cfs_rq->throttled_list,
5892 &cfs_b->throttled_cfs_rq);
5893 }
5894 raw_spin_unlock(&cfs_b->lock);
5895
5896 if (!dequeue)
5897 return false; /* Throttle no longer required. */
5898
5899 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5900
5901 /* freeze hierarchy runnable averages while throttled */
5902 rcu_read_lock();
5903 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5904 rcu_read_unlock();
5905
5906 queued_delta = cfs_rq->h_nr_queued;
5907 runnable_delta = cfs_rq->h_nr_runnable;
5908 idle_delta = cfs_rq->h_nr_idle;
5909 for_each_sched_entity(se) {
5910 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5911 int flags;
5912
5913 /* throttled entity or throttle-on-deactivate */
5914 if (!se->on_rq)
5915 goto done;
5916
5917 /*
5918 * Abuse SPECIAL to avoid delayed dequeue in this instance.
5919 * This avoids teaching dequeue_entities() about throttled
5920 * entities and keeps things relatively simple.
5921 */
5922 flags = DEQUEUE_SLEEP | DEQUEUE_SPECIAL;
5923 if (se->sched_delayed)
5924 flags |= DEQUEUE_DELAYED;
5925 dequeue_entity(qcfs_rq, se, flags);
5926
5927 if (cfs_rq_is_idle(group_cfs_rq(se)))
5928 idle_delta = cfs_rq->h_nr_queued;
5929
5930 qcfs_rq->h_nr_queued -= queued_delta;
5931 qcfs_rq->h_nr_runnable -= runnable_delta;
5932 qcfs_rq->h_nr_idle -= idle_delta;
5933
5934 if (qcfs_rq->load.weight) {
5935 /* Avoid re-evaluating load for this entity: */
5936 se = parent_entity(se);
5937 break;
5938 }
5939 }
5940
5941 for_each_sched_entity(se) {
5942 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5943 /* throttled entity or throttle-on-deactivate */
5944 if (!se->on_rq)
5945 goto done;
5946
5947 update_load_avg(qcfs_rq, se, 0);
5948 se_update_runnable(se);
5949
5950 if (cfs_rq_is_idle(group_cfs_rq(se)))
5951 idle_delta = cfs_rq->h_nr_queued;
5952
5953 qcfs_rq->h_nr_queued -= queued_delta;
5954 qcfs_rq->h_nr_runnable -= runnable_delta;
5955 qcfs_rq->h_nr_idle -= idle_delta;
5956 }
5957
5958 /* At this point se is NULL and we are at root level*/
5959 sub_nr_running(rq, queued_delta);
5960
5961 /* Stop the fair server if throttling resulted in no runnable tasks */
5962 if (rq_h_nr_queued && !rq->cfs.h_nr_queued)
5963 dl_server_stop(&rq->fair_server);
5964 done:
5965 /*
5966 * Note: distribution will already see us throttled via the
5967 * throttled-list. rq->lock protects completion.
5968 */
5969 cfs_rq->throttled = 1;
5970 SCHED_WARN_ON(cfs_rq->throttled_clock);
5971 if (cfs_rq->nr_queued)
5972 cfs_rq->throttled_clock = rq_clock(rq);
5973 return true;
5974 }
5975
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5976 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5977 {
5978 struct rq *rq = rq_of(cfs_rq);
5979 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5980 struct sched_entity *se;
5981 long queued_delta, runnable_delta, idle_delta;
5982 long rq_h_nr_queued = rq->cfs.h_nr_queued;
5983
5984 se = cfs_rq->tg->se[cpu_of(rq)];
5985
5986 cfs_rq->throttled = 0;
5987
5988 update_rq_clock(rq);
5989
5990 raw_spin_lock(&cfs_b->lock);
5991 if (cfs_rq->throttled_clock) {
5992 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5993 cfs_rq->throttled_clock = 0;
5994 }
5995 list_del_rcu(&cfs_rq->throttled_list);
5996 raw_spin_unlock(&cfs_b->lock);
5997
5998 /* update hierarchical throttle state */
5999 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6000
6001 if (!cfs_rq->load.weight) {
6002 if (!cfs_rq->on_list)
6003 return;
6004 /*
6005 * Nothing to run but something to decay (on_list)?
6006 * Complete the branch.
6007 */
6008 for_each_sched_entity(se) {
6009 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6010 break;
6011 }
6012 goto unthrottle_throttle;
6013 }
6014
6015 queued_delta = cfs_rq->h_nr_queued;
6016 runnable_delta = cfs_rq->h_nr_runnable;
6017 idle_delta = cfs_rq->h_nr_idle;
6018 for_each_sched_entity(se) {
6019 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6020
6021 /* Handle any unfinished DELAY_DEQUEUE business first. */
6022 if (se->sched_delayed) {
6023 int flags = DEQUEUE_SLEEP | DEQUEUE_DELAYED;
6024
6025 dequeue_entity(qcfs_rq, se, flags);
6026 } else if (se->on_rq)
6027 break;
6028 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
6029
6030 if (cfs_rq_is_idle(group_cfs_rq(se)))
6031 idle_delta = cfs_rq->h_nr_queued;
6032
6033 qcfs_rq->h_nr_queued += queued_delta;
6034 qcfs_rq->h_nr_runnable += runnable_delta;
6035 qcfs_rq->h_nr_idle += idle_delta;
6036
6037 /* end evaluation on encountering a throttled cfs_rq */
6038 if (cfs_rq_throttled(qcfs_rq))
6039 goto unthrottle_throttle;
6040 }
6041
6042 for_each_sched_entity(se) {
6043 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
6044
6045 update_load_avg(qcfs_rq, se, UPDATE_TG);
6046 se_update_runnable(se);
6047
6048 if (cfs_rq_is_idle(group_cfs_rq(se)))
6049 idle_delta = cfs_rq->h_nr_queued;
6050
6051 qcfs_rq->h_nr_queued += queued_delta;
6052 qcfs_rq->h_nr_runnable += runnable_delta;
6053 qcfs_rq->h_nr_idle += idle_delta;
6054
6055 /* end evaluation on encountering a throttled cfs_rq */
6056 if (cfs_rq_throttled(qcfs_rq))
6057 goto unthrottle_throttle;
6058 }
6059
6060 /* Start the fair server if un-throttling resulted in new runnable tasks */
6061 if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
6062 dl_server_start(&rq->fair_server);
6063
6064 /* At this point se is NULL and we are at root level*/
6065 add_nr_running(rq, queued_delta);
6066
6067 unthrottle_throttle:
6068 assert_list_leaf_cfs_rq(rq);
6069
6070 /* Determine whether we need to wake up potentially idle CPU: */
6071 if (rq->curr == rq->idle && rq->cfs.nr_queued)
6072 resched_curr(rq);
6073 }
6074
6075 #ifdef CONFIG_SMP
__cfsb_csd_unthrottle(void * arg)6076 static void __cfsb_csd_unthrottle(void *arg)
6077 {
6078 struct cfs_rq *cursor, *tmp;
6079 struct rq *rq = arg;
6080 struct rq_flags rf;
6081
6082 rq_lock(rq, &rf);
6083
6084 /*
6085 * Iterating over the list can trigger several call to
6086 * update_rq_clock() in unthrottle_cfs_rq().
6087 * Do it once and skip the potential next ones.
6088 */
6089 update_rq_clock(rq);
6090 rq_clock_start_loop_update(rq);
6091
6092 /*
6093 * Since we hold rq lock we're safe from concurrent manipulation of
6094 * the CSD list. However, this RCU critical section annotates the
6095 * fact that we pair with sched_free_group_rcu(), so that we cannot
6096 * race with group being freed in the window between removing it
6097 * from the list and advancing to the next entry in the list.
6098 */
6099 rcu_read_lock();
6100
6101 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6102 throttled_csd_list) {
6103 list_del_init(&cursor->throttled_csd_list);
6104
6105 if (cfs_rq_throttled(cursor))
6106 unthrottle_cfs_rq(cursor);
6107 }
6108
6109 rcu_read_unlock();
6110
6111 rq_clock_stop_loop_update(rq);
6112 rq_unlock(rq, &rf);
6113 }
6114
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6115 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6116 {
6117 struct rq *rq = rq_of(cfs_rq);
6118 bool first;
6119
6120 if (rq == this_rq()) {
6121 unthrottle_cfs_rq(cfs_rq);
6122 return;
6123 }
6124
6125 /* Already enqueued */
6126 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
6127 return;
6128
6129 first = list_empty(&rq->cfsb_csd_list);
6130 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6131 if (first)
6132 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6133 }
6134 #else
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6135 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6136 {
6137 unthrottle_cfs_rq(cfs_rq);
6138 }
6139 #endif
6140
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6141 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6142 {
6143 lockdep_assert_rq_held(rq_of(cfs_rq));
6144
6145 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
6146 cfs_rq->runtime_remaining <= 0))
6147 return;
6148
6149 __unthrottle_cfs_rq_async(cfs_rq);
6150 }
6151
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6152 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6153 {
6154 int this_cpu = smp_processor_id();
6155 u64 runtime, remaining = 1;
6156 bool throttled = false;
6157 struct cfs_rq *cfs_rq, *tmp;
6158 struct rq_flags rf;
6159 struct rq *rq;
6160 LIST_HEAD(local_unthrottle);
6161
6162 rcu_read_lock();
6163 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6164 throttled_list) {
6165 rq = rq_of(cfs_rq);
6166
6167 if (!remaining) {
6168 throttled = true;
6169 break;
6170 }
6171
6172 rq_lock_irqsave(rq, &rf);
6173 if (!cfs_rq_throttled(cfs_rq))
6174 goto next;
6175
6176 /* Already queued for async unthrottle */
6177 if (!list_empty(&cfs_rq->throttled_csd_list))
6178 goto next;
6179
6180 /* By the above checks, this should never be true */
6181 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
6182
6183 raw_spin_lock(&cfs_b->lock);
6184 runtime = -cfs_rq->runtime_remaining + 1;
6185 if (runtime > cfs_b->runtime)
6186 runtime = cfs_b->runtime;
6187 cfs_b->runtime -= runtime;
6188 remaining = cfs_b->runtime;
6189 raw_spin_unlock(&cfs_b->lock);
6190
6191 cfs_rq->runtime_remaining += runtime;
6192
6193 /* we check whether we're throttled above */
6194 if (cfs_rq->runtime_remaining > 0) {
6195 if (cpu_of(rq) != this_cpu) {
6196 unthrottle_cfs_rq_async(cfs_rq);
6197 } else {
6198 /*
6199 * We currently only expect to be unthrottling
6200 * a single cfs_rq locally.
6201 */
6202 SCHED_WARN_ON(!list_empty(&local_unthrottle));
6203 list_add_tail(&cfs_rq->throttled_csd_list,
6204 &local_unthrottle);
6205 }
6206 } else {
6207 throttled = true;
6208 }
6209
6210 next:
6211 rq_unlock_irqrestore(rq, &rf);
6212 }
6213
6214 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6215 throttled_csd_list) {
6216 struct rq *rq = rq_of(cfs_rq);
6217
6218 rq_lock_irqsave(rq, &rf);
6219
6220 list_del_init(&cfs_rq->throttled_csd_list);
6221
6222 if (cfs_rq_throttled(cfs_rq))
6223 unthrottle_cfs_rq(cfs_rq);
6224
6225 rq_unlock_irqrestore(rq, &rf);
6226 }
6227 SCHED_WARN_ON(!list_empty(&local_unthrottle));
6228
6229 rcu_read_unlock();
6230
6231 return throttled;
6232 }
6233
6234 /*
6235 * Responsible for refilling a task_group's bandwidth and unthrottling its
6236 * cfs_rqs as appropriate. If there has been no activity within the last
6237 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6238 * used to track this state.
6239 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6240 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6241 {
6242 int throttled;
6243
6244 /* no need to continue the timer with no bandwidth constraint */
6245 if (cfs_b->quota == RUNTIME_INF)
6246 goto out_deactivate;
6247
6248 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6249 cfs_b->nr_periods += overrun;
6250
6251 /* Refill extra burst quota even if cfs_b->idle */
6252 __refill_cfs_bandwidth_runtime(cfs_b);
6253
6254 /*
6255 * idle depends on !throttled (for the case of a large deficit), and if
6256 * we're going inactive then everything else can be deferred
6257 */
6258 if (cfs_b->idle && !throttled)
6259 goto out_deactivate;
6260
6261 if (!throttled) {
6262 /* mark as potentially idle for the upcoming period */
6263 cfs_b->idle = 1;
6264 return 0;
6265 }
6266
6267 /* account preceding periods in which throttling occurred */
6268 cfs_b->nr_throttled += overrun;
6269
6270 /*
6271 * This check is repeated as we release cfs_b->lock while we unthrottle.
6272 */
6273 while (throttled && cfs_b->runtime > 0) {
6274 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6275 /* we can't nest cfs_b->lock while distributing bandwidth */
6276 throttled = distribute_cfs_runtime(cfs_b);
6277 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6278 }
6279
6280 /*
6281 * While we are ensured activity in the period following an
6282 * unthrottle, this also covers the case in which the new bandwidth is
6283 * insufficient to cover the existing bandwidth deficit. (Forcing the
6284 * timer to remain active while there are any throttled entities.)
6285 */
6286 cfs_b->idle = 0;
6287
6288 return 0;
6289
6290 out_deactivate:
6291 return 1;
6292 }
6293
6294 /* a cfs_rq won't donate quota below this amount */
6295 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6296 /* minimum remaining period time to redistribute slack quota */
6297 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6298 /* how long we wait to gather additional slack before distributing */
6299 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6300
6301 /*
6302 * Are we near the end of the current quota period?
6303 *
6304 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6305 * hrtimer base being cleared by hrtimer_start. In the case of
6306 * migrate_hrtimers, base is never cleared, so we are fine.
6307 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6308 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6309 {
6310 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6311 s64 remaining;
6312
6313 /* if the call-back is running a quota refresh is already occurring */
6314 if (hrtimer_callback_running(refresh_timer))
6315 return 1;
6316
6317 /* is a quota refresh about to occur? */
6318 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6319 if (remaining < (s64)min_expire)
6320 return 1;
6321
6322 return 0;
6323 }
6324
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6325 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6326 {
6327 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6328
6329 /* if there's a quota refresh soon don't bother with slack */
6330 if (runtime_refresh_within(cfs_b, min_left))
6331 return;
6332
6333 /* don't push forwards an existing deferred unthrottle */
6334 if (cfs_b->slack_started)
6335 return;
6336 cfs_b->slack_started = true;
6337
6338 hrtimer_start(&cfs_b->slack_timer,
6339 ns_to_ktime(cfs_bandwidth_slack_period),
6340 HRTIMER_MODE_REL);
6341 }
6342
6343 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6344 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6345 {
6346 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6347 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6348
6349 if (slack_runtime <= 0)
6350 return;
6351
6352 raw_spin_lock(&cfs_b->lock);
6353 if (cfs_b->quota != RUNTIME_INF) {
6354 cfs_b->runtime += slack_runtime;
6355
6356 /* we are under rq->lock, defer unthrottling using a timer */
6357 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6358 !list_empty(&cfs_b->throttled_cfs_rq))
6359 start_cfs_slack_bandwidth(cfs_b);
6360 }
6361 raw_spin_unlock(&cfs_b->lock);
6362
6363 /* even if it's not valid for return we don't want to try again */
6364 cfs_rq->runtime_remaining -= slack_runtime;
6365 }
6366
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6367 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6368 {
6369 if (!cfs_bandwidth_used())
6370 return;
6371
6372 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6373 return;
6374
6375 __return_cfs_rq_runtime(cfs_rq);
6376 }
6377
6378 /*
6379 * This is done with a timer (instead of inline with bandwidth return) since
6380 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6381 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6382 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6383 {
6384 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6385 unsigned long flags;
6386
6387 /* confirm we're still not at a refresh boundary */
6388 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6389 cfs_b->slack_started = false;
6390
6391 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6392 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6393 return;
6394 }
6395
6396 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6397 runtime = cfs_b->runtime;
6398
6399 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6400
6401 if (!runtime)
6402 return;
6403
6404 distribute_cfs_runtime(cfs_b);
6405 }
6406
6407 /*
6408 * When a group wakes up we want to make sure that its quota is not already
6409 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6410 * runtime as update_curr() throttling can not trigger until it's on-rq.
6411 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6412 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6413 {
6414 if (!cfs_bandwidth_used())
6415 return;
6416
6417 /* an active group must be handled by the update_curr()->put() path */
6418 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6419 return;
6420
6421 /* ensure the group is not already throttled */
6422 if (cfs_rq_throttled(cfs_rq))
6423 return;
6424
6425 /* update runtime allocation */
6426 account_cfs_rq_runtime(cfs_rq, 0);
6427 if (cfs_rq->runtime_remaining <= 0)
6428 throttle_cfs_rq(cfs_rq);
6429 }
6430
sync_throttle(struct task_group * tg,int cpu)6431 static void sync_throttle(struct task_group *tg, int cpu)
6432 {
6433 struct cfs_rq *pcfs_rq, *cfs_rq;
6434
6435 if (!cfs_bandwidth_used())
6436 return;
6437
6438 if (!tg->parent)
6439 return;
6440
6441 cfs_rq = tg->cfs_rq[cpu];
6442 pcfs_rq = tg->parent->cfs_rq[cpu];
6443
6444 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6445 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6446 }
6447
6448 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6449 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6450 {
6451 if (!cfs_bandwidth_used())
6452 return false;
6453
6454 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6455 return false;
6456
6457 /*
6458 * it's possible for a throttled entity to be forced into a running
6459 * state (e.g. set_curr_task), in this case we're finished.
6460 */
6461 if (cfs_rq_throttled(cfs_rq))
6462 return true;
6463
6464 return throttle_cfs_rq(cfs_rq);
6465 }
6466
sched_cfs_slack_timer(struct hrtimer * timer)6467 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6468 {
6469 struct cfs_bandwidth *cfs_b =
6470 container_of(timer, struct cfs_bandwidth, slack_timer);
6471
6472 do_sched_cfs_slack_timer(cfs_b);
6473
6474 return HRTIMER_NORESTART;
6475 }
6476
6477 extern const u64 max_cfs_quota_period;
6478
sched_cfs_period_timer(struct hrtimer * timer)6479 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6480 {
6481 struct cfs_bandwidth *cfs_b =
6482 container_of(timer, struct cfs_bandwidth, period_timer);
6483 unsigned long flags;
6484 int overrun;
6485 int idle = 0;
6486 int count = 0;
6487
6488 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6489 for (;;) {
6490 overrun = hrtimer_forward_now(timer, cfs_b->period);
6491 if (!overrun)
6492 break;
6493
6494 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6495
6496 if (++count > 3) {
6497 u64 new, old = ktime_to_ns(cfs_b->period);
6498
6499 /*
6500 * Grow period by a factor of 2 to avoid losing precision.
6501 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6502 * to fail.
6503 */
6504 new = old * 2;
6505 if (new < max_cfs_quota_period) {
6506 cfs_b->period = ns_to_ktime(new);
6507 cfs_b->quota *= 2;
6508 cfs_b->burst *= 2;
6509
6510 pr_warn_ratelimited(
6511 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6512 smp_processor_id(),
6513 div_u64(new, NSEC_PER_USEC),
6514 div_u64(cfs_b->quota, NSEC_PER_USEC));
6515 } else {
6516 pr_warn_ratelimited(
6517 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6518 smp_processor_id(),
6519 div_u64(old, NSEC_PER_USEC),
6520 div_u64(cfs_b->quota, NSEC_PER_USEC));
6521 }
6522
6523 /* reset count so we don't come right back in here */
6524 count = 0;
6525 }
6526 }
6527 if (idle)
6528 cfs_b->period_active = 0;
6529 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6530
6531 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6532 }
6533
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6534 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6535 {
6536 raw_spin_lock_init(&cfs_b->lock);
6537 cfs_b->runtime = 0;
6538 cfs_b->quota = RUNTIME_INF;
6539 cfs_b->period = ns_to_ktime(default_cfs_period());
6540 cfs_b->burst = 0;
6541 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6542
6543 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6544 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6545 cfs_b->period_timer.function = sched_cfs_period_timer;
6546
6547 /* Add a random offset so that timers interleave */
6548 hrtimer_set_expires(&cfs_b->period_timer,
6549 get_random_u32_below(cfs_b->period));
6550 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6551 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6552 cfs_b->slack_started = false;
6553 }
6554
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6555 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6556 {
6557 cfs_rq->runtime_enabled = 0;
6558 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6559 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6560 }
6561
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6562 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6563 {
6564 lockdep_assert_held(&cfs_b->lock);
6565
6566 if (cfs_b->period_active)
6567 return;
6568
6569 cfs_b->period_active = 1;
6570 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6571 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6572 }
6573
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6574 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6575 {
6576 int __maybe_unused i;
6577
6578 /* init_cfs_bandwidth() was not called */
6579 if (!cfs_b->throttled_cfs_rq.next)
6580 return;
6581
6582 hrtimer_cancel(&cfs_b->period_timer);
6583 hrtimer_cancel(&cfs_b->slack_timer);
6584
6585 /*
6586 * It is possible that we still have some cfs_rq's pending on a CSD
6587 * list, though this race is very rare. In order for this to occur, we
6588 * must have raced with the last task leaving the group while there
6589 * exist throttled cfs_rq(s), and the period_timer must have queued the
6590 * CSD item but the remote cpu has not yet processed it. To handle this,
6591 * we can simply flush all pending CSD work inline here. We're
6592 * guaranteed at this point that no additional cfs_rq of this group can
6593 * join a CSD list.
6594 */
6595 #ifdef CONFIG_SMP
6596 for_each_possible_cpu(i) {
6597 struct rq *rq = cpu_rq(i);
6598 unsigned long flags;
6599
6600 if (list_empty(&rq->cfsb_csd_list))
6601 continue;
6602
6603 local_irq_save(flags);
6604 __cfsb_csd_unthrottle(rq);
6605 local_irq_restore(flags);
6606 }
6607 #endif
6608 }
6609
6610 /*
6611 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6612 *
6613 * The race is harmless, since modifying bandwidth settings of unhooked group
6614 * bits doesn't do much.
6615 */
6616
6617 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6618 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6619 {
6620 struct task_group *tg;
6621
6622 lockdep_assert_rq_held(rq);
6623
6624 rcu_read_lock();
6625 list_for_each_entry_rcu(tg, &task_groups, list) {
6626 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6627 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6628
6629 raw_spin_lock(&cfs_b->lock);
6630 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6631 raw_spin_unlock(&cfs_b->lock);
6632 }
6633 rcu_read_unlock();
6634 }
6635
6636 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6637 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6638 {
6639 struct task_group *tg;
6640
6641 lockdep_assert_rq_held(rq);
6642
6643 // Do not unthrottle for an active CPU
6644 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6645 return;
6646
6647 /*
6648 * The rq clock has already been updated in the
6649 * set_rq_offline(), so we should skip updating
6650 * the rq clock again in unthrottle_cfs_rq().
6651 */
6652 rq_clock_start_loop_update(rq);
6653
6654 rcu_read_lock();
6655 list_for_each_entry_rcu(tg, &task_groups, list) {
6656 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6657
6658 if (!cfs_rq->runtime_enabled)
6659 continue;
6660
6661 /*
6662 * Offline rq is schedulable till CPU is completely disabled
6663 * in take_cpu_down(), so we prevent new cfs throttling here.
6664 */
6665 cfs_rq->runtime_enabled = 0;
6666
6667 if (!cfs_rq_throttled(cfs_rq))
6668 continue;
6669
6670 /*
6671 * clock_task is not advancing so we just need to make sure
6672 * there's some valid quota amount
6673 */
6674 cfs_rq->runtime_remaining = 1;
6675 unthrottle_cfs_rq(cfs_rq);
6676 }
6677 rcu_read_unlock();
6678
6679 rq_clock_stop_loop_update(rq);
6680 }
6681
cfs_task_bw_constrained(struct task_struct * p)6682 bool cfs_task_bw_constrained(struct task_struct *p)
6683 {
6684 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6685
6686 if (!cfs_bandwidth_used())
6687 return false;
6688
6689 if (cfs_rq->runtime_enabled ||
6690 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6691 return true;
6692
6693 return false;
6694 }
6695
6696 #ifdef CONFIG_NO_HZ_FULL
6697 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6698 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6699 {
6700 int cpu = cpu_of(rq);
6701
6702 if (!cfs_bandwidth_used())
6703 return;
6704
6705 if (!tick_nohz_full_cpu(cpu))
6706 return;
6707
6708 if (rq->nr_running != 1)
6709 return;
6710
6711 /*
6712 * We know there is only one task runnable and we've just picked it. The
6713 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6714 * be otherwise able to stop the tick. Just need to check if we are using
6715 * bandwidth control.
6716 */
6717 if (cfs_task_bw_constrained(p))
6718 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6719 }
6720 #endif
6721
6722 #else /* CONFIG_CFS_BANDWIDTH */
6723
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6724 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6725 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6726 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6727 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6728 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6729
cfs_rq_throttled(struct cfs_rq * cfs_rq)6730 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6731 {
6732 return 0;
6733 }
6734
throttled_hierarchy(struct cfs_rq * cfs_rq)6735 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6736 {
6737 return 0;
6738 }
6739
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)6740 static inline int throttled_lb_pair(struct task_group *tg,
6741 int src_cpu, int dest_cpu)
6742 {
6743 return 0;
6744 }
6745
6746 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6747 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6748 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6749 #endif
6750
tg_cfs_bandwidth(struct task_group * tg)6751 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6752 {
6753 return NULL;
6754 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6755 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6756 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6757 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6758 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6759 bool cfs_task_bw_constrained(struct task_struct *p)
6760 {
6761 return false;
6762 }
6763 #endif
6764 #endif /* CONFIG_CFS_BANDWIDTH */
6765
6766 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6767 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6768 #endif
6769
6770 /**************************************************
6771 * CFS operations on tasks:
6772 */
6773
6774 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6775 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6776 {
6777 struct sched_entity *se = &p->se;
6778
6779 SCHED_WARN_ON(task_rq(p) != rq);
6780
6781 if (rq->cfs.h_nr_queued > 1) {
6782 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6783 u64 slice = se->slice;
6784 s64 delta = slice - ran;
6785
6786 if (delta < 0) {
6787 if (task_current_donor(rq, p))
6788 resched_curr(rq);
6789 return;
6790 }
6791 hrtick_start(rq, delta);
6792 }
6793 }
6794
6795 /*
6796 * called from enqueue/dequeue and updates the hrtick when the
6797 * current task is from our class and nr_running is low enough
6798 * to matter.
6799 */
hrtick_update(struct rq * rq)6800 static void hrtick_update(struct rq *rq)
6801 {
6802 struct task_struct *donor = rq->donor;
6803
6804 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
6805 return;
6806
6807 hrtick_start_fair(rq, donor);
6808 }
6809 #else /* !CONFIG_SCHED_HRTICK */
6810 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6811 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6812 {
6813 }
6814
hrtick_update(struct rq * rq)6815 static inline void hrtick_update(struct rq *rq)
6816 {
6817 }
6818 #endif
6819
6820 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)6821 static inline bool cpu_overutilized(int cpu)
6822 {
6823 unsigned long rq_util_min, rq_util_max;
6824
6825 if (!sched_energy_enabled())
6826 return false;
6827
6828 rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6829 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6830
6831 /* Return true only if the utilization doesn't fit CPU's capacity */
6832 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6833 }
6834
6835 /*
6836 * overutilized value make sense only if EAS is enabled
6837 */
is_rd_overutilized(struct root_domain * rd)6838 static inline bool is_rd_overutilized(struct root_domain *rd)
6839 {
6840 return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
6841 }
6842
set_rd_overutilized(struct root_domain * rd,bool flag)6843 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
6844 {
6845 if (!sched_energy_enabled())
6846 return;
6847
6848 WRITE_ONCE(rd->overutilized, flag);
6849 trace_sched_overutilized_tp(rd, flag);
6850 }
6851
check_update_overutilized_status(struct rq * rq)6852 static inline void check_update_overutilized_status(struct rq *rq)
6853 {
6854 /*
6855 * overutilized field is used for load balancing decisions only
6856 * if energy aware scheduler is being used
6857 */
6858
6859 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
6860 set_rd_overutilized(rq->rd, 1);
6861 }
6862 #else
check_update_overutilized_status(struct rq * rq)6863 static inline void check_update_overutilized_status(struct rq *rq) { }
6864 #endif
6865
6866 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6867 static int sched_idle_rq(struct rq *rq)
6868 {
6869 return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
6870 rq->nr_running);
6871 }
6872
6873 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)6874 static int sched_idle_cpu(int cpu)
6875 {
6876 return sched_idle_rq(cpu_rq(cpu));
6877 }
6878 #endif
6879
6880 static void
requeue_delayed_entity(struct sched_entity * se)6881 requeue_delayed_entity(struct sched_entity *se)
6882 {
6883 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6884
6885 /*
6886 * se->sched_delayed should imply: se->on_rq == 1.
6887 * Because a delayed entity is one that is still on
6888 * the runqueue competing until elegibility.
6889 */
6890 SCHED_WARN_ON(!se->sched_delayed);
6891 SCHED_WARN_ON(!se->on_rq);
6892
6893 if (sched_feat(DELAY_ZERO)) {
6894 update_entity_lag(cfs_rq, se);
6895 if (se->vlag > 0) {
6896 cfs_rq->nr_queued--;
6897 if (se != cfs_rq->curr)
6898 __dequeue_entity(cfs_rq, se);
6899 se->vlag = 0;
6900 place_entity(cfs_rq, se, 0);
6901 if (se != cfs_rq->curr)
6902 __enqueue_entity(cfs_rq, se);
6903 cfs_rq->nr_queued++;
6904 }
6905 }
6906
6907 update_load_avg(cfs_rq, se, 0);
6908 clear_delayed(se);
6909 }
6910
6911 /*
6912 * The enqueue_task method is called before nr_running is
6913 * increased. Here we update the fair scheduling stats and
6914 * then put the task into the rbtree:
6915 */
6916 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6917 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6918 {
6919 struct cfs_rq *cfs_rq;
6920 struct sched_entity *se = &p->se;
6921 int h_nr_idle = task_has_idle_policy(p);
6922 int h_nr_runnable = 1;
6923 int task_new = !(flags & ENQUEUE_WAKEUP);
6924 int rq_h_nr_queued = rq->cfs.h_nr_queued;
6925 u64 slice = 0;
6926
6927 /*
6928 * The code below (indirectly) updates schedutil which looks at
6929 * the cfs_rq utilization to select a frequency.
6930 * Let's add the task's estimated utilization to the cfs_rq's
6931 * estimated utilization, before we update schedutil.
6932 */
6933 if (!(p->se.sched_delayed && (task_on_rq_migrating(p) || (flags & ENQUEUE_RESTORE))))
6934 util_est_enqueue(&rq->cfs, p);
6935
6936 if (flags & ENQUEUE_DELAYED) {
6937 requeue_delayed_entity(se);
6938 return;
6939 }
6940
6941 /*
6942 * If in_iowait is set, the code below may not trigger any cpufreq
6943 * utilization updates, so do it here explicitly with the IOWAIT flag
6944 * passed.
6945 */
6946 if (p->in_iowait)
6947 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6948
6949 if (task_new && se->sched_delayed)
6950 h_nr_runnable = 0;
6951
6952 for_each_sched_entity(se) {
6953 if (se->on_rq) {
6954 if (se->sched_delayed)
6955 requeue_delayed_entity(se);
6956 break;
6957 }
6958 cfs_rq = cfs_rq_of(se);
6959
6960 /*
6961 * Basically set the slice of group entries to the min_slice of
6962 * their respective cfs_rq. This ensures the group can service
6963 * its entities in the desired time-frame.
6964 */
6965 if (slice) {
6966 se->slice = slice;
6967 se->custom_slice = 1;
6968 }
6969 enqueue_entity(cfs_rq, se, flags);
6970 slice = cfs_rq_min_slice(cfs_rq);
6971
6972 cfs_rq->h_nr_runnable += h_nr_runnable;
6973 cfs_rq->h_nr_queued++;
6974 cfs_rq->h_nr_idle += h_nr_idle;
6975
6976 if (cfs_rq_is_idle(cfs_rq))
6977 h_nr_idle = 1;
6978
6979 /* end evaluation on encountering a throttled cfs_rq */
6980 if (cfs_rq_throttled(cfs_rq))
6981 goto enqueue_throttle;
6982
6983 flags = ENQUEUE_WAKEUP;
6984 }
6985
6986 for_each_sched_entity(se) {
6987 cfs_rq = cfs_rq_of(se);
6988
6989 update_load_avg(cfs_rq, se, UPDATE_TG);
6990 se_update_runnable(se);
6991 update_cfs_group(se);
6992
6993 se->slice = slice;
6994 slice = cfs_rq_min_slice(cfs_rq);
6995
6996 cfs_rq->h_nr_runnable += h_nr_runnable;
6997 cfs_rq->h_nr_queued++;
6998 cfs_rq->h_nr_idle += h_nr_idle;
6999
7000 if (cfs_rq_is_idle(cfs_rq))
7001 h_nr_idle = 1;
7002
7003 /* end evaluation on encountering a throttled cfs_rq */
7004 if (cfs_rq_throttled(cfs_rq))
7005 goto enqueue_throttle;
7006 }
7007
7008 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) {
7009 /* Account for idle runtime */
7010 if (!rq->nr_running)
7011 dl_server_update_idle_time(rq, rq->curr);
7012 dl_server_start(&rq->fair_server);
7013 }
7014
7015 /* At this point se is NULL and we are at root level*/
7016 add_nr_running(rq, 1);
7017
7018 /*
7019 * Since new tasks are assigned an initial util_avg equal to
7020 * half of the spare capacity of their CPU, tiny tasks have the
7021 * ability to cross the overutilized threshold, which will
7022 * result in the load balancer ruining all the task placement
7023 * done by EAS. As a way to mitigate that effect, do not account
7024 * for the first enqueue operation of new tasks during the
7025 * overutilized flag detection.
7026 *
7027 * A better way of solving this problem would be to wait for
7028 * the PELT signals of tasks to converge before taking them
7029 * into account, but that is not straightforward to implement,
7030 * and the following generally works well enough in practice.
7031 */
7032 if (!task_new)
7033 check_update_overutilized_status(rq);
7034
7035 enqueue_throttle:
7036 assert_list_leaf_cfs_rq(rq);
7037
7038 hrtick_update(rq);
7039 }
7040
7041 static void set_next_buddy(struct sched_entity *se);
7042
7043 /*
7044 * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
7045 * failing half-way through and resume the dequeue later.
7046 *
7047 * Returns:
7048 * -1 - dequeue delayed
7049 * 0 - dequeue throttled
7050 * 1 - dequeue complete
7051 */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)7052 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7053 {
7054 bool was_sched_idle = sched_idle_rq(rq);
7055 int rq_h_nr_queued = rq->cfs.h_nr_queued;
7056 bool task_sleep = flags & DEQUEUE_SLEEP;
7057 bool task_delayed = flags & DEQUEUE_DELAYED;
7058 struct task_struct *p = NULL;
7059 int h_nr_idle = 0;
7060 int h_nr_queued = 0;
7061 int h_nr_runnable = 0;
7062 struct cfs_rq *cfs_rq;
7063 u64 slice = 0;
7064
7065 if (entity_is_task(se)) {
7066 p = task_of(se);
7067 h_nr_queued = 1;
7068 h_nr_idle = task_has_idle_policy(p);
7069 if (task_sleep || task_delayed || !se->sched_delayed)
7070 h_nr_runnable = 1;
7071 } else {
7072 cfs_rq = group_cfs_rq(se);
7073 slice = cfs_rq_min_slice(cfs_rq);
7074 }
7075
7076 for_each_sched_entity(se) {
7077 cfs_rq = cfs_rq_of(se);
7078
7079 if (!dequeue_entity(cfs_rq, se, flags)) {
7080 if (p && &p->se == se)
7081 return -1;
7082
7083 break;
7084 }
7085
7086 cfs_rq->h_nr_runnable -= h_nr_runnable;
7087 cfs_rq->h_nr_queued -= h_nr_queued;
7088 cfs_rq->h_nr_idle -= h_nr_idle;
7089
7090 if (cfs_rq_is_idle(cfs_rq))
7091 h_nr_idle = h_nr_queued;
7092
7093 /* end evaluation on encountering a throttled cfs_rq */
7094 if (cfs_rq_throttled(cfs_rq))
7095 return 0;
7096
7097 /* Don't dequeue parent if it has other entities besides us */
7098 if (cfs_rq->load.weight) {
7099 slice = cfs_rq_min_slice(cfs_rq);
7100
7101 /* Avoid re-evaluating load for this entity: */
7102 se = parent_entity(se);
7103 /*
7104 * Bias pick_next to pick a task from this cfs_rq, as
7105 * p is sleeping when it is within its sched_slice.
7106 */
7107 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
7108 set_next_buddy(se);
7109 break;
7110 }
7111 flags |= DEQUEUE_SLEEP;
7112 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7113 }
7114
7115 for_each_sched_entity(se) {
7116 cfs_rq = cfs_rq_of(se);
7117
7118 update_load_avg(cfs_rq, se, UPDATE_TG);
7119 se_update_runnable(se);
7120 update_cfs_group(se);
7121
7122 se->slice = slice;
7123 slice = cfs_rq_min_slice(cfs_rq);
7124
7125 cfs_rq->h_nr_runnable -= h_nr_runnable;
7126 cfs_rq->h_nr_queued -= h_nr_queued;
7127 cfs_rq->h_nr_idle -= h_nr_idle;
7128
7129 if (cfs_rq_is_idle(cfs_rq))
7130 h_nr_idle = h_nr_queued;
7131
7132 /* end evaluation on encountering a throttled cfs_rq */
7133 if (cfs_rq_throttled(cfs_rq))
7134 return 0;
7135 }
7136
7137 sub_nr_running(rq, h_nr_queued);
7138
7139 if (rq_h_nr_queued && !rq->cfs.h_nr_queued)
7140 dl_server_stop(&rq->fair_server);
7141
7142 /* balance early to pull high priority tasks */
7143 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7144 rq->next_balance = jiffies;
7145
7146 if (p && task_delayed) {
7147 SCHED_WARN_ON(!task_sleep);
7148 SCHED_WARN_ON(p->on_rq != 1);
7149
7150 /* Fix-up what dequeue_task_fair() skipped */
7151 hrtick_update(rq);
7152
7153 /*
7154 * Fix-up what block_task() skipped.
7155 *
7156 * Must be last, @p might not be valid after this.
7157 */
7158 __block_task(rq, p);
7159 }
7160
7161 return 1;
7162 }
7163
7164 /*
7165 * The dequeue_task method is called before nr_running is
7166 * decreased. We remove the task from the rbtree and
7167 * update the fair scheduling stats:
7168 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7169 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7170 {
7171 if (!(p->se.sched_delayed && (task_on_rq_migrating(p) || (flags & DEQUEUE_SAVE))))
7172 util_est_dequeue(&rq->cfs, p);
7173
7174 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7175 if (dequeue_entities(rq, &p->se, flags) < 0)
7176 return false;
7177
7178 /*
7179 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7180 */
7181
7182 hrtick_update(rq);
7183 return true;
7184 }
7185
7186 #ifdef CONFIG_SMP
7187
7188 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7189 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7190 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7191 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7192
7193 #ifdef CONFIG_NO_HZ_COMMON
7194
7195 static struct {
7196 cpumask_var_t idle_cpus_mask;
7197 atomic_t nr_cpus;
7198 int has_blocked; /* Idle CPUS has blocked load */
7199 int needs_update; /* Newly idle CPUs need their next_balance collated */
7200 unsigned long next_balance; /* in jiffy units */
7201 unsigned long next_blocked; /* Next update of blocked load in jiffies */
7202 } nohz ____cacheline_aligned;
7203
7204 #endif /* CONFIG_NO_HZ_COMMON */
7205
cpu_load(struct rq * rq)7206 static unsigned long cpu_load(struct rq *rq)
7207 {
7208 return cfs_rq_load_avg(&rq->cfs);
7209 }
7210
7211 /*
7212 * cpu_load_without - compute CPU load without any contributions from *p
7213 * @cpu: the CPU which load is requested
7214 * @p: the task which load should be discounted
7215 *
7216 * The load of a CPU is defined by the load of tasks currently enqueued on that
7217 * CPU as well as tasks which are currently sleeping after an execution on that
7218 * CPU.
7219 *
7220 * This method returns the load of the specified CPU by discounting the load of
7221 * the specified task, whenever the task is currently contributing to the CPU
7222 * load.
7223 */
cpu_load_without(struct rq * rq,struct task_struct * p)7224 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7225 {
7226 struct cfs_rq *cfs_rq;
7227 unsigned int load;
7228
7229 /* Task has no contribution or is new */
7230 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7231 return cpu_load(rq);
7232
7233 cfs_rq = &rq->cfs;
7234 load = READ_ONCE(cfs_rq->avg.load_avg);
7235
7236 /* Discount task's util from CPU's util */
7237 lsub_positive(&load, task_h_load(p));
7238
7239 return load;
7240 }
7241
cpu_runnable(struct rq * rq)7242 static unsigned long cpu_runnable(struct rq *rq)
7243 {
7244 return cfs_rq_runnable_avg(&rq->cfs);
7245 }
7246
cpu_runnable_without(struct rq * rq,struct task_struct * p)7247 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7248 {
7249 struct cfs_rq *cfs_rq;
7250 unsigned int runnable;
7251
7252 /* Task has no contribution or is new */
7253 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7254 return cpu_runnable(rq);
7255
7256 cfs_rq = &rq->cfs;
7257 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7258
7259 /* Discount task's runnable from CPU's runnable */
7260 lsub_positive(&runnable, p->se.avg.runnable_avg);
7261
7262 return runnable;
7263 }
7264
capacity_of(int cpu)7265 static unsigned long capacity_of(int cpu)
7266 {
7267 return cpu_rq(cpu)->cpu_capacity;
7268 }
7269
record_wakee(struct task_struct * p)7270 static void record_wakee(struct task_struct *p)
7271 {
7272 /*
7273 * Only decay a single time; tasks that have less then 1 wakeup per
7274 * jiffy will not have built up many flips.
7275 */
7276 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7277 current->wakee_flips >>= 1;
7278 current->wakee_flip_decay_ts = jiffies;
7279 }
7280
7281 if (current->last_wakee != p) {
7282 current->last_wakee = p;
7283 current->wakee_flips++;
7284 }
7285 }
7286
7287 /*
7288 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7289 *
7290 * A waker of many should wake a different task than the one last awakened
7291 * at a frequency roughly N times higher than one of its wakees.
7292 *
7293 * In order to determine whether we should let the load spread vs consolidating
7294 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7295 * partner, and a factor of lls_size higher frequency in the other.
7296 *
7297 * With both conditions met, we can be relatively sure that the relationship is
7298 * non-monogamous, with partner count exceeding socket size.
7299 *
7300 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7301 * whatever is irrelevant, spread criteria is apparent partner count exceeds
7302 * socket size.
7303 */
wake_wide(struct task_struct * p)7304 static int wake_wide(struct task_struct *p)
7305 {
7306 unsigned int master = current->wakee_flips;
7307 unsigned int slave = p->wakee_flips;
7308 int factor = __this_cpu_read(sd_llc_size);
7309
7310 if (master < slave)
7311 swap(master, slave);
7312 if (slave < factor || master < slave * factor)
7313 return 0;
7314 return 1;
7315 }
7316
7317 /*
7318 * The purpose of wake_affine() is to quickly determine on which CPU we can run
7319 * soonest. For the purpose of speed we only consider the waking and previous
7320 * CPU.
7321 *
7322 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7323 * cache-affine and is (or will be) idle.
7324 *
7325 * wake_affine_weight() - considers the weight to reflect the average
7326 * scheduling latency of the CPUs. This seems to work
7327 * for the overloaded case.
7328 */
7329 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7330 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7331 {
7332 /*
7333 * If this_cpu is idle, it implies the wakeup is from interrupt
7334 * context. Only allow the move if cache is shared. Otherwise an
7335 * interrupt intensive workload could force all tasks onto one
7336 * node depending on the IO topology or IRQ affinity settings.
7337 *
7338 * If the prev_cpu is idle and cache affine then avoid a migration.
7339 * There is no guarantee that the cache hot data from an interrupt
7340 * is more important than cache hot data on the prev_cpu and from
7341 * a cpufreq perspective, it's better to have higher utilisation
7342 * on one CPU.
7343 */
7344 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7345 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7346
7347 if (sync && cpu_rq(this_cpu)->nr_running == 1)
7348 return this_cpu;
7349
7350 if (available_idle_cpu(prev_cpu))
7351 return prev_cpu;
7352
7353 return nr_cpumask_bits;
7354 }
7355
7356 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7357 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7358 int this_cpu, int prev_cpu, int sync)
7359 {
7360 s64 this_eff_load, prev_eff_load;
7361 unsigned long task_load;
7362
7363 this_eff_load = cpu_load(cpu_rq(this_cpu));
7364
7365 if (sync) {
7366 unsigned long current_load = task_h_load(current);
7367
7368 if (current_load > this_eff_load)
7369 return this_cpu;
7370
7371 this_eff_load -= current_load;
7372 }
7373
7374 task_load = task_h_load(p);
7375
7376 this_eff_load += task_load;
7377 if (sched_feat(WA_BIAS))
7378 this_eff_load *= 100;
7379 this_eff_load *= capacity_of(prev_cpu);
7380
7381 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7382 prev_eff_load -= task_load;
7383 if (sched_feat(WA_BIAS))
7384 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7385 prev_eff_load *= capacity_of(this_cpu);
7386
7387 /*
7388 * If sync, adjust the weight of prev_eff_load such that if
7389 * prev_eff == this_eff that select_idle_sibling() will consider
7390 * stacking the wakee on top of the waker if no other CPU is
7391 * idle.
7392 */
7393 if (sync)
7394 prev_eff_load += 1;
7395
7396 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7397 }
7398
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7399 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7400 int this_cpu, int prev_cpu, int sync)
7401 {
7402 int target = nr_cpumask_bits;
7403
7404 if (sched_feat(WA_IDLE))
7405 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7406
7407 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7408 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7409
7410 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7411 if (target != this_cpu)
7412 return prev_cpu;
7413
7414 schedstat_inc(sd->ttwu_move_affine);
7415 schedstat_inc(p->stats.nr_wakeups_affine);
7416 return target;
7417 }
7418
7419 static struct sched_group *
7420 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7421
7422 /*
7423 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7424 */
7425 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7426 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7427 {
7428 unsigned long load, min_load = ULONG_MAX;
7429 unsigned int min_exit_latency = UINT_MAX;
7430 u64 latest_idle_timestamp = 0;
7431 int least_loaded_cpu = this_cpu;
7432 int shallowest_idle_cpu = -1;
7433 int i;
7434
7435 /* Check if we have any choice: */
7436 if (group->group_weight == 1)
7437 return cpumask_first(sched_group_span(group));
7438
7439 /* Traverse only the allowed CPUs */
7440 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7441 struct rq *rq = cpu_rq(i);
7442
7443 if (!sched_core_cookie_match(rq, p))
7444 continue;
7445
7446 if (sched_idle_cpu(i))
7447 return i;
7448
7449 if (available_idle_cpu(i)) {
7450 struct cpuidle_state *idle = idle_get_state(rq);
7451 if (idle && idle->exit_latency < min_exit_latency) {
7452 /*
7453 * We give priority to a CPU whose idle state
7454 * has the smallest exit latency irrespective
7455 * of any idle timestamp.
7456 */
7457 min_exit_latency = idle->exit_latency;
7458 latest_idle_timestamp = rq->idle_stamp;
7459 shallowest_idle_cpu = i;
7460 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7461 rq->idle_stamp > latest_idle_timestamp) {
7462 /*
7463 * If equal or no active idle state, then
7464 * the most recently idled CPU might have
7465 * a warmer cache.
7466 */
7467 latest_idle_timestamp = rq->idle_stamp;
7468 shallowest_idle_cpu = i;
7469 }
7470 } else if (shallowest_idle_cpu == -1) {
7471 load = cpu_load(cpu_rq(i));
7472 if (load < min_load) {
7473 min_load = load;
7474 least_loaded_cpu = i;
7475 }
7476 }
7477 }
7478
7479 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7480 }
7481
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7482 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7483 int cpu, int prev_cpu, int sd_flag)
7484 {
7485 int new_cpu = cpu;
7486
7487 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7488 return prev_cpu;
7489
7490 /*
7491 * We need task's util for cpu_util_without, sync it up to
7492 * prev_cpu's last_update_time.
7493 */
7494 if (!(sd_flag & SD_BALANCE_FORK))
7495 sync_entity_load_avg(&p->se);
7496
7497 while (sd) {
7498 struct sched_group *group;
7499 struct sched_domain *tmp;
7500 int weight;
7501
7502 if (!(sd->flags & sd_flag)) {
7503 sd = sd->child;
7504 continue;
7505 }
7506
7507 group = sched_balance_find_dst_group(sd, p, cpu);
7508 if (!group) {
7509 sd = sd->child;
7510 continue;
7511 }
7512
7513 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7514 if (new_cpu == cpu) {
7515 /* Now try balancing at a lower domain level of 'cpu': */
7516 sd = sd->child;
7517 continue;
7518 }
7519
7520 /* Now try balancing at a lower domain level of 'new_cpu': */
7521 cpu = new_cpu;
7522 weight = sd->span_weight;
7523 sd = NULL;
7524 for_each_domain(cpu, tmp) {
7525 if (weight <= tmp->span_weight)
7526 break;
7527 if (tmp->flags & sd_flag)
7528 sd = tmp;
7529 }
7530 }
7531
7532 return new_cpu;
7533 }
7534
__select_idle_cpu(int cpu,struct task_struct * p)7535 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7536 {
7537 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7538 sched_cpu_cookie_match(cpu_rq(cpu), p))
7539 return cpu;
7540
7541 return -1;
7542 }
7543
7544 #ifdef CONFIG_SCHED_SMT
7545 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7546 EXPORT_SYMBOL_GPL(sched_smt_present);
7547
set_idle_cores(int cpu,int val)7548 static inline void set_idle_cores(int cpu, int val)
7549 {
7550 struct sched_domain_shared *sds;
7551
7552 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7553 if (sds)
7554 WRITE_ONCE(sds->has_idle_cores, val);
7555 }
7556
test_idle_cores(int cpu)7557 static inline bool test_idle_cores(int cpu)
7558 {
7559 struct sched_domain_shared *sds;
7560
7561 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7562 if (sds)
7563 return READ_ONCE(sds->has_idle_cores);
7564
7565 return false;
7566 }
7567
7568 /*
7569 * Scans the local SMT mask to see if the entire core is idle, and records this
7570 * information in sd_llc_shared->has_idle_cores.
7571 *
7572 * Since SMT siblings share all cache levels, inspecting this limited remote
7573 * state should be fairly cheap.
7574 */
__update_idle_core(struct rq * rq)7575 void __update_idle_core(struct rq *rq)
7576 {
7577 int core = cpu_of(rq);
7578 int cpu;
7579
7580 rcu_read_lock();
7581 if (test_idle_cores(core))
7582 goto unlock;
7583
7584 for_each_cpu(cpu, cpu_smt_mask(core)) {
7585 if (cpu == core)
7586 continue;
7587
7588 if (!available_idle_cpu(cpu))
7589 goto unlock;
7590 }
7591
7592 set_idle_cores(core, 1);
7593 unlock:
7594 rcu_read_unlock();
7595 }
7596
7597 /*
7598 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7599 * there are no idle cores left in the system; tracked through
7600 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7601 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7602 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7603 {
7604 bool idle = true;
7605 int cpu;
7606
7607 for_each_cpu(cpu, cpu_smt_mask(core)) {
7608 if (!available_idle_cpu(cpu)) {
7609 idle = false;
7610 if (*idle_cpu == -1) {
7611 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7612 *idle_cpu = cpu;
7613 break;
7614 }
7615 continue;
7616 }
7617 break;
7618 }
7619 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7620 *idle_cpu = cpu;
7621 }
7622
7623 if (idle)
7624 return core;
7625
7626 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7627 return -1;
7628 }
7629
7630 /*
7631 * Scan the local SMT mask for idle CPUs.
7632 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7633 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7634 {
7635 int cpu;
7636
7637 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7638 if (cpu == target)
7639 continue;
7640 /*
7641 * Check if the CPU is in the LLC scheduling domain of @target.
7642 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7643 */
7644 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7645 continue;
7646 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7647 return cpu;
7648 }
7649
7650 return -1;
7651 }
7652
7653 #else /* CONFIG_SCHED_SMT */
7654
set_idle_cores(int cpu,int val)7655 static inline void set_idle_cores(int cpu, int val)
7656 {
7657 }
7658
test_idle_cores(int cpu)7659 static inline bool test_idle_cores(int cpu)
7660 {
7661 return false;
7662 }
7663
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7664 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7665 {
7666 return __select_idle_cpu(core, p);
7667 }
7668
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7669 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7670 {
7671 return -1;
7672 }
7673
7674 #endif /* CONFIG_SCHED_SMT */
7675
7676 /*
7677 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7678 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7679 * average idle time for this rq (as found in rq->avg_idle).
7680 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7681 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7682 {
7683 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7684 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7685 struct sched_domain_shared *sd_share;
7686
7687 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7688
7689 if (sched_feat(SIS_UTIL)) {
7690 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7691 if (sd_share) {
7692 /* because !--nr is the condition to stop scan */
7693 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7694 /* overloaded LLC is unlikely to have idle cpu/core */
7695 if (nr == 1)
7696 return -1;
7697 }
7698 }
7699
7700 if (static_branch_unlikely(&sched_cluster_active)) {
7701 struct sched_group *sg = sd->groups;
7702
7703 if (sg->flags & SD_CLUSTER) {
7704 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7705 if (!cpumask_test_cpu(cpu, cpus))
7706 continue;
7707
7708 if (has_idle_core) {
7709 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7710 if ((unsigned int)i < nr_cpumask_bits)
7711 return i;
7712 } else {
7713 if (--nr <= 0)
7714 return -1;
7715 idle_cpu = __select_idle_cpu(cpu, p);
7716 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7717 return idle_cpu;
7718 }
7719 }
7720 cpumask_andnot(cpus, cpus, sched_group_span(sg));
7721 }
7722 }
7723
7724 for_each_cpu_wrap(cpu, cpus, target + 1) {
7725 if (has_idle_core) {
7726 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7727 if ((unsigned int)i < nr_cpumask_bits)
7728 return i;
7729
7730 } else {
7731 if (--nr <= 0)
7732 return -1;
7733 idle_cpu = __select_idle_cpu(cpu, p);
7734 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7735 break;
7736 }
7737 }
7738
7739 if (has_idle_core)
7740 set_idle_cores(target, false);
7741
7742 return idle_cpu;
7743 }
7744
7745 /*
7746 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7747 * the task fits. If no CPU is big enough, but there are idle ones, try to
7748 * maximize capacity.
7749 */
7750 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7751 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7752 {
7753 unsigned long task_util, util_min, util_max, best_cap = 0;
7754 int fits, best_fits = 0;
7755 int cpu, best_cpu = -1;
7756 struct cpumask *cpus;
7757
7758 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7759 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7760
7761 task_util = task_util_est(p);
7762 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7763 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7764
7765 for_each_cpu_wrap(cpu, cpus, target) {
7766 unsigned long cpu_cap = capacity_of(cpu);
7767
7768 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7769 continue;
7770
7771 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7772
7773 /* This CPU fits with all requirements */
7774 if (fits > 0)
7775 return cpu;
7776 /*
7777 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7778 * Look for the CPU with best capacity.
7779 */
7780 else if (fits < 0)
7781 cpu_cap = get_actual_cpu_capacity(cpu);
7782
7783 /*
7784 * First, select CPU which fits better (-1 being better than 0).
7785 * Then, select the one with best capacity at same level.
7786 */
7787 if ((fits < best_fits) ||
7788 ((fits == best_fits) && (cpu_cap > best_cap))) {
7789 best_cap = cpu_cap;
7790 best_cpu = cpu;
7791 best_fits = fits;
7792 }
7793 }
7794
7795 return best_cpu;
7796 }
7797
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7798 static inline bool asym_fits_cpu(unsigned long util,
7799 unsigned long util_min,
7800 unsigned long util_max,
7801 int cpu)
7802 {
7803 if (sched_asym_cpucap_active())
7804 /*
7805 * Return true only if the cpu fully fits the task requirements
7806 * which include the utilization and the performance hints.
7807 */
7808 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7809
7810 return true;
7811 }
7812
7813 /*
7814 * Try and locate an idle core/thread in the LLC cache domain.
7815 */
select_idle_sibling(struct task_struct * p,int prev,int target)7816 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7817 {
7818 bool has_idle_core = false;
7819 struct sched_domain *sd;
7820 unsigned long task_util, util_min, util_max;
7821 int i, recent_used_cpu, prev_aff = -1;
7822
7823 /*
7824 * On asymmetric system, update task utilization because we will check
7825 * that the task fits with CPU's capacity.
7826 */
7827 if (sched_asym_cpucap_active()) {
7828 sync_entity_load_avg(&p->se);
7829 task_util = task_util_est(p);
7830 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7831 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7832 }
7833
7834 /*
7835 * per-cpu select_rq_mask usage
7836 */
7837 lockdep_assert_irqs_disabled();
7838
7839 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7840 asym_fits_cpu(task_util, util_min, util_max, target))
7841 return target;
7842
7843 /*
7844 * If the previous CPU is cache affine and idle, don't be stupid:
7845 */
7846 if (prev != target && cpus_share_cache(prev, target) &&
7847 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7848 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7849
7850 if (!static_branch_unlikely(&sched_cluster_active) ||
7851 cpus_share_resources(prev, target))
7852 return prev;
7853
7854 prev_aff = prev;
7855 }
7856
7857 /*
7858 * Allow a per-cpu kthread to stack with the wakee if the
7859 * kworker thread and the tasks previous CPUs are the same.
7860 * The assumption is that the wakee queued work for the
7861 * per-cpu kthread that is now complete and the wakeup is
7862 * essentially a sync wakeup. An obvious example of this
7863 * pattern is IO completions.
7864 */
7865 if (is_per_cpu_kthread(current) &&
7866 in_task() &&
7867 prev == smp_processor_id() &&
7868 this_rq()->nr_running <= 1 &&
7869 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7870 return prev;
7871 }
7872
7873 /* Check a recently used CPU as a potential idle candidate: */
7874 recent_used_cpu = p->recent_used_cpu;
7875 p->recent_used_cpu = prev;
7876 if (recent_used_cpu != prev &&
7877 recent_used_cpu != target &&
7878 cpus_share_cache(recent_used_cpu, target) &&
7879 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7880 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7881 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7882
7883 if (!static_branch_unlikely(&sched_cluster_active) ||
7884 cpus_share_resources(recent_used_cpu, target))
7885 return recent_used_cpu;
7886
7887 } else {
7888 recent_used_cpu = -1;
7889 }
7890
7891 /*
7892 * For asymmetric CPU capacity systems, our domain of interest is
7893 * sd_asym_cpucapacity rather than sd_llc.
7894 */
7895 if (sched_asym_cpucap_active()) {
7896 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7897 /*
7898 * On an asymmetric CPU capacity system where an exclusive
7899 * cpuset defines a symmetric island (i.e. one unique
7900 * capacity_orig value through the cpuset), the key will be set
7901 * but the CPUs within that cpuset will not have a domain with
7902 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7903 * capacity path.
7904 */
7905 if (sd) {
7906 i = select_idle_capacity(p, sd, target);
7907 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7908 }
7909 }
7910
7911 sd = rcu_dereference(per_cpu(sd_llc, target));
7912 if (!sd)
7913 return target;
7914
7915 if (sched_smt_active()) {
7916 has_idle_core = test_idle_cores(target);
7917
7918 if (!has_idle_core && cpus_share_cache(prev, target)) {
7919 i = select_idle_smt(p, sd, prev);
7920 if ((unsigned int)i < nr_cpumask_bits)
7921 return i;
7922 }
7923 }
7924
7925 i = select_idle_cpu(p, sd, has_idle_core, target);
7926 if ((unsigned)i < nr_cpumask_bits)
7927 return i;
7928
7929 /*
7930 * For cluster machines which have lower sharing cache like L2 or
7931 * LLC Tag, we tend to find an idle CPU in the target's cluster
7932 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7933 * use them if possible when no idle CPU found in select_idle_cpu().
7934 */
7935 if ((unsigned int)prev_aff < nr_cpumask_bits)
7936 return prev_aff;
7937 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7938 return recent_used_cpu;
7939
7940 return target;
7941 }
7942
7943 /**
7944 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7945 * @cpu: the CPU to get the utilization for
7946 * @p: task for which the CPU utilization should be predicted or NULL
7947 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7948 * @boost: 1 to enable boosting, otherwise 0
7949 *
7950 * The unit of the return value must be the same as the one of CPU capacity
7951 * so that CPU utilization can be compared with CPU capacity.
7952 *
7953 * CPU utilization is the sum of running time of runnable tasks plus the
7954 * recent utilization of currently non-runnable tasks on that CPU.
7955 * It represents the amount of CPU capacity currently used by CFS tasks in
7956 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7957 * capacity at f_max.
7958 *
7959 * The estimated CPU utilization is defined as the maximum between CPU
7960 * utilization and sum of the estimated utilization of the currently
7961 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7962 * previously-executed tasks, which helps better deduce how busy a CPU will
7963 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7964 * of such a task would be significantly decayed at this point of time.
7965 *
7966 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7967 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7968 * utilization. Boosting is implemented in cpu_util() so that internal
7969 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7970 * latter via cpu_util_cfs_boost().
7971 *
7972 * CPU utilization can be higher than the current CPU capacity
7973 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7974 * of rounding errors as well as task migrations or wakeups of new tasks.
7975 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7976 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7977 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7978 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7979 * though since this is useful for predicting the CPU capacity required
7980 * after task migrations (scheduler-driven DVFS).
7981 *
7982 * Return: (Boosted) (estimated) utilization for the specified CPU.
7983 */
7984 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7985 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7986 {
7987 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7988 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7989 unsigned long runnable;
7990
7991 if (boost) {
7992 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7993 util = max(util, runnable);
7994 }
7995
7996 /*
7997 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7998 * contribution. If @p migrates from another CPU to @cpu add its
7999 * contribution. In all the other cases @cpu is not impacted by the
8000 * migration so its util_avg is already correct.
8001 */
8002 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
8003 lsub_positive(&util, task_util(p));
8004 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
8005 util += task_util(p);
8006
8007 if (sched_feat(UTIL_EST)) {
8008 unsigned long util_est;
8009
8010 util_est = READ_ONCE(cfs_rq->avg.util_est);
8011
8012 /*
8013 * During wake-up @p isn't enqueued yet and doesn't contribute
8014 * to any cpu_rq(cpu)->cfs.avg.util_est.
8015 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
8016 * has been enqueued.
8017 *
8018 * During exec (@dst_cpu = -1) @p is enqueued and does
8019 * contribute to cpu_rq(cpu)->cfs.util_est.
8020 * Remove it to "simulate" cpu_util without @p's contribution.
8021 *
8022 * Despite the task_on_rq_queued(@p) check there is still a
8023 * small window for a possible race when an exec
8024 * select_task_rq_fair() races with LB's detach_task().
8025 *
8026 * detach_task()
8027 * deactivate_task()
8028 * p->on_rq = TASK_ON_RQ_MIGRATING;
8029 * -------------------------------- A
8030 * dequeue_task() \
8031 * dequeue_task_fair() + Race Time
8032 * util_est_dequeue() /
8033 * -------------------------------- B
8034 *
8035 * The additional check "current == p" is required to further
8036 * reduce the race window.
8037 */
8038 if (dst_cpu == cpu)
8039 util_est += _task_util_est(p);
8040 else if (p && unlikely(task_on_rq_queued(p) || current == p))
8041 lsub_positive(&util_est, _task_util_est(p));
8042
8043 util = max(util, util_est);
8044 }
8045
8046 return min(util, arch_scale_cpu_capacity(cpu));
8047 }
8048
cpu_util_cfs(int cpu)8049 unsigned long cpu_util_cfs(int cpu)
8050 {
8051 return cpu_util(cpu, NULL, -1, 0);
8052 }
8053
cpu_util_cfs_boost(int cpu)8054 unsigned long cpu_util_cfs_boost(int cpu)
8055 {
8056 return cpu_util(cpu, NULL, -1, 1);
8057 }
8058
8059 /*
8060 * cpu_util_without: compute cpu utilization without any contributions from *p
8061 * @cpu: the CPU which utilization is requested
8062 * @p: the task which utilization should be discounted
8063 *
8064 * The utilization of a CPU is defined by the utilization of tasks currently
8065 * enqueued on that CPU as well as tasks which are currently sleeping after an
8066 * execution on that CPU.
8067 *
8068 * This method returns the utilization of the specified CPU by discounting the
8069 * utilization of the specified task, whenever the task is currently
8070 * contributing to the CPU utilization.
8071 */
cpu_util_without(int cpu,struct task_struct * p)8072 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8073 {
8074 /* Task has no contribution or is new */
8075 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8076 p = NULL;
8077
8078 return cpu_util(cpu, p, -1, 0);
8079 }
8080
8081 /*
8082 * This function computes an effective utilization for the given CPU, to be
8083 * used for frequency selection given the linear relation: f = u * f_max.
8084 *
8085 * The scheduler tracks the following metrics:
8086 *
8087 * cpu_util_{cfs,rt,dl,irq}()
8088 * cpu_bw_dl()
8089 *
8090 * Where the cfs,rt and dl util numbers are tracked with the same metric and
8091 * synchronized windows and are thus directly comparable.
8092 *
8093 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8094 * which excludes things like IRQ and steal-time. These latter are then accrued
8095 * in the IRQ utilization.
8096 *
8097 * The DL bandwidth number OTOH is not a measured metric but a value computed
8098 * based on the task model parameters and gives the minimal utilization
8099 * required to meet deadlines.
8100 */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8101 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8102 unsigned long *min,
8103 unsigned long *max)
8104 {
8105 unsigned long util, irq, scale;
8106 struct rq *rq = cpu_rq(cpu);
8107
8108 scale = arch_scale_cpu_capacity(cpu);
8109
8110 /*
8111 * Early check to see if IRQ/steal time saturates the CPU, can be
8112 * because of inaccuracies in how we track these -- see
8113 * update_irq_load_avg().
8114 */
8115 irq = cpu_util_irq(rq);
8116 if (unlikely(irq >= scale)) {
8117 if (min)
8118 *min = scale;
8119 if (max)
8120 *max = scale;
8121 return scale;
8122 }
8123
8124 if (min) {
8125 /*
8126 * The minimum utilization returns the highest level between:
8127 * - the computed DL bandwidth needed with the IRQ pressure which
8128 * steals time to the deadline task.
8129 * - The minimum performance requirement for CFS and/or RT.
8130 */
8131 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8132
8133 /*
8134 * When an RT task is runnable and uclamp is not used, we must
8135 * ensure that the task will run at maximum compute capacity.
8136 */
8137 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8138 *min = max(*min, scale);
8139 }
8140
8141 /*
8142 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8143 * CFS tasks and we use the same metric to track the effective
8144 * utilization (PELT windows are synchronized) we can directly add them
8145 * to obtain the CPU's actual utilization.
8146 */
8147 util = util_cfs + cpu_util_rt(rq);
8148 util += cpu_util_dl(rq);
8149
8150 /*
8151 * The maximum hint is a soft bandwidth requirement, which can be lower
8152 * than the actual utilization because of uclamp_max requirements.
8153 */
8154 if (max)
8155 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8156
8157 if (util >= scale)
8158 return scale;
8159
8160 /*
8161 * There is still idle time; further improve the number by using the
8162 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8163 * need to scale the task numbers:
8164 *
8165 * max - irq
8166 * U' = irq + --------- * U
8167 * max
8168 */
8169 util = scale_irq_capacity(util, irq, scale);
8170 util += irq;
8171
8172 return min(scale, util);
8173 }
8174
sched_cpu_util(int cpu)8175 unsigned long sched_cpu_util(int cpu)
8176 {
8177 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8178 }
8179
8180 /*
8181 * energy_env - Utilization landscape for energy estimation.
8182 * @task_busy_time: Utilization contribution by the task for which we test the
8183 * placement. Given by eenv_task_busy_time().
8184 * @pd_busy_time: Utilization of the whole perf domain without the task
8185 * contribution. Given by eenv_pd_busy_time().
8186 * @cpu_cap: Maximum CPU capacity for the perf domain.
8187 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8188 */
8189 struct energy_env {
8190 unsigned long task_busy_time;
8191 unsigned long pd_busy_time;
8192 unsigned long cpu_cap;
8193 unsigned long pd_cap;
8194 };
8195
8196 /*
8197 * Compute the task busy time for compute_energy(). This time cannot be
8198 * injected directly into effective_cpu_util() because of the IRQ scaling.
8199 * The latter only makes sense with the most recent CPUs where the task has
8200 * run.
8201 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8202 static inline void eenv_task_busy_time(struct energy_env *eenv,
8203 struct task_struct *p, int prev_cpu)
8204 {
8205 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8206 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8207
8208 if (unlikely(irq >= max_cap))
8209 busy_time = max_cap;
8210 else
8211 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8212
8213 eenv->task_busy_time = busy_time;
8214 }
8215
8216 /*
8217 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8218 * utilization for each @pd_cpus, it however doesn't take into account
8219 * clamping since the ratio (utilization / cpu_capacity) is already enough to
8220 * scale the EM reported power consumption at the (eventually clamped)
8221 * cpu_capacity.
8222 *
8223 * The contribution of the task @p for which we want to estimate the
8224 * energy cost is removed (by cpu_util()) and must be calculated
8225 * separately (see eenv_task_busy_time). This ensures:
8226 *
8227 * - A stable PD utilization, no matter which CPU of that PD we want to place
8228 * the task on.
8229 *
8230 * - A fair comparison between CPUs as the task contribution (task_util())
8231 * will always be the same no matter which CPU utilization we rely on
8232 * (util_avg or util_est).
8233 *
8234 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8235 * exceed @eenv->pd_cap.
8236 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8237 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8238 struct cpumask *pd_cpus,
8239 struct task_struct *p)
8240 {
8241 unsigned long busy_time = 0;
8242 int cpu;
8243
8244 for_each_cpu(cpu, pd_cpus) {
8245 unsigned long util = cpu_util(cpu, p, -1, 0);
8246
8247 busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8248 }
8249
8250 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8251 }
8252
8253 /*
8254 * Compute the maximum utilization for compute_energy() when the task @p
8255 * is placed on the cpu @dst_cpu.
8256 *
8257 * Returns the maximum utilization among @eenv->cpus. This utilization can't
8258 * exceed @eenv->cpu_cap.
8259 */
8260 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8261 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8262 struct task_struct *p, int dst_cpu)
8263 {
8264 unsigned long max_util = 0;
8265 int cpu;
8266
8267 for_each_cpu(cpu, pd_cpus) {
8268 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8269 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8270 unsigned long eff_util, min, max;
8271
8272 /*
8273 * Performance domain frequency: utilization clamping
8274 * must be considered since it affects the selection
8275 * of the performance domain frequency.
8276 * NOTE: in case RT tasks are running, by default the min
8277 * utilization can be max OPP.
8278 */
8279 eff_util = effective_cpu_util(cpu, util, &min, &max);
8280
8281 /* Task's uclamp can modify min and max value */
8282 if (tsk && uclamp_is_used()) {
8283 min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8284
8285 /*
8286 * If there is no active max uclamp constraint,
8287 * directly use task's one, otherwise keep max.
8288 */
8289 if (uclamp_rq_is_idle(cpu_rq(cpu)))
8290 max = uclamp_eff_value(p, UCLAMP_MAX);
8291 else
8292 max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8293 }
8294
8295 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8296 max_util = max(max_util, eff_util);
8297 }
8298
8299 return min(max_util, eenv->cpu_cap);
8300 }
8301
8302 /*
8303 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8304 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8305 * contribution is ignored.
8306 */
8307 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)8308 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8309 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8310 {
8311 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8312 unsigned long busy_time = eenv->pd_busy_time;
8313 unsigned long energy;
8314
8315 if (dst_cpu >= 0)
8316 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8317
8318 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8319
8320 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8321
8322 return energy;
8323 }
8324
8325 /*
8326 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8327 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8328 * spare capacity in each performance domain and uses it as a potential
8329 * candidate to execute the task. Then, it uses the Energy Model to figure
8330 * out which of the CPU candidates is the most energy-efficient.
8331 *
8332 * The rationale for this heuristic is as follows. In a performance domain,
8333 * all the most energy efficient CPU candidates (according to the Energy
8334 * Model) are those for which we'll request a low frequency. When there are
8335 * several CPUs for which the frequency request will be the same, we don't
8336 * have enough data to break the tie between them, because the Energy Model
8337 * only includes active power costs. With this model, if we assume that
8338 * frequency requests follow utilization (e.g. using schedutil), the CPU with
8339 * the maximum spare capacity in a performance domain is guaranteed to be among
8340 * the best candidates of the performance domain.
8341 *
8342 * In practice, it could be preferable from an energy standpoint to pack
8343 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8344 * but that could also hurt our chances to go cluster idle, and we have no
8345 * ways to tell with the current Energy Model if this is actually a good
8346 * idea or not. So, find_energy_efficient_cpu() basically favors
8347 * cluster-packing, and spreading inside a cluster. That should at least be
8348 * a good thing for latency, and this is consistent with the idea that most
8349 * of the energy savings of EAS come from the asymmetry of the system, and
8350 * not so much from breaking the tie between identical CPUs. That's also the
8351 * reason why EAS is enabled in the topology code only for systems where
8352 * SD_ASYM_CPUCAPACITY is set.
8353 *
8354 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8355 * they don't have any useful utilization data yet and it's not possible to
8356 * forecast their impact on energy consumption. Consequently, they will be
8357 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8358 * to be energy-inefficient in some use-cases. The alternative would be to
8359 * bias new tasks towards specific types of CPUs first, or to try to infer
8360 * their util_avg from the parent task, but those heuristics could hurt
8361 * other use-cases too. So, until someone finds a better way to solve this,
8362 * let's keep things simple by re-using the existing slow path.
8363 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8364 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8365 {
8366 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8367 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8368 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8369 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8370 struct root_domain *rd = this_rq()->rd;
8371 int cpu, best_energy_cpu, target = -1;
8372 int prev_fits = -1, best_fits = -1;
8373 unsigned long best_actual_cap = 0;
8374 unsigned long prev_actual_cap = 0;
8375 struct sched_domain *sd;
8376 struct perf_domain *pd;
8377 struct energy_env eenv;
8378
8379 rcu_read_lock();
8380 pd = rcu_dereference(rd->pd);
8381 if (!pd)
8382 goto unlock;
8383
8384 /*
8385 * Energy-aware wake-up happens on the lowest sched_domain starting
8386 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8387 */
8388 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8389 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8390 sd = sd->parent;
8391 if (!sd)
8392 goto unlock;
8393
8394 target = prev_cpu;
8395
8396 sync_entity_load_avg(&p->se);
8397 if (!task_util_est(p) && p_util_min == 0)
8398 goto unlock;
8399
8400 eenv_task_busy_time(&eenv, p, prev_cpu);
8401
8402 for (; pd; pd = pd->next) {
8403 unsigned long util_min = p_util_min, util_max = p_util_max;
8404 unsigned long cpu_cap, cpu_actual_cap, util;
8405 long prev_spare_cap = -1, max_spare_cap = -1;
8406 unsigned long rq_util_min, rq_util_max;
8407 unsigned long cur_delta, base_energy;
8408 int max_spare_cap_cpu = -1;
8409 int fits, max_fits = -1;
8410
8411 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8412
8413 if (cpumask_empty(cpus))
8414 continue;
8415
8416 /* Account external pressure for the energy estimation */
8417 cpu = cpumask_first(cpus);
8418 cpu_actual_cap = get_actual_cpu_capacity(cpu);
8419
8420 eenv.cpu_cap = cpu_actual_cap;
8421 eenv.pd_cap = 0;
8422
8423 for_each_cpu(cpu, cpus) {
8424 struct rq *rq = cpu_rq(cpu);
8425
8426 eenv.pd_cap += cpu_actual_cap;
8427
8428 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8429 continue;
8430
8431 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8432 continue;
8433
8434 util = cpu_util(cpu, p, cpu, 0);
8435 cpu_cap = capacity_of(cpu);
8436
8437 /*
8438 * Skip CPUs that cannot satisfy the capacity request.
8439 * IOW, placing the task there would make the CPU
8440 * overutilized. Take uclamp into account to see how
8441 * much capacity we can get out of the CPU; this is
8442 * aligned with sched_cpu_util().
8443 */
8444 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8445 /*
8446 * Open code uclamp_rq_util_with() except for
8447 * the clamp() part. I.e.: apply max aggregation
8448 * only. util_fits_cpu() logic requires to
8449 * operate on non clamped util but must use the
8450 * max-aggregated uclamp_{min, max}.
8451 */
8452 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8453 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8454
8455 util_min = max(rq_util_min, p_util_min);
8456 util_max = max(rq_util_max, p_util_max);
8457 }
8458
8459 fits = util_fits_cpu(util, util_min, util_max, cpu);
8460 if (!fits)
8461 continue;
8462
8463 lsub_positive(&cpu_cap, util);
8464
8465 if (cpu == prev_cpu) {
8466 /* Always use prev_cpu as a candidate. */
8467 prev_spare_cap = cpu_cap;
8468 prev_fits = fits;
8469 } else if ((fits > max_fits) ||
8470 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8471 /*
8472 * Find the CPU with the maximum spare capacity
8473 * among the remaining CPUs in the performance
8474 * domain.
8475 */
8476 max_spare_cap = cpu_cap;
8477 max_spare_cap_cpu = cpu;
8478 max_fits = fits;
8479 }
8480 }
8481
8482 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8483 continue;
8484
8485 eenv_pd_busy_time(&eenv, cpus, p);
8486 /* Compute the 'base' energy of the pd, without @p */
8487 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8488
8489 /* Evaluate the energy impact of using prev_cpu. */
8490 if (prev_spare_cap > -1) {
8491 prev_delta = compute_energy(&eenv, pd, cpus, p,
8492 prev_cpu);
8493 /* CPU utilization has changed */
8494 if (prev_delta < base_energy)
8495 goto unlock;
8496 prev_delta -= base_energy;
8497 prev_actual_cap = cpu_actual_cap;
8498 best_delta = min(best_delta, prev_delta);
8499 }
8500
8501 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8502 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8503 /* Current best energy cpu fits better */
8504 if (max_fits < best_fits)
8505 continue;
8506
8507 /*
8508 * Both don't fit performance hint (i.e. uclamp_min)
8509 * but best energy cpu has better capacity.
8510 */
8511 if ((max_fits < 0) &&
8512 (cpu_actual_cap <= best_actual_cap))
8513 continue;
8514
8515 cur_delta = compute_energy(&eenv, pd, cpus, p,
8516 max_spare_cap_cpu);
8517 /* CPU utilization has changed */
8518 if (cur_delta < base_energy)
8519 goto unlock;
8520 cur_delta -= base_energy;
8521
8522 /*
8523 * Both fit for the task but best energy cpu has lower
8524 * energy impact.
8525 */
8526 if ((max_fits > 0) && (best_fits > 0) &&
8527 (cur_delta >= best_delta))
8528 continue;
8529
8530 best_delta = cur_delta;
8531 best_energy_cpu = max_spare_cap_cpu;
8532 best_fits = max_fits;
8533 best_actual_cap = cpu_actual_cap;
8534 }
8535 }
8536 rcu_read_unlock();
8537
8538 if ((best_fits > prev_fits) ||
8539 ((best_fits > 0) && (best_delta < prev_delta)) ||
8540 ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8541 target = best_energy_cpu;
8542
8543 return target;
8544
8545 unlock:
8546 rcu_read_unlock();
8547
8548 return target;
8549 }
8550
8551 /*
8552 * select_task_rq_fair: Select target runqueue for the waking task in domains
8553 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8554 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8555 *
8556 * Balances load by selecting the idlest CPU in the idlest group, or under
8557 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8558 *
8559 * Returns the target CPU number.
8560 */
8561 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8562 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8563 {
8564 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8565 struct sched_domain *tmp, *sd = NULL;
8566 int cpu = smp_processor_id();
8567 int new_cpu = prev_cpu;
8568 int want_affine = 0;
8569 /* SD_flags and WF_flags share the first nibble */
8570 int sd_flag = wake_flags & 0xF;
8571
8572 /*
8573 * required for stable ->cpus_allowed
8574 */
8575 lockdep_assert_held(&p->pi_lock);
8576 if (wake_flags & WF_TTWU) {
8577 record_wakee(p);
8578
8579 if ((wake_flags & WF_CURRENT_CPU) &&
8580 cpumask_test_cpu(cpu, p->cpus_ptr))
8581 return cpu;
8582
8583 if (!is_rd_overutilized(this_rq()->rd)) {
8584 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8585 if (new_cpu >= 0)
8586 return new_cpu;
8587 new_cpu = prev_cpu;
8588 }
8589
8590 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8591 }
8592
8593 rcu_read_lock();
8594 for_each_domain(cpu, tmp) {
8595 /*
8596 * If both 'cpu' and 'prev_cpu' are part of this domain,
8597 * cpu is a valid SD_WAKE_AFFINE target.
8598 */
8599 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8600 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8601 if (cpu != prev_cpu)
8602 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8603
8604 sd = NULL; /* Prefer wake_affine over balance flags */
8605 break;
8606 }
8607
8608 /*
8609 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8610 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8611 * will usually go to the fast path.
8612 */
8613 if (tmp->flags & sd_flag)
8614 sd = tmp;
8615 else if (!want_affine)
8616 break;
8617 }
8618
8619 if (unlikely(sd)) {
8620 /* Slow path */
8621 new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8622 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
8623 /* Fast path */
8624 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8625 }
8626 rcu_read_unlock();
8627
8628 return new_cpu;
8629 }
8630
8631 /*
8632 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8633 * cfs_rq_of(p) references at time of call are still valid and identify the
8634 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8635 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8636 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8637 {
8638 struct sched_entity *se = &p->se;
8639
8640 if (!task_on_rq_migrating(p)) {
8641 remove_entity_load_avg(se);
8642
8643 /*
8644 * Here, the task's PELT values have been updated according to
8645 * the current rq's clock. But if that clock hasn't been
8646 * updated in a while, a substantial idle time will be missed,
8647 * leading to an inflation after wake-up on the new rq.
8648 *
8649 * Estimate the missing time from the cfs_rq last_update_time
8650 * and update sched_avg to improve the PELT continuity after
8651 * migration.
8652 */
8653 migrate_se_pelt_lag(se);
8654 }
8655
8656 /* Tell new CPU we are migrated */
8657 se->avg.last_update_time = 0;
8658
8659 update_scan_period(p, new_cpu);
8660 }
8661
task_dead_fair(struct task_struct * p)8662 static void task_dead_fair(struct task_struct *p)
8663 {
8664 struct sched_entity *se = &p->se;
8665
8666 if (se->sched_delayed) {
8667 struct rq_flags rf;
8668 struct rq *rq;
8669
8670 rq = task_rq_lock(p, &rf);
8671 if (se->sched_delayed) {
8672 update_rq_clock(rq);
8673 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8674 }
8675 task_rq_unlock(rq, p, &rf);
8676 }
8677
8678 remove_entity_load_avg(se);
8679 }
8680
8681 /*
8682 * Set the max capacity the task is allowed to run at for misfit detection.
8683 */
set_task_max_allowed_capacity(struct task_struct * p)8684 static void set_task_max_allowed_capacity(struct task_struct *p)
8685 {
8686 struct asym_cap_data *entry;
8687
8688 if (!sched_asym_cpucap_active())
8689 return;
8690
8691 rcu_read_lock();
8692 list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8693 cpumask_t *cpumask;
8694
8695 cpumask = cpu_capacity_span(entry);
8696 if (!cpumask_intersects(p->cpus_ptr, cpumask))
8697 continue;
8698
8699 p->max_allowed_capacity = entry->capacity;
8700 break;
8701 }
8702 rcu_read_unlock();
8703 }
8704
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8705 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8706 {
8707 set_cpus_allowed_common(p, ctx);
8708 set_task_max_allowed_capacity(p);
8709 }
8710
8711 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8712 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8713 {
8714 if (sched_fair_runnable(rq))
8715 return 1;
8716
8717 return sched_balance_newidle(rq, rf) != 0;
8718 }
8719 #else
set_task_max_allowed_capacity(struct task_struct * p)8720 static inline void set_task_max_allowed_capacity(struct task_struct *p) {}
8721 #endif /* CONFIG_SMP */
8722
set_next_buddy(struct sched_entity * se)8723 static void set_next_buddy(struct sched_entity *se)
8724 {
8725 for_each_sched_entity(se) {
8726 if (SCHED_WARN_ON(!se->on_rq))
8727 return;
8728 if (se_is_idle(se))
8729 return;
8730 cfs_rq_of(se)->next = se;
8731 }
8732 }
8733
8734 /*
8735 * Preempt the current task with a newly woken task if needed:
8736 */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8737 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8738 {
8739 struct task_struct *donor = rq->donor;
8740 struct sched_entity *se = &donor->se, *pse = &p->se;
8741 struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8742 int cse_is_idle, pse_is_idle;
8743
8744 if (unlikely(se == pse))
8745 return;
8746
8747 /*
8748 * This is possible from callers such as attach_tasks(), in which we
8749 * unconditionally wakeup_preempt() after an enqueue (which may have
8750 * lead to a throttle). This both saves work and prevents false
8751 * next-buddy nomination below.
8752 */
8753 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8754 return;
8755
8756 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK) && !pse->sched_delayed) {
8757 set_next_buddy(pse);
8758 }
8759
8760 /*
8761 * We can come here with TIF_NEED_RESCHED already set from new task
8762 * wake up path.
8763 *
8764 * Note: this also catches the edge-case of curr being in a throttled
8765 * group (e.g. via set_curr_task), since update_curr() (in the
8766 * enqueue of curr) will have resulted in resched being set. This
8767 * prevents us from potentially nominating it as a false LAST_BUDDY
8768 * below.
8769 */
8770 if (test_tsk_need_resched(rq->curr))
8771 return;
8772
8773 if (!sched_feat(WAKEUP_PREEMPTION))
8774 return;
8775
8776 find_matching_se(&se, &pse);
8777 WARN_ON_ONCE(!pse);
8778
8779 cse_is_idle = se_is_idle(se);
8780 pse_is_idle = se_is_idle(pse);
8781
8782 /*
8783 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8784 * in the inverse case).
8785 */
8786 if (cse_is_idle && !pse_is_idle)
8787 goto preempt;
8788 if (cse_is_idle != pse_is_idle)
8789 return;
8790
8791 /*
8792 * BATCH and IDLE tasks do not preempt others.
8793 */
8794 if (unlikely(!normal_policy(p->policy)))
8795 return;
8796
8797 cfs_rq = cfs_rq_of(se);
8798 update_curr(cfs_rq);
8799 /*
8800 * If @p has a shorter slice than current and @p is eligible, override
8801 * current's slice protection in order to allow preemption.
8802 *
8803 * Note that even if @p does not turn out to be the most eligible
8804 * task at this moment, current's slice protection will be lost.
8805 */
8806 if (do_preempt_short(cfs_rq, pse, se) && se->vlag == se->deadline)
8807 se->vlag = se->deadline + 1;
8808
8809 /*
8810 * If @p has become the most eligible task, force preemption.
8811 */
8812 if (pick_eevdf(cfs_rq) == pse)
8813 goto preempt;
8814
8815 return;
8816
8817 preempt:
8818 resched_curr_lazy(rq);
8819 }
8820
pick_task_fair(struct rq * rq)8821 static struct task_struct *pick_task_fair(struct rq *rq)
8822 {
8823 struct sched_entity *se;
8824 struct cfs_rq *cfs_rq;
8825
8826 again:
8827 cfs_rq = &rq->cfs;
8828 if (!cfs_rq->nr_queued)
8829 return NULL;
8830
8831 do {
8832 /* Might not have done put_prev_entity() */
8833 if (cfs_rq->curr && cfs_rq->curr->on_rq)
8834 update_curr(cfs_rq);
8835
8836 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8837 goto again;
8838
8839 se = pick_next_entity(rq, cfs_rq);
8840 if (!se)
8841 goto again;
8842 cfs_rq = group_cfs_rq(se);
8843 } while (cfs_rq);
8844
8845 return task_of(se);
8846 }
8847
8848 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8849 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8850
8851 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8852 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8853 {
8854 struct sched_entity *se;
8855 struct task_struct *p;
8856 int new_tasks;
8857
8858 again:
8859 p = pick_task_fair(rq);
8860 if (!p)
8861 goto idle;
8862 se = &p->se;
8863
8864 #ifdef CONFIG_FAIR_GROUP_SCHED
8865 if (prev->sched_class != &fair_sched_class)
8866 goto simple;
8867
8868 __put_prev_set_next_dl_server(rq, prev, p);
8869
8870 /*
8871 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8872 * likely that a next task is from the same cgroup as the current.
8873 *
8874 * Therefore attempt to avoid putting and setting the entire cgroup
8875 * hierarchy, only change the part that actually changes.
8876 *
8877 * Since we haven't yet done put_prev_entity and if the selected task
8878 * is a different task than we started out with, try and touch the
8879 * least amount of cfs_rqs.
8880 */
8881 if (prev != p) {
8882 struct sched_entity *pse = &prev->se;
8883 struct cfs_rq *cfs_rq;
8884
8885 while (!(cfs_rq = is_same_group(se, pse))) {
8886 int se_depth = se->depth;
8887 int pse_depth = pse->depth;
8888
8889 if (se_depth <= pse_depth) {
8890 put_prev_entity(cfs_rq_of(pse), pse);
8891 pse = parent_entity(pse);
8892 }
8893 if (se_depth >= pse_depth) {
8894 set_next_entity(cfs_rq_of(se), se);
8895 se = parent_entity(se);
8896 }
8897 }
8898
8899 put_prev_entity(cfs_rq, pse);
8900 set_next_entity(cfs_rq, se);
8901
8902 __set_next_task_fair(rq, p, true);
8903 }
8904
8905 return p;
8906
8907 simple:
8908 #endif
8909 put_prev_set_next_task(rq, prev, p);
8910 return p;
8911
8912 idle:
8913 if (!rf)
8914 return NULL;
8915
8916 new_tasks = sched_balance_newidle(rq, rf);
8917
8918 /*
8919 * Because sched_balance_newidle() releases (and re-acquires) rq->lock, it is
8920 * possible for any higher priority task to appear. In that case we
8921 * must re-start the pick_next_entity() loop.
8922 */
8923 if (new_tasks < 0)
8924 return RETRY_TASK;
8925
8926 if (new_tasks > 0)
8927 goto again;
8928
8929 /*
8930 * rq is about to be idle, check if we need to update the
8931 * lost_idle_time of clock_pelt
8932 */
8933 update_idle_rq_clock_pelt(rq);
8934
8935 return NULL;
8936 }
8937
__pick_next_task_fair(struct rq * rq,struct task_struct * prev)8938 static struct task_struct *__pick_next_task_fair(struct rq *rq, struct task_struct *prev)
8939 {
8940 return pick_next_task_fair(rq, prev, NULL);
8941 }
8942
fair_server_has_tasks(struct sched_dl_entity * dl_se)8943 static bool fair_server_has_tasks(struct sched_dl_entity *dl_se)
8944 {
8945 return !!dl_se->rq->cfs.nr_queued;
8946 }
8947
fair_server_pick_task(struct sched_dl_entity * dl_se)8948 static struct task_struct *fair_server_pick_task(struct sched_dl_entity *dl_se)
8949 {
8950 return pick_task_fair(dl_se->rq);
8951 }
8952
fair_server_init(struct rq * rq)8953 void fair_server_init(struct rq *rq)
8954 {
8955 struct sched_dl_entity *dl_se = &rq->fair_server;
8956
8957 init_dl_entity(dl_se);
8958
8959 dl_server_init(dl_se, rq, fair_server_has_tasks, fair_server_pick_task);
8960 }
8961
8962 /*
8963 * Account for a descheduled task:
8964 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)8965 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
8966 {
8967 struct sched_entity *se = &prev->se;
8968 struct cfs_rq *cfs_rq;
8969
8970 for_each_sched_entity(se) {
8971 cfs_rq = cfs_rq_of(se);
8972 put_prev_entity(cfs_rq, se);
8973 }
8974 }
8975
8976 /*
8977 * sched_yield() is very simple
8978 */
yield_task_fair(struct rq * rq)8979 static void yield_task_fair(struct rq *rq)
8980 {
8981 struct task_struct *curr = rq->curr;
8982 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8983 struct sched_entity *se = &curr->se;
8984
8985 /*
8986 * Are we the only task in the tree?
8987 */
8988 if (unlikely(rq->nr_running == 1))
8989 return;
8990
8991 clear_buddies(cfs_rq, se);
8992
8993 update_rq_clock(rq);
8994 /*
8995 * Update run-time statistics of the 'current'.
8996 */
8997 update_curr(cfs_rq);
8998 /*
8999 * Tell update_rq_clock() that we've just updated,
9000 * so we don't do microscopic update in schedule()
9001 * and double the fastpath cost.
9002 */
9003 rq_clock_skip_update(rq);
9004
9005 se->deadline += calc_delta_fair(se->slice, se);
9006 }
9007
yield_to_task_fair(struct rq * rq,struct task_struct * p)9008 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9009 {
9010 struct sched_entity *se = &p->se;
9011
9012 /* throttled hierarchies are not runnable */
9013 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
9014 return false;
9015
9016 /* Tell the scheduler that we'd really like se to run next. */
9017 set_next_buddy(se);
9018
9019 yield_task_fair(rq);
9020
9021 return true;
9022 }
9023
9024 #ifdef CONFIG_SMP
9025 /**************************************************
9026 * Fair scheduling class load-balancing methods.
9027 *
9028 * BASICS
9029 *
9030 * The purpose of load-balancing is to achieve the same basic fairness the
9031 * per-CPU scheduler provides, namely provide a proportional amount of compute
9032 * time to each task. This is expressed in the following equation:
9033 *
9034 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
9035 *
9036 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9037 * W_i,0 is defined as:
9038 *
9039 * W_i,0 = \Sum_j w_i,j (2)
9040 *
9041 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9042 * is derived from the nice value as per sched_prio_to_weight[].
9043 *
9044 * The weight average is an exponential decay average of the instantaneous
9045 * weight:
9046 *
9047 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
9048 *
9049 * C_i is the compute capacity of CPU i, typically it is the
9050 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9051 * can also include other factors [XXX].
9052 *
9053 * To achieve this balance we define a measure of imbalance which follows
9054 * directly from (1):
9055 *
9056 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
9057 *
9058 * We them move tasks around to minimize the imbalance. In the continuous
9059 * function space it is obvious this converges, in the discrete case we get
9060 * a few fun cases generally called infeasible weight scenarios.
9061 *
9062 * [XXX expand on:
9063 * - infeasible weights;
9064 * - local vs global optima in the discrete case. ]
9065 *
9066 *
9067 * SCHED DOMAINS
9068 *
9069 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9070 * for all i,j solution, we create a tree of CPUs that follows the hardware
9071 * topology where each level pairs two lower groups (or better). This results
9072 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9073 * tree to only the first of the previous level and we decrease the frequency
9074 * of load-balance at each level inversely proportional to the number of CPUs in
9075 * the groups.
9076 *
9077 * This yields:
9078 *
9079 * log_2 n 1 n
9080 * \Sum { --- * --- * 2^i } = O(n) (5)
9081 * i = 0 2^i 2^i
9082 * `- size of each group
9083 * | | `- number of CPUs doing load-balance
9084 * | `- freq
9085 * `- sum over all levels
9086 *
9087 * Coupled with a limit on how many tasks we can migrate every balance pass,
9088 * this makes (5) the runtime complexity of the balancer.
9089 *
9090 * An important property here is that each CPU is still (indirectly) connected
9091 * to every other CPU in at most O(log n) steps:
9092 *
9093 * The adjacency matrix of the resulting graph is given by:
9094 *
9095 * log_2 n
9096 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
9097 * k = 0
9098 *
9099 * And you'll find that:
9100 *
9101 * A^(log_2 n)_i,j != 0 for all i,j (7)
9102 *
9103 * Showing there's indeed a path between every CPU in at most O(log n) steps.
9104 * The task movement gives a factor of O(m), giving a convergence complexity
9105 * of:
9106 *
9107 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
9108 *
9109 *
9110 * WORK CONSERVING
9111 *
9112 * In order to avoid CPUs going idle while there's still work to do, new idle
9113 * balancing is more aggressive and has the newly idle CPU iterate up the domain
9114 * tree itself instead of relying on other CPUs to bring it work.
9115 *
9116 * This adds some complexity to both (5) and (8) but it reduces the total idle
9117 * time.
9118 *
9119 * [XXX more?]
9120 *
9121 *
9122 * CGROUPS
9123 *
9124 * Cgroups make a horror show out of (2), instead of a simple sum we get:
9125 *
9126 * s_k,i
9127 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
9128 * S_k
9129 *
9130 * Where
9131 *
9132 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
9133 *
9134 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9135 *
9136 * The big problem is S_k, its a global sum needed to compute a local (W_i)
9137 * property.
9138 *
9139 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9140 * rewrite all of this once again.]
9141 */
9142
9143 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9144
9145 enum fbq_type { regular, remote, all };
9146
9147 /*
9148 * 'group_type' describes the group of CPUs at the moment of load balancing.
9149 *
9150 * The enum is ordered by pulling priority, with the group with lowest priority
9151 * first so the group_type can simply be compared when selecting the busiest
9152 * group. See update_sd_pick_busiest().
9153 */
9154 enum group_type {
9155 /* The group has spare capacity that can be used to run more tasks. */
9156 group_has_spare = 0,
9157 /*
9158 * The group is fully used and the tasks don't compete for more CPU
9159 * cycles. Nevertheless, some tasks might wait before running.
9160 */
9161 group_fully_busy,
9162 /*
9163 * One task doesn't fit with CPU's capacity and must be migrated to a
9164 * more powerful CPU.
9165 */
9166 group_misfit_task,
9167 /*
9168 * Balance SMT group that's fully busy. Can benefit from migration
9169 * a task on SMT with busy sibling to another CPU on idle core.
9170 */
9171 group_smt_balance,
9172 /*
9173 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9174 * and the task should be migrated to it instead of running on the
9175 * current CPU.
9176 */
9177 group_asym_packing,
9178 /*
9179 * The tasks' affinity constraints previously prevented the scheduler
9180 * from balancing the load across the system.
9181 */
9182 group_imbalanced,
9183 /*
9184 * The CPU is overloaded and can't provide expected CPU cycles to all
9185 * tasks.
9186 */
9187 group_overloaded
9188 };
9189
9190 enum migration_type {
9191 migrate_load = 0,
9192 migrate_util,
9193 migrate_task,
9194 migrate_misfit
9195 };
9196
9197 #define LBF_ALL_PINNED 0x01
9198 #define LBF_NEED_BREAK 0x02
9199 #define LBF_DST_PINNED 0x04
9200 #define LBF_SOME_PINNED 0x08
9201 #define LBF_ACTIVE_LB 0x10
9202
9203 struct lb_env {
9204 struct sched_domain *sd;
9205
9206 struct rq *src_rq;
9207 int src_cpu;
9208
9209 int dst_cpu;
9210 struct rq *dst_rq;
9211
9212 struct cpumask *dst_grpmask;
9213 int new_dst_cpu;
9214 enum cpu_idle_type idle;
9215 long imbalance;
9216 /* The set of CPUs under consideration for load-balancing */
9217 struct cpumask *cpus;
9218
9219 unsigned int flags;
9220
9221 unsigned int loop;
9222 unsigned int loop_break;
9223 unsigned int loop_max;
9224
9225 enum fbq_type fbq_type;
9226 enum migration_type migration_type;
9227 struct list_head tasks;
9228 };
9229
9230 /*
9231 * Is this task likely cache-hot:
9232 */
task_hot(struct task_struct * p,struct lb_env * env)9233 static int task_hot(struct task_struct *p, struct lb_env *env)
9234 {
9235 s64 delta;
9236
9237 lockdep_assert_rq_held(env->src_rq);
9238
9239 if (p->sched_class != &fair_sched_class)
9240 return 0;
9241
9242 if (unlikely(task_has_idle_policy(p)))
9243 return 0;
9244
9245 /* SMT siblings share cache */
9246 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9247 return 0;
9248
9249 /*
9250 * Buddy candidates are cache hot:
9251 */
9252 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9253 (&p->se == cfs_rq_of(&p->se)->next))
9254 return 1;
9255
9256 if (sysctl_sched_migration_cost == -1)
9257 return 1;
9258
9259 /*
9260 * Don't migrate task if the task's cookie does not match
9261 * with the destination CPU's core cookie.
9262 */
9263 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9264 return 1;
9265
9266 if (sysctl_sched_migration_cost == 0)
9267 return 0;
9268
9269 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9270
9271 return delta < (s64)sysctl_sched_migration_cost;
9272 }
9273
9274 #ifdef CONFIG_NUMA_BALANCING
9275 /*
9276 * Returns a positive value, if task migration degrades locality.
9277 * Returns 0, if task migration is not affected by locality.
9278 * Returns a negative value, if task migration improves locality i.e migration preferred.
9279 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9280 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9281 {
9282 struct numa_group *numa_group = rcu_dereference(p->numa_group);
9283 unsigned long src_weight, dst_weight;
9284 int src_nid, dst_nid, dist;
9285
9286 if (!static_branch_likely(&sched_numa_balancing))
9287 return 0;
9288
9289 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9290 return 0;
9291
9292 src_nid = cpu_to_node(env->src_cpu);
9293 dst_nid = cpu_to_node(env->dst_cpu);
9294
9295 if (src_nid == dst_nid)
9296 return 0;
9297
9298 /* Migrating away from the preferred node is always bad. */
9299 if (src_nid == p->numa_preferred_nid) {
9300 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9301 return 1;
9302 else
9303 return 0;
9304 }
9305
9306 /* Encourage migration to the preferred node. */
9307 if (dst_nid == p->numa_preferred_nid)
9308 return -1;
9309
9310 /* Leaving a core idle is often worse than degrading locality. */
9311 if (env->idle == CPU_IDLE)
9312 return 0;
9313
9314 dist = node_distance(src_nid, dst_nid);
9315 if (numa_group) {
9316 src_weight = group_weight(p, src_nid, dist);
9317 dst_weight = group_weight(p, dst_nid, dist);
9318 } else {
9319 src_weight = task_weight(p, src_nid, dist);
9320 dst_weight = task_weight(p, dst_nid, dist);
9321 }
9322
9323 return src_weight - dst_weight;
9324 }
9325
9326 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9327 static inline long migrate_degrades_locality(struct task_struct *p,
9328 struct lb_env *env)
9329 {
9330 return 0;
9331 }
9332 #endif
9333
9334 /*
9335 * Check whether the task is ineligible on the destination cpu
9336 *
9337 * When the PLACE_LAG scheduling feature is enabled and
9338 * dst_cfs_rq->nr_queued is greater than 1, if the task
9339 * is ineligible, it will also be ineligible when
9340 * it is migrated to the destination cpu.
9341 */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9342 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9343 {
9344 struct cfs_rq *dst_cfs_rq;
9345
9346 #ifdef CONFIG_FAIR_GROUP_SCHED
9347 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9348 #else
9349 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9350 #endif
9351 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9352 !entity_eligible(task_cfs_rq(p), &p->se))
9353 return 1;
9354
9355 return 0;
9356 }
9357
9358 /*
9359 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9360 */
9361 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9362 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9363 {
9364 long degrades, hot;
9365
9366 lockdep_assert_rq_held(env->src_rq);
9367 if (p->sched_task_hot)
9368 p->sched_task_hot = 0;
9369
9370 /*
9371 * We do not migrate tasks that are:
9372 * 1) delayed dequeued unless we migrate load, or
9373 * 2) throttled_lb_pair, or
9374 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9375 * 4) running (obviously), or
9376 * 5) are cache-hot on their current CPU.
9377 */
9378 if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9379 return 0;
9380
9381 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
9382 return 0;
9383
9384 /*
9385 * We want to prioritize the migration of eligible tasks.
9386 * For ineligible tasks we soft-limit them and only allow
9387 * them to migrate when nr_balance_failed is non-zero to
9388 * avoid load-balancing trying very hard to balance the load.
9389 */
9390 if (!env->sd->nr_balance_failed &&
9391 task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9392 return 0;
9393
9394 /* Disregard percpu kthreads; they are where they need to be. */
9395 if (kthread_is_per_cpu(p))
9396 return 0;
9397
9398 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9399 int cpu;
9400
9401 schedstat_inc(p->stats.nr_failed_migrations_affine);
9402
9403 env->flags |= LBF_SOME_PINNED;
9404
9405 /*
9406 * Remember if this task can be migrated to any other CPU in
9407 * our sched_group. We may want to revisit it if we couldn't
9408 * meet load balance goals by pulling other tasks on src_cpu.
9409 *
9410 * Avoid computing new_dst_cpu
9411 * - for NEWLY_IDLE
9412 * - if we have already computed one in current iteration
9413 * - if it's an active balance
9414 */
9415 if (env->idle == CPU_NEWLY_IDLE ||
9416 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9417 return 0;
9418
9419 /* Prevent to re-select dst_cpu via env's CPUs: */
9420 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
9421 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
9422 env->flags |= LBF_DST_PINNED;
9423 env->new_dst_cpu = cpu;
9424 break;
9425 }
9426 }
9427
9428 return 0;
9429 }
9430
9431 /* Record that we found at least one task that could run on dst_cpu */
9432 env->flags &= ~LBF_ALL_PINNED;
9433
9434 if (task_on_cpu(env->src_rq, p)) {
9435 schedstat_inc(p->stats.nr_failed_migrations_running);
9436 return 0;
9437 }
9438
9439 /*
9440 * Aggressive migration if:
9441 * 1) active balance
9442 * 2) destination numa is preferred
9443 * 3) task is cache cold, or
9444 * 4) too many balance attempts have failed.
9445 */
9446 if (env->flags & LBF_ACTIVE_LB)
9447 return 1;
9448
9449 degrades = migrate_degrades_locality(p, env);
9450 if (!degrades)
9451 hot = task_hot(p, env);
9452 else
9453 hot = degrades > 0;
9454
9455 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9456 if (hot)
9457 p->sched_task_hot = 1;
9458 return 1;
9459 }
9460
9461 schedstat_inc(p->stats.nr_failed_migrations_hot);
9462 return 0;
9463 }
9464
9465 /*
9466 * detach_task() -- detach the task for the migration specified in env
9467 */
detach_task(struct task_struct * p,struct lb_env * env)9468 static void detach_task(struct task_struct *p, struct lb_env *env)
9469 {
9470 lockdep_assert_rq_held(env->src_rq);
9471
9472 if (p->sched_task_hot) {
9473 p->sched_task_hot = 0;
9474 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9475 schedstat_inc(p->stats.nr_forced_migrations);
9476 }
9477
9478 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9479 set_task_cpu(p, env->dst_cpu);
9480 }
9481
9482 /*
9483 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9484 * part of active balancing operations within "domain".
9485 *
9486 * Returns a task if successful and NULL otherwise.
9487 */
detach_one_task(struct lb_env * env)9488 static struct task_struct *detach_one_task(struct lb_env *env)
9489 {
9490 struct task_struct *p;
9491
9492 lockdep_assert_rq_held(env->src_rq);
9493
9494 list_for_each_entry_reverse(p,
9495 &env->src_rq->cfs_tasks, se.group_node) {
9496 if (!can_migrate_task(p, env))
9497 continue;
9498
9499 detach_task(p, env);
9500
9501 /*
9502 * Right now, this is only the second place where
9503 * lb_gained[env->idle] is updated (other is detach_tasks)
9504 * so we can safely collect stats here rather than
9505 * inside detach_tasks().
9506 */
9507 schedstat_inc(env->sd->lb_gained[env->idle]);
9508 return p;
9509 }
9510 return NULL;
9511 }
9512
9513 /*
9514 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9515 * busiest_rq, as part of a balancing operation within domain "sd".
9516 *
9517 * Returns number of detached tasks if successful and 0 otherwise.
9518 */
detach_tasks(struct lb_env * env)9519 static int detach_tasks(struct lb_env *env)
9520 {
9521 struct list_head *tasks = &env->src_rq->cfs_tasks;
9522 unsigned long util, load;
9523 struct task_struct *p;
9524 int detached = 0;
9525
9526 lockdep_assert_rq_held(env->src_rq);
9527
9528 /*
9529 * Source run queue has been emptied by another CPU, clear
9530 * LBF_ALL_PINNED flag as we will not test any task.
9531 */
9532 if (env->src_rq->nr_running <= 1) {
9533 env->flags &= ~LBF_ALL_PINNED;
9534 return 0;
9535 }
9536
9537 if (env->imbalance <= 0)
9538 return 0;
9539
9540 while (!list_empty(tasks)) {
9541 /*
9542 * We don't want to steal all, otherwise we may be treated likewise,
9543 * which could at worst lead to a livelock crash.
9544 */
9545 if (env->idle && env->src_rq->nr_running <= 1)
9546 break;
9547
9548 env->loop++;
9549 /* We've more or less seen every task there is, call it quits */
9550 if (env->loop > env->loop_max)
9551 break;
9552
9553 /* take a breather every nr_migrate tasks */
9554 if (env->loop > env->loop_break) {
9555 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9556 env->flags |= LBF_NEED_BREAK;
9557 break;
9558 }
9559
9560 p = list_last_entry(tasks, struct task_struct, se.group_node);
9561
9562 if (!can_migrate_task(p, env))
9563 goto next;
9564
9565 switch (env->migration_type) {
9566 case migrate_load:
9567 /*
9568 * Depending of the number of CPUs and tasks and the
9569 * cgroup hierarchy, task_h_load() can return a null
9570 * value. Make sure that env->imbalance decreases
9571 * otherwise detach_tasks() will stop only after
9572 * detaching up to loop_max tasks.
9573 */
9574 load = max_t(unsigned long, task_h_load(p), 1);
9575
9576 if (sched_feat(LB_MIN) &&
9577 load < 16 && !env->sd->nr_balance_failed)
9578 goto next;
9579
9580 /*
9581 * Make sure that we don't migrate too much load.
9582 * Nevertheless, let relax the constraint if
9583 * scheduler fails to find a good waiting task to
9584 * migrate.
9585 */
9586 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9587 goto next;
9588
9589 env->imbalance -= load;
9590 break;
9591
9592 case migrate_util:
9593 util = task_util_est(p);
9594
9595 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9596 goto next;
9597
9598 env->imbalance -= util;
9599 break;
9600
9601 case migrate_task:
9602 env->imbalance--;
9603 break;
9604
9605 case migrate_misfit:
9606 /* This is not a misfit task */
9607 if (task_fits_cpu(p, env->src_cpu))
9608 goto next;
9609
9610 env->imbalance = 0;
9611 break;
9612 }
9613
9614 detach_task(p, env);
9615 list_add(&p->se.group_node, &env->tasks);
9616
9617 detached++;
9618
9619 #ifdef CONFIG_PREEMPTION
9620 /*
9621 * NEWIDLE balancing is a source of latency, so preemptible
9622 * kernels will stop after the first task is detached to minimize
9623 * the critical section.
9624 */
9625 if (env->idle == CPU_NEWLY_IDLE)
9626 break;
9627 #endif
9628
9629 /*
9630 * We only want to steal up to the prescribed amount of
9631 * load/util/tasks.
9632 */
9633 if (env->imbalance <= 0)
9634 break;
9635
9636 continue;
9637 next:
9638 if (p->sched_task_hot)
9639 schedstat_inc(p->stats.nr_failed_migrations_hot);
9640
9641 list_move(&p->se.group_node, tasks);
9642 }
9643
9644 /*
9645 * Right now, this is one of only two places we collect this stat
9646 * so we can safely collect detach_one_task() stats here rather
9647 * than inside detach_one_task().
9648 */
9649 schedstat_add(env->sd->lb_gained[env->idle], detached);
9650
9651 return detached;
9652 }
9653
9654 /*
9655 * attach_task() -- attach the task detached by detach_task() to its new rq.
9656 */
attach_task(struct rq * rq,struct task_struct * p)9657 static void attach_task(struct rq *rq, struct task_struct *p)
9658 {
9659 lockdep_assert_rq_held(rq);
9660
9661 WARN_ON_ONCE(task_rq(p) != rq);
9662 activate_task(rq, p, ENQUEUE_NOCLOCK);
9663 wakeup_preempt(rq, p, 0);
9664 }
9665
9666 /*
9667 * attach_one_task() -- attaches the task returned from detach_one_task() to
9668 * its new rq.
9669 */
attach_one_task(struct rq * rq,struct task_struct * p)9670 static void attach_one_task(struct rq *rq, struct task_struct *p)
9671 {
9672 struct rq_flags rf;
9673
9674 rq_lock(rq, &rf);
9675 update_rq_clock(rq);
9676 attach_task(rq, p);
9677 rq_unlock(rq, &rf);
9678 }
9679
9680 /*
9681 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9682 * new rq.
9683 */
attach_tasks(struct lb_env * env)9684 static void attach_tasks(struct lb_env *env)
9685 {
9686 struct list_head *tasks = &env->tasks;
9687 struct task_struct *p;
9688 struct rq_flags rf;
9689
9690 rq_lock(env->dst_rq, &rf);
9691 update_rq_clock(env->dst_rq);
9692
9693 while (!list_empty(tasks)) {
9694 p = list_first_entry(tasks, struct task_struct, se.group_node);
9695 list_del_init(&p->se.group_node);
9696
9697 attach_task(env->dst_rq, p);
9698 }
9699
9700 rq_unlock(env->dst_rq, &rf);
9701 }
9702
9703 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9704 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9705 {
9706 if (cfs_rq->avg.load_avg)
9707 return true;
9708
9709 if (cfs_rq->avg.util_avg)
9710 return true;
9711
9712 return false;
9713 }
9714
others_have_blocked(struct rq * rq)9715 static inline bool others_have_blocked(struct rq *rq)
9716 {
9717 if (cpu_util_rt(rq))
9718 return true;
9719
9720 if (cpu_util_dl(rq))
9721 return true;
9722
9723 if (hw_load_avg(rq))
9724 return true;
9725
9726 if (cpu_util_irq(rq))
9727 return true;
9728
9729 return false;
9730 }
9731
update_blocked_load_tick(struct rq * rq)9732 static inline void update_blocked_load_tick(struct rq *rq)
9733 {
9734 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9735 }
9736
update_blocked_load_status(struct rq * rq,bool has_blocked)9737 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9738 {
9739 if (!has_blocked)
9740 rq->has_blocked_load = 0;
9741 }
9742 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9743 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9744 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9745 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9746 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9747 #endif
9748
__update_blocked_others(struct rq * rq,bool * done)9749 static bool __update_blocked_others(struct rq *rq, bool *done)
9750 {
9751 bool updated;
9752
9753 /*
9754 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9755 * DL and IRQ signals have been updated before updating CFS.
9756 */
9757 updated = update_other_load_avgs(rq);
9758
9759 if (others_have_blocked(rq))
9760 *done = false;
9761
9762 return updated;
9763 }
9764
9765 #ifdef CONFIG_FAIR_GROUP_SCHED
9766
__update_blocked_fair(struct rq * rq,bool * done)9767 static bool __update_blocked_fair(struct rq *rq, bool *done)
9768 {
9769 struct cfs_rq *cfs_rq, *pos;
9770 bool decayed = false;
9771 int cpu = cpu_of(rq);
9772
9773 /*
9774 * Iterates the task_group tree in a bottom up fashion, see
9775 * list_add_leaf_cfs_rq() for details.
9776 */
9777 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9778 struct sched_entity *se;
9779
9780 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9781 update_tg_load_avg(cfs_rq);
9782
9783 if (cfs_rq->nr_queued == 0)
9784 update_idle_cfs_rq_clock_pelt(cfs_rq);
9785
9786 if (cfs_rq == &rq->cfs)
9787 decayed = true;
9788 }
9789
9790 /* Propagate pending load changes to the parent, if any: */
9791 se = cfs_rq->tg->se[cpu];
9792 if (se && !skip_blocked_update(se))
9793 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9794
9795 /*
9796 * There can be a lot of idle CPU cgroups. Don't let fully
9797 * decayed cfs_rqs linger on the list.
9798 */
9799 if (cfs_rq_is_decayed(cfs_rq))
9800 list_del_leaf_cfs_rq(cfs_rq);
9801
9802 /* Don't need periodic decay once load/util_avg are null */
9803 if (cfs_rq_has_blocked(cfs_rq))
9804 *done = false;
9805 }
9806
9807 return decayed;
9808 }
9809
9810 /*
9811 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9812 * This needs to be done in a top-down fashion because the load of a child
9813 * group is a fraction of its parents load.
9814 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9815 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9816 {
9817 struct rq *rq = rq_of(cfs_rq);
9818 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9819 unsigned long now = jiffies;
9820 unsigned long load;
9821
9822 if (cfs_rq->last_h_load_update == now)
9823 return;
9824
9825 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9826 for_each_sched_entity(se) {
9827 cfs_rq = cfs_rq_of(se);
9828 WRITE_ONCE(cfs_rq->h_load_next, se);
9829 if (cfs_rq->last_h_load_update == now)
9830 break;
9831 }
9832
9833 if (!se) {
9834 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9835 cfs_rq->last_h_load_update = now;
9836 }
9837
9838 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9839 load = cfs_rq->h_load;
9840 load = div64_ul(load * se->avg.load_avg,
9841 cfs_rq_load_avg(cfs_rq) + 1);
9842 cfs_rq = group_cfs_rq(se);
9843 cfs_rq->h_load = load;
9844 cfs_rq->last_h_load_update = now;
9845 }
9846 }
9847
task_h_load(struct task_struct * p)9848 static unsigned long task_h_load(struct task_struct *p)
9849 {
9850 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9851
9852 update_cfs_rq_h_load(cfs_rq);
9853 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9854 cfs_rq_load_avg(cfs_rq) + 1);
9855 }
9856 #else
__update_blocked_fair(struct rq * rq,bool * done)9857 static bool __update_blocked_fair(struct rq *rq, bool *done)
9858 {
9859 struct cfs_rq *cfs_rq = &rq->cfs;
9860 bool decayed;
9861
9862 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9863 if (cfs_rq_has_blocked(cfs_rq))
9864 *done = false;
9865
9866 return decayed;
9867 }
9868
task_h_load(struct task_struct * p)9869 static unsigned long task_h_load(struct task_struct *p)
9870 {
9871 return p->se.avg.load_avg;
9872 }
9873 #endif
9874
sched_balance_update_blocked_averages(int cpu)9875 static void sched_balance_update_blocked_averages(int cpu)
9876 {
9877 bool decayed = false, done = true;
9878 struct rq *rq = cpu_rq(cpu);
9879 struct rq_flags rf;
9880
9881 rq_lock_irqsave(rq, &rf);
9882 update_blocked_load_tick(rq);
9883 update_rq_clock(rq);
9884
9885 decayed |= __update_blocked_others(rq, &done);
9886 decayed |= __update_blocked_fair(rq, &done);
9887
9888 update_blocked_load_status(rq, !done);
9889 if (decayed)
9890 cpufreq_update_util(rq, 0);
9891 rq_unlock_irqrestore(rq, &rf);
9892 }
9893
9894 /********** Helpers for sched_balance_find_src_group ************************/
9895
9896 /*
9897 * sg_lb_stats - stats of a sched_group required for load-balancing:
9898 */
9899 struct sg_lb_stats {
9900 unsigned long avg_load; /* Avg load over the CPUs of the group */
9901 unsigned long group_load; /* Total load over the CPUs of the group */
9902 unsigned long group_capacity; /* Capacity over the CPUs of the group */
9903 unsigned long group_util; /* Total utilization over the CPUs of the group */
9904 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9905 unsigned int sum_nr_running; /* Nr of all tasks running in the group */
9906 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9907 unsigned int idle_cpus; /* Nr of idle CPUs in the group */
9908 unsigned int group_weight;
9909 enum group_type group_type;
9910 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9911 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9912 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9913 #ifdef CONFIG_NUMA_BALANCING
9914 unsigned int nr_numa_running;
9915 unsigned int nr_preferred_running;
9916 #endif
9917 };
9918
9919 /*
9920 * sd_lb_stats - stats of a sched_domain required for load-balancing:
9921 */
9922 struct sd_lb_stats {
9923 struct sched_group *busiest; /* Busiest group in this sd */
9924 struct sched_group *local; /* Local group in this sd */
9925 unsigned long total_load; /* Total load of all groups in sd */
9926 unsigned long total_capacity; /* Total capacity of all groups in sd */
9927 unsigned long avg_load; /* Average load across all groups in sd */
9928 unsigned int prefer_sibling; /* Tasks should go to sibling first */
9929
9930 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
9931 struct sg_lb_stats local_stat; /* Statistics of the local group */
9932 };
9933
init_sd_lb_stats(struct sd_lb_stats * sds)9934 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9935 {
9936 /*
9937 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9938 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9939 * We must however set busiest_stat::group_type and
9940 * busiest_stat::idle_cpus to the worst busiest group because
9941 * update_sd_pick_busiest() reads these before assignment.
9942 */
9943 *sds = (struct sd_lb_stats){
9944 .busiest = NULL,
9945 .local = NULL,
9946 .total_load = 0UL,
9947 .total_capacity = 0UL,
9948 .busiest_stat = {
9949 .idle_cpus = UINT_MAX,
9950 .group_type = group_has_spare,
9951 },
9952 };
9953 }
9954
scale_rt_capacity(int cpu)9955 static unsigned long scale_rt_capacity(int cpu)
9956 {
9957 unsigned long max = get_actual_cpu_capacity(cpu);
9958 struct rq *rq = cpu_rq(cpu);
9959 unsigned long used, free;
9960 unsigned long irq;
9961
9962 irq = cpu_util_irq(rq);
9963
9964 if (unlikely(irq >= max))
9965 return 1;
9966
9967 /*
9968 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9969 * (running and not running) with weights 0 and 1024 respectively.
9970 */
9971 used = cpu_util_rt(rq);
9972 used += cpu_util_dl(rq);
9973
9974 if (unlikely(used >= max))
9975 return 1;
9976
9977 free = max - used;
9978
9979 return scale_irq_capacity(free, irq, max);
9980 }
9981
update_cpu_capacity(struct sched_domain * sd,int cpu)9982 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9983 {
9984 unsigned long capacity = scale_rt_capacity(cpu);
9985 struct sched_group *sdg = sd->groups;
9986
9987 if (!capacity)
9988 capacity = 1;
9989
9990 cpu_rq(cpu)->cpu_capacity = capacity;
9991 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9992
9993 sdg->sgc->capacity = capacity;
9994 sdg->sgc->min_capacity = capacity;
9995 sdg->sgc->max_capacity = capacity;
9996 }
9997
update_group_capacity(struct sched_domain * sd,int cpu)9998 void update_group_capacity(struct sched_domain *sd, int cpu)
9999 {
10000 struct sched_domain *child = sd->child;
10001 struct sched_group *group, *sdg = sd->groups;
10002 unsigned long capacity, min_capacity, max_capacity;
10003 unsigned long interval;
10004
10005 interval = msecs_to_jiffies(sd->balance_interval);
10006 interval = clamp(interval, 1UL, max_load_balance_interval);
10007 sdg->sgc->next_update = jiffies + interval;
10008
10009 if (!child) {
10010 update_cpu_capacity(sd, cpu);
10011 return;
10012 }
10013
10014 capacity = 0;
10015 min_capacity = ULONG_MAX;
10016 max_capacity = 0;
10017
10018 if (child->flags & SD_OVERLAP) {
10019 /*
10020 * SD_OVERLAP domains cannot assume that child groups
10021 * span the current group.
10022 */
10023
10024 for_each_cpu(cpu, sched_group_span(sdg)) {
10025 unsigned long cpu_cap = capacity_of(cpu);
10026
10027 capacity += cpu_cap;
10028 min_capacity = min(cpu_cap, min_capacity);
10029 max_capacity = max(cpu_cap, max_capacity);
10030 }
10031 } else {
10032 /*
10033 * !SD_OVERLAP domains can assume that child groups
10034 * span the current group.
10035 */
10036
10037 group = child->groups;
10038 do {
10039 struct sched_group_capacity *sgc = group->sgc;
10040
10041 capacity += sgc->capacity;
10042 min_capacity = min(sgc->min_capacity, min_capacity);
10043 max_capacity = max(sgc->max_capacity, max_capacity);
10044 group = group->next;
10045 } while (group != child->groups);
10046 }
10047
10048 sdg->sgc->capacity = capacity;
10049 sdg->sgc->min_capacity = min_capacity;
10050 sdg->sgc->max_capacity = max_capacity;
10051 }
10052
10053 /*
10054 * Check whether the capacity of the rq has been noticeably reduced by side
10055 * activity. The imbalance_pct is used for the threshold.
10056 * Return true is the capacity is reduced
10057 */
10058 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10059 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10060 {
10061 return ((rq->cpu_capacity * sd->imbalance_pct) <
10062 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10063 }
10064
10065 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10066 static inline bool check_misfit_status(struct rq *rq)
10067 {
10068 return rq->misfit_task_load;
10069 }
10070
10071 /*
10072 * Group imbalance indicates (and tries to solve) the problem where balancing
10073 * groups is inadequate due to ->cpus_ptr constraints.
10074 *
10075 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10076 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10077 * Something like:
10078 *
10079 * { 0 1 2 3 } { 4 5 6 7 }
10080 * * * * *
10081 *
10082 * If we were to balance group-wise we'd place two tasks in the first group and
10083 * two tasks in the second group. Clearly this is undesired as it will overload
10084 * cpu 3 and leave one of the CPUs in the second group unused.
10085 *
10086 * The current solution to this issue is detecting the skew in the first group
10087 * by noticing the lower domain failed to reach balance and had difficulty
10088 * moving tasks due to affinity constraints.
10089 *
10090 * When this is so detected; this group becomes a candidate for busiest; see
10091 * update_sd_pick_busiest(). And calculate_imbalance() and
10092 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10093 * to create an effective group imbalance.
10094 *
10095 * This is a somewhat tricky proposition since the next run might not find the
10096 * group imbalance and decide the groups need to be balanced again. A most
10097 * subtle and fragile situation.
10098 */
10099
sg_imbalanced(struct sched_group * group)10100 static inline int sg_imbalanced(struct sched_group *group)
10101 {
10102 return group->sgc->imbalance;
10103 }
10104
10105 /*
10106 * group_has_capacity returns true if the group has spare capacity that could
10107 * be used by some tasks.
10108 * We consider that a group has spare capacity if the number of task is
10109 * smaller than the number of CPUs or if the utilization is lower than the
10110 * available capacity for CFS tasks.
10111 * For the latter, we use a threshold to stabilize the state, to take into
10112 * account the variance of the tasks' load and to return true if the available
10113 * capacity in meaningful for the load balancer.
10114 * As an example, an available capacity of 1% can appear but it doesn't make
10115 * any benefit for the load balance.
10116 */
10117 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10118 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10119 {
10120 if (sgs->sum_nr_running < sgs->group_weight)
10121 return true;
10122
10123 if ((sgs->group_capacity * imbalance_pct) <
10124 (sgs->group_runnable * 100))
10125 return false;
10126
10127 if ((sgs->group_capacity * 100) >
10128 (sgs->group_util * imbalance_pct))
10129 return true;
10130
10131 return false;
10132 }
10133
10134 /*
10135 * group_is_overloaded returns true if the group has more tasks than it can
10136 * handle.
10137 * group_is_overloaded is not equals to !group_has_capacity because a group
10138 * with the exact right number of tasks, has no more spare capacity but is not
10139 * overloaded so both group_has_capacity and group_is_overloaded return
10140 * false.
10141 */
10142 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10143 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10144 {
10145 if (sgs->sum_nr_running <= sgs->group_weight)
10146 return false;
10147
10148 if ((sgs->group_capacity * 100) <
10149 (sgs->group_util * imbalance_pct))
10150 return true;
10151
10152 if ((sgs->group_capacity * imbalance_pct) <
10153 (sgs->group_runnable * 100))
10154 return true;
10155
10156 return false;
10157 }
10158
10159 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10160 group_type group_classify(unsigned int imbalance_pct,
10161 struct sched_group *group,
10162 struct sg_lb_stats *sgs)
10163 {
10164 if (group_is_overloaded(imbalance_pct, sgs))
10165 return group_overloaded;
10166
10167 if (sg_imbalanced(group))
10168 return group_imbalanced;
10169
10170 if (sgs->group_asym_packing)
10171 return group_asym_packing;
10172
10173 if (sgs->group_smt_balance)
10174 return group_smt_balance;
10175
10176 if (sgs->group_misfit_task_load)
10177 return group_misfit_task;
10178
10179 if (!group_has_capacity(imbalance_pct, sgs))
10180 return group_fully_busy;
10181
10182 return group_has_spare;
10183 }
10184
10185 /**
10186 * sched_use_asym_prio - Check whether asym_packing priority must be used
10187 * @sd: The scheduling domain of the load balancing
10188 * @cpu: A CPU
10189 *
10190 * Always use CPU priority when balancing load between SMT siblings. When
10191 * balancing load between cores, it is not sufficient that @cpu is idle. Only
10192 * use CPU priority if the whole core is idle.
10193 *
10194 * Returns: True if the priority of @cpu must be followed. False otherwise.
10195 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10196 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10197 {
10198 if (!(sd->flags & SD_ASYM_PACKING))
10199 return false;
10200
10201 if (!sched_smt_active())
10202 return true;
10203
10204 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10205 }
10206
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10207 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10208 {
10209 /*
10210 * First check if @dst_cpu can do asym_packing load balance. Only do it
10211 * if it has higher priority than @src_cpu.
10212 */
10213 return sched_use_asym_prio(sd, dst_cpu) &&
10214 sched_asym_prefer(dst_cpu, src_cpu);
10215 }
10216
10217 /**
10218 * sched_group_asym - Check if the destination CPU can do asym_packing balance
10219 * @env: The load balancing environment
10220 * @sgs: Load-balancing statistics of the candidate busiest group
10221 * @group: The candidate busiest group
10222 *
10223 * @env::dst_cpu can do asym_packing if it has higher priority than the
10224 * preferred CPU of @group.
10225 *
10226 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10227 * otherwise.
10228 */
10229 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10230 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10231 {
10232 /*
10233 * CPU priorities do not make sense for SMT cores with more than one
10234 * busy sibling.
10235 */
10236 if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10237 (sgs->group_weight - sgs->idle_cpus != 1))
10238 return false;
10239
10240 return sched_asym(env->sd, env->dst_cpu, group->asym_prefer_cpu);
10241 }
10242
10243 /* 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)10244 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10245 struct sched_group *sg2)
10246 {
10247 if (!sg1 || !sg2)
10248 return false;
10249
10250 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10251 (sg2->flags & SD_SHARE_CPUCAPACITY);
10252 }
10253
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10254 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10255 struct sched_group *group)
10256 {
10257 if (!env->idle)
10258 return false;
10259
10260 /*
10261 * For SMT source group, it is better to move a task
10262 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10263 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10264 * will not be on.
10265 */
10266 if (group->flags & SD_SHARE_CPUCAPACITY &&
10267 sgs->sum_h_nr_running > 1)
10268 return true;
10269
10270 return false;
10271 }
10272
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10273 static inline long sibling_imbalance(struct lb_env *env,
10274 struct sd_lb_stats *sds,
10275 struct sg_lb_stats *busiest,
10276 struct sg_lb_stats *local)
10277 {
10278 int ncores_busiest, ncores_local;
10279 long imbalance;
10280
10281 if (!env->idle || !busiest->sum_nr_running)
10282 return 0;
10283
10284 ncores_busiest = sds->busiest->cores;
10285 ncores_local = sds->local->cores;
10286
10287 if (ncores_busiest == ncores_local) {
10288 imbalance = busiest->sum_nr_running;
10289 lsub_positive(&imbalance, local->sum_nr_running);
10290 return imbalance;
10291 }
10292
10293 /* Balance such that nr_running/ncores ratio are same on both groups */
10294 imbalance = ncores_local * busiest->sum_nr_running;
10295 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10296 /* Normalize imbalance and do rounding on normalization */
10297 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10298 imbalance /= ncores_local + ncores_busiest;
10299
10300 /* Take advantage of resource in an empty sched group */
10301 if (imbalance <= 1 && local->sum_nr_running == 0 &&
10302 busiest->sum_nr_running > 1)
10303 imbalance = 2;
10304
10305 return imbalance;
10306 }
10307
10308 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10309 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10310 {
10311 /*
10312 * When there is more than 1 task, the group_overloaded case already
10313 * takes care of cpu with reduced capacity
10314 */
10315 if (rq->cfs.h_nr_runnable != 1)
10316 return false;
10317
10318 return check_cpu_capacity(rq, sd);
10319 }
10320
10321 /**
10322 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10323 * @env: The load balancing environment.
10324 * @sds: Load-balancing data with statistics of the local group.
10325 * @group: sched_group whose statistics are to be updated.
10326 * @sgs: variable to hold the statistics for this group.
10327 * @sg_overloaded: sched_group is overloaded
10328 * @sg_overutilized: sched_group is overutilized
10329 */
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,bool * sg_overutilized)10330 static inline void update_sg_lb_stats(struct lb_env *env,
10331 struct sd_lb_stats *sds,
10332 struct sched_group *group,
10333 struct sg_lb_stats *sgs,
10334 bool *sg_overloaded,
10335 bool *sg_overutilized)
10336 {
10337 int i, nr_running, local_group, sd_flags = env->sd->flags;
10338 bool balancing_at_rd = !env->sd->parent;
10339
10340 memset(sgs, 0, sizeof(*sgs));
10341
10342 local_group = group == sds->local;
10343
10344 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10345 struct rq *rq = cpu_rq(i);
10346 unsigned long load = cpu_load(rq);
10347
10348 sgs->group_load += load;
10349 sgs->group_util += cpu_util_cfs(i);
10350 sgs->group_runnable += cpu_runnable(rq);
10351 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10352
10353 nr_running = rq->nr_running;
10354 sgs->sum_nr_running += nr_running;
10355
10356 if (cpu_overutilized(i))
10357 *sg_overutilized = 1;
10358
10359 /*
10360 * No need to call idle_cpu() if nr_running is not 0
10361 */
10362 if (!nr_running && idle_cpu(i)) {
10363 sgs->idle_cpus++;
10364 /* Idle cpu can't have misfit task */
10365 continue;
10366 }
10367
10368 /* Overload indicator is only updated at root domain */
10369 if (balancing_at_rd && nr_running > 1)
10370 *sg_overloaded = 1;
10371
10372 #ifdef CONFIG_NUMA_BALANCING
10373 /* Only fbq_classify_group() uses this to classify NUMA groups */
10374 if (sd_flags & SD_NUMA) {
10375 sgs->nr_numa_running += rq->nr_numa_running;
10376 sgs->nr_preferred_running += rq->nr_preferred_running;
10377 }
10378 #endif
10379 if (local_group)
10380 continue;
10381
10382 if (sd_flags & SD_ASYM_CPUCAPACITY) {
10383 /* Check for a misfit task on the cpu */
10384 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10385 sgs->group_misfit_task_load = rq->misfit_task_load;
10386 *sg_overloaded = 1;
10387 }
10388 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10389 /* Check for a task running on a CPU with reduced capacity */
10390 if (sgs->group_misfit_task_load < load)
10391 sgs->group_misfit_task_load = load;
10392 }
10393 }
10394
10395 sgs->group_capacity = group->sgc->capacity;
10396
10397 sgs->group_weight = group->group_weight;
10398
10399 /* Check if dst CPU is idle and preferred to this group */
10400 if (!local_group && env->idle && sgs->sum_h_nr_running &&
10401 sched_group_asym(env, sgs, group))
10402 sgs->group_asym_packing = 1;
10403
10404 /* Check for loaded SMT group to be balanced to dst CPU */
10405 if (!local_group && smt_balance(env, sgs, group))
10406 sgs->group_smt_balance = 1;
10407
10408 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10409
10410 /* Computing avg_load makes sense only when group is overloaded */
10411 if (sgs->group_type == group_overloaded)
10412 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10413 sgs->group_capacity;
10414 }
10415
10416 /**
10417 * update_sd_pick_busiest - return 1 on busiest group
10418 * @env: The load balancing environment.
10419 * @sds: sched_domain statistics
10420 * @sg: sched_group candidate to be checked for being the busiest
10421 * @sgs: sched_group statistics
10422 *
10423 * Determine if @sg is a busier group than the previously selected
10424 * busiest group.
10425 *
10426 * Return: %true if @sg is a busier group than the previously selected
10427 * busiest group. %false otherwise.
10428 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10429 static bool update_sd_pick_busiest(struct lb_env *env,
10430 struct sd_lb_stats *sds,
10431 struct sched_group *sg,
10432 struct sg_lb_stats *sgs)
10433 {
10434 struct sg_lb_stats *busiest = &sds->busiest_stat;
10435
10436 /* Make sure that there is at least one task to pull */
10437 if (!sgs->sum_h_nr_running)
10438 return false;
10439
10440 /*
10441 * Don't try to pull misfit tasks we can't help.
10442 * We can use max_capacity here as reduction in capacity on some
10443 * CPUs in the group should either be possible to resolve
10444 * internally or be covered by avg_load imbalance (eventually).
10445 */
10446 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10447 (sgs->group_type == group_misfit_task) &&
10448 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10449 sds->local_stat.group_type != group_has_spare))
10450 return false;
10451
10452 if (sgs->group_type > busiest->group_type)
10453 return true;
10454
10455 if (sgs->group_type < busiest->group_type)
10456 return false;
10457
10458 /*
10459 * The candidate and the current busiest group are the same type of
10460 * group. Let check which one is the busiest according to the type.
10461 */
10462
10463 switch (sgs->group_type) {
10464 case group_overloaded:
10465 /* Select the overloaded group with highest avg_load. */
10466 return sgs->avg_load > busiest->avg_load;
10467
10468 case group_imbalanced:
10469 /*
10470 * Select the 1st imbalanced group as we don't have any way to
10471 * choose one more than another.
10472 */
10473 return false;
10474
10475 case group_asym_packing:
10476 /* Prefer to move from lowest priority CPU's work */
10477 return sched_asym_prefer(sds->busiest->asym_prefer_cpu, sg->asym_prefer_cpu);
10478
10479 case group_misfit_task:
10480 /*
10481 * If we have more than one misfit sg go with the biggest
10482 * misfit.
10483 */
10484 return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10485
10486 case group_smt_balance:
10487 /*
10488 * Check if we have spare CPUs on either SMT group to
10489 * choose has spare or fully busy handling.
10490 */
10491 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10492 goto has_spare;
10493
10494 fallthrough;
10495
10496 case group_fully_busy:
10497 /*
10498 * Select the fully busy group with highest avg_load. In
10499 * theory, there is no need to pull task from such kind of
10500 * group because tasks have all compute capacity that they need
10501 * but we can still improve the overall throughput by reducing
10502 * contention when accessing shared HW resources.
10503 *
10504 * XXX for now avg_load is not computed and always 0 so we
10505 * select the 1st one, except if @sg is composed of SMT
10506 * siblings.
10507 */
10508
10509 if (sgs->avg_load < busiest->avg_load)
10510 return false;
10511
10512 if (sgs->avg_load == busiest->avg_load) {
10513 /*
10514 * SMT sched groups need more help than non-SMT groups.
10515 * If @sg happens to also be SMT, either choice is good.
10516 */
10517 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10518 return false;
10519 }
10520
10521 break;
10522
10523 case group_has_spare:
10524 /*
10525 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10526 * as we do not want to pull task off SMT core with one task
10527 * and make the core idle.
10528 */
10529 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10530 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10531 return false;
10532 else
10533 return true;
10534 }
10535 has_spare:
10536
10537 /*
10538 * Select not overloaded group with lowest number of idle CPUs
10539 * and highest number of running tasks. We could also compare
10540 * the spare capacity which is more stable but it can end up
10541 * that the group has less spare capacity but finally more idle
10542 * CPUs which means less opportunity to pull tasks.
10543 */
10544 if (sgs->idle_cpus > busiest->idle_cpus)
10545 return false;
10546 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10547 (sgs->sum_nr_running <= busiest->sum_nr_running))
10548 return false;
10549
10550 break;
10551 }
10552
10553 /*
10554 * Candidate sg has no more than one task per CPU and has higher
10555 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10556 * throughput. Maximize throughput, power/energy consequences are not
10557 * considered.
10558 */
10559 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10560 (sgs->group_type <= group_fully_busy) &&
10561 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10562 return false;
10563
10564 return true;
10565 }
10566
10567 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10568 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10569 {
10570 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10571 return regular;
10572 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10573 return remote;
10574 return all;
10575 }
10576
fbq_classify_rq(struct rq * rq)10577 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10578 {
10579 if (rq->nr_running > rq->nr_numa_running)
10580 return regular;
10581 if (rq->nr_running > rq->nr_preferred_running)
10582 return remote;
10583 return all;
10584 }
10585 #else
fbq_classify_group(struct sg_lb_stats * sgs)10586 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10587 {
10588 return all;
10589 }
10590
fbq_classify_rq(struct rq * rq)10591 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10592 {
10593 return regular;
10594 }
10595 #endif /* CONFIG_NUMA_BALANCING */
10596
10597
10598 struct sg_lb_stats;
10599
10600 /*
10601 * task_running_on_cpu - return 1 if @p is running on @cpu.
10602 */
10603
task_running_on_cpu(int cpu,struct task_struct * p)10604 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10605 {
10606 /* Task has no contribution or is new */
10607 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10608 return 0;
10609
10610 if (task_on_rq_queued(p))
10611 return 1;
10612
10613 return 0;
10614 }
10615
10616 /**
10617 * idle_cpu_without - would a given CPU be idle without p ?
10618 * @cpu: the processor on which idleness is tested.
10619 * @p: task which should be ignored.
10620 *
10621 * Return: 1 if the CPU would be idle. 0 otherwise.
10622 */
idle_cpu_without(int cpu,struct task_struct * p)10623 static int idle_cpu_without(int cpu, struct task_struct *p)
10624 {
10625 struct rq *rq = cpu_rq(cpu);
10626
10627 if (rq->curr != rq->idle && rq->curr != p)
10628 return 0;
10629
10630 /*
10631 * rq->nr_running can't be used but an updated version without the
10632 * impact of p on cpu must be used instead. The updated nr_running
10633 * be computed and tested before calling idle_cpu_without().
10634 */
10635
10636 if (rq->ttwu_pending)
10637 return 0;
10638
10639 return 1;
10640 }
10641
10642 /*
10643 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10644 * @sd: The sched_domain level to look for idlest group.
10645 * @group: sched_group whose statistics are to be updated.
10646 * @sgs: variable to hold the statistics for this group.
10647 * @p: The task for which we look for the idlest group/CPU.
10648 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10649 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10650 struct sched_group *group,
10651 struct sg_lb_stats *sgs,
10652 struct task_struct *p)
10653 {
10654 int i, nr_running;
10655
10656 memset(sgs, 0, sizeof(*sgs));
10657
10658 /* Assume that task can't fit any CPU of the group */
10659 if (sd->flags & SD_ASYM_CPUCAPACITY)
10660 sgs->group_misfit_task_load = 1;
10661
10662 for_each_cpu(i, sched_group_span(group)) {
10663 struct rq *rq = cpu_rq(i);
10664 unsigned int local;
10665
10666 sgs->group_load += cpu_load_without(rq, p);
10667 sgs->group_util += cpu_util_without(i, p);
10668 sgs->group_runnable += cpu_runnable_without(rq, p);
10669 local = task_running_on_cpu(i, p);
10670 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
10671
10672 nr_running = rq->nr_running - local;
10673 sgs->sum_nr_running += nr_running;
10674
10675 /*
10676 * No need to call idle_cpu_without() if nr_running is not 0
10677 */
10678 if (!nr_running && idle_cpu_without(i, p))
10679 sgs->idle_cpus++;
10680
10681 /* Check if task fits in the CPU */
10682 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10683 sgs->group_misfit_task_load &&
10684 task_fits_cpu(p, i))
10685 sgs->group_misfit_task_load = 0;
10686
10687 }
10688
10689 sgs->group_capacity = group->sgc->capacity;
10690
10691 sgs->group_weight = group->group_weight;
10692
10693 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10694
10695 /*
10696 * Computing avg_load makes sense only when group is fully busy or
10697 * overloaded
10698 */
10699 if (sgs->group_type == group_fully_busy ||
10700 sgs->group_type == group_overloaded)
10701 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10702 sgs->group_capacity;
10703 }
10704
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10705 static bool update_pick_idlest(struct sched_group *idlest,
10706 struct sg_lb_stats *idlest_sgs,
10707 struct sched_group *group,
10708 struct sg_lb_stats *sgs)
10709 {
10710 if (sgs->group_type < idlest_sgs->group_type)
10711 return true;
10712
10713 if (sgs->group_type > idlest_sgs->group_type)
10714 return false;
10715
10716 /*
10717 * The candidate and the current idlest group are the same type of
10718 * group. Let check which one is the idlest according to the type.
10719 */
10720
10721 switch (sgs->group_type) {
10722 case group_overloaded:
10723 case group_fully_busy:
10724 /* Select the group with lowest avg_load. */
10725 if (idlest_sgs->avg_load <= sgs->avg_load)
10726 return false;
10727 break;
10728
10729 case group_imbalanced:
10730 case group_asym_packing:
10731 case group_smt_balance:
10732 /* Those types are not used in the slow wakeup path */
10733 return false;
10734
10735 case group_misfit_task:
10736 /* Select group with the highest max capacity */
10737 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10738 return false;
10739 break;
10740
10741 case group_has_spare:
10742 /* Select group with most idle CPUs */
10743 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10744 return false;
10745
10746 /* Select group with lowest group_util */
10747 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10748 idlest_sgs->group_util <= sgs->group_util)
10749 return false;
10750
10751 break;
10752 }
10753
10754 return true;
10755 }
10756
10757 /*
10758 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
10759 * domain.
10760 *
10761 * Assumes p is allowed on at least one CPU in sd.
10762 */
10763 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10764 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10765 {
10766 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10767 struct sg_lb_stats local_sgs, tmp_sgs;
10768 struct sg_lb_stats *sgs;
10769 unsigned long imbalance;
10770 struct sg_lb_stats idlest_sgs = {
10771 .avg_load = UINT_MAX,
10772 .group_type = group_overloaded,
10773 };
10774
10775 do {
10776 int local_group;
10777
10778 /* Skip over this group if it has no CPUs allowed */
10779 if (!cpumask_intersects(sched_group_span(group),
10780 p->cpus_ptr))
10781 continue;
10782
10783 /* Skip over this group if no cookie matched */
10784 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10785 continue;
10786
10787 local_group = cpumask_test_cpu(this_cpu,
10788 sched_group_span(group));
10789
10790 if (local_group) {
10791 sgs = &local_sgs;
10792 local = group;
10793 } else {
10794 sgs = &tmp_sgs;
10795 }
10796
10797 update_sg_wakeup_stats(sd, group, sgs, p);
10798
10799 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10800 idlest = group;
10801 idlest_sgs = *sgs;
10802 }
10803
10804 } while (group = group->next, group != sd->groups);
10805
10806
10807 /* There is no idlest group to push tasks to */
10808 if (!idlest)
10809 return NULL;
10810
10811 /* The local group has been skipped because of CPU affinity */
10812 if (!local)
10813 return idlest;
10814
10815 /*
10816 * If the local group is idler than the selected idlest group
10817 * don't try and push the task.
10818 */
10819 if (local_sgs.group_type < idlest_sgs.group_type)
10820 return NULL;
10821
10822 /*
10823 * If the local group is busier than the selected idlest group
10824 * try and push the task.
10825 */
10826 if (local_sgs.group_type > idlest_sgs.group_type)
10827 return idlest;
10828
10829 switch (local_sgs.group_type) {
10830 case group_overloaded:
10831 case group_fully_busy:
10832
10833 /* Calculate allowed imbalance based on load */
10834 imbalance = scale_load_down(NICE_0_LOAD) *
10835 (sd->imbalance_pct-100) / 100;
10836
10837 /*
10838 * When comparing groups across NUMA domains, it's possible for
10839 * the local domain to be very lightly loaded relative to the
10840 * remote domains but "imbalance" skews the comparison making
10841 * remote CPUs look much more favourable. When considering
10842 * cross-domain, add imbalance to the load on the remote node
10843 * and consider staying local.
10844 */
10845
10846 if ((sd->flags & SD_NUMA) &&
10847 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10848 return NULL;
10849
10850 /*
10851 * If the local group is less loaded than the selected
10852 * idlest group don't try and push any tasks.
10853 */
10854 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10855 return NULL;
10856
10857 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10858 return NULL;
10859 break;
10860
10861 case group_imbalanced:
10862 case group_asym_packing:
10863 case group_smt_balance:
10864 /* Those type are not used in the slow wakeup path */
10865 return NULL;
10866
10867 case group_misfit_task:
10868 /* Select group with the highest max capacity */
10869 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10870 return NULL;
10871 break;
10872
10873 case group_has_spare:
10874 #ifdef CONFIG_NUMA
10875 if (sd->flags & SD_NUMA) {
10876 int imb_numa_nr = sd->imb_numa_nr;
10877 #ifdef CONFIG_NUMA_BALANCING
10878 int idlest_cpu;
10879 /*
10880 * If there is spare capacity at NUMA, try to select
10881 * the preferred node
10882 */
10883 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10884 return NULL;
10885
10886 idlest_cpu = cpumask_first(sched_group_span(idlest));
10887 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10888 return idlest;
10889 #endif /* CONFIG_NUMA_BALANCING */
10890 /*
10891 * Otherwise, keep the task close to the wakeup source
10892 * and improve locality if the number of running tasks
10893 * would remain below threshold where an imbalance is
10894 * allowed while accounting for the possibility the
10895 * task is pinned to a subset of CPUs. If there is a
10896 * real need of migration, periodic load balance will
10897 * take care of it.
10898 */
10899 if (p->nr_cpus_allowed != NR_CPUS) {
10900 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10901
10902 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10903 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10904 }
10905
10906 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10907 if (!adjust_numa_imbalance(imbalance,
10908 local_sgs.sum_nr_running + 1,
10909 imb_numa_nr)) {
10910 return NULL;
10911 }
10912 }
10913 #endif /* CONFIG_NUMA */
10914
10915 /*
10916 * Select group with highest number of idle CPUs. We could also
10917 * compare the utilization which is more stable but it can end
10918 * up that the group has less spare capacity but finally more
10919 * idle CPUs which means more opportunity to run task.
10920 */
10921 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10922 return NULL;
10923 break;
10924 }
10925
10926 return idlest;
10927 }
10928
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)10929 static void update_idle_cpu_scan(struct lb_env *env,
10930 unsigned long sum_util)
10931 {
10932 struct sched_domain_shared *sd_share;
10933 int llc_weight, pct;
10934 u64 x, y, tmp;
10935 /*
10936 * Update the number of CPUs to scan in LLC domain, which could
10937 * be used as a hint in select_idle_cpu(). The update of sd_share
10938 * could be expensive because it is within a shared cache line.
10939 * So the write of this hint only occurs during periodic load
10940 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10941 * can fire way more frequently than the former.
10942 */
10943 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10944 return;
10945
10946 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10947 if (env->sd->span_weight != llc_weight)
10948 return;
10949
10950 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10951 if (!sd_share)
10952 return;
10953
10954 /*
10955 * The number of CPUs to search drops as sum_util increases, when
10956 * sum_util hits 85% or above, the scan stops.
10957 * The reason to choose 85% as the threshold is because this is the
10958 * imbalance_pct(117) when a LLC sched group is overloaded.
10959 *
10960 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10961 * and y'= y / SCHED_CAPACITY_SCALE
10962 *
10963 * x is the ratio of sum_util compared to the CPU capacity:
10964 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10965 * y' is the ratio of CPUs to be scanned in the LLC domain,
10966 * and the number of CPUs to scan is calculated by:
10967 *
10968 * nr_scan = llc_weight * y' [2]
10969 *
10970 * When x hits the threshold of overloaded, AKA, when
10971 * x = 100 / pct, y drops to 0. According to [1],
10972 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10973 *
10974 * Scale x by SCHED_CAPACITY_SCALE:
10975 * x' = sum_util / llc_weight; [3]
10976 *
10977 * and finally [1] becomes:
10978 * y = SCHED_CAPACITY_SCALE -
10979 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10980 *
10981 */
10982 /* equation [3] */
10983 x = sum_util;
10984 do_div(x, llc_weight);
10985
10986 /* equation [4] */
10987 pct = env->sd->imbalance_pct;
10988 tmp = x * x * pct * pct;
10989 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10990 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10991 y = SCHED_CAPACITY_SCALE - tmp;
10992
10993 /* equation [2] */
10994 y *= llc_weight;
10995 do_div(y, SCHED_CAPACITY_SCALE);
10996 if ((int)y != sd_share->nr_idle_scan)
10997 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10998 }
10999
11000 /**
11001 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11002 * @env: The load balancing environment.
11003 * @sds: variable to hold the statistics for this sched_domain.
11004 */
11005
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11006 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11007 {
11008 struct sched_group *sg = env->sd->groups;
11009 struct sg_lb_stats *local = &sds->local_stat;
11010 struct sg_lb_stats tmp_sgs;
11011 unsigned long sum_util = 0;
11012 bool sg_overloaded = 0, sg_overutilized = 0;
11013
11014 do {
11015 struct sg_lb_stats *sgs = &tmp_sgs;
11016 int local_group;
11017
11018 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11019 if (local_group) {
11020 sds->local = sg;
11021 sgs = local;
11022
11023 if (env->idle != CPU_NEWLY_IDLE ||
11024 time_after_eq(jiffies, sg->sgc->next_update))
11025 update_group_capacity(env->sd, env->dst_cpu);
11026 }
11027
11028 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11029
11030 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11031 sds->busiest = sg;
11032 sds->busiest_stat = *sgs;
11033 }
11034
11035 /* Now, start updating sd_lb_stats */
11036 sds->total_load += sgs->group_load;
11037 sds->total_capacity += sgs->group_capacity;
11038
11039 sum_util += sgs->group_util;
11040 sg = sg->next;
11041 } while (sg != env->sd->groups);
11042
11043 /*
11044 * Indicate that the child domain of the busiest group prefers tasks
11045 * go to a child's sibling domains first. NB the flags of a sched group
11046 * are those of the child domain.
11047 */
11048 if (sds->busiest)
11049 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11050
11051
11052 if (env->sd->flags & SD_NUMA)
11053 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11054
11055 if (!env->sd->parent) {
11056 /* update overload indicator if we are at root domain */
11057 set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11058
11059 /* Update over-utilization (tipping point, U >= 0) indicator */
11060 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11061 } else if (sg_overutilized) {
11062 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11063 }
11064
11065 update_idle_cpu_scan(env, sum_util);
11066 }
11067
11068 /**
11069 * calculate_imbalance - Calculate the amount of imbalance present within the
11070 * groups of a given sched_domain during load balance.
11071 * @env: load balance environment
11072 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11073 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11074 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11075 {
11076 struct sg_lb_stats *local, *busiest;
11077
11078 local = &sds->local_stat;
11079 busiest = &sds->busiest_stat;
11080
11081 if (busiest->group_type == group_misfit_task) {
11082 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11083 /* Set imbalance to allow misfit tasks to be balanced. */
11084 env->migration_type = migrate_misfit;
11085 env->imbalance = 1;
11086 } else {
11087 /*
11088 * Set load imbalance to allow moving task from cpu
11089 * with reduced capacity.
11090 */
11091 env->migration_type = migrate_load;
11092 env->imbalance = busiest->group_misfit_task_load;
11093 }
11094 return;
11095 }
11096
11097 if (busiest->group_type == group_asym_packing) {
11098 /*
11099 * In case of asym capacity, we will try to migrate all load to
11100 * the preferred CPU.
11101 */
11102 env->migration_type = migrate_task;
11103 env->imbalance = busiest->sum_h_nr_running;
11104 return;
11105 }
11106
11107 if (busiest->group_type == group_smt_balance) {
11108 /* Reduce number of tasks sharing CPU capacity */
11109 env->migration_type = migrate_task;
11110 env->imbalance = 1;
11111 return;
11112 }
11113
11114 if (busiest->group_type == group_imbalanced) {
11115 /*
11116 * In the group_imb case we cannot rely on group-wide averages
11117 * to ensure CPU-load equilibrium, try to move any task to fix
11118 * the imbalance. The next load balance will take care of
11119 * balancing back the system.
11120 */
11121 env->migration_type = migrate_task;
11122 env->imbalance = 1;
11123 return;
11124 }
11125
11126 /*
11127 * Try to use spare capacity of local group without overloading it or
11128 * emptying busiest.
11129 */
11130 if (local->group_type == group_has_spare) {
11131 if ((busiest->group_type > group_fully_busy) &&
11132 !(env->sd->flags & SD_SHARE_LLC)) {
11133 /*
11134 * If busiest is overloaded, try to fill spare
11135 * capacity. This might end up creating spare capacity
11136 * in busiest or busiest still being overloaded but
11137 * there is no simple way to directly compute the
11138 * amount of load to migrate in order to balance the
11139 * system.
11140 */
11141 env->migration_type = migrate_util;
11142 env->imbalance = max(local->group_capacity, local->group_util) -
11143 local->group_util;
11144
11145 /*
11146 * In some cases, the group's utilization is max or even
11147 * higher than capacity because of migrations but the
11148 * local CPU is (newly) idle. There is at least one
11149 * waiting task in this overloaded busiest group. Let's
11150 * try to pull it.
11151 */
11152 if (env->idle && env->imbalance == 0) {
11153 env->migration_type = migrate_task;
11154 env->imbalance = 1;
11155 }
11156
11157 return;
11158 }
11159
11160 if (busiest->group_weight == 1 || sds->prefer_sibling) {
11161 /*
11162 * When prefer sibling, evenly spread running tasks on
11163 * groups.
11164 */
11165 env->migration_type = migrate_task;
11166 env->imbalance = sibling_imbalance(env, sds, busiest, local);
11167 } else {
11168
11169 /*
11170 * If there is no overload, we just want to even the number of
11171 * idle CPUs.
11172 */
11173 env->migration_type = migrate_task;
11174 env->imbalance = max_t(long, 0,
11175 (local->idle_cpus - busiest->idle_cpus));
11176 }
11177
11178 #ifdef CONFIG_NUMA
11179 /* Consider allowing a small imbalance between NUMA groups */
11180 if (env->sd->flags & SD_NUMA) {
11181 env->imbalance = adjust_numa_imbalance(env->imbalance,
11182 local->sum_nr_running + 1,
11183 env->sd->imb_numa_nr);
11184 }
11185 #endif
11186
11187 /* Number of tasks to move to restore balance */
11188 env->imbalance >>= 1;
11189
11190 return;
11191 }
11192
11193 /*
11194 * Local is fully busy but has to take more load to relieve the
11195 * busiest group
11196 */
11197 if (local->group_type < group_overloaded) {
11198 /*
11199 * Local will become overloaded so the avg_load metrics are
11200 * finally needed.
11201 */
11202
11203 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11204 local->group_capacity;
11205
11206 /*
11207 * If the local group is more loaded than the selected
11208 * busiest group don't try to pull any tasks.
11209 */
11210 if (local->avg_load >= busiest->avg_load) {
11211 env->imbalance = 0;
11212 return;
11213 }
11214
11215 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11216 sds->total_capacity;
11217
11218 /*
11219 * If the local group is more loaded than the average system
11220 * load, don't try to pull any tasks.
11221 */
11222 if (local->avg_load >= sds->avg_load) {
11223 env->imbalance = 0;
11224 return;
11225 }
11226
11227 }
11228
11229 /*
11230 * Both group are or will become overloaded and we're trying to get all
11231 * the CPUs to the average_load, so we don't want to push ourselves
11232 * above the average load, nor do we wish to reduce the max loaded CPU
11233 * below the average load. At the same time, we also don't want to
11234 * reduce the group load below the group capacity. Thus we look for
11235 * the minimum possible imbalance.
11236 */
11237 env->migration_type = migrate_load;
11238 env->imbalance = min(
11239 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11240 (sds->avg_load - local->avg_load) * local->group_capacity
11241 ) / SCHED_CAPACITY_SCALE;
11242 }
11243
11244 /******* sched_balance_find_src_group() helpers end here *********************/
11245
11246 /*
11247 * Decision matrix according to the local and busiest group type:
11248 *
11249 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11250 * has_spare nr_idle balanced N/A N/A balanced balanced
11251 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
11252 * misfit_task force N/A N/A N/A N/A N/A
11253 * asym_packing force force N/A N/A force force
11254 * imbalanced force force N/A N/A force force
11255 * overloaded force force N/A N/A force avg_load
11256 *
11257 * N/A : Not Applicable because already filtered while updating
11258 * statistics.
11259 * balanced : The system is balanced for these 2 groups.
11260 * force : Calculate the imbalance as load migration is probably needed.
11261 * avg_load : Only if imbalance is significant enough.
11262 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
11263 * different in groups.
11264 */
11265
11266 /**
11267 * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11268 * if there is an imbalance.
11269 * @env: The load balancing environment.
11270 *
11271 * Also calculates the amount of runnable load which should be moved
11272 * to restore balance.
11273 *
11274 * Return: - The busiest group if imbalance exists.
11275 */
sched_balance_find_src_group(struct lb_env * env)11276 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11277 {
11278 struct sg_lb_stats *local, *busiest;
11279 struct sd_lb_stats sds;
11280
11281 init_sd_lb_stats(&sds);
11282
11283 /*
11284 * Compute the various statistics relevant for load balancing at
11285 * this level.
11286 */
11287 update_sd_lb_stats(env, &sds);
11288
11289 /* There is no busy sibling group to pull tasks from */
11290 if (!sds.busiest)
11291 goto out_balanced;
11292
11293 busiest = &sds.busiest_stat;
11294
11295 /* Misfit tasks should be dealt with regardless of the avg load */
11296 if (busiest->group_type == group_misfit_task)
11297 goto force_balance;
11298
11299 if (!is_rd_overutilized(env->dst_rq->rd) &&
11300 rcu_dereference(env->dst_rq->rd->pd))
11301 goto out_balanced;
11302
11303 /* ASYM feature bypasses nice load balance check */
11304 if (busiest->group_type == group_asym_packing)
11305 goto force_balance;
11306
11307 /*
11308 * If the busiest group is imbalanced the below checks don't
11309 * work because they assume all things are equal, which typically
11310 * isn't true due to cpus_ptr constraints and the like.
11311 */
11312 if (busiest->group_type == group_imbalanced)
11313 goto force_balance;
11314
11315 local = &sds.local_stat;
11316 /*
11317 * If the local group is busier than the selected busiest group
11318 * don't try and pull any tasks.
11319 */
11320 if (local->group_type > busiest->group_type)
11321 goto out_balanced;
11322
11323 /*
11324 * When groups are overloaded, use the avg_load to ensure fairness
11325 * between tasks.
11326 */
11327 if (local->group_type == group_overloaded) {
11328 /*
11329 * If the local group is more loaded than the selected
11330 * busiest group don't try to pull any tasks.
11331 */
11332 if (local->avg_load >= busiest->avg_load)
11333 goto out_balanced;
11334
11335 /* XXX broken for overlapping NUMA groups */
11336 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11337 sds.total_capacity;
11338
11339 /*
11340 * Don't pull any tasks if this group is already above the
11341 * domain average load.
11342 */
11343 if (local->avg_load >= sds.avg_load)
11344 goto out_balanced;
11345
11346 /*
11347 * If the busiest group is more loaded, use imbalance_pct to be
11348 * conservative.
11349 */
11350 if (100 * busiest->avg_load <=
11351 env->sd->imbalance_pct * local->avg_load)
11352 goto out_balanced;
11353 }
11354
11355 /*
11356 * Try to move all excess tasks to a sibling domain of the busiest
11357 * group's child domain.
11358 */
11359 if (sds.prefer_sibling && local->group_type == group_has_spare &&
11360 sibling_imbalance(env, &sds, busiest, local) > 1)
11361 goto force_balance;
11362
11363 if (busiest->group_type != group_overloaded) {
11364 if (!env->idle) {
11365 /*
11366 * If the busiest group is not overloaded (and as a
11367 * result the local one too) but this CPU is already
11368 * busy, let another idle CPU try to pull task.
11369 */
11370 goto out_balanced;
11371 }
11372
11373 if (busiest->group_type == group_smt_balance &&
11374 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11375 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
11376 goto force_balance;
11377 }
11378
11379 if (busiest->group_weight > 1 &&
11380 local->idle_cpus <= (busiest->idle_cpus + 1)) {
11381 /*
11382 * If the busiest group is not overloaded
11383 * and there is no imbalance between this and busiest
11384 * group wrt idle CPUs, it is balanced. The imbalance
11385 * becomes significant if the diff is greater than 1
11386 * otherwise we might end up to just move the imbalance
11387 * on another group. Of course this applies only if
11388 * there is more than 1 CPU per group.
11389 */
11390 goto out_balanced;
11391 }
11392
11393 if (busiest->sum_h_nr_running == 1) {
11394 /*
11395 * busiest doesn't have any tasks waiting to run
11396 */
11397 goto out_balanced;
11398 }
11399 }
11400
11401 force_balance:
11402 /* Looks like there is an imbalance. Compute it */
11403 calculate_imbalance(env, &sds);
11404 return env->imbalance ? sds.busiest : NULL;
11405
11406 out_balanced:
11407 env->imbalance = 0;
11408 return NULL;
11409 }
11410
11411 /*
11412 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11413 */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11414 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11415 struct sched_group *group)
11416 {
11417 struct rq *busiest = NULL, *rq;
11418 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11419 unsigned int busiest_nr = 0;
11420 int i;
11421
11422 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11423 unsigned long capacity, load, util;
11424 unsigned int nr_running;
11425 enum fbq_type rt;
11426
11427 rq = cpu_rq(i);
11428 rt = fbq_classify_rq(rq);
11429
11430 /*
11431 * We classify groups/runqueues into three groups:
11432 * - regular: there are !numa tasks
11433 * - remote: there are numa tasks that run on the 'wrong' node
11434 * - all: there is no distinction
11435 *
11436 * In order to avoid migrating ideally placed numa tasks,
11437 * ignore those when there's better options.
11438 *
11439 * If we ignore the actual busiest queue to migrate another
11440 * task, the next balance pass can still reduce the busiest
11441 * queue by moving tasks around inside the node.
11442 *
11443 * If we cannot move enough load due to this classification
11444 * the next pass will adjust the group classification and
11445 * allow migration of more tasks.
11446 *
11447 * Both cases only affect the total convergence complexity.
11448 */
11449 if (rt > env->fbq_type)
11450 continue;
11451
11452 nr_running = rq->cfs.h_nr_runnable;
11453 if (!nr_running)
11454 continue;
11455
11456 capacity = capacity_of(i);
11457
11458 /*
11459 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11460 * eventually lead to active_balancing high->low capacity.
11461 * Higher per-CPU capacity is considered better than balancing
11462 * average load.
11463 */
11464 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11465 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11466 nr_running == 1)
11467 continue;
11468
11469 /*
11470 * Make sure we only pull tasks from a CPU of lower priority
11471 * when balancing between SMT siblings.
11472 *
11473 * If balancing between cores, let lower priority CPUs help
11474 * SMT cores with more than one busy sibling.
11475 */
11476 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11477 continue;
11478
11479 switch (env->migration_type) {
11480 case migrate_load:
11481 /*
11482 * When comparing with load imbalance, use cpu_load()
11483 * which is not scaled with the CPU capacity.
11484 */
11485 load = cpu_load(rq);
11486
11487 if (nr_running == 1 && load > env->imbalance &&
11488 !check_cpu_capacity(rq, env->sd))
11489 break;
11490
11491 /*
11492 * For the load comparisons with the other CPUs,
11493 * consider the cpu_load() scaled with the CPU
11494 * capacity, so that the load can be moved away
11495 * from the CPU that is potentially running at a
11496 * lower capacity.
11497 *
11498 * Thus we're looking for max(load_i / capacity_i),
11499 * crosswise multiplication to rid ourselves of the
11500 * division works out to:
11501 * load_i * capacity_j > load_j * capacity_i;
11502 * where j is our previous maximum.
11503 */
11504 if (load * busiest_capacity > busiest_load * capacity) {
11505 busiest_load = load;
11506 busiest_capacity = capacity;
11507 busiest = rq;
11508 }
11509 break;
11510
11511 case migrate_util:
11512 util = cpu_util_cfs_boost(i);
11513
11514 /*
11515 * Don't try to pull utilization from a CPU with one
11516 * running task. Whatever its utilization, we will fail
11517 * detach the task.
11518 */
11519 if (nr_running <= 1)
11520 continue;
11521
11522 if (busiest_util < util) {
11523 busiest_util = util;
11524 busiest = rq;
11525 }
11526 break;
11527
11528 case migrate_task:
11529 if (busiest_nr < nr_running) {
11530 busiest_nr = nr_running;
11531 busiest = rq;
11532 }
11533 break;
11534
11535 case migrate_misfit:
11536 /*
11537 * For ASYM_CPUCAPACITY domains with misfit tasks we
11538 * simply seek the "biggest" misfit task.
11539 */
11540 if (rq->misfit_task_load > busiest_load) {
11541 busiest_load = rq->misfit_task_load;
11542 busiest = rq;
11543 }
11544
11545 break;
11546
11547 }
11548 }
11549
11550 return busiest;
11551 }
11552
11553 /*
11554 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11555 * so long as it is large enough.
11556 */
11557 #define MAX_PINNED_INTERVAL 512
11558
11559 static inline bool
asym_active_balance(struct lb_env * env)11560 asym_active_balance(struct lb_env *env)
11561 {
11562 /*
11563 * ASYM_PACKING needs to force migrate tasks from busy but lower
11564 * priority CPUs in order to pack all tasks in the highest priority
11565 * CPUs. When done between cores, do it only if the whole core if the
11566 * whole core is idle.
11567 *
11568 * If @env::src_cpu is an SMT core with busy siblings, let
11569 * the lower priority @env::dst_cpu help it. Do not follow
11570 * CPU priority.
11571 */
11572 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11573 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11574 !sched_use_asym_prio(env->sd, env->src_cpu));
11575 }
11576
11577 static inline bool
imbalanced_active_balance(struct lb_env * env)11578 imbalanced_active_balance(struct lb_env *env)
11579 {
11580 struct sched_domain *sd = env->sd;
11581
11582 /*
11583 * The imbalanced case includes the case of pinned tasks preventing a fair
11584 * distribution of the load on the system but also the even distribution of the
11585 * threads on a system with spare capacity
11586 */
11587 if ((env->migration_type == migrate_task) &&
11588 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11589 return 1;
11590
11591 return 0;
11592 }
11593
need_active_balance(struct lb_env * env)11594 static int need_active_balance(struct lb_env *env)
11595 {
11596 struct sched_domain *sd = env->sd;
11597
11598 if (asym_active_balance(env))
11599 return 1;
11600
11601 if (imbalanced_active_balance(env))
11602 return 1;
11603
11604 /*
11605 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11606 * It's worth migrating the task if the src_cpu's capacity is reduced
11607 * because of other sched_class or IRQs if more capacity stays
11608 * available on dst_cpu.
11609 */
11610 if (env->idle &&
11611 (env->src_rq->cfs.h_nr_runnable == 1)) {
11612 if ((check_cpu_capacity(env->src_rq, sd)) &&
11613 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11614 return 1;
11615 }
11616
11617 if (env->migration_type == migrate_misfit)
11618 return 1;
11619
11620 return 0;
11621 }
11622
11623 static int active_load_balance_cpu_stop(void *data);
11624
should_we_balance(struct lb_env * env)11625 static int should_we_balance(struct lb_env *env)
11626 {
11627 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11628 struct sched_group *sg = env->sd->groups;
11629 int cpu, idle_smt = -1;
11630
11631 /*
11632 * Ensure the balancing environment is consistent; can happen
11633 * when the softirq triggers 'during' hotplug.
11634 */
11635 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11636 return 0;
11637
11638 /*
11639 * In the newly idle case, we will allow all the CPUs
11640 * to do the newly idle load balance.
11641 *
11642 * However, we bail out if we already have tasks or a wakeup pending,
11643 * to optimize wakeup latency.
11644 */
11645 if (env->idle == CPU_NEWLY_IDLE) {
11646 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11647 return 0;
11648 return 1;
11649 }
11650
11651 cpumask_copy(swb_cpus, group_balance_mask(sg));
11652 /* Try to find first idle CPU */
11653 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11654 if (!idle_cpu(cpu))
11655 continue;
11656
11657 /*
11658 * Don't balance to idle SMT in busy core right away when
11659 * balancing cores, but remember the first idle SMT CPU for
11660 * later consideration. Find CPU on an idle core first.
11661 */
11662 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11663 if (idle_smt == -1)
11664 idle_smt = cpu;
11665 /*
11666 * If the core is not idle, and first SMT sibling which is
11667 * idle has been found, then its not needed to check other
11668 * SMT siblings for idleness:
11669 */
11670 #ifdef CONFIG_SCHED_SMT
11671 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11672 #endif
11673 continue;
11674 }
11675
11676 /*
11677 * Are we the first idle core in a non-SMT domain or higher,
11678 * or the first idle CPU in a SMT domain?
11679 */
11680 return cpu == env->dst_cpu;
11681 }
11682
11683 /* Are we the first idle CPU with busy siblings? */
11684 if (idle_smt != -1)
11685 return idle_smt == env->dst_cpu;
11686
11687 /* Are we the first CPU of this group ? */
11688 return group_balance_cpu(sg) == env->dst_cpu;
11689 }
11690
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)11691 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
11692 enum cpu_idle_type idle)
11693 {
11694 if (!schedstat_enabled())
11695 return;
11696
11697 switch (env->migration_type) {
11698 case migrate_load:
11699 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
11700 break;
11701 case migrate_util:
11702 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
11703 break;
11704 case migrate_task:
11705 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
11706 break;
11707 case migrate_misfit:
11708 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
11709 break;
11710 }
11711 }
11712
11713 /*
11714 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11715 * tasks if there is an imbalance.
11716 */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11717 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11718 struct sched_domain *sd, enum cpu_idle_type idle,
11719 int *continue_balancing)
11720 {
11721 int ld_moved, cur_ld_moved, active_balance = 0;
11722 struct sched_domain *sd_parent = sd->parent;
11723 struct sched_group *group;
11724 struct rq *busiest;
11725 struct rq_flags rf;
11726 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11727 struct lb_env env = {
11728 .sd = sd,
11729 .dst_cpu = this_cpu,
11730 .dst_rq = this_rq,
11731 .dst_grpmask = group_balance_mask(sd->groups),
11732 .idle = idle,
11733 .loop_break = SCHED_NR_MIGRATE_BREAK,
11734 .cpus = cpus,
11735 .fbq_type = all,
11736 .tasks = LIST_HEAD_INIT(env.tasks),
11737 };
11738
11739 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11740
11741 schedstat_inc(sd->lb_count[idle]);
11742
11743 redo:
11744 if (!should_we_balance(&env)) {
11745 *continue_balancing = 0;
11746 goto out_balanced;
11747 }
11748
11749 group = sched_balance_find_src_group(&env);
11750 if (!group) {
11751 schedstat_inc(sd->lb_nobusyg[idle]);
11752 goto out_balanced;
11753 }
11754
11755 busiest = sched_balance_find_src_rq(&env, group);
11756 if (!busiest) {
11757 schedstat_inc(sd->lb_nobusyq[idle]);
11758 goto out_balanced;
11759 }
11760
11761 WARN_ON_ONCE(busiest == env.dst_rq);
11762
11763 update_lb_imbalance_stat(&env, sd, idle);
11764
11765 env.src_cpu = busiest->cpu;
11766 env.src_rq = busiest;
11767
11768 ld_moved = 0;
11769 /* Clear this flag as soon as we find a pullable task */
11770 env.flags |= LBF_ALL_PINNED;
11771 if (busiest->nr_running > 1) {
11772 /*
11773 * Attempt to move tasks. If sched_balance_find_src_group has found
11774 * an imbalance but busiest->nr_running <= 1, the group is
11775 * still unbalanced. ld_moved simply stays zero, so it is
11776 * correctly treated as an imbalance.
11777 */
11778 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11779
11780 more_balance:
11781 rq_lock_irqsave(busiest, &rf);
11782 update_rq_clock(busiest);
11783
11784 /*
11785 * cur_ld_moved - load moved in current iteration
11786 * ld_moved - cumulative load moved across iterations
11787 */
11788 cur_ld_moved = detach_tasks(&env);
11789
11790 /*
11791 * We've detached some tasks from busiest_rq. Every
11792 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11793 * unlock busiest->lock, and we are able to be sure
11794 * that nobody can manipulate the tasks in parallel.
11795 * See task_rq_lock() family for the details.
11796 */
11797
11798 rq_unlock(busiest, &rf);
11799
11800 if (cur_ld_moved) {
11801 attach_tasks(&env);
11802 ld_moved += cur_ld_moved;
11803 }
11804
11805 local_irq_restore(rf.flags);
11806
11807 if (env.flags & LBF_NEED_BREAK) {
11808 env.flags &= ~LBF_NEED_BREAK;
11809 goto more_balance;
11810 }
11811
11812 /*
11813 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11814 * us and move them to an alternate dst_cpu in our sched_group
11815 * where they can run. The upper limit on how many times we
11816 * iterate on same src_cpu is dependent on number of CPUs in our
11817 * sched_group.
11818 *
11819 * This changes load balance semantics a bit on who can move
11820 * load to a given_cpu. In addition to the given_cpu itself
11821 * (or a ilb_cpu acting on its behalf where given_cpu is
11822 * nohz-idle), we now have balance_cpu in a position to move
11823 * load to given_cpu. In rare situations, this may cause
11824 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11825 * _independently_ and at _same_ time to move some load to
11826 * given_cpu) causing excess load to be moved to given_cpu.
11827 * This however should not happen so much in practice and
11828 * moreover subsequent load balance cycles should correct the
11829 * excess load moved.
11830 */
11831 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11832
11833 /* Prevent to re-select dst_cpu via env's CPUs */
11834 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11835
11836 env.dst_rq = cpu_rq(env.new_dst_cpu);
11837 env.dst_cpu = env.new_dst_cpu;
11838 env.flags &= ~LBF_DST_PINNED;
11839 env.loop = 0;
11840 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11841
11842 /*
11843 * Go back to "more_balance" rather than "redo" since we
11844 * need to continue with same src_cpu.
11845 */
11846 goto more_balance;
11847 }
11848
11849 /*
11850 * We failed to reach balance because of affinity.
11851 */
11852 if (sd_parent) {
11853 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11854
11855 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11856 *group_imbalance = 1;
11857 }
11858
11859 /* All tasks on this runqueue were pinned by CPU affinity */
11860 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11861 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11862 /*
11863 * Attempting to continue load balancing at the current
11864 * sched_domain level only makes sense if there are
11865 * active CPUs remaining as possible busiest CPUs to
11866 * pull load from which are not contained within the
11867 * destination group that is receiving any migrated
11868 * load.
11869 */
11870 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11871 env.loop = 0;
11872 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11873 goto redo;
11874 }
11875 goto out_all_pinned;
11876 }
11877 }
11878
11879 if (!ld_moved) {
11880 schedstat_inc(sd->lb_failed[idle]);
11881 /*
11882 * Increment the failure counter only on periodic balance.
11883 * We do not want newidle balance, which can be very
11884 * frequent, pollute the failure counter causing
11885 * excessive cache_hot migrations and active balances.
11886 *
11887 * Similarly for migration_misfit which is not related to
11888 * load/util migration, don't pollute nr_balance_failed.
11889 */
11890 if (idle != CPU_NEWLY_IDLE &&
11891 env.migration_type != migrate_misfit)
11892 sd->nr_balance_failed++;
11893
11894 if (need_active_balance(&env)) {
11895 unsigned long flags;
11896
11897 raw_spin_rq_lock_irqsave(busiest, flags);
11898
11899 /*
11900 * Don't kick the active_load_balance_cpu_stop,
11901 * if the curr task on busiest CPU can't be
11902 * moved to this_cpu:
11903 */
11904 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11905 raw_spin_rq_unlock_irqrestore(busiest, flags);
11906 goto out_one_pinned;
11907 }
11908
11909 /* Record that we found at least one task that could run on this_cpu */
11910 env.flags &= ~LBF_ALL_PINNED;
11911
11912 /*
11913 * ->active_balance synchronizes accesses to
11914 * ->active_balance_work. Once set, it's cleared
11915 * only after active load balance is finished.
11916 */
11917 if (!busiest->active_balance) {
11918 busiest->active_balance = 1;
11919 busiest->push_cpu = this_cpu;
11920 active_balance = 1;
11921 }
11922
11923 preempt_disable();
11924 raw_spin_rq_unlock_irqrestore(busiest, flags);
11925 if (active_balance) {
11926 stop_one_cpu_nowait(cpu_of(busiest),
11927 active_load_balance_cpu_stop, busiest,
11928 &busiest->active_balance_work);
11929 }
11930 preempt_enable();
11931 }
11932 } else {
11933 sd->nr_balance_failed = 0;
11934 }
11935
11936 if (likely(!active_balance) || need_active_balance(&env)) {
11937 /* We were unbalanced, so reset the balancing interval */
11938 sd->balance_interval = sd->min_interval;
11939 }
11940
11941 goto out;
11942
11943 out_balanced:
11944 /*
11945 * We reach balance although we may have faced some affinity
11946 * constraints. Clear the imbalance flag only if other tasks got
11947 * a chance to move and fix the imbalance.
11948 */
11949 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11950 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11951
11952 if (*group_imbalance)
11953 *group_imbalance = 0;
11954 }
11955
11956 out_all_pinned:
11957 /*
11958 * We reach balance because all tasks are pinned at this level so
11959 * we can't migrate them. Let the imbalance flag set so parent level
11960 * can try to migrate them.
11961 */
11962 schedstat_inc(sd->lb_balanced[idle]);
11963
11964 sd->nr_balance_failed = 0;
11965
11966 out_one_pinned:
11967 ld_moved = 0;
11968
11969 /*
11970 * sched_balance_newidle() disregards balance intervals, so we could
11971 * repeatedly reach this code, which would lead to balance_interval
11972 * skyrocketing in a short amount of time. Skip the balance_interval
11973 * increase logic to avoid that.
11974 *
11975 * Similarly misfit migration which is not necessarily an indication of
11976 * the system being busy and requires lb to backoff to let it settle
11977 * down.
11978 */
11979 if (env.idle == CPU_NEWLY_IDLE ||
11980 env.migration_type == migrate_misfit)
11981 goto out;
11982
11983 /* tune up the balancing interval */
11984 if ((env.flags & LBF_ALL_PINNED &&
11985 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11986 sd->balance_interval < sd->max_interval)
11987 sd->balance_interval *= 2;
11988 out:
11989 return ld_moved;
11990 }
11991
11992 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)11993 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11994 {
11995 unsigned long interval = sd->balance_interval;
11996
11997 if (cpu_busy)
11998 interval *= sd->busy_factor;
11999
12000 /* scale ms to jiffies */
12001 interval = msecs_to_jiffies(interval);
12002
12003 /*
12004 * Reduce likelihood of busy balancing at higher domains racing with
12005 * balancing at lower domains by preventing their balancing periods
12006 * from being multiples of each other.
12007 */
12008 if (cpu_busy)
12009 interval -= 1;
12010
12011 interval = clamp(interval, 1UL, max_load_balance_interval);
12012
12013 return interval;
12014 }
12015
12016 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12017 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12018 {
12019 unsigned long interval, next;
12020
12021 /* used by idle balance, so cpu_busy = 0 */
12022 interval = get_sd_balance_interval(sd, 0);
12023 next = sd->last_balance + interval;
12024
12025 if (time_after(*next_balance, next))
12026 *next_balance = next;
12027 }
12028
12029 /*
12030 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12031 * running tasks off the busiest CPU onto idle CPUs. It requires at
12032 * least 1 task to be running on each physical CPU where possible, and
12033 * avoids physical / logical imbalances.
12034 */
active_load_balance_cpu_stop(void * data)12035 static int active_load_balance_cpu_stop(void *data)
12036 {
12037 struct rq *busiest_rq = data;
12038 int busiest_cpu = cpu_of(busiest_rq);
12039 int target_cpu = busiest_rq->push_cpu;
12040 struct rq *target_rq = cpu_rq(target_cpu);
12041 struct sched_domain *sd;
12042 struct task_struct *p = NULL;
12043 struct rq_flags rf;
12044
12045 rq_lock_irq(busiest_rq, &rf);
12046 /*
12047 * Between queueing the stop-work and running it is a hole in which
12048 * CPUs can become inactive. We should not move tasks from or to
12049 * inactive CPUs.
12050 */
12051 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12052 goto out_unlock;
12053
12054 /* Make sure the requested CPU hasn't gone down in the meantime: */
12055 if (unlikely(busiest_cpu != smp_processor_id() ||
12056 !busiest_rq->active_balance))
12057 goto out_unlock;
12058
12059 /* Is there any task to move? */
12060 if (busiest_rq->nr_running <= 1)
12061 goto out_unlock;
12062
12063 /*
12064 * This condition is "impossible", if it occurs
12065 * we need to fix it. Originally reported by
12066 * Bjorn Helgaas on a 128-CPU setup.
12067 */
12068 WARN_ON_ONCE(busiest_rq == target_rq);
12069
12070 /* Search for an sd spanning us and the target CPU. */
12071 rcu_read_lock();
12072 for_each_domain(target_cpu, sd) {
12073 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12074 break;
12075 }
12076
12077 if (likely(sd)) {
12078 struct lb_env env = {
12079 .sd = sd,
12080 .dst_cpu = target_cpu,
12081 .dst_rq = target_rq,
12082 .src_cpu = busiest_rq->cpu,
12083 .src_rq = busiest_rq,
12084 .idle = CPU_IDLE,
12085 .flags = LBF_ACTIVE_LB,
12086 };
12087
12088 schedstat_inc(sd->alb_count);
12089 update_rq_clock(busiest_rq);
12090
12091 p = detach_one_task(&env);
12092 if (p) {
12093 schedstat_inc(sd->alb_pushed);
12094 /* Active balancing done, reset the failure counter. */
12095 sd->nr_balance_failed = 0;
12096 } else {
12097 schedstat_inc(sd->alb_failed);
12098 }
12099 }
12100 rcu_read_unlock();
12101 out_unlock:
12102 busiest_rq->active_balance = 0;
12103 rq_unlock(busiest_rq, &rf);
12104
12105 if (p)
12106 attach_one_task(target_rq, p);
12107
12108 local_irq_enable();
12109
12110 return 0;
12111 }
12112
12113 /*
12114 * This flag serializes load-balancing passes over large domains
12115 * (above the NODE topology level) - only one load-balancing instance
12116 * may run at a time, to reduce overhead on very large systems with
12117 * lots of CPUs and large NUMA distances.
12118 *
12119 * - Note that load-balancing passes triggered while another one
12120 * is executing are skipped and not re-tried.
12121 *
12122 * - Also note that this does not serialize rebalance_domains()
12123 * execution, as non-SD_SERIALIZE domains will still be
12124 * load-balanced in parallel.
12125 */
12126 static atomic_t sched_balance_running = ATOMIC_INIT(0);
12127
12128 /*
12129 * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12130 * This trades load-balance latency on larger machines for less cross talk.
12131 */
update_max_interval(void)12132 void update_max_interval(void)
12133 {
12134 max_load_balance_interval = HZ*num_online_cpus()/10;
12135 }
12136
update_newidle_cost(struct sched_domain * sd,u64 cost)12137 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
12138 {
12139 if (cost > sd->max_newidle_lb_cost) {
12140 /*
12141 * Track max cost of a domain to make sure to not delay the
12142 * next wakeup on the CPU.
12143 */
12144 sd->max_newidle_lb_cost = cost;
12145 sd->last_decay_max_lb_cost = jiffies;
12146 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
12147 /*
12148 * Decay the newidle max times by ~1% per second to ensure that
12149 * it is not outdated and the current max cost is actually
12150 * shorter.
12151 */
12152 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12153 sd->last_decay_max_lb_cost = jiffies;
12154
12155 return true;
12156 }
12157
12158 return false;
12159 }
12160
12161 /*
12162 * It checks each scheduling domain to see if it is due to be balanced,
12163 * and initiates a balancing operation if so.
12164 *
12165 * Balancing parameters are set up in init_sched_domains.
12166 */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12167 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12168 {
12169 int continue_balancing = 1;
12170 int cpu = rq->cpu;
12171 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12172 unsigned long interval;
12173 struct sched_domain *sd;
12174 /* Earliest time when we have to do rebalance again */
12175 unsigned long next_balance = jiffies + 60*HZ;
12176 int update_next_balance = 0;
12177 int need_serialize, need_decay = 0;
12178 u64 max_cost = 0;
12179
12180 rcu_read_lock();
12181 for_each_domain(cpu, sd) {
12182 /*
12183 * Decay the newidle max times here because this is a regular
12184 * visit to all the domains.
12185 */
12186 need_decay = update_newidle_cost(sd, 0);
12187 max_cost += sd->max_newidle_lb_cost;
12188
12189 /*
12190 * Stop the load balance at this level. There is another
12191 * CPU in our sched group which is doing load balancing more
12192 * actively.
12193 */
12194 if (!continue_balancing) {
12195 if (need_decay)
12196 continue;
12197 break;
12198 }
12199
12200 interval = get_sd_balance_interval(sd, busy);
12201
12202 need_serialize = sd->flags & SD_SERIALIZE;
12203 if (need_serialize) {
12204 if (atomic_cmpxchg_acquire(&sched_balance_running, 0, 1))
12205 goto out;
12206 }
12207
12208 if (time_after_eq(jiffies, sd->last_balance + interval)) {
12209 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12210 /*
12211 * The LBF_DST_PINNED logic could have changed
12212 * env->dst_cpu, so we can't know our idle
12213 * state even if we migrated tasks. Update it.
12214 */
12215 idle = idle_cpu(cpu);
12216 busy = !idle && !sched_idle_cpu(cpu);
12217 }
12218 sd->last_balance = jiffies;
12219 interval = get_sd_balance_interval(sd, busy);
12220 }
12221 if (need_serialize)
12222 atomic_set_release(&sched_balance_running, 0);
12223 out:
12224 if (time_after(next_balance, sd->last_balance + interval)) {
12225 next_balance = sd->last_balance + interval;
12226 update_next_balance = 1;
12227 }
12228 }
12229 if (need_decay) {
12230 /*
12231 * Ensure the rq-wide value also decays but keep it at a
12232 * reasonable floor to avoid funnies with rq->avg_idle.
12233 */
12234 rq->max_idle_balance_cost =
12235 max((u64)sysctl_sched_migration_cost, max_cost);
12236 }
12237 rcu_read_unlock();
12238
12239 /*
12240 * next_balance will be updated only when there is a need.
12241 * When the cpu is attached to null domain for ex, it will not be
12242 * updated.
12243 */
12244 if (likely(update_next_balance))
12245 rq->next_balance = next_balance;
12246
12247 }
12248
on_null_domain(struct rq * rq)12249 static inline int on_null_domain(struct rq *rq)
12250 {
12251 return unlikely(!rcu_dereference_sched(rq->sd));
12252 }
12253
12254 #ifdef CONFIG_NO_HZ_COMMON
12255 /*
12256 * NOHZ idle load balancing (ILB) details:
12257 *
12258 * - When one of the busy CPUs notices that there may be an idle rebalancing
12259 * needed, they will kick the idle load balancer, which then does idle
12260 * load balancing for all the idle CPUs.
12261 */
find_new_ilb(void)12262 static inline int find_new_ilb(void)
12263 {
12264 const struct cpumask *hk_mask;
12265 int ilb_cpu;
12266
12267 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12268
12269 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12270
12271 if (ilb_cpu == smp_processor_id())
12272 continue;
12273
12274 if (idle_cpu(ilb_cpu))
12275 return ilb_cpu;
12276 }
12277
12278 return -1;
12279 }
12280
12281 /*
12282 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12283 * SMP function call (IPI).
12284 *
12285 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12286 * (if there is one).
12287 */
kick_ilb(unsigned int flags)12288 static void kick_ilb(unsigned int flags)
12289 {
12290 int ilb_cpu;
12291
12292 /*
12293 * Increase nohz.next_balance only when if full ilb is triggered but
12294 * not if we only update stats.
12295 */
12296 if (flags & NOHZ_BALANCE_KICK)
12297 nohz.next_balance = jiffies+1;
12298
12299 ilb_cpu = find_new_ilb();
12300 if (ilb_cpu < 0)
12301 return;
12302
12303 /*
12304 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12305 * i.e. all bits in flags are already set in ilb_cpu.
12306 */
12307 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12308 return;
12309
12310 /*
12311 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12312 * the first flag owns it; cleared by nohz_csd_func().
12313 */
12314 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12315 if (flags & NOHZ_KICK_MASK)
12316 return;
12317
12318 /*
12319 * This way we generate an IPI on the target CPU which
12320 * is idle, and the softirq performing NOHZ idle load balancing
12321 * will be run before returning from the IPI.
12322 */
12323 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12324 }
12325
12326 /*
12327 * Current decision point for kicking the idle load balancer in the presence
12328 * of idle CPUs in the system.
12329 */
nohz_balancer_kick(struct rq * rq)12330 static void nohz_balancer_kick(struct rq *rq)
12331 {
12332 unsigned long now = jiffies;
12333 struct sched_domain_shared *sds;
12334 struct sched_domain *sd;
12335 int nr_busy, i, cpu = rq->cpu;
12336 unsigned int flags = 0;
12337
12338 if (unlikely(rq->idle_balance))
12339 return;
12340
12341 /*
12342 * We may be recently in ticked or tickless idle mode. At the first
12343 * busy tick after returning from idle, we will update the busy stats.
12344 */
12345 nohz_balance_exit_idle(rq);
12346
12347 /*
12348 * None are in tickless mode and hence no need for NOHZ idle load
12349 * balancing:
12350 */
12351 if (likely(!atomic_read(&nohz.nr_cpus)))
12352 return;
12353
12354 if (READ_ONCE(nohz.has_blocked) &&
12355 time_after(now, READ_ONCE(nohz.next_blocked)))
12356 flags = NOHZ_STATS_KICK;
12357
12358 if (time_before(now, nohz.next_balance))
12359 goto out;
12360
12361 if (rq->nr_running >= 2) {
12362 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12363 goto out;
12364 }
12365
12366 rcu_read_lock();
12367
12368 sd = rcu_dereference(rq->sd);
12369 if (sd) {
12370 /*
12371 * If there's a runnable CFS task and the current CPU has reduced
12372 * capacity, kick the ILB to see if there's a better CPU to run on:
12373 */
12374 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12375 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12376 goto unlock;
12377 }
12378 }
12379
12380 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12381 if (sd) {
12382 /*
12383 * When ASYM_PACKING; see if there's a more preferred CPU
12384 * currently idle; in which case, kick the ILB to move tasks
12385 * around.
12386 *
12387 * When balancing between cores, all the SMT siblings of the
12388 * preferred CPU must be idle.
12389 */
12390 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12391 if (sched_asym(sd, i, cpu)) {
12392 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12393 goto unlock;
12394 }
12395 }
12396 }
12397
12398 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12399 if (sd) {
12400 /*
12401 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12402 * to run the misfit task on.
12403 */
12404 if (check_misfit_status(rq)) {
12405 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12406 goto unlock;
12407 }
12408
12409 /*
12410 * For asymmetric systems, we do not want to nicely balance
12411 * cache use, instead we want to embrace asymmetry and only
12412 * ensure tasks have enough CPU capacity.
12413 *
12414 * Skip the LLC logic because it's not relevant in that case.
12415 */
12416 goto unlock;
12417 }
12418
12419 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12420 if (sds) {
12421 /*
12422 * If there is an imbalance between LLC domains (IOW we could
12423 * increase the overall cache utilization), we need a less-loaded LLC
12424 * domain to pull some load from. Likewise, we may need to spread
12425 * load within the current LLC domain (e.g. packed SMT cores but
12426 * other CPUs are idle). We can't really know from here how busy
12427 * the others are - so just get a NOHZ balance going if it looks
12428 * like this LLC domain has tasks we could move.
12429 */
12430 nr_busy = atomic_read(&sds->nr_busy_cpus);
12431 if (nr_busy > 1) {
12432 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12433 goto unlock;
12434 }
12435 }
12436 unlock:
12437 rcu_read_unlock();
12438 out:
12439 if (READ_ONCE(nohz.needs_update))
12440 flags |= NOHZ_NEXT_KICK;
12441
12442 if (flags)
12443 kick_ilb(flags);
12444 }
12445
set_cpu_sd_state_busy(int cpu)12446 static void set_cpu_sd_state_busy(int cpu)
12447 {
12448 struct sched_domain *sd;
12449
12450 rcu_read_lock();
12451 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12452
12453 if (!sd || !sd->nohz_idle)
12454 goto unlock;
12455 sd->nohz_idle = 0;
12456
12457 atomic_inc(&sd->shared->nr_busy_cpus);
12458 unlock:
12459 rcu_read_unlock();
12460 }
12461
nohz_balance_exit_idle(struct rq * rq)12462 void nohz_balance_exit_idle(struct rq *rq)
12463 {
12464 SCHED_WARN_ON(rq != this_rq());
12465
12466 if (likely(!rq->nohz_tick_stopped))
12467 return;
12468
12469 rq->nohz_tick_stopped = 0;
12470 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12471 atomic_dec(&nohz.nr_cpus);
12472
12473 set_cpu_sd_state_busy(rq->cpu);
12474 }
12475
set_cpu_sd_state_idle(int cpu)12476 static void set_cpu_sd_state_idle(int cpu)
12477 {
12478 struct sched_domain *sd;
12479
12480 rcu_read_lock();
12481 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12482
12483 if (!sd || sd->nohz_idle)
12484 goto unlock;
12485 sd->nohz_idle = 1;
12486
12487 atomic_dec(&sd->shared->nr_busy_cpus);
12488 unlock:
12489 rcu_read_unlock();
12490 }
12491
12492 /*
12493 * This routine will record that the CPU is going idle with tick stopped.
12494 * This info will be used in performing idle load balancing in the future.
12495 */
nohz_balance_enter_idle(int cpu)12496 void nohz_balance_enter_idle(int cpu)
12497 {
12498 struct rq *rq = cpu_rq(cpu);
12499
12500 SCHED_WARN_ON(cpu != smp_processor_id());
12501
12502 /* If this CPU is going down, then nothing needs to be done: */
12503 if (!cpu_active(cpu))
12504 return;
12505
12506 /*
12507 * Can be set safely without rq->lock held
12508 * If a clear happens, it will have evaluated last additions because
12509 * rq->lock is held during the check and the clear
12510 */
12511 rq->has_blocked_load = 1;
12512
12513 /*
12514 * The tick is still stopped but load could have been added in the
12515 * meantime. We set the nohz.has_blocked flag to trig a check of the
12516 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12517 * of nohz.has_blocked can only happen after checking the new load
12518 */
12519 if (rq->nohz_tick_stopped)
12520 goto out;
12521
12522 /* If we're a completely isolated CPU, we don't play: */
12523 if (on_null_domain(rq))
12524 return;
12525
12526 rq->nohz_tick_stopped = 1;
12527
12528 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12529 atomic_inc(&nohz.nr_cpus);
12530
12531 /*
12532 * Ensures that if nohz_idle_balance() fails to observe our
12533 * @idle_cpus_mask store, it must observe the @has_blocked
12534 * and @needs_update stores.
12535 */
12536 smp_mb__after_atomic();
12537
12538 set_cpu_sd_state_idle(cpu);
12539
12540 WRITE_ONCE(nohz.needs_update, 1);
12541 out:
12542 /*
12543 * Each time a cpu enter idle, we assume that it has blocked load and
12544 * enable the periodic update of the load of idle CPUs
12545 */
12546 WRITE_ONCE(nohz.has_blocked, 1);
12547 }
12548
update_nohz_stats(struct rq * rq)12549 static bool update_nohz_stats(struct rq *rq)
12550 {
12551 unsigned int cpu = rq->cpu;
12552
12553 if (!rq->has_blocked_load)
12554 return false;
12555
12556 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12557 return false;
12558
12559 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12560 return true;
12561
12562 sched_balance_update_blocked_averages(cpu);
12563
12564 return rq->has_blocked_load;
12565 }
12566
12567 /*
12568 * Internal function that runs load balance for all idle CPUs. The load balance
12569 * can be a simple update of blocked load or a complete load balance with
12570 * tasks movement depending of flags.
12571 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12572 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12573 {
12574 /* Earliest time when we have to do rebalance again */
12575 unsigned long now = jiffies;
12576 unsigned long next_balance = now + 60*HZ;
12577 bool has_blocked_load = false;
12578 int update_next_balance = 0;
12579 int this_cpu = this_rq->cpu;
12580 int balance_cpu;
12581 struct rq *rq;
12582
12583 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12584
12585 /*
12586 * We assume there will be no idle load after this update and clear
12587 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12588 * set the has_blocked flag and trigger another update of idle load.
12589 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12590 * setting the flag, we are sure to not clear the state and not
12591 * check the load of an idle cpu.
12592 *
12593 * Same applies to idle_cpus_mask vs needs_update.
12594 */
12595 if (flags & NOHZ_STATS_KICK)
12596 WRITE_ONCE(nohz.has_blocked, 0);
12597 if (flags & NOHZ_NEXT_KICK)
12598 WRITE_ONCE(nohz.needs_update, 0);
12599
12600 /*
12601 * Ensures that if we miss the CPU, we must see the has_blocked
12602 * store from nohz_balance_enter_idle().
12603 */
12604 smp_mb();
12605
12606 /*
12607 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12608 * chance for other idle cpu to pull load.
12609 */
12610 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12611 if (!idle_cpu(balance_cpu))
12612 continue;
12613
12614 /*
12615 * If this CPU gets work to do, stop the load balancing
12616 * work being done for other CPUs. Next load
12617 * balancing owner will pick it up.
12618 */
12619 if (!idle_cpu(this_cpu) && need_resched()) {
12620 if (flags & NOHZ_STATS_KICK)
12621 has_blocked_load = true;
12622 if (flags & NOHZ_NEXT_KICK)
12623 WRITE_ONCE(nohz.needs_update, 1);
12624 goto abort;
12625 }
12626
12627 rq = cpu_rq(balance_cpu);
12628
12629 if (flags & NOHZ_STATS_KICK)
12630 has_blocked_load |= update_nohz_stats(rq);
12631
12632 /*
12633 * If time for next balance is due,
12634 * do the balance.
12635 */
12636 if (time_after_eq(jiffies, rq->next_balance)) {
12637 struct rq_flags rf;
12638
12639 rq_lock_irqsave(rq, &rf);
12640 update_rq_clock(rq);
12641 rq_unlock_irqrestore(rq, &rf);
12642
12643 if (flags & NOHZ_BALANCE_KICK)
12644 sched_balance_domains(rq, CPU_IDLE);
12645 }
12646
12647 if (time_after(next_balance, rq->next_balance)) {
12648 next_balance = rq->next_balance;
12649 update_next_balance = 1;
12650 }
12651 }
12652
12653 /*
12654 * next_balance will be updated only when there is a need.
12655 * When the CPU is attached to null domain for ex, it will not be
12656 * updated.
12657 */
12658 if (likely(update_next_balance))
12659 nohz.next_balance = next_balance;
12660
12661 if (flags & NOHZ_STATS_KICK)
12662 WRITE_ONCE(nohz.next_blocked,
12663 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12664
12665 abort:
12666 /* There is still blocked load, enable periodic update */
12667 if (has_blocked_load)
12668 WRITE_ONCE(nohz.has_blocked, 1);
12669 }
12670
12671 /*
12672 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12673 * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12674 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12675 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12676 {
12677 unsigned int flags = this_rq->nohz_idle_balance;
12678
12679 if (!flags)
12680 return false;
12681
12682 this_rq->nohz_idle_balance = 0;
12683
12684 if (idle != CPU_IDLE)
12685 return false;
12686
12687 _nohz_idle_balance(this_rq, flags);
12688
12689 return true;
12690 }
12691
12692 /*
12693 * Check if we need to directly run the ILB for updating blocked load before
12694 * entering idle state. Here we run ILB directly without issuing IPIs.
12695 *
12696 * Note that when this function is called, the tick may not yet be stopped on
12697 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12698 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12699 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12700 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12701 * called from this function on (this) CPU that's not yet in the mask. That's
12702 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12703 * updating the blocked load of already idle CPUs without waking up one of
12704 * those idle CPUs and outside the preempt disable / IRQ off phase of the local
12705 * cpu about to enter idle, because it can take a long time.
12706 */
nohz_run_idle_balance(int cpu)12707 void nohz_run_idle_balance(int cpu)
12708 {
12709 unsigned int flags;
12710
12711 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12712
12713 /*
12714 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12715 * (i.e. NOHZ_STATS_KICK set) and will do the same.
12716 */
12717 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12718 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12719 }
12720
nohz_newidle_balance(struct rq * this_rq)12721 static void nohz_newidle_balance(struct rq *this_rq)
12722 {
12723 int this_cpu = this_rq->cpu;
12724
12725 /* Will wake up very soon. No time for doing anything else*/
12726 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12727 return;
12728
12729 /* Don't need to update blocked load of idle CPUs*/
12730 if (!READ_ONCE(nohz.has_blocked) ||
12731 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12732 return;
12733
12734 /*
12735 * Set the need to trigger ILB in order to update blocked load
12736 * before entering idle state.
12737 */
12738 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12739 }
12740
12741 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)12742 static inline void nohz_balancer_kick(struct rq *rq) { }
12743
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12744 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12745 {
12746 return false;
12747 }
12748
nohz_newidle_balance(struct rq * this_rq)12749 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12750 #endif /* CONFIG_NO_HZ_COMMON */
12751
12752 /*
12753 * sched_balance_newidle is called by schedule() if this_cpu is about to become
12754 * idle. Attempts to pull tasks from other CPUs.
12755 *
12756 * Returns:
12757 * < 0 - we released the lock and there are !fair tasks present
12758 * 0 - failed, no new tasks
12759 * > 0 - success, new (fair) tasks present
12760 */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)12761 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
12762 {
12763 unsigned long next_balance = jiffies + HZ;
12764 int this_cpu = this_rq->cpu;
12765 int continue_balancing = 1;
12766 u64 t0, t1, curr_cost = 0;
12767 struct sched_domain *sd;
12768 int pulled_task = 0;
12769
12770 update_misfit_status(NULL, this_rq);
12771
12772 /*
12773 * There is a task waiting to run. No need to search for one.
12774 * Return 0; the task will be enqueued when switching to idle.
12775 */
12776 if (this_rq->ttwu_pending)
12777 return 0;
12778
12779 /*
12780 * We must set idle_stamp _before_ calling sched_balance_rq()
12781 * for CPU_NEWLY_IDLE, such that we measure the this duration
12782 * as idle time.
12783 */
12784 this_rq->idle_stamp = rq_clock(this_rq);
12785
12786 /*
12787 * Do not pull tasks towards !active CPUs...
12788 */
12789 if (!cpu_active(this_cpu))
12790 return 0;
12791
12792 /*
12793 * This is OK, because current is on_cpu, which avoids it being picked
12794 * for load-balance and preemption/IRQs are still disabled avoiding
12795 * further scheduler activity on it and we're being very careful to
12796 * re-start the picking loop.
12797 */
12798 rq_unpin_lock(this_rq, rf);
12799
12800 rcu_read_lock();
12801 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12802
12803 if (!get_rd_overloaded(this_rq->rd) ||
12804 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12805
12806 if (sd)
12807 update_next_balance(sd, &next_balance);
12808 rcu_read_unlock();
12809
12810 goto out;
12811 }
12812 rcu_read_unlock();
12813
12814 raw_spin_rq_unlock(this_rq);
12815
12816 t0 = sched_clock_cpu(this_cpu);
12817 sched_balance_update_blocked_averages(this_cpu);
12818
12819 rcu_read_lock();
12820 for_each_domain(this_cpu, sd) {
12821 u64 domain_cost;
12822
12823 update_next_balance(sd, &next_balance);
12824
12825 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12826 break;
12827
12828 if (sd->flags & SD_BALANCE_NEWIDLE) {
12829
12830 pulled_task = sched_balance_rq(this_cpu, this_rq,
12831 sd, CPU_NEWLY_IDLE,
12832 &continue_balancing);
12833
12834 t1 = sched_clock_cpu(this_cpu);
12835 domain_cost = t1 - t0;
12836 update_newidle_cost(sd, domain_cost);
12837
12838 curr_cost += domain_cost;
12839 t0 = t1;
12840 }
12841
12842 /*
12843 * Stop searching for tasks to pull if there are
12844 * now runnable tasks on this rq.
12845 */
12846 if (pulled_task || !continue_balancing)
12847 break;
12848 }
12849 rcu_read_unlock();
12850
12851 raw_spin_rq_lock(this_rq);
12852
12853 if (curr_cost > this_rq->max_idle_balance_cost)
12854 this_rq->max_idle_balance_cost = curr_cost;
12855
12856 /*
12857 * While browsing the domains, we released the rq lock, a task could
12858 * have been enqueued in the meantime. Since we're not going idle,
12859 * pretend we pulled a task.
12860 */
12861 if (this_rq->cfs.h_nr_queued && !pulled_task)
12862 pulled_task = 1;
12863
12864 /* Is there a task of a high priority class? */
12865 if (this_rq->nr_running != this_rq->cfs.h_nr_queued)
12866 pulled_task = -1;
12867
12868 out:
12869 /* Move the next balance forward */
12870 if (time_after(this_rq->next_balance, next_balance))
12871 this_rq->next_balance = next_balance;
12872
12873 if (pulled_task)
12874 this_rq->idle_stamp = 0;
12875 else
12876 nohz_newidle_balance(this_rq);
12877
12878 rq_repin_lock(this_rq, rf);
12879
12880 return pulled_task;
12881 }
12882
12883 /*
12884 * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
12885 *
12886 * - directly from the local sched_tick() for periodic load balancing
12887 *
12888 * - indirectly from a remote sched_tick() for NOHZ idle balancing
12889 * through the SMP cross-call nohz_csd_func()
12890 */
sched_balance_softirq(void)12891 static __latent_entropy void sched_balance_softirq(void)
12892 {
12893 struct rq *this_rq = this_rq();
12894 enum cpu_idle_type idle = this_rq->idle_balance;
12895 /*
12896 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
12897 * balancing on behalf of the other idle CPUs whose ticks are
12898 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
12899 * give the idle CPUs a chance to load balance. Else we may
12900 * load balance only within the local sched_domain hierarchy
12901 * and abort nohz_idle_balance altogether if we pull some load.
12902 */
12903 if (nohz_idle_balance(this_rq, idle))
12904 return;
12905
12906 /* normal load balance */
12907 sched_balance_update_blocked_averages(this_rq->cpu);
12908 sched_balance_domains(this_rq, idle);
12909 }
12910
12911 /*
12912 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12913 */
sched_balance_trigger(struct rq * rq)12914 void sched_balance_trigger(struct rq *rq)
12915 {
12916 /*
12917 * Don't need to rebalance while attached to NULL domain or
12918 * runqueue CPU is not active
12919 */
12920 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12921 return;
12922
12923 if (time_after_eq(jiffies, rq->next_balance))
12924 raise_softirq(SCHED_SOFTIRQ);
12925
12926 nohz_balancer_kick(rq);
12927 }
12928
rq_online_fair(struct rq * rq)12929 static void rq_online_fair(struct rq *rq)
12930 {
12931 update_sysctl();
12932
12933 update_runtime_enabled(rq);
12934 }
12935
rq_offline_fair(struct rq * rq)12936 static void rq_offline_fair(struct rq *rq)
12937 {
12938 update_sysctl();
12939
12940 /* Ensure any throttled groups are reachable by pick_next_task */
12941 unthrottle_offline_cfs_rqs(rq);
12942
12943 /* Ensure that we remove rq contribution to group share: */
12944 clear_tg_offline_cfs_rqs(rq);
12945 }
12946
12947 #endif /* CONFIG_SMP */
12948
12949 #ifdef CONFIG_SCHED_CORE
12950 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)12951 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12952 {
12953 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12954 u64 slice = se->slice;
12955
12956 return (rtime * min_nr_tasks > slice);
12957 }
12958
12959 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)12960 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12961 {
12962 if (!sched_core_enabled(rq))
12963 return;
12964
12965 /*
12966 * If runqueue has only one task which used up its slice and
12967 * if the sibling is forced idle, then trigger schedule to
12968 * give forced idle task a chance.
12969 *
12970 * sched_slice() considers only this active rq and it gets the
12971 * whole slice. But during force idle, we have siblings acting
12972 * like a single runqueue and hence we need to consider runnable
12973 * tasks on this CPU and the forced idle CPU. Ideally, we should
12974 * go through the forced idle rq, but that would be a perf hit.
12975 * We can assume that the forced idle CPU has at least
12976 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12977 * if we need to give up the CPU.
12978 */
12979 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
12980 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12981 resched_curr(rq);
12982 }
12983
12984 /*
12985 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12986 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)12987 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12988 bool forceidle)
12989 {
12990 for_each_sched_entity(se) {
12991 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12992
12993 if (forceidle) {
12994 if (cfs_rq->forceidle_seq == fi_seq)
12995 break;
12996 cfs_rq->forceidle_seq = fi_seq;
12997 }
12998
12999 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
13000 }
13001 }
13002
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13003 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13004 {
13005 struct sched_entity *se = &p->se;
13006
13007 if (p->sched_class != &fair_sched_class)
13008 return;
13009
13010 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13011 }
13012
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13013 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13014 bool in_fi)
13015 {
13016 struct rq *rq = task_rq(a);
13017 const struct sched_entity *sea = &a->se;
13018 const struct sched_entity *seb = &b->se;
13019 struct cfs_rq *cfs_rqa;
13020 struct cfs_rq *cfs_rqb;
13021 s64 delta;
13022
13023 SCHED_WARN_ON(task_rq(b)->core != rq->core);
13024
13025 #ifdef CONFIG_FAIR_GROUP_SCHED
13026 /*
13027 * Find an se in the hierarchy for tasks a and b, such that the se's
13028 * are immediate siblings.
13029 */
13030 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13031 int sea_depth = sea->depth;
13032 int seb_depth = seb->depth;
13033
13034 if (sea_depth >= seb_depth)
13035 sea = parent_entity(sea);
13036 if (sea_depth <= seb_depth)
13037 seb = parent_entity(seb);
13038 }
13039
13040 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13041 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13042
13043 cfs_rqa = sea->cfs_rq;
13044 cfs_rqb = seb->cfs_rq;
13045 #else
13046 cfs_rqa = &task_rq(a)->cfs;
13047 cfs_rqb = &task_rq(b)->cfs;
13048 #endif
13049
13050 /*
13051 * Find delta after normalizing se's vruntime with its cfs_rq's
13052 * min_vruntime_fi, which would have been updated in prior calls
13053 * to se_fi_update().
13054 */
13055 delta = (s64)(sea->vruntime - seb->vruntime) +
13056 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
13057
13058 return delta > 0;
13059 }
13060
task_is_throttled_fair(struct task_struct * p,int cpu)13061 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13062 {
13063 struct cfs_rq *cfs_rq;
13064
13065 #ifdef CONFIG_FAIR_GROUP_SCHED
13066 cfs_rq = task_group(p)->cfs_rq[cpu];
13067 #else
13068 cfs_rq = &cpu_rq(cpu)->cfs;
13069 #endif
13070 return throttled_hierarchy(cfs_rq);
13071 }
13072 #else
task_tick_core(struct rq * rq,struct task_struct * curr)13073 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13074 #endif
13075
13076 /*
13077 * scheduler tick hitting a task of our scheduling class.
13078 *
13079 * NOTE: This function can be called remotely by the tick offload that
13080 * goes along full dynticks. Therefore no local assumption can be made
13081 * and everything must be accessed through the @rq and @curr passed in
13082 * parameters.
13083 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13084 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13085 {
13086 struct cfs_rq *cfs_rq;
13087 struct sched_entity *se = &curr->se;
13088
13089 for_each_sched_entity(se) {
13090 cfs_rq = cfs_rq_of(se);
13091 entity_tick(cfs_rq, se, queued);
13092 }
13093
13094 if (static_branch_unlikely(&sched_numa_balancing))
13095 task_tick_numa(rq, curr);
13096
13097 update_misfit_status(curr, rq);
13098 check_update_overutilized_status(task_rq(curr));
13099
13100 task_tick_core(rq, curr);
13101 }
13102
13103 /*
13104 * called on fork with the child task as argument from the parent's context
13105 * - child not yet on the tasklist
13106 * - preemption disabled
13107 */
task_fork_fair(struct task_struct * p)13108 static void task_fork_fair(struct task_struct *p)
13109 {
13110 set_task_max_allowed_capacity(p);
13111 }
13112
13113 /*
13114 * Priority of the task has changed. Check to see if we preempt
13115 * the current task.
13116 */
13117 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)13118 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
13119 {
13120 if (!task_on_rq_queued(p))
13121 return;
13122
13123 if (rq->cfs.nr_queued == 1)
13124 return;
13125
13126 /*
13127 * Reschedule if we are currently running on this runqueue and
13128 * our priority decreased, or if we are not currently running on
13129 * this runqueue and our priority is higher than the current's
13130 */
13131 if (task_current_donor(rq, p)) {
13132 if (p->prio > oldprio)
13133 resched_curr(rq);
13134 } else
13135 wakeup_preempt(rq, p, 0);
13136 }
13137
13138 #ifdef CONFIG_FAIR_GROUP_SCHED
13139 /*
13140 * Propagate the changes of the sched_entity across the tg tree to make it
13141 * visible to the root
13142 */
propagate_entity_cfs_rq(struct sched_entity * se)13143 static void propagate_entity_cfs_rq(struct sched_entity *se)
13144 {
13145 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13146
13147 if (cfs_rq_throttled(cfs_rq))
13148 return;
13149
13150 if (!throttled_hierarchy(cfs_rq))
13151 list_add_leaf_cfs_rq(cfs_rq);
13152
13153 /* Start to propagate at parent */
13154 se = se->parent;
13155
13156 for_each_sched_entity(se) {
13157 cfs_rq = cfs_rq_of(se);
13158
13159 update_load_avg(cfs_rq, se, UPDATE_TG);
13160
13161 if (cfs_rq_throttled(cfs_rq))
13162 break;
13163
13164 if (!throttled_hierarchy(cfs_rq))
13165 list_add_leaf_cfs_rq(cfs_rq);
13166 }
13167 }
13168 #else
propagate_entity_cfs_rq(struct sched_entity * se)13169 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13170 #endif
13171
detach_entity_cfs_rq(struct sched_entity * se)13172 static void detach_entity_cfs_rq(struct sched_entity *se)
13173 {
13174 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13175
13176 #ifdef CONFIG_SMP
13177 /*
13178 * In case the task sched_avg hasn't been attached:
13179 * - A forked task which hasn't been woken up by wake_up_new_task().
13180 * - A task which has been woken up by try_to_wake_up() but is
13181 * waiting for actually being woken up by sched_ttwu_pending().
13182 */
13183 if (!se->avg.last_update_time)
13184 return;
13185 #endif
13186
13187 /* Catch up with the cfs_rq and remove our load when we leave */
13188 update_load_avg(cfs_rq, se, 0);
13189 detach_entity_load_avg(cfs_rq, se);
13190 update_tg_load_avg(cfs_rq);
13191 propagate_entity_cfs_rq(se);
13192 }
13193
attach_entity_cfs_rq(struct sched_entity * se)13194 static void attach_entity_cfs_rq(struct sched_entity *se)
13195 {
13196 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13197
13198 /* Synchronize entity with its cfs_rq */
13199 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13200 attach_entity_load_avg(cfs_rq, se);
13201 update_tg_load_avg(cfs_rq);
13202 propagate_entity_cfs_rq(se);
13203 }
13204
detach_task_cfs_rq(struct task_struct * p)13205 static void detach_task_cfs_rq(struct task_struct *p)
13206 {
13207 struct sched_entity *se = &p->se;
13208
13209 detach_entity_cfs_rq(se);
13210 }
13211
attach_task_cfs_rq(struct task_struct * p)13212 static void attach_task_cfs_rq(struct task_struct *p)
13213 {
13214 struct sched_entity *se = &p->se;
13215
13216 attach_entity_cfs_rq(se);
13217 }
13218
switched_from_fair(struct rq * rq,struct task_struct * p)13219 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13220 {
13221 detach_task_cfs_rq(p);
13222 }
13223
switched_to_fair(struct rq * rq,struct task_struct * p)13224 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13225 {
13226 SCHED_WARN_ON(p->se.sched_delayed);
13227
13228 attach_task_cfs_rq(p);
13229
13230 set_task_max_allowed_capacity(p);
13231
13232 if (task_on_rq_queued(p)) {
13233 /*
13234 * We were most likely switched from sched_rt, so
13235 * kick off the schedule if running, otherwise just see
13236 * if we can still preempt the current task.
13237 */
13238 if (task_current_donor(rq, p))
13239 resched_curr(rq);
13240 else
13241 wakeup_preempt(rq, p, 0);
13242 }
13243 }
13244
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13245 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13246 {
13247 struct sched_entity *se = &p->se;
13248
13249 #ifdef CONFIG_SMP
13250 if (task_on_rq_queued(p)) {
13251 /*
13252 * Move the next running task to the front of the list, so our
13253 * cfs_tasks list becomes MRU one.
13254 */
13255 list_move(&se->group_node, &rq->cfs_tasks);
13256 }
13257 #endif
13258 if (!first)
13259 return;
13260
13261 SCHED_WARN_ON(se->sched_delayed);
13262
13263 if (hrtick_enabled_fair(rq))
13264 hrtick_start_fair(rq, p);
13265
13266 update_misfit_status(p, rq);
13267 sched_fair_update_stop_tick(rq, p);
13268 }
13269
13270 /*
13271 * Account for a task changing its policy or group.
13272 *
13273 * This routine is mostly called to set cfs_rq->curr field when a task
13274 * migrates between groups/classes.
13275 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13276 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13277 {
13278 struct sched_entity *se = &p->se;
13279
13280 for_each_sched_entity(se) {
13281 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13282
13283 set_next_entity(cfs_rq, se);
13284 /* ensure bandwidth has been allocated on our new cfs_rq */
13285 account_cfs_rq_runtime(cfs_rq, 0);
13286 }
13287
13288 __set_next_task_fair(rq, p, first);
13289 }
13290
init_cfs_rq(struct cfs_rq * cfs_rq)13291 void init_cfs_rq(struct cfs_rq *cfs_rq)
13292 {
13293 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13294 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
13295 #ifdef CONFIG_SMP
13296 raw_spin_lock_init(&cfs_rq->removed.lock);
13297 #endif
13298 }
13299
13300 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13301 static void task_change_group_fair(struct task_struct *p)
13302 {
13303 /*
13304 * We couldn't detach or attach a forked task which
13305 * hasn't been woken up by wake_up_new_task().
13306 */
13307 if (READ_ONCE(p->__state) == TASK_NEW)
13308 return;
13309
13310 detach_task_cfs_rq(p);
13311
13312 #ifdef CONFIG_SMP
13313 /* Tell se's cfs_rq has been changed -- migrated */
13314 p->se.avg.last_update_time = 0;
13315 #endif
13316 set_task_rq(p, task_cpu(p));
13317 attach_task_cfs_rq(p);
13318 }
13319
free_fair_sched_group(struct task_group * tg)13320 void free_fair_sched_group(struct task_group *tg)
13321 {
13322 int i;
13323
13324 for_each_possible_cpu(i) {
13325 if (tg->cfs_rq)
13326 kfree(tg->cfs_rq[i]);
13327 if (tg->se)
13328 kfree(tg->se[i]);
13329 }
13330
13331 kfree(tg->cfs_rq);
13332 kfree(tg->se);
13333 }
13334
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13335 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13336 {
13337 struct sched_entity *se;
13338 struct cfs_rq *cfs_rq;
13339 int i;
13340
13341 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13342 if (!tg->cfs_rq)
13343 goto err;
13344 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13345 if (!tg->se)
13346 goto err;
13347
13348 tg->shares = NICE_0_LOAD;
13349
13350 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13351
13352 for_each_possible_cpu(i) {
13353 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13354 GFP_KERNEL, cpu_to_node(i));
13355 if (!cfs_rq)
13356 goto err;
13357
13358 se = kzalloc_node(sizeof(struct sched_entity_stats),
13359 GFP_KERNEL, cpu_to_node(i));
13360 if (!se)
13361 goto err_free_rq;
13362
13363 init_cfs_rq(cfs_rq);
13364 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13365 init_entity_runnable_average(se);
13366 }
13367
13368 return 1;
13369
13370 err_free_rq:
13371 kfree(cfs_rq);
13372 err:
13373 return 0;
13374 }
13375
online_fair_sched_group(struct task_group * tg)13376 void online_fair_sched_group(struct task_group *tg)
13377 {
13378 struct sched_entity *se;
13379 struct rq_flags rf;
13380 struct rq *rq;
13381 int i;
13382
13383 for_each_possible_cpu(i) {
13384 rq = cpu_rq(i);
13385 se = tg->se[i];
13386 rq_lock_irq(rq, &rf);
13387 update_rq_clock(rq);
13388 attach_entity_cfs_rq(se);
13389 sync_throttle(tg, i);
13390 rq_unlock_irq(rq, &rf);
13391 }
13392 }
13393
unregister_fair_sched_group(struct task_group * tg)13394 void unregister_fair_sched_group(struct task_group *tg)
13395 {
13396 int cpu;
13397
13398 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13399
13400 for_each_possible_cpu(cpu) {
13401 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13402 struct sched_entity *se = tg->se[cpu];
13403 struct rq *rq = cpu_rq(cpu);
13404
13405 if (se) {
13406 if (se->sched_delayed) {
13407 guard(rq_lock_irqsave)(rq);
13408 if (se->sched_delayed) {
13409 update_rq_clock(rq);
13410 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13411 }
13412 list_del_leaf_cfs_rq(cfs_rq);
13413 }
13414 remove_entity_load_avg(se);
13415 }
13416
13417 /*
13418 * Only empty task groups can be destroyed; so we can speculatively
13419 * check on_list without danger of it being re-added.
13420 */
13421 if (cfs_rq->on_list) {
13422 guard(rq_lock_irqsave)(rq);
13423 list_del_leaf_cfs_rq(cfs_rq);
13424 }
13425 }
13426 }
13427
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13428 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13429 struct sched_entity *se, int cpu,
13430 struct sched_entity *parent)
13431 {
13432 struct rq *rq = cpu_rq(cpu);
13433
13434 cfs_rq->tg = tg;
13435 cfs_rq->rq = rq;
13436 init_cfs_rq_runtime(cfs_rq);
13437
13438 tg->cfs_rq[cpu] = cfs_rq;
13439 tg->se[cpu] = se;
13440
13441 /* se could be NULL for root_task_group */
13442 if (!se)
13443 return;
13444
13445 if (!parent) {
13446 se->cfs_rq = &rq->cfs;
13447 se->depth = 0;
13448 } else {
13449 se->cfs_rq = parent->my_q;
13450 se->depth = parent->depth + 1;
13451 }
13452
13453 se->my_q = cfs_rq;
13454 /* guarantee group entities always have weight */
13455 update_load_set(&se->load, NICE_0_LOAD);
13456 se->parent = parent;
13457 }
13458
13459 static DEFINE_MUTEX(shares_mutex);
13460
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13461 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13462 {
13463 int i;
13464
13465 lockdep_assert_held(&shares_mutex);
13466
13467 /*
13468 * We can't change the weight of the root cgroup.
13469 */
13470 if (!tg->se[0])
13471 return -EINVAL;
13472
13473 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13474
13475 if (tg->shares == shares)
13476 return 0;
13477
13478 tg->shares = shares;
13479 for_each_possible_cpu(i) {
13480 struct rq *rq = cpu_rq(i);
13481 struct sched_entity *se = tg->se[i];
13482 struct rq_flags rf;
13483
13484 /* Propagate contribution to hierarchy */
13485 rq_lock_irqsave(rq, &rf);
13486 update_rq_clock(rq);
13487 for_each_sched_entity(se) {
13488 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13489 update_cfs_group(se);
13490 }
13491 rq_unlock_irqrestore(rq, &rf);
13492 }
13493
13494 return 0;
13495 }
13496
sched_group_set_shares(struct task_group * tg,unsigned long shares)13497 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13498 {
13499 int ret;
13500
13501 mutex_lock(&shares_mutex);
13502 if (tg_is_idle(tg))
13503 ret = -EINVAL;
13504 else
13505 ret = __sched_group_set_shares(tg, shares);
13506 mutex_unlock(&shares_mutex);
13507
13508 return ret;
13509 }
13510
sched_group_set_idle(struct task_group * tg,long idle)13511 int sched_group_set_idle(struct task_group *tg, long idle)
13512 {
13513 int i;
13514
13515 if (tg == &root_task_group)
13516 return -EINVAL;
13517
13518 if (idle < 0 || idle > 1)
13519 return -EINVAL;
13520
13521 mutex_lock(&shares_mutex);
13522
13523 if (tg->idle == idle) {
13524 mutex_unlock(&shares_mutex);
13525 return 0;
13526 }
13527
13528 tg->idle = idle;
13529
13530 for_each_possible_cpu(i) {
13531 struct rq *rq = cpu_rq(i);
13532 struct sched_entity *se = tg->se[i];
13533 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
13534 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13535 long idle_task_delta;
13536 struct rq_flags rf;
13537
13538 rq_lock_irqsave(rq, &rf);
13539
13540 grp_cfs_rq->idle = idle;
13541 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13542 goto next_cpu;
13543
13544 idle_task_delta = grp_cfs_rq->h_nr_queued -
13545 grp_cfs_rq->h_nr_idle;
13546 if (!cfs_rq_is_idle(grp_cfs_rq))
13547 idle_task_delta *= -1;
13548
13549 for_each_sched_entity(se) {
13550 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13551
13552 if (!se->on_rq)
13553 break;
13554
13555 cfs_rq->h_nr_idle += idle_task_delta;
13556
13557 /* Already accounted at parent level and above. */
13558 if (cfs_rq_is_idle(cfs_rq))
13559 break;
13560 }
13561
13562 next_cpu:
13563 rq_unlock_irqrestore(rq, &rf);
13564 }
13565
13566 /* Idle groups have minimum weight. */
13567 if (tg_is_idle(tg))
13568 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13569 else
13570 __sched_group_set_shares(tg, NICE_0_LOAD);
13571
13572 mutex_unlock(&shares_mutex);
13573 return 0;
13574 }
13575
13576 #endif /* CONFIG_FAIR_GROUP_SCHED */
13577
13578
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13579 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13580 {
13581 struct sched_entity *se = &task->se;
13582 unsigned int rr_interval = 0;
13583
13584 /*
13585 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13586 * idle runqueue:
13587 */
13588 if (rq->cfs.load.weight)
13589 rr_interval = NS_TO_JIFFIES(se->slice);
13590
13591 return rr_interval;
13592 }
13593
13594 /*
13595 * All the scheduling class methods:
13596 */
13597 DEFINE_SCHED_CLASS(fair) = {
13598
13599 .enqueue_task = enqueue_task_fair,
13600 .dequeue_task = dequeue_task_fair,
13601 .yield_task = yield_task_fair,
13602 .yield_to_task = yield_to_task_fair,
13603
13604 .wakeup_preempt = check_preempt_wakeup_fair,
13605
13606 .pick_task = pick_task_fair,
13607 .pick_next_task = __pick_next_task_fair,
13608 .put_prev_task = put_prev_task_fair,
13609 .set_next_task = set_next_task_fair,
13610
13611 #ifdef CONFIG_SMP
13612 .balance = balance_fair,
13613 .select_task_rq = select_task_rq_fair,
13614 .migrate_task_rq = migrate_task_rq_fair,
13615
13616 .rq_online = rq_online_fair,
13617 .rq_offline = rq_offline_fair,
13618
13619 .task_dead = task_dead_fair,
13620 .set_cpus_allowed = set_cpus_allowed_fair,
13621 #endif
13622
13623 .task_tick = task_tick_fair,
13624 .task_fork = task_fork_fair,
13625
13626 .reweight_task = reweight_task_fair,
13627 .prio_changed = prio_changed_fair,
13628 .switched_from = switched_from_fair,
13629 .switched_to = switched_to_fair,
13630
13631 .get_rr_interval = get_rr_interval_fair,
13632
13633 .update_curr = update_curr_fair,
13634
13635 #ifdef CONFIG_FAIR_GROUP_SCHED
13636 .task_change_group = task_change_group_fair,
13637 #endif
13638
13639 #ifdef CONFIG_SCHED_CORE
13640 .task_is_throttled = task_is_throttled_fair,
13641 #endif
13642
13643 #ifdef CONFIG_UCLAMP_TASK
13644 .uclamp_enabled = 1,
13645 #endif
13646 };
13647
13648 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)13649 void print_cfs_stats(struct seq_file *m, int cpu)
13650 {
13651 struct cfs_rq *cfs_rq, *pos;
13652
13653 rcu_read_lock();
13654 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13655 print_cfs_rq(m, cpu, cfs_rq);
13656 rcu_read_unlock();
13657 }
13658
13659 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13660 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13661 {
13662 int node;
13663 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13664 struct numa_group *ng;
13665
13666 rcu_read_lock();
13667 ng = rcu_dereference(p->numa_group);
13668 for_each_online_node(node) {
13669 if (p->numa_faults) {
13670 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13671 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13672 }
13673 if (ng) {
13674 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13675 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13676 }
13677 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13678 }
13679 rcu_read_unlock();
13680 }
13681 #endif /* CONFIG_NUMA_BALANCING */
13682 #endif /* CONFIG_SCHED_DEBUG */
13683
init_sched_fair_class(void)13684 __init void init_sched_fair_class(void)
13685 {
13686 #ifdef CONFIG_SMP
13687 int i;
13688
13689 for_each_possible_cpu(i) {
13690 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13691 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13692 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13693 GFP_KERNEL, cpu_to_node(i));
13694
13695 #ifdef CONFIG_CFS_BANDWIDTH
13696 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13697 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13698 #endif
13699 }
13700
13701 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
13702
13703 #ifdef CONFIG_NO_HZ_COMMON
13704 nohz.next_balance = jiffies;
13705 nohz.next_blocked = jiffies;
13706 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13707 #endif
13708 #endif /* SMP */
13709
13710 }
13711